@undefineds.co/xpod 0.4.28 → 0.4.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/ApiServer.js +4 -0
- package/dist/api/ai-gateway/AiGatewayService.d.ts +55 -0
- package/dist/api/ai-gateway/AiGatewayService.js +145 -6
- package/dist/api/ai-gateway/auth/AiConnectionsInvocationKeyIssuer.js +5 -3
- package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.d.ts +16 -49
- package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.js +6 -71
- package/dist/api/ai-gateway/auth/InvocationTokenAuthenticator.js +1 -0
- package/dist/api/ai-gateway/auth/InvocationTokenCodec.d.ts +4 -0
- package/dist/api/ai-gateway/auth/InvocationTokenCodec.js +8 -1
- package/dist/api/ai-gateway/connect/FileSessionImportAdapter.d.ts +3 -0
- package/dist/api/ai-gateway/connect/FileSessionImportAdapter.js +23 -3
- package/dist/api/ai-gateway/connect/SessionImportProfiles.d.ts +9 -1
- package/dist/api/ai-gateway/connect/SessionImportProfiles.js +4 -3
- package/dist/api/ai-gateway/connect/index.d.ts +40 -0
- package/dist/api/ai-gateway/connect/index.js +194 -4
- package/dist/api/ai-gateway/models/PodModelSelectionRepository.js +1 -1
- package/dist/api/ai-gateway/pod/OwnerPodAccess.js +5 -0
- package/dist/api/ai-gateway/pod/PodBaseUrlResolver.d.ts +11 -2
- package/dist/api/ai-gateway/pod/PodBaseUrlResolver.js +72 -10
- package/dist/api/ai-gateway/quota/ProviderQuotaAdapter.js +1 -1
- package/dist/api/ai-gateway/routing/ModelRouter.d.ts +7 -0
- package/dist/api/ai-gateway/routing/ModelRouter.js +13 -10
- package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.d.ts +1 -5
- package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.js +8 -63
- package/dist/api/auth/AuthContext.d.ts +4 -0
- package/dist/api/auth/ClientCredentialsAuthenticator.js +11 -5
- package/dist/api/auth/SolidSessionFactory.d.ts +50 -4
- package/dist/api/auth/SolidSessionFactory.js +114 -4
- package/dist/api/chatkit/pod-store.d.ts +8 -1
- package/dist/api/chatkit/pod-store.js +54 -3
- package/dist/api/container/common.js +34 -60
- package/dist/api/container/index.js +0 -3
- package/dist/api/container/routes.js +1 -8
- package/dist/api/container/types.d.ts +2 -9
- package/dist/api/container/types.js +0 -5
- package/dist/api/handlers/AiGatewayManagementHandler.d.ts +4 -12
- package/dist/api/handlers/AiGatewayManagementHandler.js +18 -258
- package/dist/api/middleware/AuthMiddleware.js +29 -1
- package/dist/api/runs/PiAgentRuntimeDriver.js +6 -1
- package/dist/cli/index.js +2 -1
- package/dist/identity/oidc/PodOwnershipResolver.js +16 -6
- package/dist/runtime/ingress-port.d.ts +9 -2
- package/dist/runtime/ingress-port.js +7 -2
- package/dist/runtime/local-secret-file.d.ts +1 -1
- package/dist/runtime/runner/node/CommunitySolidServerCssRunner.d.ts +3 -1
- package/dist/runtime/runner/node/CommunitySolidServerCssRunner.js +31 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +3 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +96 -67
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.d.ts +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.d.ts +1 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +81 -23
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.d.ts +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.d.ts +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/fingerprint.d.ts +1 -0
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/fingerprint.js +7 -0
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.d.ts +1 -2
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.js +0 -33
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.js +68 -22
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/types.d.ts +37 -10
- package/node_modules/@undefineds.co/ai-connections/dist/controller.js +5 -54
- package/node_modules/@undefineds.co/ai-connections/dist/error-wording.js +7 -2
- package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.cjs +405 -0
- package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.d.ts +14 -0
- package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.js +36 -0
- package/node_modules/@undefineds.co/ai-connections/dist/service-access.js +5 -26
- package/node_modules/@undefineds.co/ai-connections/package.json +10 -2
- package/node_modules/@undefineds.co/extension-sdk/dist/solid-permissions.js +131 -13
- package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +7 -1
- package/node_modules/@undefineds.co/extension-sdk/package.json +1 -1
- package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +38 -5
- package/node_modules/@undefineds.co/pod-collections/dist/mapping.d.ts +8 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mapping.js +34 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mutations.d.ts +2 -1
- package/node_modules/@undefineds.co/pod-collections/dist/mutations.js +6 -4
- package/node_modules/@undefineds.co/pod-collections/dist/sync.js +4 -3
- package/node_modules/@undefineds.co/pod-collections/package.json +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.d.ts +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.js +2 -2
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpViews.js +2 -2
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.d.ts +3 -3
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.js +5 -5
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.d.ts +5 -5
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.js +5 -5
- package/node_modules/@undefineds.co/shared-ui/dist/theme.css +32 -5
- package/node_modules/@undefineds.co/shared-ui/package.json +1 -1
- package/package.json +2 -2
- package/static/app/assets/main.css +1 -1
- package/static/app/assets/main.js +18 -18
- package/static/dashboard/assets/{AccountAuthBoundary-Dv52SZc6.js → AccountAuthBoundary-CuqXFEW4.js} +1 -1
- package/static/dashboard/assets/{DesktopOidcCallback-DaT_Rumf.js → DesktopOidcCallback-7i-yOvPW.js} +1 -1
- package/static/dashboard/assets/DevicePages-D1m_BNtX.js +2 -0
- package/static/dashboard/assets/ModelsPage-0qWGa5Y6.js +12 -0
- package/static/dashboard/assets/{PaneListHeader-DtvnRmFq.js → PaneListHeader-uWdPgJ0E.js} +1 -1
- package/static/dashboard/assets/{PodDeletionAuthorizationPanel-BJk_8rJq.js → PodDeletionAuthorizationPanel-C22bhZeD.js} +3 -3
- package/static/dashboard/assets/{PodPage-C4gzEspV.js → PodPage-Dyo3yCb-.js} +1 -1
- package/static/dashboard/assets/{SystemSettingsPage-HaNrP1H1.js → SystemSettingsPage-CeX-oG_a.js} +1 -1
- package/static/dashboard/assets/{TasksPage-BdO5K2L7.js → TasksPage-B0EoyRYT.js} +1 -1
- package/static/dashboard/assets/{WebDesktopEntry-Cj9_ZfJU.js → WebDesktopEntry-DT44RrTa.js} +1 -1
- package/static/dashboard/assets/XpodAiConnectionsPodStore-EXCqZPmb.js +3 -0
- package/static/dashboard/assets/XpodShellApp-BEzi4f1j.css +1 -0
- package/static/dashboard/assets/XpodShellApp-DAFsxamX.js +4 -0
- package/static/dashboard/assets/{account-session-DlcKNG7k.js → account-session-rRAOF7nF.js} +1 -1
- package/static/dashboard/assets/{button-wslF55uZ.js → button-WVnQUNG-.js} +1 -1
- package/static/dashboard/assets/{collection-runtime-uxxgEu13.js → collection-runtime-BAJQ8Qub.js} +1 -1
- package/static/dashboard/assets/{createLucideIcon-BJQl82Qk.js → createLucideIcon-BWelSi3L.js} +1 -1
- package/static/dashboard/assets/dashboard-hSOBxPcP.css +1 -0
- package/static/dashboard/assets/{dashboard-Or0gnkou.js → dashboard-vmne1ZE0.js} +2 -2
- package/static/dashboard/assets/{index-BqFeOML9.js → index-HDQQ8asz.js} +1 -1
- package/static/dashboard/assets/{index-DgKn1twH.js → index-gtv-MAHl.js} +1 -1
- package/static/dashboard/assets/{label-CS6Sx6Zb.js → label-tKuCTJm2.js} +1 -1
- package/static/dashboard/assets/{list-UyhlCFKk.js → list-CKq3KHke.js} +1 -1
- package/static/dashboard/assets/{nav-item-style-CW1Nnorq.js → nav-item-style-B2gI7c52.js} +1 -1
- package/static/dashboard/assets/pod-collections-host-BqOAkacM.js +8 -0
- package/static/dashboard/assets/{safe-continuation-ClWAhcma.js → safe-continuation-BsKjDpAA.js} +1 -1
- package/static/dashboard/assets/{section-header-CEIEcco-.js → section-header-DM0JU-wk.js} +1 -1
- package/static/dashboard/assets/{setting-row-CaYv3dfF.js → setting-row-XiH7UjWy.js} +1 -1
- package/static/dashboard/assets/{xpod-remembered-login-BUF9fin1.js → xpod-remembered-login-nv1g1sfC.js} +4 -4
- package/static/dashboard/dashboard.html +2 -2
- package/static/settings/assets/{AccountAuthBoundary-Chqd38oU.js → AccountAuthBoundary-DAUR0omy.js} +1 -1
- package/static/settings/assets/{DesktopOidcCallback-VUrOSM_q.js → DesktopOidcCallback-BNZAZMWY.js} +1 -1
- package/static/settings/assets/DevicePages-BO9SrXRp.js +2 -0
- package/static/settings/assets/ModelsPage-DREEXdf3.js +12 -0
- package/static/settings/assets/{PaneListHeader-B5RkRqr4.js → PaneListHeader-CeUH0JjQ.js} +1 -1
- package/static/settings/assets/{PodDeletionAuthorizationPanel-DPM-5Izt.js → PodDeletionAuthorizationPanel-Ch4--l4b.js} +3 -3
- package/static/settings/assets/{PodPage-CxND6wwc.js → PodPage-CqJBj3GJ.js} +1 -1
- package/static/settings/assets/{SystemSettingsPage-C8EdMkW7.js → SystemSettingsPage-2LSjpqUa.js} +1 -1
- package/static/settings/assets/{TasksPage-DuqptEm8.js → TasksPage-DA5IRxlP.js} +1 -1
- package/static/settings/assets/{WebDesktopEntry-BRcyktkv.js → WebDesktopEntry-BVelF1q0.js} +1 -1
- package/static/settings/assets/XpodAiConnectionsPodStore-O5-2qBsx.js +3 -0
- package/static/settings/assets/XpodShellApp-BEzi4f1j.css +1 -0
- package/static/settings/assets/XpodShellApp-D1b3kqD0.js +4 -0
- package/static/settings/assets/XpodThemeProvider-hSOBxPcP.css +1 -0
- package/static/settings/assets/{XpodThemeProvider-DK3pIdRG.js → XpodThemeProvider-rUdAw66p.js} +2 -2
- package/static/settings/assets/{account-session-DJOZ03xr.js → account-session-BD1q8D_o.js} +1 -1
- package/static/settings/assets/auth-callback-PWS7okI8.js +1 -0
- package/static/settings/assets/{button-D3yW-2o1.js → button-ZJYFB218.js} +1 -1
- package/static/settings/assets/{collection-runtime-DfGo25mh.js → collection-runtime-C2FHCCXJ.js} +1 -1
- package/static/settings/assets/{createLucideIcon-CacwLsmB.js → createLucideIcon-B2wXvYTD.js} +1 -1
- package/static/settings/assets/{index-r5KRYsKC.js → index-JFAkaKZH.js} +1 -1
- package/static/settings/assets/{label-MJjUmvzG.js → label-BLrTAmGy.js} +1 -1
- package/static/settings/assets/{list-Ce-5k1MX.js → list-Cm96vvJO.js} +1 -1
- package/static/settings/assets/{nav-item-style-ZUbL8KOZ.js → nav-item-style-C2upI7sr.js} +1 -1
- package/static/settings/assets/pod-collections-host-BqOAkacM.js +8 -0
- package/static/settings/assets/{safe-continuation-vlBZFSlU.js → safe-continuation-CYaRj3rj.js} +1 -1
- package/static/settings/assets/{section-header-DGJdEvQw.js → section-header-BviL5H8E.js} +1 -1
- package/static/settings/assets/{setting-row-C7tuFiho.js → setting-row-BYikj0YO.js} +1 -1
- package/static/settings/assets/{settings-CyQPih1O.js → settings-CpoDG_Qr.js} +1 -1
- package/static/settings/assets/{xpod-remembered-login-D-TzzT5K.js → xpod-remembered-login-BJ4QUSXy.js} +4 -4
- package/static/settings/auth-callback.html +3 -3
- package/static/settings/settings.html +3 -3
- package/dist/api/ai-gateway/auth/GatewayApiKey.d.ts +0 -28
- package/dist/api/ai-gateway/auth/GatewayApiKey.js +0 -162
- package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.d.ts +0 -26
- package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.js +0 -97
- package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.d.ts +0 -67
- package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.js +0 -340
- package/dist/runtime/gateway-locator-secret.d.ts +0 -5
- package/dist/runtime/gateway-locator-secret.js +0 -30
- package/static/dashboard/assets/DevicePages-HjclpIVm.js +0 -2
- package/static/dashboard/assets/ModelsPage-Be2TPd-x.js +0 -11
- package/static/dashboard/assets/XpodAiConnectionsPodStore-B7gmXBmC.js +0 -3
- package/static/dashboard/assets/XpodShellApp-Bwom2xL3.css +0 -1
- package/static/dashboard/assets/XpodShellApp-D_KY4nCW.js +0 -4
- package/static/dashboard/assets/dashboard-CbJ-JkrI.css +0 -1
- package/static/dashboard/assets/pod-collections-host-DjK2xf-b.js +0 -8
- package/static/settings/assets/DevicePages-C6qwvWwu.js +0 -2
- package/static/settings/assets/ModelsPage-Ry_dObRQ.js +0 -11
- package/static/settings/assets/XpodAiConnectionsPodStore-CyA_BJVC.js +0 -3
- package/static/settings/assets/XpodShellApp-Bwom2xL3.css +0 -1
- package/static/settings/assets/XpodShellApp-CsivHJl0.js +0 -4
- package/static/settings/assets/XpodThemeProvider-CbJ-JkrI.css +0 -1
- package/static/settings/assets/auth-callback-GIBYEz_7.js +0 -1
- package/static/settings/assets/pod-collections-host-DjK2xf-b.js +0 -8
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/XpodShellApp-
|
|
2
|
-
import{c as createLucideIcon$1}from"./createLucideIcon-CacwLsmB.js";import{r as reactExports,j as jsxRuntimeExports,g as useXpodAuthWindowSurface,h as getXpodAuthSurfaceHost,_ as __vitePreload,k as getDefaultExportFromCjs,l as getAugmentedNamespace,m as commonjsGlobal}from"./XpodThemeProvider-DK3pIdRG.js";import{c as cn,B as Button,u as useComposedRefs,e as createSlottable,d as controlFocusClass}from"./button-D3yW-2o1.js";import{c as createContextScope,P as Primitive,q as useCallbackRef,r as useLayoutEffect2,f as Card,p as createLucideIcon,t as reactDomExports,v as Presence,w as DismissableLayer,y as useId,u as useControllableState,a as composeEventHandlers,z as Portal$1,I as Input}from"./PodDeletionAuthorizationPanel-DPM-5Izt.js";import{X as XpodMark,f as resolveSolidLocalRouteUrl,h as createSolidLocalRouteFetch,p as probeSolidLocalRouteStatus}from"./account-session-DJOZ03xr.js";function _mergeNamespaces(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const a in n)if(a!=="default"&&!(a in r)){const i=Object.getOwnPropertyDescriptor(n,a);i&&Object.defineProperty(r,a,i.get?i:{enumerable:!0,get:()=>n[a]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var __defProp$4=Object.defineProperty,__name$4=(r,e)=>__defProp$4(r,"name",{value:e,configurable:!0}),AVATAR_NAME="Avatar",[createAvatarContext,createAvatarScope]=createContextScope(AVATAR_NAME),STATIC_IMAGE_COUNT_STATE=[0,()=>{}],[AvatarProvider,useAvatarContext]=createAvatarContext(AVATAR_NAME),Avatar$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,...a}=e,[i,o]=reactExports.useState("idle"),[s,d]=useImageCount();return jsxRuntimeExports.jsx(AvatarProvider,{scope:n,imageLoadingStatus:i,setImageLoadingStatus:o,imageCount:s,setImageCount:d,children:jsxRuntimeExports.jsx(Primitive.span,{...a,ref:t})})},"Avatar")),IMAGE_NAME="AvatarImage",AvatarImage$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,src:a,onLoadingStatusChange:i,...o}=e,s=useAvatarContext(IMAGE_NAME,n);s.setImageCount;const d=useImageLoadingStatus(a,{referrerPolicy:o.referrerPolicy,crossOrigin:o.crossOrigin,loadingStatus:s.imageLoadingStatus,setLoadingStatus:s.setImageLoadingStatus}),u=useCallbackRef(p=>{i?.(p)}),c=reactExports.useRef(d);return useLayoutEffect2(()=>{const p=c.current;c.current=d,d!==p&&u(d)},[d,u]),d==="loaded"?jsxRuntimeExports.jsx(Primitive.img,{...o,ref:t,src:a}):null},"AvatarImage")),FALLBACK_NAME="AvatarFallback",AvatarFallback$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,delayMs:a,...i}=e,o=useAvatarContext(FALLBACK_NAME,n),[s,d]=reactExports.useState(a===void 0);return reactExports.useEffect(()=>{if(a!==void 0){const u=window.setTimeout(()=>d(!0),a);return()=>window.clearTimeout(u)}},[a]),s&&o.imageLoadingStatus!=="loaded"?jsxRuntimeExports.jsx(Primitive.span,{...i,ref:t}):null},"AvatarFallback"));function useImageLoadingStatus(r,{loadingStatus:e,setLoadingStatus:t,referrerPolicy:n,crossOrigin:a}){return useLayoutEffect2(()=>{if(!r){t("error");return}const i=new window.Image,o=__name$4(d=>{const u=d.currentTarget;t(getImageLoadingStatus(u))},"handleLoad"),s=__name$4(()=>t("error"),"handleError");return i.addEventListener("load",o),i.addEventListener("error",s),n&&(i.referrerPolicy=n),i.crossOrigin=a??null,i.src=r,t(getImageLoadingStatus(i)),()=>{i.removeEventListener("load",o),i.removeEventListener("error",s),t("idle")}},[r,a,n,t]),e}__name$4(useImageLoadingStatus,"useImageLoadingStatus");function getImageLoadingStatus(r){return r.complete?r.naturalWidth>0?"loaded":"error":"loading"}__name$4(getImageLoadingStatus,"getImageLoadingStatus");function useImageCount(){return STATIC_IMAGE_COUNT_STATE}__name$4(useImageCount,"useImageCount");function useUpdateImageCount(r){}__name$4(useUpdateImageCount,"useUpdateImageCount");const Avatar=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(Avatar$1,{ref:t,className:cn("relative flex shrink-0 overflow-hidden",r),...e}));Avatar.displayName=Avatar$1.displayName;const AvatarImage=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(AvatarImage$1,{ref:t,className:cn("h-full w-full object-cover",r),...e}));AvatarImage.displayName=AvatarImage$1.displayName;const AvatarFallback=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(AvatarFallback$1,{ref:t,className:cn("flex h-full w-full items-center justify-center bg-muted text-lg font-semibold",r),...e}));AvatarFallback.displayName=AvatarFallback$1.displayName;function AuthSurfaceBody({children:r,className:e}){return jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-body",className:cn("min-h-0",e),children:r})}const FOCUSABLE_SELECTOR=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function getFocusable(r){return Array.from(r.querySelectorAll(FOCUSABLE_SELECTOR)).filter(e=>e.getAttribute("aria-hidden")!=="true")}function AuthSurface({mode:r,title:e,children:t,presentation:n="standard",host:a="document",lead:i,onClose:o,closeLabel:s,closeOnEscape:d=!0,className:u,contentClassName:c}){const p=reactExports.useRef(null),_=reactExports.useRef(null),m=reactExports.useId();reactExports.useLayoutEffect(()=>{if(r!=="modal"||typeof document>"u")return;_.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const b=p.current;if(b){const N=getFocusable(b);(n==="compact"?b:N[0]??b).focus()}return()=>{_.current?.focus(),_.current=null}},[r,n]),reactExports.useLayoutEffect(()=>{if(r!=="modal"||typeof document>"u")return;const b=N=>{if(N.key==="Escape"){d&&o&&(N.preventDefault(),o());return}if(N.key!=="Tab")return;const O=p.current;if(!O)return;const X=getFocusable(O);if(X.length===0){N.preventDefault(),O.focus();return}const ee=document.activeElement,V=X.indexOf(ee),U=N.shiftKey?V<=0?X.length-1:V-1:V===X.length-1?0:V+1;N.preventDefault(),X[U].focus()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[d,r,o]);const S=r==="modal"?{role:"dialog","aria-modal":!0,"aria-labelledby":m}:{role:"region","aria-labelledby":m},A=n==="compact",h=a==="window",T=A?"flex min-h-0 flex-1 flex-col overflow-y-auto":"max-h-[min(80vh,48rem)] overflow-y-auto",w=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[A?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h1",{id:m,className:"sr-only",children:e}),r==="modal"&&o&&s?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":s,className:"absolute right-2 top-2 z-[var(--layer-sticky)]",children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border/60 p-4",children:[jsxRuntimeExports.jsx("h1",{id:m,className:"text-lg font-semibold text-foreground",children:e}),r==="modal"&&o&&s?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":s,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}),i?jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-lead",className:cn(A?"shrink-0 px-5 pt-7 has-[[data-presentation=compact]]:pt-5":"border-b border-border/60 p-4"),children:i}):null,jsxRuntimeExports.jsx(AuthSurfaceBody,{className:cn(T,c),children:t})]});return jsxRuntimeExports.jsx("div",{"data-testid":`auth-surface-${r}`,"data-auth-surface-mode":r,"data-auth-surface-presentation":A?"compact":void 0,"data-auth-surface-host":h?"window":void 0,className:cn(h?"fixed inset-0 z-[var(--layer-modal)] flex items-stretch justify-stretch overflow-hidden bg-card p-0":r==="modal"?cn("fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center p-4","bg-background"):r==="page"?"flex min-h-[100dvh] w-full items-center justify-center bg-background p-4":"flex min-h-0 w-full items-center justify-center p-4",u),children:h?jsxRuntimeExports.jsx("div",{ref:p,...S,"data-auth-surface-frame":"window",tabIndex:-1,className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden bg-card text-card-foreground focus:outline-none",children:w}):A?jsxRuntimeExports.jsx("div",{ref:p,...S,"data-auth-surface-frame":"compact",tabIndex:-1,style:{outline:"none"},className:"flex h-[400px] w-[280px] max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] min-w-0 flex-col overflow-y-auto overscroll-contain focus:outline-none",children:w}):jsxRuntimeExports.jsx(Card,{ref:p,...S,tabIndex:-1,style:{outline:"none"},className:cn("relative flex min-h-0 w-full flex-col border-border bg-card text-card-foreground focus:outline-none",r==="embedded"?"max-w-none shadow-none":"max-w-lg"),children:w})})}const __iconNode$7=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Check=createLucideIcon("check",__iconNode$7);const __iconNode$6=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Cloud=createLucideIcon("cloud",__iconNode$6);const __iconNode$5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Info=createLucideIcon("info",__iconNode$5);const __iconNode$4=[["path",{d:"M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z",key:"1pdavp"}],["path",{d:"M20.054 15.987H3.946",key:"14rxg9"}]],Laptop=createLucideIcon("laptop",__iconNode$4);const __iconNode$3=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle$1=createLucideIcon("loader-circle",__iconNode$3);const __iconNode$2=[["path",{d:"M5 12h14",key:"1ays0h"}]],Minus=createLucideIcon("minus",__iconNode$2),sides=["top","right","bottom","left"],min=Math.min,max$1=Math.max,round=Math.round,floor=Math.floor,createCoords=r=>({x:r,y:r}),oppositeSideMap={left:"right",right:"left",bottom:"top",top:"bottom"};function clamp(r,e,t){return max$1(r,min(e,t))}function evaluate(r,e){return typeof r=="function"?r(e):r}function getSide(r){return r.split("-")[0]}function getAlignment(r){return r.split("-")[1]}function getOppositeAxis(r){return r==="x"?"y":"x"}function getAxisLength(r){return r==="y"?"height":"width"}function getSideAxis(r){const e=r[0];return e==="t"||e==="b"?"y":"x"}function getAlignmentAxis(r){return getOppositeAxis(getSideAxis(r))}function getAlignmentSides(r,e,t){t===void 0&&(t=!1);const n=getAlignment(r),a=getAlignmentAxis(r),i=getAxisLength(a);let o=a==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(o=getOppositePlacement(o)),[o,getOppositePlacement(o)]}function getExpandedPlacements(r){const e=getOppositePlacement(r);return[getOppositeAlignmentPlacement(r),e,getOppositeAlignmentPlacement(e)]}function getOppositeAlignmentPlacement(r){return r.includes("start")?r.replace("start","end"):r.replace("end","start")}const lrPlacement=["left","right"],rlPlacement=["right","left"],tbPlacement=["top","bottom"],btPlacement=["bottom","top"];function getSideList(r,e,t){switch(r){case"top":case"bottom":return t?e?rlPlacement:lrPlacement:e?lrPlacement:rlPlacement;case"left":case"right":return e?tbPlacement:btPlacement;default:return[]}}function getOppositeAxisPlacements(r,e,t,n){const a=getAlignment(r);let i=getSideList(getSide(r),t==="start",n);return a&&(i=i.map(o=>o+"-"+a),e&&(i=i.concat(i.map(getOppositeAlignmentPlacement)))),i}function getOppositePlacement(r){const e=getSide(r);return oppositeSideMap[e]+r.slice(e.length)}function expandPaddingObject(r){var e,t,n,a;return{top:(e=r.top)!=null?e:0,right:(t=r.right)!=null?t:0,bottom:(n=r.bottom)!=null?n:0,left:(a=r.left)!=null?a:0}}function getPaddingObject(r){return typeof r!="number"?expandPaddingObject(r):{top:r,right:r,bottom:r,left:r}}function rectToClientRect(r){const{x:e,y:t,width:n,height:a}=r;return{width:n,height:a,top:t,left:e,right:e+n,bottom:t+a,x:e,y:t}}function computeCoordsFromPlacement(r,e,t){let{reference:n,floating:a}=r;const i=getSideAxis(e),o=getAlignmentAxis(e),s=getAxisLength(o),d=getSide(e),u=i==="y",c=n.x+n.width/2-a.width/2,p=n.y+n.height/2-a.height/2,_=n[s]/2-a[s]/2;let m;switch(d){case"top":m={x:c,y:n.y-a.height};break;case"bottom":m={x:c,y:n.y+n.height};break;case"right":m={x:n.x+n.width,y:p};break;case"left":m={x:n.x-a.width,y:p};break;default:m={x:n.x,y:n.y}}const S=getAlignment(e);return S&&(m[o]+=_*(S==="end"?1:-1)*(t&&u?-1:1)),m}async function detectOverflow(r,e){var t;e===void 0&&(e={});const{x:n,y:a,platform:i,rects:o,elements:s,strategy:d}=r,{boundary:u="clippingAncestors",rootBoundary:c="viewport",elementContext:p="floating",altBoundary:_=!1,padding:m=0}=evaluate(e,r),S=getPaddingObject(m),h=s[_?p==="floating"?"reference":"floating":p],T=rectToClientRect(await i.getClippingRect({element:(t=await(i.isElement==null?void 0:i.isElement(h)))==null||t?h:h.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(s.floating)),boundary:u,rootBoundary:c,strategy:d})),w=p==="floating"?{x:n,y:a,width:o.floating.width,height:o.floating.height}:o.reference,b=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),N=await(i.isElement==null?void 0:i.isElement(b))&&await(i.getScale==null?void 0:i.getScale(b))||{x:1,y:1},O=rectToClientRect(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:w,offsetParent:b,strategy:d}):w);return{top:(T.top-O.top+S.top)/N.y,bottom:(O.bottom-T.bottom+S.bottom)/N.y,left:(T.left-O.left+S.left)/N.x,right:(O.right-T.right+S.right)/N.x}}const MAX_RESET_COUNT=50,computePosition$1=async(r,e,t)=>{const{placement:n="bottom",strategy:a="absolute",middleware:i=[],platform:o}=t,s=o.detectOverflow?o:{...o,detectOverflow},d=await(o.isRTL==null?void 0:o.isRTL(e));let u=await o.getElementRects({reference:r,floating:e,strategy:a}),{x:c,y:p}=computeCoordsFromPlacement(u,n,d),_=n,m=0;const S={};for(let A=0;A<i.length;A++){const h=i[A];if(!h)continue;const{name:T,fn:w}=h,{x:b,y:N,data:O,reset:X}=await w({x:c,y:p,initialPlacement:n,placement:_,strategy:a,middlewareData:S,rects:u,platform:s,elements:{reference:r,floating:e}});c=b??c,p=N??p,S[T]={...S[T],...O},X&&m<MAX_RESET_COUNT&&(m++,typeof X=="object"&&(X.placement&&(_=X.placement),X.rects&&(u=X.rects===!0?await o.getElementRects({reference:r,floating:e,strategy:a}):X.rects),{x:c,y:p}=computeCoordsFromPlacement(u,_,d)),A=-1)}return{x:c,y:p,placement:_,strategy:a,middlewareData:S}},arrow$3=r=>({name:"arrow",options:r,async fn(e){const{x:t,y:n,placement:a,rects:i,platform:o,elements:s,middlewareData:d}=e,{element:u,padding:c=0}=evaluate(r,e)||{};if(u==null)return{};const p=getPaddingObject(c),_={x:t,y:n},m=getAlignmentAxis(a),S=getAxisLength(m),A=await o.getDimensions(u),h=m==="y",T=h?"top":"left",w=h?"bottom":"right",b=h?"clientHeight":"clientWidth",N=i.reference[S]+i.reference[m]-_[m]-i.floating[S],O=_[m]-i.reference[m],X=await(o.getOffsetParent==null?void 0:o.getOffsetParent(u));let ee=X?X[b]:0;(!ee||!await(o.isElement==null?void 0:o.isElement(X)))&&(ee=s.floating[b]||i.floating[S]);const V=N/2-O/2,U=ee/2-A[S]/2-1,v=min(p[T],U),x=min(p[w],U),I=ee-A[S]-x,E=ee/2-A[S]/2+V,Q=clamp(v,E,I),K=!d.arrow&&getAlignment(a)!=null&&E!==Q&&i.reference[S]/2-(E<v?v:x)-A[S]/2<0,te=K?E<v?E-v:E-I:0;return{[m]:_[m]+te,data:{[m]:Q,centerOffset:E-Q-te,...K&&{alignmentOffset:te}},reset:K}}}),flip$2=function(r){return r===void 0&&(r={}),{name:"flip",options:r,async fn(e){var t,n;const{placement:a,middlewareData:i,rects:o,initialPlacement:s,platform:d,elements:u}=e,{mainAxis:c=!0,crossAxis:p=!0,fallbackPlacements:_,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:A=!0,...h}=evaluate(r,e);if((t=i.arrow)!=null&&t.alignmentOffset)return{};const T=getSide(a),w=getSideAxis(s),b=getSide(s)===s,N=await(d.isRTL==null?void 0:d.isRTL(u.floating)),O=_||(b||!A?[getOppositePlacement(s)]:getExpandedPlacements(s)),X=S!=="none";!_&&X&&O.push(...getOppositeAxisPlacements(s,A,S,N));const ee=[s,...O],V=await d.detectOverflow(e,h),U=[];let v=((n=i.flip)==null?void 0:n.overflows)||[];if(c&&U.push(V[T]),p){const Q=getAlignmentSides(a,o,N);U.push(V[Q[0]],V[Q[1]])}if(v=[...v,{placement:a,overflows:U}],!U.every(Q=>Q<=0)){var x,I;const Q=(((x=i.flip)==null?void 0:x.index)||0)+1,K=ee[Q];if(K&&(!(p==="alignment"?w!==getSideAxis(K):!1)||v.every(D=>getSideAxis(D.placement)===w?D.overflows[0]>0:!0)))return{data:{index:Q,overflows:v},reset:{placement:K}};let te=(I=v.filter(se=>se.overflows[0]<=0).sort((se,D)=>se.overflows[1]-D.overflows[1])[0])==null?void 0:I.placement;if(!te)switch(m){case"bestFit":{var E;const se=(E=v.filter(D=>{if(X){const ne=getSideAxis(D.placement);return ne===w||ne==="y"}return!0}).map(D=>[D.placement,D.overflows.filter(ne=>ne>0).reduce((ne,y)=>ne+y,0)]).sort((D,ne)=>D[1]-ne[1])[0])==null?void 0:E[0];se&&(te=se);break}case"initialPlacement":te=s;break}if(a!==te)return{reset:{placement:te}}}return{}}}};function getSideOffsets(r,e){return{top:r.top-e.height,right:r.right-e.width,bottom:r.bottom-e.height,left:r.left-e.width}}function isAnySideFullyClipped(r){return sides.some(e=>r[e]>=0)}const hide$2=function(r){return r===void 0&&(r={}),{name:"hide",options:r,async fn(e){const{rects:t,platform:n}=e,{strategy:a="referenceHidden",...i}=evaluate(r,e);switch(a){case"referenceHidden":{const o=await n.detectOverflow(e,{...i,elementContext:"reference"}),s=getSideOffsets(o,t.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:isAnySideFullyClipped(s)}}}case"escaped":{const o=await n.detectOverflow(e,{...i,altBoundary:!0}),s=getSideOffsets(o,t.floating);return{data:{escapedOffsets:s,escaped:isAnySideFullyClipped(s)}}}default:return{}}}}},originSides=new Set(["left","top"]);async function convertValueToCoords(r,e){const{placement:t,platform:n,elements:a}=r,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),o=getSide(t),s=getAlignment(t),d=getSideAxis(t)==="y",u=originSides.has(o)?-1:1,c=i&&d?-1:1,p=evaluate(e,r);let{mainAxis:_,crossAxis:m,alignmentAxis:S}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return s&&typeof S=="number"&&(m=s==="end"?S*-1:S),d?{x:m*c,y:_*u}:{x:_*u,y:m*c}}const offset$2=function(r){return r===void 0&&(r=0),{name:"offset",options:r,async fn(e){var t,n;const{x:a,y:i,placement:o,middlewareData:s}=e,d=await convertValueToCoords(e,r);return o===((t=s.offset)==null?void 0:t.placement)&&(n=s.arrow)!=null&&n.alignmentOffset?{}:{x:a+d.x,y:i+d.y,data:{...d,placement:o}}}}},shift$2=function(r){return r===void 0&&(r={}),{name:"shift",options:r,async fn(e){const{x:t,y:n,placement:a,platform:i}=e,{mainAxis:o=!0,crossAxis:s=!1,limiter:d={fn:w=>{let{x:b,y:N}=w;return{x:b,y:N}}},...u}=evaluate(r,e),c={x:t,y:n},p=await i.detectOverflow(e,u),_=getSideAxis(a),m=getOppositeAxis(_);let S=c[m],A=c[_];const h=(w,b)=>clamp(b+p[w==="y"?"top":"left"],b,b-p[w==="y"?"bottom":"right"]);o&&(S=h(m,S)),s&&(A=h(_,A));const T=d.fn({...e,[m]:S,[_]:A});return{...T,data:{x:T.x-t,y:T.y-n,enabled:{[m]:o,[_]:s}}}}}},limitShift$2=function(r){return r===void 0&&(r={}),{options:r,fn(e){var t,n;const{x:a,y:i,placement:o,rects:s,middlewareData:d}=e,{offset:u=0,mainAxis:c=!0,crossAxis:p=!0}=evaluate(r,e),_={x:a,y:i},m=getSideAxis(o),S=getOppositeAxis(m);let A=_[S],h=_[m];const T=evaluate(u,e),w=typeof T=="number"?{mainAxis:T,crossAxis:0}:{mainAxis:(t=T.mainAxis)!=null?t:0,crossAxis:(n=T.crossAxis)!=null?n:0};if(c){const O=S==="y"?"height":"width",X=s.reference[S]-s.floating[O]+w.mainAxis,ee=s.reference[S]+s.reference[O]-w.mainAxis;A<X?A=X:A>ee&&(A=ee)}if(p){var b,N;const O=S==="y"?"width":"height",X=originSides.has(getSide(o)),ee=s.reference[m]-s.floating[O]+(X&&((b=d.offset)==null?void 0:b[m])||0)+(X?0:w.crossAxis),V=s.reference[m]+s.reference[O]+(X?0:((N=d.offset)==null?void 0:N[m])||0)-(X?w.crossAxis:0);h<ee?h=ee:h>V&&(h=V)}return{[S]:A,[m]:h}}}},size$2=function(r){return r===void 0&&(r={}),{name:"size",options:r,async fn(e){const{placement:t,rects:n,platform:a,elements:i}=e,{apply:o=()=>{},...s}=evaluate(r,e),d=await a.detectOverflow(e,s),u=getSide(t),c=getAlignment(t),p=getSideAxis(t)==="y",{width:_,height:m}=n.floating;let S,A;u==="top"||u==="bottom"?(S=u,A=c===(await(a.isRTL==null?void 0:a.isRTL(i.floating))?"start":"end")?"left":"right"):(A=u,S=c==="end"?"top":"bottom");const h=m-d.top-d.bottom,T=_-d.left-d.right,w=min(m-d[S],h),b=min(_-d[A],T),N=e.middlewareData.shift,O=!N;let X=w,ee=b;N!=null&&N.enabled.x&&(ee=T),N!=null&&N.enabled.y&&(X=h),O&&!c&&(p?ee=_-2*max$1(d.left,d.right):X=m-2*max$1(d.top,d.bottom)),await o({...e,availableWidth:ee,availableHeight:X});const V=await a.getDimensions(i.floating);return _!==V.width||m!==V.height?{reset:{rects:!0}}:{}}}};function hasWindow(){return typeof window<"u"}function getNodeName(r){return isNode$1(r)?(r.nodeName||"").toLowerCase():"#document"}function getWindow(r){var e;return(r==null||(e=r.ownerDocument)==null?void 0:e.defaultView)||window}function getDocumentElement(r){var e;return(e=(isNode$1(r)?r.ownerDocument:r.document)||window.document)==null?void 0:e.documentElement}function isNode$1(r){return hasWindow()?r instanceof Node||r instanceof getWindow(r).Node:!1}function isElement(r){return hasWindow()?r instanceof Element||r instanceof getWindow(r).Element:!1}function isHTMLElement(r){return hasWindow()?r instanceof HTMLElement||r instanceof getWindow(r).HTMLElement:!1}function isShadowRoot(r){return!hasWindow()||typeof ShadowRoot>"u"?!1:r instanceof ShadowRoot||r instanceof getWindow(r).ShadowRoot}function isOverflowElement(r){const{overflow:e,overflowX:t,overflowY:n,display:a}=getComputedStyle$1(r);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&a!=="inline"&&a!=="contents"}function isTableElement(r){return/^(table|td|th)$/.test(getNodeName(r))}function isTopLayer(r){try{if(r.matches(":popover-open"))return!0}catch{}try{return r.matches(":modal")}catch{return!1}}const willChangeRe=/transform|translate|scale|rotate|perspective|filter/,containRe=/paint|layout|strict|content/,isNotNone=r=>!!r&&r!=="none";let isWebKitValue;function isContainingBlock(r){const e=isElement(r)?getComputedStyle$1(r):r;return isNotNone(e.transform)||isNotNone(e.translate)||isNotNone(e.scale)||isNotNone(e.rotate)||isNotNone(e.perspective)||!isWebKit()&&(isNotNone(e.backdropFilter)||isNotNone(e.filter))||willChangeRe.test(e.willChange||"")||containRe.test(e.contain||"")}function getContainingBlock(r){let e=getParentNode(r);for(;isHTMLElement(e)&&!isLastTraversableNode(e);){if(isContainingBlock(e))return e;if(isTopLayer(e))return null;e=getParentNode(e)}return null}function isWebKit(){return isWebKitValue==null&&(isWebKitValue=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),isWebKitValue}function isLastTraversableNode(r){return/^(html|body|#document)$/.test(getNodeName(r))}function getComputedStyle$1(r){return getWindow(r).getComputedStyle(r)}function getNodeScroll(r){return isElement(r)?{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}:{scrollLeft:r.scrollX,scrollTop:r.scrollY}}function getParentNode(r){if(getNodeName(r)==="html")return r;const e=r.assignedSlot||r.parentNode||isShadowRoot(r)&&r.host||getDocumentElement(r);return isShadowRoot(e)?e.host:e}function getNearestOverflowAncestor(r){const e=getParentNode(r);return isLastTraversableNode(e)?(r.ownerDocument||r).body:isHTMLElement(e)&&isOverflowElement(e)?e:getNearestOverflowAncestor(e)}function getOverflowAncestors(r,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const a=getNearestOverflowAncestor(r),i=a===((n=r.ownerDocument)==null?void 0:n.body),o=getWindow(a);if(i){const s=getFrameElement(o);return e.concat(o,o.visualViewport||[],isOverflowElement(a)?a:[],s&&t?getOverflowAncestors(s):[])}else return e.concat(a,getOverflowAncestors(a,[],t))}function getFrameElement(r){return r.parent&&Object.getPrototypeOf(r.parent)?r.frameElement:null}function getCssDimensions(r){const e=getComputedStyle$1(r);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const a=isHTMLElement(r),i=a?r.offsetWidth:t,o=a?r.offsetHeight:n,s=round(t)!==i||round(n)!==o;return s&&(t=i,n=o),{width:t,height:n,$:s}}function unwrapElement(r){return isElement(r)?r:r.contextElement}function getScale(r){const e=unwrapElement(r);if(!isHTMLElement(e))return createCoords(1);const t=e.getBoundingClientRect(),{width:n,height:a,$:i}=getCssDimensions(e);let o=(i?round(t.width):t.width)/n,s=(i?round(t.height):t.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}const noOffsets=createCoords(0);function getVisualOffsets(r){const e=getWindow(r);return!isWebKit()||!e.visualViewport?noOffsets:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function shouldAddVisualOffsets(r,e,t){return e===void 0&&(e=!1),!!t&&e&&t===getWindow(r)}function getBoundingClientRect(r,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const a=r.getBoundingClientRect(),i=unwrapElement(r);let o=createCoords(1);e&&(n?isElement(n)&&(o=getScale(n)):o=getScale(r));const s=shouldAddVisualOffsets(i,t,n)?getVisualOffsets(i):createCoords(0);let d=(a.left+s.x)/o.x,u=(a.top+s.y)/o.y,c=a.width/o.x,p=a.height/o.y;if(i&&n){const _=getWindow(i),m=isElement(n)?getWindow(n):n;let S=_,A=getFrameElement(S);for(;A&&m!==S;){const h=getScale(A),T=A.getBoundingClientRect(),w=getComputedStyle$1(A),b=T.left+(A.clientLeft+parseFloat(w.paddingLeft))*h.x,N=T.top+(A.clientTop+parseFloat(w.paddingTop))*h.y;d*=h.x,u*=h.y,c*=h.x,p*=h.y,d+=b,u+=N,S=getWindow(A),A=getFrameElement(S)}}return rectToClientRect({width:c,height:p,x:d,y:u})}function getWindowScrollBarX(r,e){const t=getNodeScroll(r).scrollLeft;return e?e.left+t:getBoundingClientRect(getDocumentElement(r)).left+t}function getHTMLOffset(r,e){const t=r.getBoundingClientRect(),n=t.left+e.scrollLeft-getWindowScrollBarX(r,t),a=t.top+e.scrollTop;return{x:n,y:a}}function convertOffsetParentRelativeRectToViewportRelativeRect(r){let{elements:e,rect:t,offsetParent:n,strategy:a}=r;const i=a==="fixed",o=getDocumentElement(n),s=e?isTopLayer(e.floating):!1;if(n===o||s&&i)return t;let d={scrollLeft:0,scrollTop:0},u=createCoords(1);const c=createCoords(0),p=isHTMLElement(n);if((p||!i)&&((getNodeName(n)!=="body"||isOverflowElement(o))&&(d=getNodeScroll(n)),p)){const m=getBoundingClientRect(n);u=getScale(n),c.x=m.x+n.clientLeft,c.y=m.y+n.clientTop}const _=o&&!p&&!i?getHTMLOffset(o,d):createCoords(0);return{width:t.width*u.x,height:t.height*u.y,x:t.x*u.x-d.scrollLeft*u.x+c.x+_.x,y:t.y*u.y-d.scrollTop*u.y+c.y+_.y}}function getClientRects(r){return r.getClientRects?Array.from(r.getClientRects()):[]}function getDocumentRect(r){const e=getNodeScroll(r),t=r.ownerDocument.body,n=max$1(r.scrollWidth,r.clientWidth,t.scrollWidth,t.clientWidth),a=max$1(r.scrollHeight,r.clientHeight,t.scrollHeight,t.clientHeight);let i=-e.scrollLeft+getWindowScrollBarX(r);const o=-e.scrollTop;return getComputedStyle$1(t).direction==="rtl"&&(i+=max$1(r.clientWidth,t.clientWidth)-n),{width:n,height:a,x:i,y:o}}const SCROLLBAR_MAX=25;function getViewportRect(r,e,t){t===void 0&&(t="viewport");const n=t==="layoutViewport",a=getWindow(r),i=getDocumentElement(r),o=a.visualViewport;let s=i.clientWidth,d=i.clientHeight,u=0,c=0;if(o){const _=!isWebKit()||e==="fixed";n?_||(u=-o.offsetLeft,c=-o.offsetTop):(s=o.width,d=o.height,_&&(u=o.offsetLeft,c=o.offsetTop))}if(getWindowScrollBarX(i)<=0){const _=i.ownerDocument,m=_.body,S=getComputedStyle(m),A=_.compatMode==="CSS1Compat"&&parseFloat(S.marginLeft)+parseFloat(S.marginRight)||0,h=Math.abs(i.clientWidth-m.clientWidth-A),T=getComputedStyle(i).scrollbarGutter==="stable both-edges"?h/2:h;T<=SCROLLBAR_MAX&&(s-=T)}return{width:s,height:d,x:u,y:c}}function getInnerBoundingClientRect(r,e){const t=getBoundingClientRect(r,!0,e==="fixed"),n=t.top+r.clientTop,a=t.left+r.clientLeft,i=getScale(r),o=r.clientWidth*i.x,s=r.clientHeight*i.y,d=a*i.x,u=n*i.y;return{width:o,height:s,x:d,y:u}}function getClientRectFromClippingAncestor(r,e,t){let n;if(e==="viewport"||e==="layoutViewport")n=getViewportRect(r,t,e);else if(e==="document")n=getDocumentRect(getDocumentElement(r));else if(isElement(e))n=getInnerBoundingClientRect(e,t);else{const a=getVisualOffsets(r);n={x:e.x-a.x,y:e.y-a.y,width:e.width,height:e.height}}return rectToClientRect(n)}function getClippingElementAncestors(r,e){const t=e.get(r);if(t)return t;let n=getOverflowAncestors(r,[],!1).filter(s=>isElement(s)&&getNodeName(s)!=="body"),a=null;const i=getComputedStyle$1(r).position==="fixed";let o=i?getParentNode(r):r;for(;isElement(o)&&!isLastTraversableNode(o);){const s=getComputedStyle$1(o),d=isContainingBlock(o),u=a?a.position:i?"fixed":"";!d&&(u==="fixed"||u==="absolute"&&s.position==="static")?n=n.filter(p=>p!==o):a=s,o=getParentNode(o)}return e.set(r,n),n}function getClippingRect(r){let{element:e,boundary:t,rootBoundary:n,strategy:a}=r;const o=[...t==="clippingAncestors"?isTopLayer(e)?[]:getClippingElementAncestors(e,this._c):[].concat(t),n],s=getClientRectFromClippingAncestor(e,o[0],a);let d=s.top,u=s.right,c=s.bottom,p=s.left;for(let _=1;_<o.length;_++){const m=getClientRectFromClippingAncestor(e,o[_],a);d=max$1(m.top,d),u=min(m.right,u),c=min(m.bottom,c),p=max$1(m.left,p)}return{width:u-p,height:c-d,x:p,y:d}}function getDimensions(r){const{width:e,height:t}=getCssDimensions(r);return{width:e,height:t}}function getRectRelativeToOffsetParent(r,e,t){const n=isHTMLElement(e),a=getDocumentElement(e),i=t==="fixed",o=getBoundingClientRect(r,!0,i,e);let s={scrollLeft:0,scrollTop:0};const d=createCoords(0);if((n||!i)&&((getNodeName(e)!=="body"||isOverflowElement(a))&&(s=getNodeScroll(e)),n)){const _=getBoundingClientRect(e,!0,i,e);d.x=_.x+e.clientLeft,d.y=_.y+e.clientTop}!n&&a&&(d.x=getWindowScrollBarX(a));const u=a&&!n&&!i?getHTMLOffset(a,s):createCoords(0),c=o.left+s.scrollLeft-d.x-u.x,p=o.top+s.scrollTop-d.y-u.y;return{x:c,y:p,width:o.width,height:o.height}}function isStaticPositioned(r){return getComputedStyle$1(r).position==="static"}function getTrueOffsetParent(r,e){if(!isHTMLElement(r)||getComputedStyle$1(r).position==="fixed")return null;if(e)return e(r);let t=r.offsetParent;return getDocumentElement(r)===t&&(t=t.ownerDocument.body),t}function getOffsetParent(r,e){const t=getWindow(r);if(isTopLayer(r))return t;if(!isHTMLElement(r)){let a=getParentNode(r);for(;a&&!isLastTraversableNode(a);){if(isElement(a)&&!isStaticPositioned(a))return a;a=getParentNode(a)}return t}let n=getTrueOffsetParent(r,e);for(;n&&isTableElement(n)&&isStaticPositioned(n);)n=getTrueOffsetParent(n,e);return n&&isLastTraversableNode(n)&&isStaticPositioned(n)&&!isContainingBlock(n)?t:n||getContainingBlock(r)||t}const getElementRects=async function(r){const e=this.getOffsetParent||getOffsetParent,t=this.getDimensions,n=await t(r.floating);return{reference:getRectRelativeToOffsetParent(r.reference,await e(r.floating),r.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function isRTL(r){return getComputedStyle$1(r).direction==="rtl"}const platform={convertOffsetParentRelativeRectToViewportRelativeRect,getDocumentElement,getClippingRect,getOffsetParent,getElementRects,getClientRects,getDimensions,getScale,isElement,isRTL};function rectsAreEqual(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function observeMove(r,e,t){let n=null,a;const i=getDocumentElement(r);function o(){var c;clearTimeout(a),(c=n)==null||c.disconnect(),n=null}function s(c,p){c===void 0&&(c=!1),p===void 0&&(p=1),o();const _=r.getBoundingClientRect(),{left:m,top:S,width:A,height:h}=_;if(c||e(),!A||!h)return;const T=floor(S),w=floor(i.clientWidth-(m+A)),b=floor(i.clientHeight-(S+h)),N=floor(m),X={rootMargin:-T+"px "+-w+"px "+-b+"px "+-N+"px",threshold:max$1(0,min(1,p))||1};let ee=!0;function V(U){const v=U[0].intersectionRatio;if(!rectsAreEqual(_,r.getBoundingClientRect()))return s();if(v!==p){if(!ee)return s();v?s(!1,v):a=setTimeout(()=>{s(!1,1e-7)},1e3)}ee=!1}try{n=new IntersectionObserver(V,{...X,root:i.ownerDocument})}catch{n=new IntersectionObserver(V,X)}n.observe(r)}const d=getWindow(r),u=()=>s(t);return d.addEventListener("resize",u),s(!0),()=>{d.removeEventListener("resize",u),o()}}function autoUpdate(r,e,t,n){n===void 0&&(n={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:d=!1}=n,u=unwrapElement(r),c=a||i?[...u?getOverflowAncestors(u):[],...e?getOverflowAncestors(e):[]]:[];c.forEach(T=>{a&&T.addEventListener("scroll",t),i&&T.addEventListener("resize",t)});const p=u&&s?observeMove(u,t,i):null;let _=-1,m=null;o&&(m=new ResizeObserver(T=>{let[w]=T;w&&w.target===u&&m&&e&&(m.unobserve(e),cancelAnimationFrame(_),_=requestAnimationFrame(()=>{var b;(b=m)==null||b.observe(e)})),t()}),u&&!d&&m.observe(u),e&&m.observe(e));let S,A=d?getBoundingClientRect(r):null;d&&h();function h(){const T=getBoundingClientRect(r);A&&!rectsAreEqual(A,T)&&t(),A=T,S=requestAnimationFrame(h)}return t(),()=>{var T;c.forEach(w=>{a&&w.removeEventListener("scroll",t),i&&w.removeEventListener("resize",t)}),p?.(),(T=m)==null||T.disconnect(),m=null,d&&cancelAnimationFrame(S)}}const offset$1=offset$2,shift$1=shift$2,flip$1=flip$2,size$1=size$2,hide$1=hide$2,arrow$2=arrow$3,limitShift$1=limitShift$2,computePosition=(r,e,t)=>{const n=new Map,a=t??{},i={...platform,...a.platform,_c:n};return computePosition$1(r,e,{...a,platform:i})};var isClient=typeof document<"u",noop$8=function(){},index$6=isClient?reactExports.useLayoutEffect:noop$8;function deepEqual$1(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(typeof r=="function"&&r.toString()===e.toString())return!0;let t,n,a;if(r&&e&&typeof r=="object"){if(Array.isArray(r)){if(t=r.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!deepEqual$1(r[n],e[n]))return!1;return!0}if(a=Object.keys(r),t=a.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,a[n]))return!1;for(n=t;n--!==0;){const i=a[n];if(!(i==="_owner"&&r.$$typeof)&&!deepEqual$1(r[i],e[i]))return!1}return!0}return r!==r&&e!==e}function getDPR(r){return typeof window>"u"?1:(r.ownerDocument.defaultView||window).devicePixelRatio||1}function roundByDPR(r,e){const t=getDPR(r);return Math.round(e*t)/t}function useLatestRef(r){const e=reactExports.useRef(r);return index$6(()=>{e.current=r}),e}function useFloating(r){r===void 0&&(r={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:a,elements:{reference:i,floating:o}={},transform:s=!0,whileElementsMounted:d,open:u}=r,[c,p]=reactExports.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[_,m]=reactExports.useState(n);deepEqual$1(_,n)||m(n);const[S,A]=reactExports.useState(null),[h,T]=reactExports.useState(null),w=reactExports.useCallback(D=>{D!==X.current&&(X.current=D,A(D))},[]),b=reactExports.useCallback(D=>{D!==ee.current&&(ee.current=D,T(D))},[]),N=i||S,O=o||h,X=reactExports.useRef(null),ee=reactExports.useRef(null),V=reactExports.useRef(c),U=d!=null,v=useLatestRef(d),x=useLatestRef(a),I=useLatestRef(u),E=reactExports.useCallback(()=>{if(!X.current||!ee.current)return;const D={placement:e,strategy:t,middleware:_};x.current&&(D.platform=x.current),computePosition(X.current,ee.current,D).then(ne=>{const y={...ne,isPositioned:I.current!==!1};Q.current&&!deepEqual$1(V.current,y)&&(V.current=y,reactDomExports.flushSync(()=>{p(y)}))})},[_,e,t,x,I]);index$6(()=>{u===!1&&V.current.isPositioned&&(V.current.isPositioned=!1,p(D=>({...D,isPositioned:!1})))},[u]);const Q=reactExports.useRef(!1);index$6(()=>(Q.current=!0,()=>{Q.current=!1}),[]),index$6(()=>{if(N&&(X.current=N),O&&(ee.current=O),N&&O){if(v.current)return v.current(N,O,E);E()}},[N,O,E,v,U]);const K=reactExports.useMemo(()=>({reference:X,floating:ee,setReference:w,setFloating:b}),[w,b]),te=reactExports.useMemo(()=>({reference:N,floating:O}),[N,O]),se=reactExports.useMemo(()=>{const D={position:t,left:0,top:0};if(!te.floating)return D;const ne=roundByDPR(te.floating,c.x),y=roundByDPR(te.floating,c.y);return s?{...D,transform:"translate("+ne+"px, "+y+"px)",...getDPR(te.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:ne,top:y}},[t,s,te.floating,c.x,c.y]);return reactExports.useMemo(()=>({...c,update:E,refs:K,elements:te,floatingStyles:se}),[c,E,K,te,se])}const arrow$1=r=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:r,fn(t){const{element:n,padding:a}=typeof r=="function"?r(t):r;return n&&e(n)?n.current!=null?arrow$2({element:n.current,padding:a}).fn(t):{}:n?arrow$2({element:n,padding:a}).fn(t):{}}}},offset=(r,e)=>{const t=offset$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},shift=(r,e)=>{const t=shift$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},limitShift=(r,e)=>({fn:limitShift$1(r).fn,options:[r,e]}),flip=(r,e)=>{const t=flip$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},size=(r,e)=>{const t=size$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},hide=(r,e)=>{const t=hide$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},arrow=(r,e)=>{const t=arrow$1(r);return{name:t.name,fn:t.fn,options:[r,e]}};var __defProp$3=Object.defineProperty,__name$3=(r,e)=>__defProp$3(r,"name",{value:e,configurable:!0});function useSize(r){const[e,t]=reactExports.useState(void 0);return useLayoutEffect2(()=>{if(r){t({width:r.offsetWidth,height:r.offsetHeight});const n=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let o,s;if("borderBoxSize"in i){const d=i.borderBoxSize,u=Array.isArray(d)?d[0]:d;o=u.inlineSize,s=u.blockSize}else o=r.offsetWidth,s=r.offsetHeight;t({width:o,height:s})});return n.observe(r,{box:"border-box"}),()=>n.unobserve(r)}else t(void 0)},[r]),e}__name$3(useSize,"useSize");var __defProp$2=Object.defineProperty,__name$2=(r,e)=>__defProp$2(r,"name",{value:e,configurable:!0}),POPPER_NAME="Popper",[createPopperContext,createPopperScope]=createContextScope(POPPER_NAME),[PopperProvider,usePopperContext]=createPopperContext(POPPER_NAME),Popper=__name$2(r=>{const{__scopePopper:e,children:t}=r,[n,a]=reactExports.useState(null),[i,o]=reactExports.useState(void 0);return jsxRuntimeExports.jsx(PopperProvider,{scope:e,anchor:n,onAnchorChange:a,placementState:i,setPlacementState:o,children:t})},"Popper"),ANCHOR_NAME="PopperAnchor",PopperAnchor=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:n,virtualRef:a,...i}=e,o=usePopperContext(ANCHOR_NAME,n),s=reactExports.useRef(null),d=o.onAnchorChange,u=reactExports.useCallback(A=>{s.current=A,A&&d(A)},[d]),c=useComposedRefs(t,u),p=reactExports.useRef(null);reactExports.useEffect(()=>{if(!a)return;const A=p.current;p.current=a.current,A!==p.current&&d(p.current)});const _=o.placementState&&getSideAndAlignFromPlacement(o.placementState),m=_?.[0],S=_?.[1];return a?null:jsxRuntimeExports.jsx(Primitive.div,{"data-radix-popper-side":m,"data-radix-popper-align":S,...i,ref:c})},"PopperAnchor")),CONTENT_NAME$1="PopperContent",[PopperContentProvider,useContentContext]=createPopperContext(CONTENT_NAME$1),PopperContent=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:n,side:a="bottom",sideOffset:i=0,align:o="center",alignOffset:s=0,arrowPadding:d=0,avoidCollisions:u=!0,collisionBoundary:c=[],collisionPadding:p=0,sticky:_="partial",hideWhenDetached:m=!1,updatePositionStrategy:S="optimized",onPlaced:A,...h}=e,T=usePopperContext(CONTENT_NAME$1,n),[w,b]=reactExports.useState(null),N=useComposedRefs(t,b),[O,X]=reactExports.useState(null),ee=useSize(O),V=ee?.width??0,U=ee?.height??0,v=a+(o!=="center"?"-"+o:""),x=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},I=Array.isArray(c)?c:[c],E=I.length>0,Q={padding:x,boundary:I.filter(isNotNull),altBoundary:E},{refs:K,floatingStyles:te,placement:se,isPositioned:D,middlewareData:ne}=useFloating({strategy:"fixed",placement:v,whileElementsMounted:__name$2((...M)=>autoUpdate(...M,{animationFrame:S==="always"}),"whileElementsMounted"),elements:{reference:T.anchor},middleware:[offset({mainAxis:i+U,alignmentAxis:s}),u&&shift({mainAxis:!0,crossAxis:!1,limiter:_==="partial"?limitShift():void 0,...Q}),u&&flip({...Q}),size({...Q,apply:__name$2(({elements:M,rects:Z,availableWidth:z,availableHeight:G})=>{const{width:g,height:R}=Z.reference,q=M.floating.style;q.setProperty("--radix-popper-available-width",`${z}px`),q.setProperty("--radix-popper-available-height",`${G}px`),q.setProperty("--radix-popper-anchor-width",`${g}px`),q.setProperty("--radix-popper-anchor-height",`${R}px`)},"apply")}),O&&arrow({element:O,padding:d}),transformOrigin({arrowWidth:V,arrowHeight:U}),m&&hide({strategy:"referenceHidden",...Q,boundary:E?Q.boundary:void 0})]}),y=T.setPlacementState;useLayoutEffect2(()=>(y(se),()=>{y(void 0)}),[se,y]);const[C,re]=getSideAndAlignFromPlacement(se),F=useCallbackRef(A);useLayoutEffect2(()=>{D&&F?.()},[D,F]);const ie=ne.arrow?.x,oe=ne.arrow?.y,le=ne.arrow?.centerOffset!==0,[ue,P]=reactExports.useState();return useLayoutEffect2(()=>{w&&P(window.getComputedStyle(w).zIndex)},[w]),jsxRuntimeExports.jsx("div",{ref:K.setFloating,"data-radix-popper-content-wrapper":"",style:{...te,transform:D?te.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ue,"--radix-popper-transform-origin":[ne.transformOrigin?.x,ne.transformOrigin?.y].join(" "),...ne.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:jsxRuntimeExports.jsx(PopperContentProvider,{scope:n,placedSide:C,placedAlign:re,onArrowChange:X,arrowX:ie,arrowY:oe,shouldHideArrow:le,children:jsxRuntimeExports.jsx(Primitive.div,{"data-side":C,"data-align":re,...h,ref:N,style:{...h.style,animation:D?h.style?.animation:"none"}})})})},"PopperContent"));function isNotNull(r){return r!==null}__name$2(isNotNull,"isNotNull");var transformOrigin=__name$2(r=>({name:"transformOrigin",options:r,fn(e){const{placement:t,rects:n,middlewareData:a}=e,o=a.arrow?.centerOffset!==0,s=o?0:r.arrowWidth,d=o?0:r.arrowHeight,[u,c]=getSideAndAlignFromPlacement(t),p={start:"0%",center:"50%",end:"100%"}[c],_=(a.arrow?.x??0)+s/2,m=(a.arrow?.y??0)+d/2;let S="",A="";return u==="bottom"?(S=o?p:`${_}px`,A=`${-d}px`):u==="top"?(S=o?p:`${_}px`,A=`${n.floating.height+d}px`):u==="right"?(S=`${-d}px`,A=o?p:`${m}px`):u==="left"&&(S=`${n.floating.width+d}px`,A=o?p:`${m}px`),{data:{x:S,y:A}}}}),"transformOrigin");function getSideAndAlignFromPlacement(r){const[e,t="center"]=r.split("-");return[e,t]}__name$2(getSideAndAlignFromPlacement,"getSideAndAlignFromPlacement");var Root2=Popper,Anchor=PopperAnchor,Content=PopperContent,__defProp$1=Object.defineProperty,__name$1=(r,e)=>__defProp$1(r,"name",{value:e,configurable:!0}),VISUALLY_HIDDEN_STYLES=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),VisuallyHidden=reactExports.forwardRef(__name$1(function(e,t){return jsxRuntimeExports.jsx(Primitive.span,{...e,ref:t,style:{...VISUALLY_HIDDEN_STYLES,...e.style}})},"VisuallyHidden")),Root=VisuallyHidden,__defProp=Object.defineProperty,__name=(r,e)=>__defProp(r,"name",{value:e,configurable:!0}),[createTooltipContext,createTooltipScope]=createContextScope("Tooltip",[createPopperScope]),usePopperScope=createPopperScope(),PROVIDER_NAME="TooltipProvider",DEFAULT_DELAY_DURATION=700,TOOLTIP_OPEN="tooltip.open",[TooltipProviderContextProvider,useTooltipProviderContext]=createTooltipContext(PROVIDER_NAME),TooltipProvider$1=__name(r=>{const{__scopeTooltip:e,delayDuration:t=DEFAULT_DELAY_DURATION,skipDelayDuration:n=300,disableHoverableContent:a=!1,children:i}=r,o=reactExports.useRef(!0),s=reactExports.useRef(!1),d=reactExports.useRef(0);return reactExports.useEffect(()=>{const u=d.current;return()=>window.clearTimeout(u)},[]),jsxRuntimeExports.jsx(TooltipProviderContextProvider,{scope:e,isOpenDelayedRef:o,delayDuration:t,onOpen:reactExports.useCallback(()=>{n<=0||(window.clearTimeout(d.current),o.current=!1)},[n]),onClose:reactExports.useCallback(()=>{n<=0||(window.clearTimeout(d.current),d.current=window.setTimeout(()=>o.current=!0,n))},[n]),isPointerInTransitRef:s,onPointerInTransitChange:reactExports.useCallback(u=>{s.current=u},[]),disableHoverableContent:a,children:i})},"TooltipProvider"),TOOLTIP_NAME="Tooltip",[TooltipContextProvider,useTooltipContext]=createTooltipContext(TOOLTIP_NAME),Tooltip$1=__name(r=>{const{__scopeTooltip:e,children:t,open:n,defaultOpen:a,onOpenChange:i,disableHoverableContent:o,delayDuration:s}=r,d=useTooltipProviderContext(TOOLTIP_NAME,r.__scopeTooltip),u=usePopperScope(e),[c,p]=reactExports.useState(null),[_,m]=reactExports.useState(void 0),S=useId(),A=reactExports.useRef(0),h=o??d.disableHoverableContent,T=s??d.delayDuration,w=reactExports.useRef(!1),[b,N]=useControllableState({prop:n,defaultProp:a??!1,onChange:__name(v=>{v?(d.onOpen(),document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN))):d.onClose(),i?.(v)},"onChange"),caller:TOOLTIP_NAME}),O=reactExports.useMemo(()=>b?w.current?"delayed-open":"instant-open":"closed",[b]),X=reactExports.useCallback(()=>{window.clearTimeout(A.current),A.current=0,w.current=!1,N(!0)},[N]),ee=reactExports.useCallback(()=>{window.clearTimeout(A.current),A.current=0,N(!1)},[N]),V=reactExports.useCallback(()=>{window.clearTimeout(A.current),A.current=window.setTimeout(()=>{w.current=!0,N(!0),A.current=0},T)},[T,N]);reactExports.useEffect(()=>()=>{A.current&&(window.clearTimeout(A.current),A.current=0)},[]);const U=_??S;return jsxRuntimeExports.jsx(Root2,{...u,children:jsxRuntimeExports.jsx(TooltipContextProvider,{scope:e,contentId:U,setContentId:m,open:b,stateAttribute:O,trigger:c,onTriggerChange:p,onTriggerEnter:reactExports.useCallback(()=>{d.isOpenDelayedRef.current?V():X()},[d.isOpenDelayedRef,V,X]),onTriggerLeave:reactExports.useCallback(()=>{h?ee():(window.clearTimeout(A.current),A.current=0)},[ee,h]),onOpen:X,onClose:ee,disableHoverableContent:h,children:t})})},"Tooltip"),TRIGGER_NAME="TooltipTrigger",TooltipTrigger$1=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:n,...a}=e,i=useTooltipContext(TRIGGER_NAME,n),o=useTooltipProviderContext(TRIGGER_NAME,n),s=usePopperScope(n),d=reactExports.useRef(null),u=useComposedRefs(t,d,i.onTriggerChange),c=reactExports.useRef(!1),p=reactExports.useRef(!1),_=reactExports.useCallback(()=>c.current=!1,[]);return reactExports.useEffect(()=>()=>document.removeEventListener("pointerup",_),[_]),jsxRuntimeExports.jsx(Anchor,{asChild:!0,...s,children:jsxRuntimeExports.jsx(Primitive.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...a,ref:u,onPointerMove:composeEventHandlers(e.onPointerMove,m=>{m.pointerType!=="touch"&&!p.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),p.current=!0)}),onPointerLeave:composeEventHandlers(e.onPointerLeave,()=>{i.onTriggerLeave(),p.current=!1}),onPointerDown:composeEventHandlers(e.onPointerDown,()=>{i.open&&i.onClose(),c.current=!0,document.addEventListener("pointerup",_,{once:!0})}),onFocus:composeEventHandlers(e.onFocus,()=>{c.current||i.onOpen()}),onBlur:composeEventHandlers(e.onBlur,i.onClose),onClick:composeEventHandlers(e.onClick,i.onClose)})})},"TooltipTrigger")),PORTAL_NAME="TooltipPortal",[PortalProvider,usePortalContext]=createTooltipContext(PORTAL_NAME,{forceMount:void 0}),TooltipPortal$1=__name(r=>{const{__scopeTooltip:e,forceMount:t,children:n,container:a}=r,i=useTooltipContext(PORTAL_NAME,e);return jsxRuntimeExports.jsx(PortalProvider,{scope:e,forceMount:t,children:jsxRuntimeExports.jsx(Presence,{present:t||i.open,children:jsxRuntimeExports.jsx(Portal$1,{asChild:!0,container:a,children:n})})})},"TooltipPortal"),CONTENT_NAME="TooltipContent",TooltipContent$1=reactExports.forwardRef(__name(function(e,t){const n=usePortalContext(CONTENT_NAME,e.__scopeTooltip),{forceMount:a=n.forceMount,side:i="top",...o}=e,s=useTooltipContext(CONTENT_NAME,e.__scopeTooltip);return jsxRuntimeExports.jsx(Presence,{present:a||s.open,children:s.disableHoverableContent?jsxRuntimeExports.jsx(TooltipContentImpl,{side:i,...o,ref:t}):jsxRuntimeExports.jsx(TooltipContentHoverable,{side:i,...o,ref:t})})},"TooltipContent")),TooltipContentHoverable=reactExports.forwardRef(__name(function(e,t){const n=useTooltipContext(CONTENT_NAME,e.__scopeTooltip),a=useTooltipProviderContext(CONTENT_NAME,e.__scopeTooltip),i=reactExports.useRef(null),o=useComposedRefs(t,i),[s,d]=reactExports.useState(null),{trigger:u,onClose:c}=n,p=i.current,{onPointerInTransitChange:_}=a,m=reactExports.useCallback(()=>{d(null),_(!1)},[_]),S=reactExports.useCallback((A,h)=>{const T=A.currentTarget,w={x:A.clientX,y:A.clientY},b=getExitSideFromRect(w,T.getBoundingClientRect()),N=getPaddedExitPoints(w,b),O=getPointsFromRect(h.getBoundingClientRect()),X=getHull([...N,...O]);d(X),_(!0)},[_]);return reactExports.useEffect(()=>()=>m(),[m]),reactExports.useEffect(()=>{if(u&&p){const A=__name(T=>S(T,p),"handleTriggerLeave"),h=__name(T=>S(T,u),"handleContentLeave");return u.addEventListener("pointerleave",A),p.addEventListener("pointerleave",h),()=>{u.removeEventListener("pointerleave",A),p.removeEventListener("pointerleave",h)}}},[u,p,S,m]),reactExports.useEffect(()=>{if(s){const A=__name(h=>{const T=h.target,w={x:h.clientX,y:h.clientY},b=u?.contains(T)||p?.contains(T),N=!isPointInPolygon(w,s);b?m():N&&(m(),c())},"handleTrackPointerGrace");return document.addEventListener("pointermove",A),()=>document.removeEventListener("pointermove",A)}},[u,p,s,c,m]),jsxRuntimeExports.jsx(TooltipContentImpl,{...e,ref:o})},"TooltipContentHoverable")),Slottable=createSlottable("TooltipContent"),TooltipContentImpl=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:n,children:a,"aria-label":i,id:o,onEscapeKeyDown:s,onPointerDownOutside:d,...u}=e,c=useTooltipContext(CONTENT_NAME,n),p=usePopperScope(n),{onClose:_}=c;reactExports.useEffect(()=>(document.addEventListener(TOOLTIP_OPEN,_),()=>document.removeEventListener(TOOLTIP_OPEN,_)),[_]),reactExports.useEffect(()=>{if(c.trigger){const S=__name(A=>{A.target instanceof Node&&A.target.contains(c.trigger)&&_()},"handleScroll");return window.addEventListener("scroll",S,{capture:!0}),()=>window.removeEventListener("scroll",S,{capture:!0})}},[c.trigger,_]);const{setContentId:m}=c;return useLayoutEffect2(()=>(m(o),()=>{m(void 0)}),[o,m]),jsxRuntimeExports.jsx(DismissableLayer,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:d,onFocusOutside:S=>S.preventDefault(),onDismiss:_,children:jsxRuntimeExports.jsxs(Content,{"data-state":c.stateAttribute,role:i?void 0:"tooltip",id:i?void 0:c.contentId,...p,...u,ref:t,style:{...u.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[jsxRuntimeExports.jsx(Slottable,{children:a}),i?jsxRuntimeExports.jsx(Root,{id:c.contentId,role:"tooltip",children:i}):null]})})},"TooltipContentImpl"));function getExitSideFromRect(r,e){const t=Math.abs(e.top-r.y),n=Math.abs(e.bottom-r.y),a=Math.abs(e.right-r.x),i=Math.abs(e.left-r.x);switch(Math.min(t,n,a,i)){case i:return"left";case a:return"right";case t:return"top";case n:return"bottom";default:throw new Error("unreachable")}}__name(getExitSideFromRect,"getExitSideFromRect");function getPaddedExitPoints(r,e,t=5){const n=[];switch(e){case"top":n.push({x:r.x-t,y:r.y+t},{x:r.x+t,y:r.y+t});break;case"bottom":n.push({x:r.x-t,y:r.y-t},{x:r.x+t,y:r.y-t});break;case"left":n.push({x:r.x+t,y:r.y-t},{x:r.x+t,y:r.y+t});break;case"right":n.push({x:r.x-t,y:r.y-t},{x:r.x-t,y:r.y+t});break}return n}__name(getPaddedExitPoints,"getPaddedExitPoints");function getPointsFromRect(r){const{top:e,right:t,bottom:n,left:a}=r;return[{x:a,y:e},{x:t,y:e},{x:t,y:n},{x:a,y:n}]}__name(getPointsFromRect,"getPointsFromRect");function isPointInPolygon(r,e){const{x:t,y:n}=r;let a=!1;for(let i=0,o=e.length-1;i<e.length;o=i++){const s=e[i],d=e[o],u=s.x,c=s.y,p=d.x,_=d.y;c>n!=_>n&&t<(p-u)*(n-c)/(_-c)+u&&(a=!a)}return a}__name(isPointInPolygon,"isPointInPolygon");function getHull(r){const e=r.slice();return e.sort((t,n)=>t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0),getHullPresorted(e)}__name(getHull,"getHull");function getHullPresorted(r){if(r.length<=1)return r.slice();const e=[];for(let n=0;n<r.length;n++){const a=r[n];for(;e.length>=2;){const i=e[e.length-1],o=e[e.length-2];if((i.x-o.x)*(a.y-o.y)>=(i.y-o.y)*(a.x-o.x))e.pop();else break}e.push(a)}e.pop();const t=[];for(let n=r.length-1;n>=0;n--){const a=r[n];for(;t.length>=2;){const i=t[t.length-1],o=t[t.length-2];if((i.x-o.x)*(a.y-o.y)>=(i.y-o.y)*(a.x-o.x))t.pop();else break}t.push(a)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}__name(getHullPresorted,"getHullPresorted");var Provider=TooltipProvider$1,Root3=Tooltip$1,Trigger=TooltipTrigger$1,Portal=TooltipPortal$1,Content2=TooltipContent$1;const TooltipProvider=Provider,Tooltip=Root3,TooltipTrigger=Trigger,TooltipPortal=Portal,TooltipContent=reactExports.forwardRef(({className:r,sideOffset:e=4,...t},n)=>jsxRuntimeExports.jsx(Content2,{ref:n,sideOffset:e,className:cn("z-[var(--layer-popover)] overflow-hidden rounded-md border border-border/50 bg-popover","px-2 py-1 text-xs text-popover-foreground shadow-md","animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...t}));TooltipContent.displayName=Content2.displayName;function BrandInfo({logo:r,info:e,infoLabel:t="Details",className:n}){const[a,i]=reactExports.useState(!1),o=reactExports.useRef(null);return jsxRuntimeExports.jsxs("div",{className:cn("inline-flex min-w-0 items-center gap-1",n),children:[r,e!=null&&e!==!1?jsxRuntimeExports.jsx(TooltipProvider,{delayDuration:150,children:jsxRuntimeExports.jsxs(Tooltip,{open:a,onOpenChange:i,children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("button",{ref:o,type:"button","aria-label":t,"aria-expanded":a,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-primary/10 hover:text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onPointerDown:s=>s.preventDefault(),onClick:s=>{s.preventDefault(),i(d=>!d)},children:jsxRuntimeExports.jsx(Info,{className:"h-4 w-4","aria-hidden":"true"})})}),jsxRuntimeExports.jsx(TooltipPortal,{children:jsxRuntimeExports.jsx(TooltipContent,{side:"bottom",align:"center",collisionPadding:12,onPointerDownOutside:s=>{s.target instanceof Node&&o.current?.contains(s.target)&&s.preventDefault()},className:"max-w-[min(320px,calc(100vw-24px))] space-y-2 p-3 text-left leading-relaxed [overflow-wrap:anywhere]",children:e})})]})}):null]})}const Checkbox=reactExports.forwardRef(({className:r,indeterminate:e=!1,...t},n)=>{const a=reactExports.useRef(null);return reactExports.useImperativeHandle(n,()=>a.current),reactExports.useEffect(()=>{a.current&&(a.current.indeterminate=e)}),jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0 items-center justify-center align-middle",children:[jsxRuntimeExports.jsx("input",{...t,ref:a,type:"checkbox",className:cn("peer m-0 h-4 w-4 shrink-0 appearance-none rounded border border-input bg-background checked:border-primary checked:bg-primary checked:bg-none indeterminate:border-primary indeterminate:bg-primary indeterminate:bg-none disabled:cursor-not-allowed disabled:opacity-50",controlFocusClass,r)}),jsxRuntimeExports.jsx(Check,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-checked:block peer-indeterminate:hidden peer-disabled:opacity-50",strokeWidth:3}),jsxRuntimeExports.jsx(Minus,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-indeterminate:block peer-disabled:opacity-50",strokeWidth:3})]})});Checkbox.displayName="Checkbox";function FormField({label:r,error:e,hint:t,labelAside:n,children:a,className:i,...o}){const s=reactExports.useId(),d=`${s}-error`,u=`${s}-hint`,c=[e?d:void 0,t?u:void 0].filter(Boolean).join(" ")||void 0;return jsxRuntimeExports.jsxs("div",{...o,className:cn("flex flex-col gap-1.5",i),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("label",{htmlFor:s,className:"text-[13px] font-medium text-foreground",children:r}),n]}),a({id:s,...e?{"aria-invalid":!0}:{},"aria-describedby":c}),e?jsxRuntimeExports.jsx("p",{id:d,role:"alert",className:"text-[13px] text-destructive",children:e}):null,t?jsxRuntimeExports.jsx("div",{id:u,className:"text-[13px] text-muted-foreground",children:t}):null]})}const EmailInput=reactExports.forwardRef(({onInput:r,onChange:e,autoCapitalize:t="none",spellCheck:n=!1,...a},i)=>{const o=reactExports.useRef(null),s=reactExports.useRef(null);reactExports.useImperativeHandle(i,()=>o.current,[]);const d=reactExports.useCallback(c=>{const p=s.current??(s.current=c.ownerDocument.createElement("input"));p.type="email",p.multiple=c.multiple,p.required=c.required,p.value=c.value,c.setCustomValidity(p.validity.valid?"":p.validationMessage)},[]);reactExports.useLayoutEffect(()=>{o.current&&d(o.current)}),reactExports.useEffect(()=>{const c=o.current,p=c?.form;if(!c||!p)return;const _=()=>queueMicrotask(()=>d(c));return p.addEventListener("reset",_),()=>p.removeEventListener("reset",_)},[a.form,d]);const u=c=>{d(c),queueMicrotask(()=>d(c))};return jsxRuntimeExports.jsx(Input,{...a,ref:o,type:"text",inputMode:"email",autoCapitalize:t,spellCheck:n,onInput:c=>{u(c.currentTarget),r?.(c)},onChange:c=>{u(c.currentTarget),e?.(c)}})});EmailInput.displayName="EmailInput";const FOCUSABLE=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","summary",'[tabindex]:not([tabindex="-1"])'].join(","),PRIMARY_SELECTOR="[data-pod-sign-in-primary]";function isReachable(r){if(r.hidden||r.closest("[hidden]")||r.matches(":disabled"))return!1;const e=r.ownerDocument.defaultView?.getComputedStyle(r);if(e&&(e.display==="none"||e.visibility==="hidden"))return!1;for(let t=r.parentElement;t;t=t.parentElement){if(t.tagName!=="DETAILS"||t.open)continue;const n=Array.from(t.children).find(a=>a.tagName==="SUMMARY");if(!n||!(n===r||n.contains(r)))return!1}return!0}function useModalFocus(r,e){const t=reactExports.useRef(null),n=reactExports.useRef(e);return n.current=e,reactExports.useEffect(()=>{if(!r)return;const a=document.activeElement instanceof HTMLElement?document.activeElement:null;t.current?.focus();const i=o=>{if(o.key==="Escape"&&n.current){o.preventDefault(),n.current();return}if(o.key!=="Tab")return;const s=t.current;if(!s)return;const d=Array.from(s.querySelectorAll(FOCUSABLE)).filter(isReachable);if(d.length===0){o.preventDefault(),s.focus();return}const u=d.indexOf(document.activeElement);if(!o.shiftKey&&document.activeElement===s){const p=d.find(_=>_.matches(PRIMARY_SELECTOR));if(p){o.preventDefault(),p.focus();return}}const c=o.shiftKey?u<=0?d.length-1:u-1:u===d.length-1?0:u+1;o.preventDefault(),d[c]?.focus()};return document.addEventListener("keydown",i),()=>{document.removeEventListener("keydown",i),a?.focus()}},[r]),t}const bodyClass="flex min-h-0 w-full max-w-[360px] flex-1 flex-col";function PodSignInFrame({presentation:r,ariaLabel:e,appIntro:t,children:n,modal:a=!0,onClose:i,closeLabel:o,dataAttributes:s}){const d=r==="dialog"&&a,u=useModalFocus(d,i),c=t;if(r==="window")return jsxRuntimeExports.jsx("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"window",...s,className:"pod-sign-in flex h-full min-h-0 w-full min-w-0 justify-center overflow-hidden bg-background text-foreground",children:jsxRuntimeExports.jsx("div",{className:bodyClass,children:n})});if(r==="page")return jsxRuntimeExports.jsxs("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"page",...s,className:"pod-sign-in grid min-h-[100dvh] w-full bg-background text-foreground md:grid-cols-2",children:[c?jsxRuntimeExports.jsx("aside",{"data-pod-sign-in":"intro",className:"hidden flex-col justify-center gap-6 bg-[hsl(var(--sunken))] px-12 py-10 md:flex",children:c}):null,jsxRuntimeExports.jsx("div",{className:cn("flex min-w-0 items-center justify-center px-4 py-8",c?"":"md:col-span-2"),children:jsxRuntimeExports.jsx("div",{className:bodyClass,children:n})})]});const p=jsxRuntimeExports.jsxs("div",{ref:u,role:d?"dialog":"region","aria-modal":d?!0:void 0,"aria-label":e,tabIndex:-1,"data-pod-sign-in-frame":"dialog",...s,className:cn("pod-sign-in relative flex max-h-[90dvh] w-[min(400px,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-lg focus:outline-none motion-safe:animate-in motion-safe:fade-in-0"),children:[d&&i&&o?jsxRuntimeExports.jsx("button",{type:"button","aria-label":o,className:"absolute right-2 top-2 flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",onClick:i,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null,jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"mx-auto"),children:n})]});return d?jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center bg-background/80 p-4",children:p}):jsxRuntimeExports.jsx("div",{className:"flex w-full items-center justify-center p-4",children:p})}function StorageBadge({kind:r,label:e}){const t=r==="cloud"?Cloud:Laptop;return jsxRuntimeExports.jsx("span",{role:"img","aria-label":e,title:e,"data-storage-kind":r,className:"flex h-[18px] w-[18px] items-center justify-center rounded-full border border-background bg-card text-foreground",children:jsxRuntimeExports.jsx(t,{"aria-hidden":"true",className:"h-3 w-3"})})}const zhCN={restoring:"正在恢复登录…",enterApp:"进入 {app}",reauthenticate:"重新登录",useAnother:"使用其他账号",expiredLine:"登录已过期,需要重新确认",chooseTitle:"登录",chooseLead:"用你的 WebID 账号登录,数据保存在你自己的 Pod 里",useXpod:"使用 Xpod 账号登录",useOtherSolid:"使用其他 Solid 账号",customLabel:"账号服务地址或 WebID",customPlaceholder:"https://example.com/",customSubmit:"继续",noAccount:"没有账号?",register:"注册 Xpod",noticeDetailsToggle:"详情",noticeCopy:"复制",noticeCopied:"已复制",whatIsPod:"什么是 Pod?",whatIsPodBody:"Pod 是保存你数据的个人空间。",whatIsWebId:"什么是 WebID?",whatIsWebIdBody:"WebID 是登录用的身份,它指向你的个人资料和 Pod。",signInWith:"使用 {service} 登录",select:"选择",selected:"已选择",choosePodTitle:"选择 Pod",choosePodLead:"选择要继续使用的 Pod",retry:"重试",goCreate:"去创建",refreshPage:"刷新页面",startAndEnter:"启动 Xpod 并进入",openXpod:"打开 Xpod",noticeUnreachable:"暂时连不上 Xpod,请稍后再试",noticeIncomplete:"登录没有完成,请再试一次",noticeNoWebId:"还没有 WebID",noticeCancelled:"登录已取消",noticeLocalStopped:"这台电脑上的 Xpod 没有运行",noticePending:"上次登录尚未结束",serviceLabel:"账号服务",signInTitle:"登录 {service}",returnToApp:"完成后回到 {app}",email:"邮箱",password:"密码",forgotPassword:"忘记密码?",rememberDevice:"在这台设备上保持登录",signIn:"登录",registerLink:"注册账号",registerTitle:"注册 {service}",username:"用户名",registerSubmit:"注册",haveAccount:"已有账号?登录",podElsewhereSummary:"想用你自己的独立部署存放 Pod?",podElsewhereBody:"注册后,可以在账号页的“存储”里把 Pod 建到你自己的独立部署上;它和当前账号服务是分开的,普通浏览器不会自动把 Pod 转到本机。",noWebIdTitle:"还没有 WebID",noWebIdLead:"新建一个 WebID 来登录 {app},数据存在它的 Pod 里",webIdName:"WebID 名称",noWebIdLocation:"存放在当前服务",createAndContinue:"创建并继续",chooseOtherLocation:"存到边缘设备(打开账号页)",consentTitle:"授权 {app}",unverifiedWarning:"未能验证这个应用的来源,请确认是你要使用的应用",chooseWebId:"用哪个 WebID 登录?",consentConsequence:"{app} 将以这个身份读写你的数据,之后可以在 Xpod 中收回。",requestDetails:"请求详情",scopes:"权限范围",clientId:"应用标识",webIdFull:"WebID",rememberChoice:"以后不再询问",manageAccount:"管理账号",switchAccount:"换一个账号",deny:"拒绝",allow:"允许",storageCloud:"数据存在 Xpod 云端",storageEdge:"数据存在边缘设备上",hostedStorage:"账号服务托管",independentStorage:"独立部署",identityAddress:"WebID(身份地址)",storageAddress:"Pod(存储地址)",showAddresses:"查看地址",webIdSectionTitle:"WebID",webIdEmpty:"还没有 WebID。新建一个,用它登录应用。",createWebId:"新建 WebID",linkExistingWebId:"关联已有 WebID",podOnDevice:"Pod 在 {device}",authorizedApps:"已授权 {count} 个应用",createStepName:"名称",createStepLocation:"存放在",createNameHint:"WebID 地址",changeDevice:"更换 ›",cannotChangeLater:"创建后不能直接更换,以后要换请使用迁移",createPod:"创建 WebID 和 Pod",startDeviceXpod:"启动这台设备上的 Xpod",creatingNote:"关闭页面不会中断创建",cancel:"取消",devicePickerTitle:"选择存放设备",addDevice:"+ 添加设备",deviceSectionTitle:"设备",deviceStatusOk:"正常",deviceStatusUnreachable:"⚠ 其他设备访问不到",deviceStatusStopped:"Xpod 已停止",deviceStatusOffline:"离线",deviceCloud:"Xpod 云端",deviceEdge:"边缘",podCount:"{count} 个 Pod",networkAction:"网络",fixAction:"处理",collapseAction:"收起",webIdSectionHint:"登录应用时使用的身份,数据存在它的 Pod 里",deviceSectionHint:"Pod 可以存放的地方,网络设置跟着设备走",credentialSectionHint:"让脚本或服务以某个 WebID 直接访问 Pod",startAction:"启动",networkTitle:"网络访问",probeLocal:"这台电脑",probeLan:"局域网",probeWan:"其他网络",probeIdle:"未检测",probeChecking:"检测中",probeOk:"可以访问",probeFailed:"不通",tunnelTitle:"选择隧道",enableAndRecheck:"开启并重新检测",enableAndCheck:"开启并检测",recheck:"重新检测",skipForNow:"跳过,稍后设置",reachableVia:"通过 {tunnel} 可以访问",networkFootnote:"只影响其他设备;这台电脑上照常可用",addDeviceTitle:"添加设备",stepInstall:"安装并登录",stepNetwork:"检查网络",stepDone:"完成",joinThisComputer:"把这台电脑加入",installOnOther:"在那台设备上安装 Xpod 边缘并登录本账号",waitingForDevice:"正在等待新设备上线,登录后这里会自动继续",deviceOnline:"已上线",finish:"完成",useThisDevice:"用这台设备",credentialSectionTitle:"密钥",credentialEmpty:"还没有密钥。",createCredential:"新建密钥",revokeCredential:"删除",resumeTitle:"{app} 正在等你完成授权",resumeWaiting:"在下面新建一个 WebID,完成后就能回去授权",resumeReady:"WebID 已就绪,可以回去授权了",resumeCancel:"取消授权",resumeContinue:"继续授权 {app}",close:"关闭"},en={restoring:"Restoring your sign-in…",enterApp:"Open {app}",reauthenticate:"Sign in again",useAnother:"Use another account",expiredLine:"Your sign-in expired. Please confirm again.",chooseTitle:"Sign in",chooseLead:"Sign in with your WebID account. Your data stays in your own Pod.",useXpod:"Sign in with Xpod",useOtherSolid:"Use another Solid account",customLabel:"Sign-in service address or WebID",customPlaceholder:"https://example.com/",customSubmit:"Continue",noAccount:"No account?",register:"Register for Xpod",noticeDetailsToggle:"Details",noticeCopy:"Copy",noticeCopied:"Copied",whatIsPod:"What is a Pod?",whatIsPodBody:"A Pod is a personal space that holds your data.",whatIsWebId:"What is a WebID?",whatIsWebIdBody:"A WebID is the identity you sign in with. It points to your profile and your Pod.",signInWith:"Sign in with {service}",select:"Select",selected:"Selected",choosePodTitle:"Choose a Pod",choosePodLead:"Choose the Pod to continue with",retry:"Retry",goCreate:"Create one",refreshPage:"Refresh page",startAndEnter:"Start Xpod and open",openXpod:"Open Xpod",noticeUnreachable:"Cannot reach Xpod right now. Please try again later.",noticeIncomplete:"Sign-in did not finish. Please try again.",noticeNoWebId:"No WebID yet",noticeCancelled:"Sign-in cancelled",noticeLocalStopped:"Xpod is not running on this computer",noticePending:"The previous sign-in has not finished",serviceLabel:"Sign-in service",signInTitle:"Sign in to {service}",returnToApp:"You will return to {app}",email:"Email",password:"Password",forgotPassword:"Forgot password?",rememberDevice:"Keep me signed in on this device",signIn:"Sign in",registerLink:"Register",registerTitle:"Register for {service}",username:"Username",registerSubmit:"Register",haveAccount:"Already have an account? Sign in",podElsewhereSummary:"Want it on your own standalone deployment?",podElsewhereBody:"After registering, create the Pod on your own standalone deployment under Storage on the account page; it is separate from this account service.",noWebIdTitle:"No WebID yet",noWebIdLead:"Create a WebID to sign in to {app}. Your data lives in its Pod.",webIdName:"WebID name",noWebIdLocation:"Stored on the current service",createAndContinue:"Create and continue",chooseOtherLocation:"Store on an edge device (open account page)",consentTitle:"Authorize {app}",unverifiedWarning:"We could not verify this application. Make sure it is the one you meant to use.",chooseWebId:"Which WebID do you sign in with?",consentConsequence:"{app} will read and write your data as this identity. You can revoke it later in Xpod.",requestDetails:"Request details",scopes:"Permissions",clientId:"Application ID",webIdFull:"WebID",rememberChoice:"Do not ask again",manageAccount:"Manage account",switchAccount:"Switch account",deny:"Deny",allow:"Allow",storageCloud:"Data is stored on Xpod Cloud",storageEdge:"Data is stored on an edge device",hostedStorage:"Hosted by account service",independentStorage:"Independent deployment",identityAddress:"WebID (identity address)",storageAddress:"Pod (storage address)",showAddresses:"View addresses",webIdSectionTitle:"WebID",webIdEmpty:"No WebID yet. Create one to sign in to applications.",createWebId:"New WebID",linkExistingWebId:"Link an existing WebID",podOnDevice:"Pod on {device}",authorizedApps:"{count} authorized apps",createStepName:"Name",createStepLocation:"Store on",createNameHint:"WebID address",changeDevice:"Change ›",cannotChangeLater:"It cannot be changed directly after creation. Use migration later.",createPod:"Create WebID and Pod",startDeviceXpod:"Start Xpod on this device",creatingNote:"Closing this page will not interrupt creation",cancel:"Cancel",devicePickerTitle:"Choose where to store",addDevice:"+ Add device",deviceSectionTitle:"Devices",deviceStatusOk:"Healthy",deviceStatusUnreachable:"⚠ Not reachable from other devices",deviceStatusStopped:"Xpod stopped",deviceStatusOffline:"Offline",deviceCloud:"Xpod Cloud",deviceEdge:"Edge",podCount:"{count} Pods",networkAction:"Network",fixAction:"Fix",collapseAction:"Collapse",webIdSectionHint:"The identity you sign in to apps with. Your data lives in its Pod.",deviceSectionHint:"Places a Pod can live. Network settings follow the device.",credentialSectionHint:"Let a script or service reach a Pod directly as one WebID.",startAction:"Start",networkTitle:"Network access",probeLocal:"This computer",probeLan:"Local network",probeWan:"Other networks",probeIdle:"Not checked",probeChecking:"Checking",probeOk:"Reachable",probeFailed:"Unreachable",tunnelTitle:"Choose a tunnel",enableAndRecheck:"Enable and recheck",enableAndCheck:"Enable and check",recheck:"Recheck",skipForNow:"Skip, set up later",reachableVia:"Reachable through {tunnel}",networkFootnote:"Only affects other devices. This computer keeps working as usual.",addDeviceTitle:"Add a device",stepInstall:"Install and sign in",stepNetwork:"Check network",stepDone:"Done",joinThisComputer:"Add this computer",installOnOther:"Install Xpod Edge on that device and sign in to this account",waitingForDevice:"Waiting for the new device to come online. This continues automatically after sign-in.",deviceOnline:"Online",finish:"Done",useThisDevice:"Use this device",credentialSectionTitle:"Credentials",credentialEmpty:"No credentials yet.",createCredential:"New credential",revokeCredential:"Delete",resumeTitle:"{app} is waiting for you to finish authorizing",resumeWaiting:"Create a WebID below, then you can go back and authorize",resumeReady:"Your WebID is ready. You can go back and authorize.",resumeCancel:"Cancel authorization",resumeContinue:"Continue authorizing {app}",close:"Close"},podSignInCopy={"zh-CN":zhCN,en};function resolvePodSignInCopy(r="zh-CN",e){return{...podSignInCopy[r],...e}}function formatCopy(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{const a=e[n];return a===void 0?t:String(a)})}function IdpChrome({serviceName:r,serviceHost:e,icon:t,serviceLabel:n,locale:a}){const i=n??resolvePodSignInCopy(a).serviceLabel;return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"idp-chrome",className:"flex h-11 shrink-0 items-center gap-2 border-b border-border bg-[hsl(var(--sunken))] px-4 text-[13px] text-foreground",children:[jsxRuntimeExports.jsx("span",{className:"flex shrink-0 items-center justify-center",children:t??jsxRuntimeExports.jsx(XpodMark,{size:24})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 truncate font-medium",children:[r," · ",i]}),e?jsxRuntimeExports.jsx("span",{className:"ml-auto truncate font-mono text-xs text-muted-foreground",children:e}):null]})}const primaryButtonClass="h-auto min-h-11 w-full whitespace-normal break-normal rounded-lg py-2 text-sm font-medium leading-snug",outlineButtonClass=primaryButtonClass,textButtonClass="h-auto min-h-9 max-w-full whitespace-normal break-normal rounded-lg px-2 py-1 text-sm font-medium leading-snug",fieldClass="h-11 w-full rounded-lg border border-input bg-card px-3 text-sm text-foreground placeholder:text-muted-foreground disabled:opacity-60";function Spinner({className:r}){return jsxRuntimeExports.jsx(LoaderCircle$1,{"aria-hidden":"true",className:cn("h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none",r)})}function ActionButton({busy:r=!1,children:e,disabled:t,...n}){return jsxRuntimeExports.jsxs(Button,{type:"button",...n,disabled:t||r,"aria-busy":r||void 0,children:[r?jsxRuntimeExports.jsx(Spinner,{className:"mr-2"}):null,e]})}function SourceMark({icon:r,name:e}){return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"source",className:"flex h-6 items-center gap-2 text-[13px] text-muted-foreground",children:[r?jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"flex h-6 w-6 shrink-0 items-center justify-center overflow-hidden rounded-md",children:r}):null,jsxRuntimeExports.jsx("span",{className:"truncate",children:e})]})}function PodAvatar({name:r,avatarUrl:e,storage:t,size:n=56}){return jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0",style:{width:n,height:n},"data-pod-sign-in":"avatar",children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-full w-full rounded-full","aria-hidden":"true",children:[e?jsxRuntimeExports.jsx(AvatarImage,{src:e,alt:""}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"text-base",children:Array.from(r.trim())[0]?.toUpperCase()??"?"})]}),t?jsxRuntimeExports.jsx("span",{className:"absolute -bottom-0.5 -right-0.5",children:jsxRuntimeExports.jsx(StorageBadge,{kind:t.kind,label:t.label})}):null]})}function Field(r){return jsxRuntimeExports.jsx(FormField,{...r,"data-pod-sign-in":"field"})}function Disclosure({summary:r,children:e,className:t}){return jsxRuntimeExports.jsxs("details",{className:cn("text-[13px] text-muted-foreground",t),children:[jsxRuntimeExports.jsx("summary",{className:"cursor-pointer select-none rounded py-1 text-[13px] font-medium text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",children:r}),jsxRuntimeExports.jsx("div",{className:"pt-1 leading-5",children:e})]})}function CheckboxRow({checked:r,onChange:e,label:t,disabled:n}){return jsxRuntimeExports.jsxs("label",{className:"flex min-h-9 cursor-pointer items-center gap-2 text-sm text-foreground",children:[jsxRuntimeExports.jsx(Checkbox,{checked:r,disabled:n,onChange:a=>e(a.target.checked)}),t]})}function usePastDelay(r){const[e,t]=reactExports.useState(!1);return reactExports.useEffect(()=>{const n=setTimeout(()=>t(!0),r);return()=>clearTimeout(n)},[r]),e}function ScreenLayout({chrome:r,children:e,actions:t,onSubmit:n,mainClassName:a,...i}){const o=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[r,jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"main",className:cn("flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-6 pb-2 pt-5",a),children:e}),t?jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"actions",className:"flex shrink-0 flex-col gap-3 px-6 pb-6 pt-3",children:t}):null]}),s="flex min-h-0 flex-1 flex-col";return n?jsxRuntimeExports.jsx("form",{...i,onSubmit:n,className:s,noValidate:!0,children:o}):jsxRuntimeExports.jsx("div",{...i,className:s,children:o})}function resolveIdpCopy({locale:r,copy:e}){return resolvePodSignInCopy(r,e)}function IdpFrameHeader({serviceName:r="Xpod",serviceHost:e,serviceIcon:t,locale:n,copy:a}){return jsxRuntimeExports.jsx(IdpChrome,{serviceName:r,serviceHost:e,icon:t,locale:n,serviceLabel:a?.serviceLabel})}const inputClass=fieldClass;function TextAction({href:r,onClick:e,disabled:t,className:n,children:a}){const i=cn(textButtonClass,"inline-flex shrink-0 items-center justify-center text-primary hover:underline",n);return r&&!t?jsxRuntimeExports.jsx("a",{href:r,className:i,children:a}):jsxRuntimeExports.jsx("button",{type:"button",className:i,disabled:t,onClick:e,children:a})}function IdpSignInView(r){const{serviceName:e,returnToAppName:t,error:n,fieldErrors:a,pending:i=!1,remember:o,defaultEmail:s="",defaultPassword:d="",onFieldChange:u,onRememberChange:c,onSubmit:p,onForgot:_,forgotHref:m,onRegister:S,registerHref:A,onUseOtherSolid:h}=r,T=resolveIdpCopy(r),[w,b]=reactExports.useState(s),[N,O]=reactExports.useState(d),X=ee=>{ee.preventDefault(),i||p({email:w.trim(),password:N})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-sign-in",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...r}),onSubmit:X,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[n?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:n}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:i,children:T.signIn}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[S||A?jsxRuntimeExports.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1 gap-y-0",children:[jsxRuntimeExports.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:T.noAccount}),jsxRuntimeExports.jsx(TextAction,{href:A,disabled:i,onClick:S,children:T.registerLink})]}):jsxRuntimeExports.jsx("span",{}),h?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"text-primary hover:underline"),disabled:i,onClick:h,children:T.useOtherSolid}):null]})]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(T.signInTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(T.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"fields",className:"flex flex-col gap-4",children:[jsxRuntimeExports.jsx(Field,{label:T.email,error:a?.email,children:ee=>jsxRuntimeExports.jsx(EmailInput,{...ee,name:"email",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:w,disabled:i,onChange:V=>{b(V.target.value),u?.("email",V.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:T.password,error:a?.password,labelAside:_||m?jsxRuntimeExports.jsx(TextAction,{className:"min-h-7 text-[13px]",href:m,onClick:_,children:T.forgotPassword}):void 0,children:ee=>jsxRuntimeExports.jsx(Input,{...ee,name:"password",type:"password",autoComplete:"current-password",className:inputClass,value:N,disabled:i,onChange:V=>{O(V.target.value),u?.("password",V.target.value)}})}),c?jsxRuntimeExports.jsx(CheckboxRow,{checked:o,onChange:c,label:T.rememberDevice,disabled:i}):null]})]})}function IdpRegisterView(r){const{serviceName:e,returnToAppName:t,usernamePreview:n,requireUsername:a,fieldErrors:i,error:o,pending:s=!1,defaultEmail:d="",defaultPassword:u="",defaultUsername:c="",onFieldChange:p,onSubmit:_,onSignIn:m}=r,S=resolveIdpCopy(r),[A,h]=reactExports.useState(c),[T,w]=reactExports.useState(d),[b,N]=reactExports.useState(u),O=X=>{X.preventDefault(),!s&&_({...a?{username:A.trim()}:{},email:T.trim(),password:b})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-register",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...r}),onSubmit:O,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[o?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:o}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:s,children:S.registerSubmit}),m?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"self-center text-primary hover:underline"),disabled:s,onClick:m,children:S.haveAccount}):null]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(S.registerTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(S.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-4",children:[a?jsxRuntimeExports.jsx(Field,{label:S.username,error:i?.username,hint:n?jsxRuntimeExports.jsx("span",{role:"status",className:"font-mono text-xs",children:n}):void 0,children:X=>jsxRuntimeExports.jsx(Input,{...X,name:"username",type:"text",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:A,disabled:s,onChange:ee=>{h(ee.target.value),p?.("username",ee.target.value)}})}):null,jsxRuntimeExports.jsx(Field,{label:S.email,error:i?.email,children:X=>jsxRuntimeExports.jsx(EmailInput,{...X,name:"email",autoComplete:"email",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:T,disabled:s,onChange:ee=>{w(ee.target.value),p?.("email",ee.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:S.password,error:i?.password,children:X=>jsxRuntimeExports.jsx(Input,{...X,name:"password",type:"password",autoComplete:"new-password",className:inputClass,value:b,disabled:s,onChange:ee=>{N(ee.target.value),p?.("password",ee.target.value)}})}),jsxRuntimeExports.jsx(Disclosure,{summary:S.podElsewhereSummary,children:S.podElsewhereBody})]})]})}const __iconNode$1=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],CircleAlert=createLucideIcon$1("circle-alert",__iconNode$1);const __iconNode=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon$1("loader-circle",__iconNode);function WebAccountLayout({title:r,description:e,children:t,host:n="document",bare:a=!1,intro:i,serviceIcon:o}){const s=reactExports.useId(),d=n==="window",u=d?"window":"page";return jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:d?"h-dvh w-full overflow-hidden":void 0,children:jsxRuntimeExports.jsx(PodSignInFrame,{presentation:d?"window":"page",ariaLabel:r,appIntro:i,dataAttributes:{"data-web-account-layout":u,"data-web-account-host":d?"window":"document"},children:jsxRuntimeExports.jsx("div",{"data-testid":"web-account-panel","data-web-account-layout":u,"data-web-account-host":d?"window":"document",className:"flex min-h-0 min-w-0 flex-1 flex-col",children:a?t:jsxRuntimeExports.jsxs(ScreenLayout,{chrome:jsxRuntimeExports.jsx(IdpChrome,{serviceName:"Xpod",serviceHost:window.location.host,icon:o}),children:[jsxRuntimeExports.jsxs("header",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{id:s,className:"text-[17px] font-semibold text-foreground",children:r}),e?jsxRuntimeExports.jsx("p",{className:"text-sm leading-[22px] text-muted-foreground",children:e}):null]}),t]})})})})}const introCopy={"zh-CN":{name:"Xpod 账号服务",proposition:"一个账号,管理你的 WebID 和它背后的 Pod。",points:[{title:"WebID 是你的身份",detail:"登录应用时使用它;数据存在你自己的 Pod 里。"},{title:"Pod 存在哪里由你决定",detail:"Xpod 云端或你自己的设备,创建后可以在这里查看。"},{title:"密钥按需签发",detail:"为脚本或服务单独创建凭据,不再需要就撤销。"}]},en:{name:"Xpod accounts",proposition:"One account for your WebID and the Pod behind it.",points:[{title:"Your WebID is your identity",detail:"Apps sign you in with it; your data stays in your own Pod."},{title:"You choose where the Pod lives",detail:"Xpod cloud or your own device, reviewable here after creation."},{title:"Credentials on demand",detail:"Issue a key per script or service, and revoke it when it is done."}]}};function XpodAccountServiceIntro({serviceHost:r,locale:e="zh-CN"}){const t=introCopy[e];return jsxRuntimeExports.jsxs("div",{"data-testid":"web-account-introduction",className:"flex max-w-[460px] flex-col gap-7",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(XpodMark,{size:44}),jsxRuntimeExports.jsx("span",{className:"text-[22px] font-semibold leading-none text-foreground",children:t.name})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"m-0 text-[28px] font-semibold leading-[38px] text-foreground",children:t.proposition}),r?jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground",children:r}):null]}),jsxRuntimeExports.jsx("ul",{className:"m-0 flex list-none flex-col gap-4 p-0",children:t.points.map(n=>jsxRuntimeExports.jsxs("li",{className:"flex gap-3",children:[jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"mt-2 h-2 w-2 shrink-0 rounded-full bg-primary"}),jsxRuntimeExports.jsxs("span",{className:"flex flex-col gap-0.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[15px] font-semibold text-foreground",children:n.title}),jsxRuntimeExports.jsx("span",{className:"text-sm leading-[22px] text-muted-foreground",children:n.detail})]})]},n.title))})]})}function parseIdentity(r){if(!r||typeof r!="object")throw new Error("Missing deployment identity");const e=r;if(e.edition!=="cloud"&&e.edition!=="local"||typeof e.managed!="boolean")throw new Error("Invalid deployment identity");let t;if(e.edition==="local"&&e.managed&&typeof e.oidcIssuer=="string"){const a=new URL(e.oidcIssuer);if(!["http:","https:"].includes(a.protocol)||a.username||a.password||a.search||a.hash)throw new Error("Invalid account service");t=a.href.replace(/\/$/u,"")}let n;if(typeof e.publicUrl=="string"){const a=new URL(e.publicUrl);if(!["http:","https:"].includes(a.protocol)||a.username||a.password||a.search||a.hash)throw new Error("Invalid public service address");n=a.href}return{edition:e.edition,managed:e.managed,oidcIssuer:t,publicUrl:n}}function XpodDeploymentIdentity({renderLogo:r,className:e}={}){const[t,n]=reactExports.useState();reactExports.useEffect(()=>{const o=new AbortController;return(async()=>{try{const s=await fetch("/api/service-info",{headers:{accept:"application/json"},cache:"no-store",signal:o.signal});if(!s.ok)throw new Error("Deployment identity unavailable");const d=parseIdentity(await s.json());o.signal.aborted||n(d)}catch{o.signal.aborted||n(null)}})(),()=>o.abort()},[]);const a=t?t.edition==="cloud"?"云端":t.managed?"托管部署":"独立部署":t===null?"部署信息暂不可用":"正在识别部署…",i=r?r(a):jsxRuntimeExports.jsxs("span",{"data-testid":"xpod-deployment-logo",className:"inline-flex flex-col items-center gap-0.5",children:[jsxRuntimeExports.jsx(XpodMark,{size:24}),jsxRuntimeExports.jsx("span",{className:"text-[8px] font-medium leading-none text-primary",children:t?a:t===null?"未知":"…"}),t?null:jsxRuntimeExports.jsx("span",{className:"sr-only",children:a})]});return jsxRuntimeExports.jsx("div",{"data-testid":"xpod-deployment-identity",className:e,children:jsxRuntimeExports.jsx(BrandInfo,{logo:i,infoLabel:"部署详情",info:jsxRuntimeExports.jsxs("div",{className:"space-y-2 leading-relaxed",children:[jsxRuntimeExports.jsx("p",{className:"font-semibold",children:"部署详情"}),t?jsxRuntimeExports.jsxs("p",{children:["部署类型:",t.edition==="cloud"?"Cloud":t.managed?"Local · 云端托管":"Local · 独立部署"]}):jsxRuntimeExports.jsx("p",{children:a}),jsxRuntimeExports.jsxs("p",{children:["当前访问:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:window.location.origin})]}),t?jsxRuntimeExports.jsxs("p",{children:[t.edition==="local"?"节点地址":"服务地址",":",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.publicUrl??(t.managed?"尚未分配":"尚未配置")})]}):null,t?.oidcIssuer&&t.oidcIssuer!==window.location.origin?jsxRuntimeExports.jsxs("p",{children:["账号服务:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.oidcIssuer})]}):null]})})})}function XpodAuthSurface(r){const e=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(e==="window"),jsxRuntimeExports.jsx(AuthSurface,{...r,presentation:"compact",host:e})}function XpodSignInFrame({ariaLabel:r,children:e}){const t=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(t==="window"),jsxRuntimeExports.jsx(PodSignInFrame,{presentation:t==="window"?"window":"page",ariaLabel:r,children:e})}function XpodAccountPageSurface({title:r,children:e,bare:t=!1,intro:n,presentation:a="compact"}){const i=getXpodAuthSurfaceHost(),o=a==="compact";return useXpodAuthWindowSurface(i==="window",o?"account":"workspace"),jsxRuntimeExports.jsx(WebAccountLayout,{title:r,host:o?i:"document",bare:t,intro:n??jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),children:e})}function credentialViewCopy(r){return{email:r.emailLabel,password:r.passwordLabel,username:r.usernameLabel,signIn:r.loginAction,registerSubmit:r.registerAction,rememberDevice:"记住账号"}}function XpodBlockingAccountCredentialsSurface(r){const e=getXpodAuthSurfaceHost(),t=r.mode!=="register";useXpodAuthWindowSurface(e==="window",t?"account":"workspace");const{mode:n,values:a,onChange:i,onSubmit:o,onFieldChange:s,onModeChange:d,rememberAccount:u=!0,onRememberAccountChange:c,pending:p=!1,errors:_,copy:m,surfaceTitle:S,footer:A,onForgot:h,onRegister:T,forgotHref:w,registerHref:b}=r,N={serviceName:"Xpod",serviceHost:window.location.host,serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),copy:credentialViewCopy(m)},O=(X,ee)=>{i({...a,[X]:ee}),s?.(X,ee)};return jsxRuntimeExports.jsxs(WebAccountLayout,{title:S,host:t?e:"document",bare:!0,intro:jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),children:[n==="register"?jsxRuntimeExports.jsx(IdpRegisterView,{...N,requireUsername:!1,pending:p,defaultEmail:a.email,defaultPassword:a.password,error:_?.form,fieldErrors:{email:_?.email,password:_?.password},onFieldChange:O,onSubmit:X=>{o({...a,...X})},onSignIn:d?()=>d("login"):void 0}):jsxRuntimeExports.jsx(IdpSignInView,{...N,pending:p,remember:u,defaultEmail:a.email,defaultPassword:a.password,error:_?.form,fieldErrors:{email:_?.email,password:_?.password},onFieldChange:O,onRememberChange:c,onSubmit:X=>{o({...a,...X})},onForgot:h,forgotHref:w,registerHref:b,onRegister:T??(d?()=>d("register"):void 0)}),A?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:A}):null]})}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(r=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(r));for(let n=0;n<r;n++)e+=urlAlphabet[t[n]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<r;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=r=>typeof r=="object"&&r!==null&&typeof r.value=="string",hasTermValue=r=>typeof r=="object"&&r!==null&&typeof r.term=="object"&&r.term!==null&&typeof r.term?.value=="string",resolveTermIri=r=>{if(typeof r=="string")return r;if(hasStringValue$2(r))return r.value;if(hasTermValue(r))return r.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is$1(r,e){if(!r||typeof r!="object")return!1;if(r instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=r.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:n,query:a}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:n,query:a,isExisting:!a,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,n,a=!1){this[SubqueryConfig]={sql:e,selection:t,alias:n,isWith:a}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const a=(is$1(e,Subquery)?e[SubqueryConfig].selection:is$1(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is$1(a,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!a.isSelectionField)return a.sql;const i=a.clone();return i.isSelectionField=!0,i}if(is$1(a,SQL)){if(this.config.sqlBehavior==="sql")return a;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is$1(a,Column)?this.config.alias?new Proxy(a,new ColumnAliasProxyHandler(new Proxy(a.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):a:typeof a!="object"||a===null?a:new Proxy(a,new SelectionProxyHandler(this.config))}}function orderSelectedFields(r,e){return Object.entries(r).reduce((t,[n,a])=>{if(typeof n!="string")return t;const i=e?[...e,n]:[n];return is$1(a,Column)||is$1(a,SQL)||is$1(a,SQL.Aliased)?t.push({path:i,field:a}):is$1(a,Table)?t.push(...orderSelectedFields(a[Table.Symbol.Columns],i)):t.push(...orderSelectedFields(a,i)),t},[])}function applyMixins(r,e){for(const t of e)for(const n of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(r.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)||Object.create(null))}function getTableLikeName(r){return is$1(r,Subquery)?r[SubqueryConfig].alias:is$1(r,View)?r[ViewBaseConfig].name:is$1(r,SQL)?void 0:r[Table.Symbol.IsAlias]?r[Table.Symbol.Name]:r[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,n){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=n}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(r,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:n,session:a,dialect:i,withList:o,distinct:s}){super(),this.config={withList:o,table:e,fields:{...t},distinct:s},this.isPartialSelect=n,this.session=a,this.dialect=i,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,n)=>{const a=this.tableName,i=getTableLikeName(t);if(typeof i=="string"&&this.config.joins?.some(o=>o.alias===i))throw new Error(`Alias "${i}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof a=="string"&&(this.config.fields={[a]:this.config.fields}),typeof i=="string"&&!is$1(t,SQL))){const o=is$1(t,Subquery)?t[SubqueryConfig].selection:is$1(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[i]=o}if(typeof n=="function"&&(n=n(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:t,joinType:e,alias:i}),typeof i=="string")switch(e){case"left":{this.joinsNotNullableMap[i]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[i]=!0;break}case"inner":{this.joinsNotNullableMap[i]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[i]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:n,dialect:a,joinsNotNullableMap:i}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const o=orderSelectedFields(n.fields),s=t.prepareQuery(a.sqlToQuery(this.getSQL()),o,e);return s.joinsNotNullableMap=i,s})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(r){return typeof r=="object"&&r!==null&&"getSQL"in r&&typeof r.getSQL=="function"}function mergeQueries(r){const e={sql:"",params:[]};for(const t of r)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,t){const n=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:a,escapeParam:i,prepareTyping:o,inlineParams:s,paramStartIndex:d}=n;return mergeQueries(e.map(u=>{if(is$1(u,StringChunk))return{sql:u.value.join(""),params:[]};if(is$1(u,Name))return{sql:a(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){const c=[new StringChunk("(")];for(const[p,_]of u.entries())c.push(_),p<u.length-1&&c.push(new StringChunk(", "));return c.push(new StringChunk(")")),this.buildQueryFromSourceParams(c,n)}if(is$1(u,SQL))return this.buildQueryFromSourceParams(u.queryChunks,{...n,inlineParams:s||u.shouldInlineParams});if(is$1(u,Table)){const c=u[Table.Symbol.Schema],p=u[Table.Symbol.Name];return{sql:c===void 0?a(p):a(c)+"."+a(p),params:[]}}if(is$1(u,Column))return{sql:a(u.table[Table.Symbol.Name])+"."+a(u.name),params:[]};if(is$1(u,View)){const c=u[ViewBaseConfig].schema,p=u[ViewBaseConfig].name;return{sql:c===void 0?a(p):a(c)+"."+a(p),params:[]}}if(is$1(u,Param)){const c=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(is$1(c,SQL))return this.buildQueryFromSourceParams([c],n);if(s)return{sql:this.mapInlineParam(c,n),params:[]};let p;return o!==void 0&&(p=[o(u.encoder)]),{sql:i(d.value++,c),params:[c],typings:p}}return is$1(u,Placeholder)?{sql:i(d.value++,u),params:[u]}:is$1(u,SQL.Aliased)&&u.fieldAlias!==void 0?{sql:a(u.fieldAlias),params:[]}:is$1(u,Subquery)?u[SubqueryConfig].isWith?{sql:a(u[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),u[SubqueryConfig].sql,new StringChunk(") "),new Name(u[SubqueryConfig].alias)],n):isSQLWrapper(u)?this.buildQueryFromSourceParams([new StringChunk("("),u.getSQL(),new StringChunk(")")],n):is$1(u,Relation)?this.buildQueryFromSourceParams([u.sourceTable,new StringChunk("."),sql.identifier(u.fieldName)],n):s?{sql:this.mapInlineParam(u,n),params:[]}:{sql:i(d.value++,u),params:[u]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const n=e.toString();return t(n==="[object Object]"?JSON.stringify(e):n)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:r=>r},noopEncoder={mapToDriverValue:r=>r};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(r,...e){const t=[];(e.length>0||r.length>0&&r[0]!=="")&&t.push(new StringChunk(r[0]));for(const[n,a]of e.entries())t.push(a,new StringChunk(r[n+1]));return new SQL(t)}(function(r){function e(){return new SQL([])}r.empty=e;function t(d){return new SQL(d)}r.fromList=t;function n(d){return new SQL([new StringChunk(d)])}r.raw=n;function a(d,u){const c=[];for(const[p,_]of d.entries())p>0&&u!==void 0&&c.push(u),c.push(_);return new SQL(c)}r.join=a;function i(d){return new Name(d)}r.identifier=i;function o(d){return new Placeholder(d)}r.placeholder=o;function s(d,u){return new Param(d,u)}r.param=s})(sql||(sql={}));(function(r){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(n,a){this.sql=n,this.fieldAlias=a}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}r.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const a=e[Table.Symbol.Columns];if(!a)return a;const i={};return Object.keys(a).map(o=>{i[o]=new Proxy(a[o],new ColumnAliasProxyHandler(new Proxy(e,this)))}),i}const n=e[t];return is$1(n,Column)?new Proxy(n,new ColumnAliasProxyHandler(new Proxy(e,this))):n}}var _a$b;class ColumnBuilder{constructor(e,t,n={},a,i){this.name=e,this.dataType=t,this.options={...n},this._predicateUri=a,this.elementType=i??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,n={},a){this.name=e,this.dataType=t,this.options=n,this.tableName=a}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,n={}){super(e,"array",n),this.elementType=t}}function boolean$2(r,e={}){return new ColumnBuilder(r,"boolean",e)}function timestamp(r,e={}){return new ColumnBuilder(r,"datetime",e)}function json(r,e={}){return new ColumnBuilder(r,"json",e)}function object$1(r,e={}){return new ColumnBuilder(r,"object",e)}function uri(r,e={}){return new ColumnBuilder(r,"uri",e)}function id(r="id",e={}){const t=new PodStringColumn(r,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(r,e={}){return new ColumnBuilder(r,"string",e)}function integer$1(r,e={}){return new ColumnBuilder(r,"integer",e)}function date$3(r,e={}){return new ColumnBuilder(r,"datetime",e)}function text(r,e={}){return new ColumnBuilder(r,"string",e)}function real(r,e={}){return new ColumnBuilder(r,"integer",e)}function validateColumnOverride(r,e,t){const n=r.getPredicateUri?.()??r.options?.predicate,a=e.options?.predicate;if(n&&a&&n!==a)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${a}",子 schema 尝试改为 "${n}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(r,e){const t={};for(const[n,a]of Object.entries(r.columns))t[n]=a;for(const[n,a]of Object.entries(e)){const i=r.columns[n];if(i&&!(a instanceof PodColumnBase)){validateColumnOverride(a,i,n);const o=a;!o.getPredicateUri?.()&&!o.options?.predicate&&(o.options={...o.options,predicate:i.options?.predicate})}t[n]=a}return t}function renderDefaultIdTemplate(r,e){if(!/\{[^{}]+\}/.test(r))return r;if(/\{\s*id\s*\}/.test(r))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},n=resolveDate(t,e.now),a={yyyy:String(n.getUTCFullYear()),MM:String(n.getUTCMonth()+1).padStart(2,"0"),dd:String(n.getUTCDate()).padStart(2,"0")};return r.replace(/\{([^{}]+)\}/g,(i,o)=>{const s=o.trim();if(s==="key")return e.key;if(s==="yyyy")return a.yyyy;if(s==="MM")return a.MM;if(s==="dd")return a.dd;const d=resolveExpression(s,t,e);return d==null?"":String(d)})}function resolveDate(r,e=new Date){const t=r.createdAt??r.favoredAt??r.indexedAt??e,n=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(n.getTime())?n:e}function resolveExpression(r,e,t){const n=parseExpression(r);let a=resolveTemplatePath(n.path,e,t);for(const i of n.transforms)a=applyTransform(a,i,n.path,t);return n.selector?applyPathSelector(a,n.selector):a}function parseExpression(r){const e=r.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():r,[n,...a]=t.split("|").map(i=>i.trim()).filter(Boolean);return{path:n??r,transforms:a,selector:e?.[2]?.trim()}}function resolveTemplatePath(r,e,t){const n=r.split("."),a=n[0];return n.reduce((i,o,s)=>{if(typeof i=="string")return a?resolveResourceProperty(i,a,o,t):void 0;if(!(!i||typeof i!="object"))return a&&isResourceProperty(o)&&!((o==="id"||o==="key")&&o in i)?resolveResourceProperty(i,a,o,t):s>0&&o==="id"&&readRef(i)?extractResourceId(i,a??"",t):i[o]},e)}function isResourceProperty(r){return r==="id"||r==="key"||r==="doc"||r==="document"||r==="dir"||r==="owner"}function resolveResourceProperty(r,e,t,n){if(t==="id")return extractResourceId(r,e,n);const a=extractResourceId(r,e,n);if(a){if(t==="key"){const i=extractTemplateValuesForField(r,e,n);return i?.key??i?.id??deriveResourceKey(a)}if(t==="doc"||t==="document")return resourceDocument(a);if(t==="dir"||t==="owner")return deriveOwnerDir(a)}}function applyTransform(r,e,t,n){if(e==="slug")return slugifyValue(String(r??""));const a=extractResourceId(r,t,n);if(e==="resource")return a;if(e==="document")return a?resourceDocument(a):"";if(e==="owner")return a?deriveOwnerDir(a):"";const i=extractTemplateValuesForField(r,t,n);return e==="id"?i?.id??i?.key??a??"":i?.[e]??""}function extractResourceId(r,e,t){const n=readRef(r);if(!n)return null;const a=resolveLinkedResource(e,t);if(!a)return normalizePodDataResourceId$1(n);if(!isCompleteResourceId$1(n))return renderLinkedResourceId(a,n);const i=relativeSubjectFromRef$1(a,n);return normalizePodDataResourceId$1(i??n)}function extractTemplateValuesForField(r,e,t){const n=readRef(r);if(!n)return null;const a=resolveLinkedResource(e,t);if(!a)return null;const i=relativeSubjectFromRef$1(a,n)??(isCompleteResourceId$1(n)?null:renderLinkedResourceId(a,n));if(!i)return null;const o=resourceTemplate(a);return o?extractVarsFromTemplate(normalizePodDataResourceId$1(i),o):{id:normalizePodDataResourceId$1(i)}}function resolveLinkedResource(r,e){const t=e.links?.[r];if(t)return t;const n=e.resource?.columns?.[r];return n?.getLinkTable?.()??n?.options?.linkTable??null}function resourceTemplate(r){const e=r.getSubjectTemplate?.()??r.config?.subjectTemplate;if(e)return e;const t=r.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(r,e){const t=resourceTemplate(r);if(!t)return e;const n=r.columns?.id?.options?.defaultValue;return typeof n=="function"?String(n(e,{})):t.replace(/\{([^}]+)\}/g,(a,i)=>{const o=parseTemplateField(i);return o==="id"||o==="key"?e:""})}function readRef(r){if(typeof r=="string"&&r.length>0)return r;if(!r||typeof r!="object")return null;const e=r,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(r){return normalizeResourcePath$1(r.getResourcePath?.()??r.config?.base??"")}function relativeSubjectFromRef$1(r,e){const t=resourcePath(r);if(!t)return normalizePodDataResourceId$1(e);const n=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const a of n){const i=e.indexOf(a);if(i<0)continue;let o=e.slice(i+a.length);return o.startsWith("/")&&(o=o.slice(1)),o.length>0?o:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(r,e){let t=0;const n=new Map,a=[];let i=0;for(const s of e.matchAll(/\{([^}]+)\}/g)){a.push(escapeRegExp$1(e.slice(i,s.index)));const d=`var${t++}`;n.set(d,parseTemplateField(s[1]??"")),a.push(`(?<${d}>.+?)`),i=s.index+s[0].length}a.push(escapeRegExp$1(e.slice(i)));const o=a.join("");try{const s=r.match(new RegExp(`^${o}$`));if(!s?.groups)return null;const d={};for(const[u,c]of Object.entries(s.groups)){const p=n.get(u);!p||c===void 0||(d[p]=decodeURIComponent(c))}return d}catch{return null}}function parseTemplateField(r){const e=r.split("|").map(n=>n.trim()).filter(Boolean)[0]??r,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(r){return r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(r,e){const t=splitResourcePath(r);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const n=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!n)throw new Error(`Invalid id default path selector [${e}]`);const a=n[1]===""?0:normalizeSliceIndex(Number(n[1]),t.length),i=n[2]===""?t.length:normalizeSliceIndex(Number(n[2]),t.length);return t.slice(a,i).join("/")}function splitResourcePath(r){const e=readRef(r);if(!e)return null;const t=normalizePodDataResourceId$1(e),[n,a]=t.split("#"),i=(n??t).split("/").filter(Boolean);return a&&i.push(a),i}function normalizePodDataResourceId$1(r){const e=r.indexOf("#"),[t,n=""]=e>=0?[r.slice(0,e),r.slice(e)]:[r,""],a=t.indexOf("/.data/");return`${a>=0?t.slice(a+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${n}`}function normalizeResourcePath$1(r){return r.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(r){return/^https?:\/\//u.test(r)||r.startsWith("/")||r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(r)}function deriveOwnerDir(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#"),n=t>=0?e.slice(0,t):e,a=t>=0?e.slice(t+1):"",i=n.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(i?.[1])return i[1];if(n==="task/index.ttl"&&a&&a!=="this")return`task/${a}`;const o=n.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(o?.[1])return o[1];const s=n.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(s?.[1])return s[1];const d=n.split("/").filter(Boolean);return d.length>1?d.slice(0,-1).join("/"):n}function resourceDocument(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#");if(t>=0){const s=e.slice(t+1);if(s&&s!=="this"&&s!=="me"&&s!=="it")return s}const n=resourceDocument(e).replace(/\/+$/u,""),a=n.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(a?.[1])return a[1];const i=n.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(i?.[1])return i[1];const o=n.split("/").filter(Boolean);return o.length>0?o[o.length-1]:e}function slugifyValue(r){return r.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(r,e){return r<0?e+r:r}function normalizeSliceIndex(r,e){const t=r<0?e+r:r;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(r){const e=r.split("|").map(n=>n.trim()).filter(Boolean)[0]??r,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(r){return r.trim().replace(/^(\.\/)+/,"")}function podResourcePath(r){return normalizeResourcePath(r.getResourcePath?.()??r.config?.base??"")}function podResourceSubjectTemplate(r){return r.getSubjectTemplate?.()??r.config?.subjectTemplate}function podResourceIdDefaultTemplate(r){const e=r.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(r){const e=podResourcePath(r),t=normalizeResourcePath(r.getContainerPath?.()??r.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(r,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(r);return t?`${t}${e}`:e}function templateRelativeSubject(r,e){if((podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r))?.startsWith("#")&&!e.startsWith("#")){const n=e.indexOf("#");if(n>=0)return e.slice(n)}return e}function isBaseRelativeSubjectId$1(r){return!r||/^https?:\/\//.test(r)||r.startsWith("/")?!1:r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(r)}function isTemplateCompleteResourceId(r,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r);return t?extractTemplateValues(templateRelativeSubject(r,e),t)!==null:!1}function isResourceRelativeSubjectId(r,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(r,e)}function relativeSubjectFromRef(r,e){const t=podResourcePath(r);if(!t)return null;const n=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const a of n){const i=e.indexOf(a);if(i<0)continue;let o=e.slice(i+a.length);if(o.startsWith("/")&&(o=o.slice(1)),o.length>0)return o}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(r,e)?normalizeResourcePath(e):null}function extractTemplateValues(r,e){if(!e.includes("{"))return r===e?{}:null;let t=0;const n=new Map,a=[];let i=0;for(const s of e.matchAll(/\{([^}]+)\}/g)){a.push(escapeRegExp(e.slice(i,s.index)));const d=`var${t++}`;n.set(d,parseTemplateVariableField$1(s[1]??"")),a.push(`(?<${d}>.+?)`),i=s.index+s[0].length}a.push(escapeRegExp(e.slice(i)));const o=`^${a.join("")}$`;try{const s=r.match(new RegExp(o));if(!s?.groups)return null;const d={};for(const[u,c]of Object.entries(s.groups)){const p=n.get(u);if(!p||c===void 0)continue;const _=decodeURIComponent(c);if(p in d&&d[p]!==_)return null;d[p]=_}return d}catch{return null}}function escapeRegExp(r){return r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(r,e){if(!e)return null;const t=relativeSubjectFromRef(r,e);if(!t)return null;const n=qualifyFragmentResourceId(r,t),a=podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r),i=a?extractTemplateValues(templateRelativeSubject(r,n),a):{id:decodeURIComponent(n)};return i?{resourceId:decodeURIComponent(n),templateValues:i}:null}function extractPodResourceTemplateValue(r,e,t="id"){return parsePodResourceRef(r,e)?.templateValues[t]??null}function resolvePodBaseUrl(r){const e=r.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(r){if(!r||typeof r!="object")return null;const e=r,t=typeof e.getDialect=="function"?e.getDialect():null,n=readPodUrl(t);if(n)return resolvePodBaseUrl(n);const a=typeof e.getSession=="function"?e.getSession():e.session,i=readPodUrl(a);if(i)return resolvePodBaseUrl(i);const o=readWebId(a);return o&&o.includes("/profile/card#me")?resolvePodBaseUrl(o):null}function normalizePodDataResourceId(r){const e=r.indexOf("#"),[t,n=""]=e>=0?[r.slice(0,e),r.slice(e)]:[r,""],a=t.indexOf("/.data/");return`${a>=0?t.slice(a+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${n}`}function resolvePodResourceId(r,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(r,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(r,e),normalizePodDataResourceId(e);const n=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!n)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(n)||isTemplateCompleteResourceId(r,n))return normalizePodDataResourceId(n);const a=resolveDefaultResourceId(r,n,e);if(a)return normalizePodDataResourceId(a);const i=podResourceSubjectTemplate(r);return normalizePodDataResourceId(i?renderSubjectTemplateResourceId(i,n,e):n)}function buildPodResourceIri(r,e){const t=resolvePodBaseUrl(r);if(!t||/^https?:\/\//u.test(e))return e;const n=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(n.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(r,e,t){const n=resolveKnownTargetIri(t);if(n)return n;const a=resolvePodRootTargetPath(t);if(a)return buildPodResourceIri(r,a);const i=resolvePodResourceId(e,t),o=isResourceRelativeSubjectId(e,i)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(i)}`:e.resolveUri?.(i)??`/.data/${normalizePodDataResourceId(i)}`;return buildPodResourceIri(r,o)}function buildPodResourceIriForDatabase(r,e,t){const n=resolvePodBaseUrlFromDatabase(r);if(!n)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(n,e,t)}function resolvePodResourceIriForDatabase(r,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(r,e,t)}catch{return null}}function resolveKnownTargetIri(r){if(typeof r=="string")return/^https?:\/\//u.test(r)?r:null;const e=r["@id"]??r.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(r){if(typeof r=="string")return r.startsWith("/")?r:null;const e=typeof r.id=="string"?r.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(r){return/^https?:\/\//u.test(r)||r.startsWith("/")||r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(r)}function assertCompleteStringResourceId(r,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(r,e))return;const t=r.columns?.id?.options?.defaultValue!==void 0,n=podResourceSubjectTemplate(r);if(t||n)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(r,e,t){const n=r.columns?.id?.options?.defaultValue;if(n===void 0)return null;if(typeof n=="string")return renderDefaultIdTemplate(n,{key:e,row:t,resource:r});if(typeof n!="function")return String(n);const a=n;return a.length===0?String(a()):String(a(e,t))}function renderSubjectTemplateResourceId(r,e,t){const n=r.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(n,{key:encodeURIComponent(e),row:t})}function readPodUrl(r){if(!r||typeof r!="object")return null;const e=r,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(r){if(!r||typeof r!="object")return null;const e=r,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,n){this.initialized=!1;const a=n.type;if(!a)throw new Error("podTable requires a type (RDF class) via options.type");const i=n.typeIndex,o=i==="private"||i==="public",s=this.resolveBase(n.base,e);this.resourcePath=s.resourcePath,this.containerPath=s.containerPath;const d=this.resolveSubjectTemplate(n.subjectTemplate,s.resourcePath,s.containerPath,e);this.subjectTemplate=d.template,this.hasCustomSubjectTemplate=d.isCustom,this.resourceMode=n.resourceMode??(n.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=n.sparqlEndpoint,this.registerTypeIndexEnabled=o&&n.autoRegister!==!1,this.config={name:e,base:s.resourcePath,type:resolveTermIri(a),namespace:n.namespace,typeIndex:o?i:void 0,saiRegistryPath:n.saiRegistryPath,autoRegister:n.autoRegister,containerPath:s.containerPath,hooks:n.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(n.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let u=0;for(const c of Object.values(t))if(c.options.primaryKey&&u++,c.table=this,c.tableName=e,!c.options.predicate&&!c._virtualId&&!n.namespace)throw new Error(`Column "${c.name}" in table "${e}" is missing a predicate.`);if(u!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${u}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const n=t.replace(/\{id\}/g,e);return n.startsWith("#")?`${this.resourcePath}${n}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${n}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const n=this.normalizeBaseInput(e),a=this.normalizeResourcePath(n);if(a.endsWith("/")){const o=this.ensureTrailingSlash(a);return{resourcePath:o,containerPath:o}}const i=this.ensureTrailingSlash(this.deriveContainerPath(a));return{resourcePath:a,containerPath:i}}normalizeBaseInput(e){const t=e.trim(),n=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(n){const[,a,i]=n,o=a.toLowerCase(),s=i.trim();return o==="http"||o==="https"?`${o}://${s}`:s.startsWith("/")?s:`/${s}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const n=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return n.startsWith("/")?n:`/${n}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n===-1?"/":t.slice(0,n+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,n,a){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const n=(Array.isArray(e)?e:[e]).map(a=>resolveTermIri(a)).filter(a=>a&&a.length>0);return Array.from(new Set(n))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(r,e,t){const n={};for(const[a,i]of Object.entries(e)){if(i instanceof PodColumnBase){n[a]=i;continue}let o;switch(i.dataType){case"integer":o=new PodIntegerColumn(i.name,i.options);break;case"datetime":o=new PodDateTimeColumn(i.name,i.options);break;case"boolean":o=new PodBooleanColumn(i.name,i.options);break;case"json":o=new PodJsonColumn(i.name,i.options);break;case"object":o=new PodObjectColumn(i.name,i.options);break;case"array":{const d=i.elementType??i.options.baseType??"string";o=new PodArrayColumn(i.name,d,i.options);break}case"uri":o=new PodUriColumn(i.name,i.options);break;default:o=new PodStringColumn(i.name,i.options);break}const s=i.getPredicateUri?.();s&&o.predicate(s),n[a]=o}return new PodTable(r,n,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const n=mergeSchemaColumns(this,e),a=[this.type];return this.subClassOf&&a.push(...this.subClassOf),solidSchema(n,{...t,subClassOf:a})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(r,e){const t={};for(const[n,a]of Object.entries(r)){if(a instanceof PodColumnBase){t[n]=a;continue}let i;switch(a.dataType){case"integer":i=new PodIntegerColumn(a.name,a.options);break;case"datetime":i=new PodDateTimeColumn(a.name,a.options);break;case"boolean":i=new PodBooleanColumn(a.name,a.options);break;case"json":i=new PodJsonColumn(a.name,a.options);break;case"object":i=new PodObjectColumn(a.name,a.options);break;case"array":{const s=a.elementType??a.options.baseType??"string";i=new PodArrayColumn(a.name,s,a.options);break}case"uri":i=new PodUriColumn(a.name,a.options);break;default:i=new PodStringColumn(a.name,a.options);break}const o=a.getPredicateUri?.();o&&i.predicate(o),t[n]=i}return new SolidSchema(t,e)}function isSolidSchema(r){return r instanceof SolidSchema||r?.$kind==="SolidSchema"}const XSD$e="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(r,e){if(!r)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const a=e.getMapping()?.columns?.[r.name];if(a?.predicate)return a.predicate}if(typeof r.getPredicateUri=="function")return r.getPredicateUri();if(r._predicateUri)return r._predicateUri;if(r.predicate&&typeof r.predicate=="string")return r.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof r.getPredicate=="function")try{return r.getPredicate(t)}catch{}return r.options?.predicate?r.options.predicate:t?`${typeof t=="string"?t:t.uri}${r.name}`:(r.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",r),`http://example.org/${r.name}`)}function formatValue$1(r,e,t,n){return Array.isArray(r)?r.map(a=>formatSingleValue(a,e,t,n)):formatSingleValue(r,e,t,n)}function formatSingleValue(r,e,t,n){if(r==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const a=String(r);if(a.startsWith("<")&&a.endsWith(">")){const i=a.slice(1,-1);return t&&!t.isAbsoluteUri(i)?`<${t.resolveLink(i,e,n)}>`:a}return t?`<${t.resolveLink(a,e,n)}>`:a.startsWith("<")?a:`<${a}>`}return typeof r=="string"?!e&&(r.startsWith("http://")||r.startsWith("https://"))?`<${r}>`:`"${r.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof r=="number"?Number.isInteger(r)?String(r):`"${r}"^^<${XSD$e}decimal>`:typeof r=="boolean"?`"${r}"^^<${XSD$e}boolean>`:r instanceof Date?`"${r.toISOString()}"^^<${XSD$e}dateTime>`:`"${String(r)}"`}function resolveColumn(r,e){if(r&&typeof r=="object"&&r instanceof PodColumnBase)return r;if(r&&typeof r=="object"&&"name"in r){const t=r.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof r=="string"){const t=e.columns[r];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(r)}`)}function generateSubjectUri(r,e,t){const n=t.resolveSubject(e,r);if(!n)throw new Error("Failed to generate subject URI");return n}var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,n){super(),this.left=e,this.operator=t,this.right=n,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(r,e){return new BinaryExpression(r,"=",e)}function like(r,e){return new BinaryExpression(r,"LIKE",e)}function inArray(r,e){return new BinaryExpression(r,"IN",e)}function and(...r){return new LogicalExpression("AND",r.filter(Boolean))}function or(...r){return new LogicalExpression("OR",r.filter(Boolean))}function parseActivityStreamsMessage(r){const e=JSON.parse(r);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,n=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!n.ok)throw new Error(`SSE connection failed: ${n.status} ${n.statusText}`);if(!n.body)throw new Error("SSE response has no body");this.contentType=n.headers.get("content-type")||"",this._connected=!0,this.reader=n.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:n,value:a}=await this.reader.read();if(n){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const i=e.decode(a,{stream:!0});t+=i,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(n){n.name!=="AbortError"&&this.handleError(n)}}processTurtleBuffer(e){const t=e.split(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/XpodShellApp-D1b3kqD0.js","assets/XpodThemeProvider-rUdAw66p.js","assets/XpodThemeProvider-hSOBxPcP.css","assets/button-ZJYFB218.js","assets/PodDeletionAuthorizationPanel-Ch4--l4b.js","assets/account-session-BD1q8D_o.js","assets/safe-continuation-CYaRj3rj.js","assets/nav-item-style-C2upI7sr.js","assets/createLucideIcon-B2wXvYTD.js","assets/XpodShellApp-BEzi4f1j.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as createLucideIcon$1}from"./createLucideIcon-B2wXvYTD.js";import{r as reactExports,j as jsxRuntimeExports,g as useXpodAuthWindowSurface,h as getXpodAuthSurfaceHost,_ as __vitePreload,k as getDefaultExportFromCjs,l as getAugmentedNamespace,m as commonjsGlobal}from"./XpodThemeProvider-rUdAw66p.js";import{c as cn,B as Button,u as useComposedRefs,e as createSlottable,d as controlFocusClass}from"./button-ZJYFB218.js";import{c as createContextScope,P as Primitive,q as useCallbackRef,r as useLayoutEffect2,f as Card,p as createLucideIcon,t as reactDomExports,v as Presence,w as DismissableLayer,y as useId,u as useControllableState,a as composeEventHandlers,z as Portal$1,I as Input}from"./PodDeletionAuthorizationPanel-Ch4--l4b.js";import{X as XpodMark,f as resolveSolidLocalRouteUrl,h as createSolidLocalRouteFetch,p as probeSolidLocalRouteStatus}from"./account-session-BD1q8D_o.js";function _mergeNamespaces(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const a in n)if(a!=="default"&&!(a in r)){const i=Object.getOwnPropertyDescriptor(n,a);i&&Object.defineProperty(r,a,i.get?i:{enumerable:!0,get:()=>n[a]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var __defProp$4=Object.defineProperty,__name$4=(r,e)=>__defProp$4(r,"name",{value:e,configurable:!0}),AVATAR_NAME="Avatar",[createAvatarContext,createAvatarScope]=createContextScope(AVATAR_NAME),STATIC_IMAGE_COUNT_STATE=[0,()=>{}],[AvatarProvider,useAvatarContext]=createAvatarContext(AVATAR_NAME),Avatar$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,...a}=e,[i,o]=reactExports.useState("idle"),[s,d]=useImageCount();return jsxRuntimeExports.jsx(AvatarProvider,{scope:n,imageLoadingStatus:i,setImageLoadingStatus:o,imageCount:s,setImageCount:d,children:jsxRuntimeExports.jsx(Primitive.span,{...a,ref:t})})},"Avatar")),IMAGE_NAME="AvatarImage",AvatarImage$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,src:a,onLoadingStatusChange:i,...o}=e,s=useAvatarContext(IMAGE_NAME,n);s.setImageCount;const d=useImageLoadingStatus(a,{referrerPolicy:o.referrerPolicy,crossOrigin:o.crossOrigin,loadingStatus:s.imageLoadingStatus,setLoadingStatus:s.setImageLoadingStatus}),u=useCallbackRef(p=>{i?.(p)}),c=reactExports.useRef(d);return useLayoutEffect2(()=>{const p=c.current;c.current=d,d!==p&&u(d)},[d,u]),d==="loaded"?jsxRuntimeExports.jsx(Primitive.img,{...o,ref:t,src:a}):null},"AvatarImage")),FALLBACK_NAME="AvatarFallback",AvatarFallback$1=reactExports.forwardRef(__name$4(function(e,t){const{__scopeAvatar:n,delayMs:a,...i}=e,o=useAvatarContext(FALLBACK_NAME,n),[s,d]=reactExports.useState(a===void 0);return reactExports.useEffect(()=>{if(a!==void 0){const u=window.setTimeout(()=>d(!0),a);return()=>window.clearTimeout(u)}},[a]),s&&o.imageLoadingStatus!=="loaded"?jsxRuntimeExports.jsx(Primitive.span,{...i,ref:t}):null},"AvatarFallback"));function useImageLoadingStatus(r,{loadingStatus:e,setLoadingStatus:t,referrerPolicy:n,crossOrigin:a}){return useLayoutEffect2(()=>{if(!r){t("error");return}const i=new window.Image,o=__name$4(d=>{const u=d.currentTarget;t(getImageLoadingStatus(u))},"handleLoad"),s=__name$4(()=>t("error"),"handleError");return i.addEventListener("load",o),i.addEventListener("error",s),n&&(i.referrerPolicy=n),i.crossOrigin=a??null,i.src=r,t(getImageLoadingStatus(i)),()=>{i.removeEventListener("load",o),i.removeEventListener("error",s),t("idle")}},[r,a,n,t]),e}__name$4(useImageLoadingStatus,"useImageLoadingStatus");function getImageLoadingStatus(r){return r.complete?r.naturalWidth>0?"loaded":"error":"loading"}__name$4(getImageLoadingStatus,"getImageLoadingStatus");function useImageCount(){return STATIC_IMAGE_COUNT_STATE}__name$4(useImageCount,"useImageCount");function useUpdateImageCount(r){}__name$4(useUpdateImageCount,"useUpdateImageCount");const Avatar=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(Avatar$1,{ref:t,className:cn("relative flex shrink-0 overflow-hidden",r),...e}));Avatar.displayName=Avatar$1.displayName;const AvatarImage=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(AvatarImage$1,{ref:t,className:cn("h-full w-full object-cover",r),...e}));AvatarImage.displayName=AvatarImage$1.displayName;const AvatarFallback=reactExports.forwardRef(({className:r,...e},t)=>jsxRuntimeExports.jsx(AvatarFallback$1,{ref:t,className:cn("flex h-full w-full items-center justify-center bg-muted text-lg font-semibold",r),...e}));AvatarFallback.displayName=AvatarFallback$1.displayName;function AuthSurfaceBody({children:r,className:e}){return jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-body",className:cn("min-h-0",e),children:r})}const FOCUSABLE_SELECTOR=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function getFocusable(r){return Array.from(r.querySelectorAll(FOCUSABLE_SELECTOR)).filter(e=>e.getAttribute("aria-hidden")!=="true")}function AuthSurface({mode:r,title:e,children:t,presentation:n="standard",host:a="document",lead:i,onClose:o,closeLabel:s,closeOnEscape:d=!0,className:u,contentClassName:c}){const p=reactExports.useRef(null),_=reactExports.useRef(null),m=reactExports.useId();reactExports.useLayoutEffect(()=>{if(r!=="modal"||typeof document>"u")return;_.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const b=p.current;if(b){const N=getFocusable(b);(n==="compact"?b:N[0]??b).focus()}return()=>{_.current?.focus(),_.current=null}},[r,n]),reactExports.useLayoutEffect(()=>{if(r!=="modal"||typeof document>"u")return;const b=N=>{if(N.key==="Escape"){d&&o&&(N.preventDefault(),o());return}if(N.key!=="Tab")return;const O=p.current;if(!O)return;const X=getFocusable(O);if(X.length===0){N.preventDefault(),O.focus();return}const ee=document.activeElement,V=X.indexOf(ee),U=N.shiftKey?V<=0?X.length-1:V-1:V===X.length-1?0:V+1;N.preventDefault(),X[U].focus()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[d,r,o]);const S=r==="modal"?{role:"dialog","aria-modal":!0,"aria-labelledby":m}:{role:"region","aria-labelledby":m},A=n==="compact",h=a==="window",T=A?"flex min-h-0 flex-1 flex-col overflow-y-auto":"max-h-[min(80vh,48rem)] overflow-y-auto",w=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[A?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h1",{id:m,className:"sr-only",children:e}),r==="modal"&&o&&s?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":s,className:"absolute right-2 top-2 z-[var(--layer-sticky)]",children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border/60 p-4",children:[jsxRuntimeExports.jsx("h1",{id:m,className:"text-lg font-semibold text-foreground",children:e}),r==="modal"&&o&&s?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",onClick:o,"aria-label":s,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null]}),i?jsxRuntimeExports.jsx("div",{"data-testid":"auth-surface-lead",className:cn(A?"shrink-0 px-5 pt-7 has-[[data-presentation=compact]]:pt-5":"border-b border-border/60 p-4"),children:i}):null,jsxRuntimeExports.jsx(AuthSurfaceBody,{className:cn(T,c),children:t})]});return jsxRuntimeExports.jsx("div",{"data-testid":`auth-surface-${r}`,"data-auth-surface-mode":r,"data-auth-surface-presentation":A?"compact":void 0,"data-auth-surface-host":h?"window":void 0,className:cn(h?"fixed inset-0 z-[var(--layer-modal)] flex items-stretch justify-stretch overflow-hidden bg-card p-0":r==="modal"?cn("fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center p-4","bg-background"):r==="page"?"flex min-h-[100dvh] w-full items-center justify-center bg-background p-4":"flex min-h-0 w-full items-center justify-center p-4",u),children:h?jsxRuntimeExports.jsx("div",{ref:p,...S,"data-auth-surface-frame":"window",tabIndex:-1,className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden bg-card text-card-foreground focus:outline-none",children:w}):A?jsxRuntimeExports.jsx("div",{ref:p,...S,"data-auth-surface-frame":"compact",tabIndex:-1,style:{outline:"none"},className:"flex h-[400px] w-[280px] max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] min-w-0 flex-col overflow-y-auto overscroll-contain focus:outline-none",children:w}):jsxRuntimeExports.jsx(Card,{ref:p,...S,tabIndex:-1,style:{outline:"none"},className:cn("relative flex min-h-0 w-full flex-col border-border bg-card text-card-foreground focus:outline-none",r==="embedded"?"max-w-none shadow-none":"max-w-lg"),children:w})})}const __iconNode$7=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Check=createLucideIcon("check",__iconNode$7);const __iconNode$6=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Cloud=createLucideIcon("cloud",__iconNode$6);const __iconNode$5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Info=createLucideIcon("info",__iconNode$5);const __iconNode$4=[["path",{d:"M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z",key:"1pdavp"}],["path",{d:"M20.054 15.987H3.946",key:"14rxg9"}]],Laptop=createLucideIcon("laptop",__iconNode$4);const __iconNode$3=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle$1=createLucideIcon("loader-circle",__iconNode$3);const __iconNode$2=[["path",{d:"M5 12h14",key:"1ays0h"}]],Minus=createLucideIcon("minus",__iconNode$2),sides=["top","right","bottom","left"],min=Math.min,max$1=Math.max,round=Math.round,floor=Math.floor,createCoords=r=>({x:r,y:r}),oppositeSideMap={left:"right",right:"left",bottom:"top",top:"bottom"};function clamp(r,e,t){return max$1(r,min(e,t))}function evaluate(r,e){return typeof r=="function"?r(e):r}function getSide(r){return r.split("-")[0]}function getAlignment(r){return r.split("-")[1]}function getOppositeAxis(r){return r==="x"?"y":"x"}function getAxisLength(r){return r==="y"?"height":"width"}function getSideAxis(r){const e=r[0];return e==="t"||e==="b"?"y":"x"}function getAlignmentAxis(r){return getOppositeAxis(getSideAxis(r))}function getAlignmentSides(r,e,t){t===void 0&&(t=!1);const n=getAlignment(r),a=getAlignmentAxis(r),i=getAxisLength(a);let o=a==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(o=getOppositePlacement(o)),[o,getOppositePlacement(o)]}function getExpandedPlacements(r){const e=getOppositePlacement(r);return[getOppositeAlignmentPlacement(r),e,getOppositeAlignmentPlacement(e)]}function getOppositeAlignmentPlacement(r){return r.includes("start")?r.replace("start","end"):r.replace("end","start")}const lrPlacement=["left","right"],rlPlacement=["right","left"],tbPlacement=["top","bottom"],btPlacement=["bottom","top"];function getSideList(r,e,t){switch(r){case"top":case"bottom":return t?e?rlPlacement:lrPlacement:e?lrPlacement:rlPlacement;case"left":case"right":return e?tbPlacement:btPlacement;default:return[]}}function getOppositeAxisPlacements(r,e,t,n){const a=getAlignment(r);let i=getSideList(getSide(r),t==="start",n);return a&&(i=i.map(o=>o+"-"+a),e&&(i=i.concat(i.map(getOppositeAlignmentPlacement)))),i}function getOppositePlacement(r){const e=getSide(r);return oppositeSideMap[e]+r.slice(e.length)}function expandPaddingObject(r){var e,t,n,a;return{top:(e=r.top)!=null?e:0,right:(t=r.right)!=null?t:0,bottom:(n=r.bottom)!=null?n:0,left:(a=r.left)!=null?a:0}}function getPaddingObject(r){return typeof r!="number"?expandPaddingObject(r):{top:r,right:r,bottom:r,left:r}}function rectToClientRect(r){const{x:e,y:t,width:n,height:a}=r;return{width:n,height:a,top:t,left:e,right:e+n,bottom:t+a,x:e,y:t}}function computeCoordsFromPlacement(r,e,t){let{reference:n,floating:a}=r;const i=getSideAxis(e),o=getAlignmentAxis(e),s=getAxisLength(o),d=getSide(e),u=i==="y",c=n.x+n.width/2-a.width/2,p=n.y+n.height/2-a.height/2,_=n[s]/2-a[s]/2;let m;switch(d){case"top":m={x:c,y:n.y-a.height};break;case"bottom":m={x:c,y:n.y+n.height};break;case"right":m={x:n.x+n.width,y:p};break;case"left":m={x:n.x-a.width,y:p};break;default:m={x:n.x,y:n.y}}const S=getAlignment(e);return S&&(m[o]+=_*(S==="end"?1:-1)*(t&&u?-1:1)),m}async function detectOverflow(r,e){var t;e===void 0&&(e={});const{x:n,y:a,platform:i,rects:o,elements:s,strategy:d}=r,{boundary:u="clippingAncestors",rootBoundary:c="viewport",elementContext:p="floating",altBoundary:_=!1,padding:m=0}=evaluate(e,r),S=getPaddingObject(m),h=s[_?p==="floating"?"reference":"floating":p],T=rectToClientRect(await i.getClippingRect({element:(t=await(i.isElement==null?void 0:i.isElement(h)))==null||t?h:h.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(s.floating)),boundary:u,rootBoundary:c,strategy:d})),w=p==="floating"?{x:n,y:a,width:o.floating.width,height:o.floating.height}:o.reference,b=await(i.getOffsetParent==null?void 0:i.getOffsetParent(s.floating)),N=await(i.isElement==null?void 0:i.isElement(b))&&await(i.getScale==null?void 0:i.getScale(b))||{x:1,y:1},O=rectToClientRect(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:w,offsetParent:b,strategy:d}):w);return{top:(T.top-O.top+S.top)/N.y,bottom:(O.bottom-T.bottom+S.bottom)/N.y,left:(T.left-O.left+S.left)/N.x,right:(O.right-T.right+S.right)/N.x}}const MAX_RESET_COUNT=50,computePosition$1=async(r,e,t)=>{const{placement:n="bottom",strategy:a="absolute",middleware:i=[],platform:o}=t,s=o.detectOverflow?o:{...o,detectOverflow},d=await(o.isRTL==null?void 0:o.isRTL(e));let u=await o.getElementRects({reference:r,floating:e,strategy:a}),{x:c,y:p}=computeCoordsFromPlacement(u,n,d),_=n,m=0;const S={};for(let A=0;A<i.length;A++){const h=i[A];if(!h)continue;const{name:T,fn:w}=h,{x:b,y:N,data:O,reset:X}=await w({x:c,y:p,initialPlacement:n,placement:_,strategy:a,middlewareData:S,rects:u,platform:s,elements:{reference:r,floating:e}});c=b??c,p=N??p,S[T]={...S[T],...O},X&&m<MAX_RESET_COUNT&&(m++,typeof X=="object"&&(X.placement&&(_=X.placement),X.rects&&(u=X.rects===!0?await o.getElementRects({reference:r,floating:e,strategy:a}):X.rects),{x:c,y:p}=computeCoordsFromPlacement(u,_,d)),A=-1)}return{x:c,y:p,placement:_,strategy:a,middlewareData:S}},arrow$3=r=>({name:"arrow",options:r,async fn(e){const{x:t,y:n,placement:a,rects:i,platform:o,elements:s,middlewareData:d}=e,{element:u,padding:c=0}=evaluate(r,e)||{};if(u==null)return{};const p=getPaddingObject(c),_={x:t,y:n},m=getAlignmentAxis(a),S=getAxisLength(m),A=await o.getDimensions(u),h=m==="y",T=h?"top":"left",w=h?"bottom":"right",b=h?"clientHeight":"clientWidth",N=i.reference[S]+i.reference[m]-_[m]-i.floating[S],O=_[m]-i.reference[m],X=await(o.getOffsetParent==null?void 0:o.getOffsetParent(u));let ee=X?X[b]:0;(!ee||!await(o.isElement==null?void 0:o.isElement(X)))&&(ee=s.floating[b]||i.floating[S]);const V=N/2-O/2,U=ee/2-A[S]/2-1,v=min(p[T],U),x=min(p[w],U),I=ee-A[S]-x,E=ee/2-A[S]/2+V,Q=clamp(v,E,I),K=!d.arrow&&getAlignment(a)!=null&&E!==Q&&i.reference[S]/2-(E<v?v:x)-A[S]/2<0,te=K?E<v?E-v:E-I:0;return{[m]:_[m]+te,data:{[m]:Q,centerOffset:E-Q-te,...K&&{alignmentOffset:te}},reset:K}}}),flip$2=function(r){return r===void 0&&(r={}),{name:"flip",options:r,async fn(e){var t,n;const{placement:a,middlewareData:i,rects:o,initialPlacement:s,platform:d,elements:u}=e,{mainAxis:c=!0,crossAxis:p=!0,fallbackPlacements:_,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:A=!0,...h}=evaluate(r,e);if((t=i.arrow)!=null&&t.alignmentOffset)return{};const T=getSide(a),w=getSideAxis(s),b=getSide(s)===s,N=await(d.isRTL==null?void 0:d.isRTL(u.floating)),O=_||(b||!A?[getOppositePlacement(s)]:getExpandedPlacements(s)),X=S!=="none";!_&&X&&O.push(...getOppositeAxisPlacements(s,A,S,N));const ee=[s,...O],V=await d.detectOverflow(e,h),U=[];let v=((n=i.flip)==null?void 0:n.overflows)||[];if(c&&U.push(V[T]),p){const Q=getAlignmentSides(a,o,N);U.push(V[Q[0]],V[Q[1]])}if(v=[...v,{placement:a,overflows:U}],!U.every(Q=>Q<=0)){var x,I;const Q=(((x=i.flip)==null?void 0:x.index)||0)+1,K=ee[Q];if(K&&(!(p==="alignment"?w!==getSideAxis(K):!1)||v.every(D=>getSideAxis(D.placement)===w?D.overflows[0]>0:!0)))return{data:{index:Q,overflows:v},reset:{placement:K}};let te=(I=v.filter(se=>se.overflows[0]<=0).sort((se,D)=>se.overflows[1]-D.overflows[1])[0])==null?void 0:I.placement;if(!te)switch(m){case"bestFit":{var E;const se=(E=v.filter(D=>{if(X){const ne=getSideAxis(D.placement);return ne===w||ne==="y"}return!0}).map(D=>[D.placement,D.overflows.filter(ne=>ne>0).reduce((ne,y)=>ne+y,0)]).sort((D,ne)=>D[1]-ne[1])[0])==null?void 0:E[0];se&&(te=se);break}case"initialPlacement":te=s;break}if(a!==te)return{reset:{placement:te}}}return{}}}};function getSideOffsets(r,e){return{top:r.top-e.height,right:r.right-e.width,bottom:r.bottom-e.height,left:r.left-e.width}}function isAnySideFullyClipped(r){return sides.some(e=>r[e]>=0)}const hide$2=function(r){return r===void 0&&(r={}),{name:"hide",options:r,async fn(e){const{rects:t,platform:n}=e,{strategy:a="referenceHidden",...i}=evaluate(r,e);switch(a){case"referenceHidden":{const o=await n.detectOverflow(e,{...i,elementContext:"reference"}),s=getSideOffsets(o,t.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:isAnySideFullyClipped(s)}}}case"escaped":{const o=await n.detectOverflow(e,{...i,altBoundary:!0}),s=getSideOffsets(o,t.floating);return{data:{escapedOffsets:s,escaped:isAnySideFullyClipped(s)}}}default:return{}}}}},originSides=new Set(["left","top"]);async function convertValueToCoords(r,e){const{placement:t,platform:n,elements:a}=r,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),o=getSide(t),s=getAlignment(t),d=getSideAxis(t)==="y",u=originSides.has(o)?-1:1,c=i&&d?-1:1,p=evaluate(e,r);let{mainAxis:_,crossAxis:m,alignmentAxis:S}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return s&&typeof S=="number"&&(m=s==="end"?S*-1:S),d?{x:m*c,y:_*u}:{x:_*u,y:m*c}}const offset$2=function(r){return r===void 0&&(r=0),{name:"offset",options:r,async fn(e){var t,n;const{x:a,y:i,placement:o,middlewareData:s}=e,d=await convertValueToCoords(e,r);return o===((t=s.offset)==null?void 0:t.placement)&&(n=s.arrow)!=null&&n.alignmentOffset?{}:{x:a+d.x,y:i+d.y,data:{...d,placement:o}}}}},shift$2=function(r){return r===void 0&&(r={}),{name:"shift",options:r,async fn(e){const{x:t,y:n,placement:a,platform:i}=e,{mainAxis:o=!0,crossAxis:s=!1,limiter:d={fn:w=>{let{x:b,y:N}=w;return{x:b,y:N}}},...u}=evaluate(r,e),c={x:t,y:n},p=await i.detectOverflow(e,u),_=getSideAxis(a),m=getOppositeAxis(_);let S=c[m],A=c[_];const h=(w,b)=>clamp(b+p[w==="y"?"top":"left"],b,b-p[w==="y"?"bottom":"right"]);o&&(S=h(m,S)),s&&(A=h(_,A));const T=d.fn({...e,[m]:S,[_]:A});return{...T,data:{x:T.x-t,y:T.y-n,enabled:{[m]:o,[_]:s}}}}}},limitShift$2=function(r){return r===void 0&&(r={}),{options:r,fn(e){var t,n;const{x:a,y:i,placement:o,rects:s,middlewareData:d}=e,{offset:u=0,mainAxis:c=!0,crossAxis:p=!0}=evaluate(r,e),_={x:a,y:i},m=getSideAxis(o),S=getOppositeAxis(m);let A=_[S],h=_[m];const T=evaluate(u,e),w=typeof T=="number"?{mainAxis:T,crossAxis:0}:{mainAxis:(t=T.mainAxis)!=null?t:0,crossAxis:(n=T.crossAxis)!=null?n:0};if(c){const O=S==="y"?"height":"width",X=s.reference[S]-s.floating[O]+w.mainAxis,ee=s.reference[S]+s.reference[O]-w.mainAxis;A<X?A=X:A>ee&&(A=ee)}if(p){var b,N;const O=S==="y"?"width":"height",X=originSides.has(getSide(o)),ee=s.reference[m]-s.floating[O]+(X&&((b=d.offset)==null?void 0:b[m])||0)+(X?0:w.crossAxis),V=s.reference[m]+s.reference[O]+(X?0:((N=d.offset)==null?void 0:N[m])||0)-(X?w.crossAxis:0);h<ee?h=ee:h>V&&(h=V)}return{[S]:A,[m]:h}}}},size$2=function(r){return r===void 0&&(r={}),{name:"size",options:r,async fn(e){const{placement:t,rects:n,platform:a,elements:i}=e,{apply:o=()=>{},...s}=evaluate(r,e),d=await a.detectOverflow(e,s),u=getSide(t),c=getAlignment(t),p=getSideAxis(t)==="y",{width:_,height:m}=n.floating;let S,A;u==="top"||u==="bottom"?(S=u,A=c===(await(a.isRTL==null?void 0:a.isRTL(i.floating))?"start":"end")?"left":"right"):(A=u,S=c==="end"?"top":"bottom");const h=m-d.top-d.bottom,T=_-d.left-d.right,w=min(m-d[S],h),b=min(_-d[A],T),N=e.middlewareData.shift,O=!N;let X=w,ee=b;N!=null&&N.enabled.x&&(ee=T),N!=null&&N.enabled.y&&(X=h),O&&!c&&(p?ee=_-2*max$1(d.left,d.right):X=m-2*max$1(d.top,d.bottom)),await o({...e,availableWidth:ee,availableHeight:X});const V=await a.getDimensions(i.floating);return _!==V.width||m!==V.height?{reset:{rects:!0}}:{}}}};function hasWindow(){return typeof window<"u"}function getNodeName(r){return isNode$1(r)?(r.nodeName||"").toLowerCase():"#document"}function getWindow(r){var e;return(r==null||(e=r.ownerDocument)==null?void 0:e.defaultView)||window}function getDocumentElement(r){var e;return(e=(isNode$1(r)?r.ownerDocument:r.document)||window.document)==null?void 0:e.documentElement}function isNode$1(r){return hasWindow()?r instanceof Node||r instanceof getWindow(r).Node:!1}function isElement(r){return hasWindow()?r instanceof Element||r instanceof getWindow(r).Element:!1}function isHTMLElement(r){return hasWindow()?r instanceof HTMLElement||r instanceof getWindow(r).HTMLElement:!1}function isShadowRoot(r){return!hasWindow()||typeof ShadowRoot>"u"?!1:r instanceof ShadowRoot||r instanceof getWindow(r).ShadowRoot}function isOverflowElement(r){const{overflow:e,overflowX:t,overflowY:n,display:a}=getComputedStyle$1(r);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&a!=="inline"&&a!=="contents"}function isTableElement(r){return/^(table|td|th)$/.test(getNodeName(r))}function isTopLayer(r){try{if(r.matches(":popover-open"))return!0}catch{}try{return r.matches(":modal")}catch{return!1}}const willChangeRe=/transform|translate|scale|rotate|perspective|filter/,containRe=/paint|layout|strict|content/,isNotNone=r=>!!r&&r!=="none";let isWebKitValue;function isContainingBlock(r){const e=isElement(r)?getComputedStyle$1(r):r;return isNotNone(e.transform)||isNotNone(e.translate)||isNotNone(e.scale)||isNotNone(e.rotate)||isNotNone(e.perspective)||!isWebKit()&&(isNotNone(e.backdropFilter)||isNotNone(e.filter))||willChangeRe.test(e.willChange||"")||containRe.test(e.contain||"")}function getContainingBlock(r){let e=getParentNode(r);for(;isHTMLElement(e)&&!isLastTraversableNode(e);){if(isContainingBlock(e))return e;if(isTopLayer(e))return null;e=getParentNode(e)}return null}function isWebKit(){return isWebKitValue==null&&(isWebKitValue=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),isWebKitValue}function isLastTraversableNode(r){return/^(html|body|#document)$/.test(getNodeName(r))}function getComputedStyle$1(r){return getWindow(r).getComputedStyle(r)}function getNodeScroll(r){return isElement(r)?{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}:{scrollLeft:r.scrollX,scrollTop:r.scrollY}}function getParentNode(r){if(getNodeName(r)==="html")return r;const e=r.assignedSlot||r.parentNode||isShadowRoot(r)&&r.host||getDocumentElement(r);return isShadowRoot(e)?e.host:e}function getNearestOverflowAncestor(r){const e=getParentNode(r);return isLastTraversableNode(e)?(r.ownerDocument||r).body:isHTMLElement(e)&&isOverflowElement(e)?e:getNearestOverflowAncestor(e)}function getOverflowAncestors(r,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const a=getNearestOverflowAncestor(r),i=a===((n=r.ownerDocument)==null?void 0:n.body),o=getWindow(a);if(i){const s=getFrameElement(o);return e.concat(o,o.visualViewport||[],isOverflowElement(a)?a:[],s&&t?getOverflowAncestors(s):[])}else return e.concat(a,getOverflowAncestors(a,[],t))}function getFrameElement(r){return r.parent&&Object.getPrototypeOf(r.parent)?r.frameElement:null}function getCssDimensions(r){const e=getComputedStyle$1(r);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const a=isHTMLElement(r),i=a?r.offsetWidth:t,o=a?r.offsetHeight:n,s=round(t)!==i||round(n)!==o;return s&&(t=i,n=o),{width:t,height:n,$:s}}function unwrapElement(r){return isElement(r)?r:r.contextElement}function getScale(r){const e=unwrapElement(r);if(!isHTMLElement(e))return createCoords(1);const t=e.getBoundingClientRect(),{width:n,height:a,$:i}=getCssDimensions(e);let o=(i?round(t.width):t.width)/n,s=(i?round(t.height):t.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!s||!Number.isFinite(s))&&(s=1),{x:o,y:s}}const noOffsets=createCoords(0);function getVisualOffsets(r){const e=getWindow(r);return!isWebKit()||!e.visualViewport?noOffsets:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function shouldAddVisualOffsets(r,e,t){return e===void 0&&(e=!1),!!t&&e&&t===getWindow(r)}function getBoundingClientRect(r,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const a=r.getBoundingClientRect(),i=unwrapElement(r);let o=createCoords(1);e&&(n?isElement(n)&&(o=getScale(n)):o=getScale(r));const s=shouldAddVisualOffsets(i,t,n)?getVisualOffsets(i):createCoords(0);let d=(a.left+s.x)/o.x,u=(a.top+s.y)/o.y,c=a.width/o.x,p=a.height/o.y;if(i&&n){const _=getWindow(i),m=isElement(n)?getWindow(n):n;let S=_,A=getFrameElement(S);for(;A&&m!==S;){const h=getScale(A),T=A.getBoundingClientRect(),w=getComputedStyle$1(A),b=T.left+(A.clientLeft+parseFloat(w.paddingLeft))*h.x,N=T.top+(A.clientTop+parseFloat(w.paddingTop))*h.y;d*=h.x,u*=h.y,c*=h.x,p*=h.y,d+=b,u+=N,S=getWindow(A),A=getFrameElement(S)}}return rectToClientRect({width:c,height:p,x:d,y:u})}function getWindowScrollBarX(r,e){const t=getNodeScroll(r).scrollLeft;return e?e.left+t:getBoundingClientRect(getDocumentElement(r)).left+t}function getHTMLOffset(r,e){const t=r.getBoundingClientRect(),n=t.left+e.scrollLeft-getWindowScrollBarX(r,t),a=t.top+e.scrollTop;return{x:n,y:a}}function convertOffsetParentRelativeRectToViewportRelativeRect(r){let{elements:e,rect:t,offsetParent:n,strategy:a}=r;const i=a==="fixed",o=getDocumentElement(n),s=e?isTopLayer(e.floating):!1;if(n===o||s&&i)return t;let d={scrollLeft:0,scrollTop:0},u=createCoords(1);const c=createCoords(0),p=isHTMLElement(n);if((p||!i)&&((getNodeName(n)!=="body"||isOverflowElement(o))&&(d=getNodeScroll(n)),p)){const m=getBoundingClientRect(n);u=getScale(n),c.x=m.x+n.clientLeft,c.y=m.y+n.clientTop}const _=o&&!p&&!i?getHTMLOffset(o,d):createCoords(0);return{width:t.width*u.x,height:t.height*u.y,x:t.x*u.x-d.scrollLeft*u.x+c.x+_.x,y:t.y*u.y-d.scrollTop*u.y+c.y+_.y}}function getClientRects(r){return r.getClientRects?Array.from(r.getClientRects()):[]}function getDocumentRect(r){const e=getNodeScroll(r),t=r.ownerDocument.body,n=max$1(r.scrollWidth,r.clientWidth,t.scrollWidth,t.clientWidth),a=max$1(r.scrollHeight,r.clientHeight,t.scrollHeight,t.clientHeight);let i=-e.scrollLeft+getWindowScrollBarX(r);const o=-e.scrollTop;return getComputedStyle$1(t).direction==="rtl"&&(i+=max$1(r.clientWidth,t.clientWidth)-n),{width:n,height:a,x:i,y:o}}const SCROLLBAR_MAX=25;function getViewportRect(r,e,t){t===void 0&&(t="viewport");const n=t==="layoutViewport",a=getWindow(r),i=getDocumentElement(r),o=a.visualViewport;let s=i.clientWidth,d=i.clientHeight,u=0,c=0;if(o){const _=!isWebKit()||e==="fixed";n?_||(u=-o.offsetLeft,c=-o.offsetTop):(s=o.width,d=o.height,_&&(u=o.offsetLeft,c=o.offsetTop))}if(getWindowScrollBarX(i)<=0){const _=i.ownerDocument,m=_.body,S=getComputedStyle(m),A=_.compatMode==="CSS1Compat"&&parseFloat(S.marginLeft)+parseFloat(S.marginRight)||0,h=Math.abs(i.clientWidth-m.clientWidth-A),T=getComputedStyle(i).scrollbarGutter==="stable both-edges"?h/2:h;T<=SCROLLBAR_MAX&&(s-=T)}return{width:s,height:d,x:u,y:c}}function getInnerBoundingClientRect(r,e){const t=getBoundingClientRect(r,!0,e==="fixed"),n=t.top+r.clientTop,a=t.left+r.clientLeft,i=getScale(r),o=r.clientWidth*i.x,s=r.clientHeight*i.y,d=a*i.x,u=n*i.y;return{width:o,height:s,x:d,y:u}}function getClientRectFromClippingAncestor(r,e,t){let n;if(e==="viewport"||e==="layoutViewport")n=getViewportRect(r,t,e);else if(e==="document")n=getDocumentRect(getDocumentElement(r));else if(isElement(e))n=getInnerBoundingClientRect(e,t);else{const a=getVisualOffsets(r);n={x:e.x-a.x,y:e.y-a.y,width:e.width,height:e.height}}return rectToClientRect(n)}function getClippingElementAncestors(r,e){const t=e.get(r);if(t)return t;let n=getOverflowAncestors(r,[],!1).filter(s=>isElement(s)&&getNodeName(s)!=="body"),a=null;const i=getComputedStyle$1(r).position==="fixed";let o=i?getParentNode(r):r;for(;isElement(o)&&!isLastTraversableNode(o);){const s=getComputedStyle$1(o),d=isContainingBlock(o),u=a?a.position:i?"fixed":"";!d&&(u==="fixed"||u==="absolute"&&s.position==="static")?n=n.filter(p=>p!==o):a=s,o=getParentNode(o)}return e.set(r,n),n}function getClippingRect(r){let{element:e,boundary:t,rootBoundary:n,strategy:a}=r;const o=[...t==="clippingAncestors"?isTopLayer(e)?[]:getClippingElementAncestors(e,this._c):[].concat(t),n],s=getClientRectFromClippingAncestor(e,o[0],a);let d=s.top,u=s.right,c=s.bottom,p=s.left;for(let _=1;_<o.length;_++){const m=getClientRectFromClippingAncestor(e,o[_],a);d=max$1(m.top,d),u=min(m.right,u),c=min(m.bottom,c),p=max$1(m.left,p)}return{width:u-p,height:c-d,x:p,y:d}}function getDimensions(r){const{width:e,height:t}=getCssDimensions(r);return{width:e,height:t}}function getRectRelativeToOffsetParent(r,e,t){const n=isHTMLElement(e),a=getDocumentElement(e),i=t==="fixed",o=getBoundingClientRect(r,!0,i,e);let s={scrollLeft:0,scrollTop:0};const d=createCoords(0);if((n||!i)&&((getNodeName(e)!=="body"||isOverflowElement(a))&&(s=getNodeScroll(e)),n)){const _=getBoundingClientRect(e,!0,i,e);d.x=_.x+e.clientLeft,d.y=_.y+e.clientTop}!n&&a&&(d.x=getWindowScrollBarX(a));const u=a&&!n&&!i?getHTMLOffset(a,s):createCoords(0),c=o.left+s.scrollLeft-d.x-u.x,p=o.top+s.scrollTop-d.y-u.y;return{x:c,y:p,width:o.width,height:o.height}}function isStaticPositioned(r){return getComputedStyle$1(r).position==="static"}function getTrueOffsetParent(r,e){if(!isHTMLElement(r)||getComputedStyle$1(r).position==="fixed")return null;if(e)return e(r);let t=r.offsetParent;return getDocumentElement(r)===t&&(t=t.ownerDocument.body),t}function getOffsetParent(r,e){const t=getWindow(r);if(isTopLayer(r))return t;if(!isHTMLElement(r)){let a=getParentNode(r);for(;a&&!isLastTraversableNode(a);){if(isElement(a)&&!isStaticPositioned(a))return a;a=getParentNode(a)}return t}let n=getTrueOffsetParent(r,e);for(;n&&isTableElement(n)&&isStaticPositioned(n);)n=getTrueOffsetParent(n,e);return n&&isLastTraversableNode(n)&&isStaticPositioned(n)&&!isContainingBlock(n)?t:n||getContainingBlock(r)||t}const getElementRects=async function(r){const e=this.getOffsetParent||getOffsetParent,t=this.getDimensions,n=await t(r.floating);return{reference:getRectRelativeToOffsetParent(r.reference,await e(r.floating),r.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function isRTL(r){return getComputedStyle$1(r).direction==="rtl"}const platform={convertOffsetParentRelativeRectToViewportRelativeRect,getDocumentElement,getClippingRect,getOffsetParent,getElementRects,getClientRects,getDimensions,getScale,isElement,isRTL};function rectsAreEqual(r,e){return r.x===e.x&&r.y===e.y&&r.width===e.width&&r.height===e.height}function observeMove(r,e,t){let n=null,a;const i=getDocumentElement(r);function o(){var c;clearTimeout(a),(c=n)==null||c.disconnect(),n=null}function s(c,p){c===void 0&&(c=!1),p===void 0&&(p=1),o();const _=r.getBoundingClientRect(),{left:m,top:S,width:A,height:h}=_;if(c||e(),!A||!h)return;const T=floor(S),w=floor(i.clientWidth-(m+A)),b=floor(i.clientHeight-(S+h)),N=floor(m),X={rootMargin:-T+"px "+-w+"px "+-b+"px "+-N+"px",threshold:max$1(0,min(1,p))||1};let ee=!0;function V(U){const v=U[0].intersectionRatio;if(!rectsAreEqual(_,r.getBoundingClientRect()))return s();if(v!==p){if(!ee)return s();v?s(!1,v):a=setTimeout(()=>{s(!1,1e-7)},1e3)}ee=!1}try{n=new IntersectionObserver(V,{...X,root:i.ownerDocument})}catch{n=new IntersectionObserver(V,X)}n.observe(r)}const d=getWindow(r),u=()=>s(t);return d.addEventListener("resize",u),s(!0),()=>{d.removeEventListener("resize",u),o()}}function autoUpdate(r,e,t,n){n===void 0&&(n={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:d=!1}=n,u=unwrapElement(r),c=a||i?[...u?getOverflowAncestors(u):[],...e?getOverflowAncestors(e):[]]:[];c.forEach(T=>{a&&T.addEventListener("scroll",t),i&&T.addEventListener("resize",t)});const p=u&&s?observeMove(u,t,i):null;let _=-1,m=null;o&&(m=new ResizeObserver(T=>{let[w]=T;w&&w.target===u&&m&&e&&(m.unobserve(e),cancelAnimationFrame(_),_=requestAnimationFrame(()=>{var b;(b=m)==null||b.observe(e)})),t()}),u&&!d&&m.observe(u),e&&m.observe(e));let S,A=d?getBoundingClientRect(r):null;d&&h();function h(){const T=getBoundingClientRect(r);A&&!rectsAreEqual(A,T)&&t(),A=T,S=requestAnimationFrame(h)}return t(),()=>{var T;c.forEach(w=>{a&&w.removeEventListener("scroll",t),i&&w.removeEventListener("resize",t)}),p?.(),(T=m)==null||T.disconnect(),m=null,d&&cancelAnimationFrame(S)}}const offset$1=offset$2,shift$1=shift$2,flip$1=flip$2,size$1=size$2,hide$1=hide$2,arrow$2=arrow$3,limitShift$1=limitShift$2,computePosition=(r,e,t)=>{const n=new Map,a=t??{},i={...platform,...a.platform,_c:n};return computePosition$1(r,e,{...a,platform:i})};var isClient=typeof document<"u",noop$8=function(){},index$6=isClient?reactExports.useLayoutEffect:noop$8;function deepEqual$1(r,e){if(r===e)return!0;if(typeof r!=typeof e)return!1;if(typeof r=="function"&&r.toString()===e.toString())return!0;let t,n,a;if(r&&e&&typeof r=="object"){if(Array.isArray(r)){if(t=r.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!deepEqual$1(r[n],e[n]))return!1;return!0}if(a=Object.keys(r),t=a.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,a[n]))return!1;for(n=t;n--!==0;){const i=a[n];if(!(i==="_owner"&&r.$$typeof)&&!deepEqual$1(r[i],e[i]))return!1}return!0}return r!==r&&e!==e}function getDPR(r){return typeof window>"u"?1:(r.ownerDocument.defaultView||window).devicePixelRatio||1}function roundByDPR(r,e){const t=getDPR(r);return Math.round(e*t)/t}function useLatestRef(r){const e=reactExports.useRef(r);return index$6(()=>{e.current=r}),e}function useFloating(r){r===void 0&&(r={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:a,elements:{reference:i,floating:o}={},transform:s=!0,whileElementsMounted:d,open:u}=r,[c,p]=reactExports.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[_,m]=reactExports.useState(n);deepEqual$1(_,n)||m(n);const[S,A]=reactExports.useState(null),[h,T]=reactExports.useState(null),w=reactExports.useCallback(D=>{D!==X.current&&(X.current=D,A(D))},[]),b=reactExports.useCallback(D=>{D!==ee.current&&(ee.current=D,T(D))},[]),N=i||S,O=o||h,X=reactExports.useRef(null),ee=reactExports.useRef(null),V=reactExports.useRef(c),U=d!=null,v=useLatestRef(d),x=useLatestRef(a),I=useLatestRef(u),E=reactExports.useCallback(()=>{if(!X.current||!ee.current)return;const D={placement:e,strategy:t,middleware:_};x.current&&(D.platform=x.current),computePosition(X.current,ee.current,D).then(ne=>{const y={...ne,isPositioned:I.current!==!1};Q.current&&!deepEqual$1(V.current,y)&&(V.current=y,reactDomExports.flushSync(()=>{p(y)}))})},[_,e,t,x,I]);index$6(()=>{u===!1&&V.current.isPositioned&&(V.current.isPositioned=!1,p(D=>({...D,isPositioned:!1})))},[u]);const Q=reactExports.useRef(!1);index$6(()=>(Q.current=!0,()=>{Q.current=!1}),[]),index$6(()=>{if(N&&(X.current=N),O&&(ee.current=O),N&&O){if(v.current)return v.current(N,O,E);E()}},[N,O,E,v,U]);const K=reactExports.useMemo(()=>({reference:X,floating:ee,setReference:w,setFloating:b}),[w,b]),te=reactExports.useMemo(()=>({reference:N,floating:O}),[N,O]),se=reactExports.useMemo(()=>{const D={position:t,left:0,top:0};if(!te.floating)return D;const ne=roundByDPR(te.floating,c.x),y=roundByDPR(te.floating,c.y);return s?{...D,transform:"translate("+ne+"px, "+y+"px)",...getDPR(te.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:ne,top:y}},[t,s,te.floating,c.x,c.y]);return reactExports.useMemo(()=>({...c,update:E,refs:K,elements:te,floatingStyles:se}),[c,E,K,te,se])}const arrow$1=r=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:r,fn(t){const{element:n,padding:a}=typeof r=="function"?r(t):r;return n&&e(n)?n.current!=null?arrow$2({element:n.current,padding:a}).fn(t):{}:n?arrow$2({element:n,padding:a}).fn(t):{}}}},offset=(r,e)=>{const t=offset$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},shift=(r,e)=>{const t=shift$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},limitShift=(r,e)=>({fn:limitShift$1(r).fn,options:[r,e]}),flip=(r,e)=>{const t=flip$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},size=(r,e)=>{const t=size$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},hide=(r,e)=>{const t=hide$1(r);return{name:t.name,fn:t.fn,options:[r,e]}},arrow=(r,e)=>{const t=arrow$1(r);return{name:t.name,fn:t.fn,options:[r,e]}};var __defProp$3=Object.defineProperty,__name$3=(r,e)=>__defProp$3(r,"name",{value:e,configurable:!0});function useSize(r){const[e,t]=reactExports.useState(void 0);return useLayoutEffect2(()=>{if(r){t({width:r.offsetWidth,height:r.offsetHeight});const n=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let o,s;if("borderBoxSize"in i){const d=i.borderBoxSize,u=Array.isArray(d)?d[0]:d;o=u.inlineSize,s=u.blockSize}else o=r.offsetWidth,s=r.offsetHeight;t({width:o,height:s})});return n.observe(r,{box:"border-box"}),()=>n.unobserve(r)}else t(void 0)},[r]),e}__name$3(useSize,"useSize");var __defProp$2=Object.defineProperty,__name$2=(r,e)=>__defProp$2(r,"name",{value:e,configurable:!0}),POPPER_NAME="Popper",[createPopperContext,createPopperScope]=createContextScope(POPPER_NAME),[PopperProvider,usePopperContext]=createPopperContext(POPPER_NAME),Popper=__name$2(r=>{const{__scopePopper:e,children:t}=r,[n,a]=reactExports.useState(null),[i,o]=reactExports.useState(void 0);return jsxRuntimeExports.jsx(PopperProvider,{scope:e,anchor:n,onAnchorChange:a,placementState:i,setPlacementState:o,children:t})},"Popper"),ANCHOR_NAME="PopperAnchor",PopperAnchor=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:n,virtualRef:a,...i}=e,o=usePopperContext(ANCHOR_NAME,n),s=reactExports.useRef(null),d=o.onAnchorChange,u=reactExports.useCallback(A=>{s.current=A,A&&d(A)},[d]),c=useComposedRefs(t,u),p=reactExports.useRef(null);reactExports.useEffect(()=>{if(!a)return;const A=p.current;p.current=a.current,A!==p.current&&d(p.current)});const _=o.placementState&&getSideAndAlignFromPlacement(o.placementState),m=_?.[0],S=_?.[1];return a?null:jsxRuntimeExports.jsx(Primitive.div,{"data-radix-popper-side":m,"data-radix-popper-align":S,...i,ref:c})},"PopperAnchor")),CONTENT_NAME$1="PopperContent",[PopperContentProvider,useContentContext]=createPopperContext(CONTENT_NAME$1),PopperContent=reactExports.forwardRef(__name$2(function(e,t){const{__scopePopper:n,side:a="bottom",sideOffset:i=0,align:o="center",alignOffset:s=0,arrowPadding:d=0,avoidCollisions:u=!0,collisionBoundary:c=[],collisionPadding:p=0,sticky:_="partial",hideWhenDetached:m=!1,updatePositionStrategy:S="optimized",onPlaced:A,...h}=e,T=usePopperContext(CONTENT_NAME$1,n),[w,b]=reactExports.useState(null),N=useComposedRefs(t,b),[O,X]=reactExports.useState(null),ee=useSize(O),V=ee?.width??0,U=ee?.height??0,v=a+(o!=="center"?"-"+o:""),x=typeof p=="number"?p:{top:0,right:0,bottom:0,left:0,...p},I=Array.isArray(c)?c:[c],E=I.length>0,Q={padding:x,boundary:I.filter(isNotNull),altBoundary:E},{refs:K,floatingStyles:te,placement:se,isPositioned:D,middlewareData:ne}=useFloating({strategy:"fixed",placement:v,whileElementsMounted:__name$2((...M)=>autoUpdate(...M,{animationFrame:S==="always"}),"whileElementsMounted"),elements:{reference:T.anchor},middleware:[offset({mainAxis:i+U,alignmentAxis:s}),u&&shift({mainAxis:!0,crossAxis:!1,limiter:_==="partial"?limitShift():void 0,...Q}),u&&flip({...Q}),size({...Q,apply:__name$2(({elements:M,rects:Z,availableWidth:z,availableHeight:G})=>{const{width:g,height:R}=Z.reference,q=M.floating.style;q.setProperty("--radix-popper-available-width",`${z}px`),q.setProperty("--radix-popper-available-height",`${G}px`),q.setProperty("--radix-popper-anchor-width",`${g}px`),q.setProperty("--radix-popper-anchor-height",`${R}px`)},"apply")}),O&&arrow({element:O,padding:d}),transformOrigin({arrowWidth:V,arrowHeight:U}),m&&hide({strategy:"referenceHidden",...Q,boundary:E?Q.boundary:void 0})]}),y=T.setPlacementState;useLayoutEffect2(()=>(y(se),()=>{y(void 0)}),[se,y]);const[C,re]=getSideAndAlignFromPlacement(se),F=useCallbackRef(A);useLayoutEffect2(()=>{D&&F?.()},[D,F]);const ie=ne.arrow?.x,oe=ne.arrow?.y,le=ne.arrow?.centerOffset!==0,[ue,P]=reactExports.useState();return useLayoutEffect2(()=>{w&&P(window.getComputedStyle(w).zIndex)},[w]),jsxRuntimeExports.jsx("div",{ref:K.setFloating,"data-radix-popper-content-wrapper":"",style:{...te,transform:D?te.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ue,"--radix-popper-transform-origin":[ne.transformOrigin?.x,ne.transformOrigin?.y].join(" "),...ne.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:jsxRuntimeExports.jsx(PopperContentProvider,{scope:n,placedSide:C,placedAlign:re,onArrowChange:X,arrowX:ie,arrowY:oe,shouldHideArrow:le,children:jsxRuntimeExports.jsx(Primitive.div,{"data-side":C,"data-align":re,...h,ref:N,style:{...h.style,animation:D?h.style?.animation:"none"}})})})},"PopperContent"));function isNotNull(r){return r!==null}__name$2(isNotNull,"isNotNull");var transformOrigin=__name$2(r=>({name:"transformOrigin",options:r,fn(e){const{placement:t,rects:n,middlewareData:a}=e,o=a.arrow?.centerOffset!==0,s=o?0:r.arrowWidth,d=o?0:r.arrowHeight,[u,c]=getSideAndAlignFromPlacement(t),p={start:"0%",center:"50%",end:"100%"}[c],_=(a.arrow?.x??0)+s/2,m=(a.arrow?.y??0)+d/2;let S="",A="";return u==="bottom"?(S=o?p:`${_}px`,A=`${-d}px`):u==="top"?(S=o?p:`${_}px`,A=`${n.floating.height+d}px`):u==="right"?(S=`${-d}px`,A=o?p:`${m}px`):u==="left"&&(S=`${n.floating.width+d}px`,A=o?p:`${m}px`),{data:{x:S,y:A}}}}),"transformOrigin");function getSideAndAlignFromPlacement(r){const[e,t="center"]=r.split("-");return[e,t]}__name$2(getSideAndAlignFromPlacement,"getSideAndAlignFromPlacement");var Root2=Popper,Anchor=PopperAnchor,Content=PopperContent,__defProp$1=Object.defineProperty,__name$1=(r,e)=>__defProp$1(r,"name",{value:e,configurable:!0}),VISUALLY_HIDDEN_STYLES=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),VisuallyHidden=reactExports.forwardRef(__name$1(function(e,t){return jsxRuntimeExports.jsx(Primitive.span,{...e,ref:t,style:{...VISUALLY_HIDDEN_STYLES,...e.style}})},"VisuallyHidden")),Root=VisuallyHidden,__defProp=Object.defineProperty,__name=(r,e)=>__defProp(r,"name",{value:e,configurable:!0}),[createTooltipContext,createTooltipScope]=createContextScope("Tooltip",[createPopperScope]),usePopperScope=createPopperScope(),PROVIDER_NAME="TooltipProvider",DEFAULT_DELAY_DURATION=700,TOOLTIP_OPEN="tooltip.open",[TooltipProviderContextProvider,useTooltipProviderContext]=createTooltipContext(PROVIDER_NAME),TooltipProvider$1=__name(r=>{const{__scopeTooltip:e,delayDuration:t=DEFAULT_DELAY_DURATION,skipDelayDuration:n=300,disableHoverableContent:a=!1,children:i}=r,o=reactExports.useRef(!0),s=reactExports.useRef(!1),d=reactExports.useRef(0);return reactExports.useEffect(()=>{const u=d.current;return()=>window.clearTimeout(u)},[]),jsxRuntimeExports.jsx(TooltipProviderContextProvider,{scope:e,isOpenDelayedRef:o,delayDuration:t,onOpen:reactExports.useCallback(()=>{n<=0||(window.clearTimeout(d.current),o.current=!1)},[n]),onClose:reactExports.useCallback(()=>{n<=0||(window.clearTimeout(d.current),d.current=window.setTimeout(()=>o.current=!0,n))},[n]),isPointerInTransitRef:s,onPointerInTransitChange:reactExports.useCallback(u=>{s.current=u},[]),disableHoverableContent:a,children:i})},"TooltipProvider"),TOOLTIP_NAME="Tooltip",[TooltipContextProvider,useTooltipContext]=createTooltipContext(TOOLTIP_NAME),Tooltip$1=__name(r=>{const{__scopeTooltip:e,children:t,open:n,defaultOpen:a,onOpenChange:i,disableHoverableContent:o,delayDuration:s}=r,d=useTooltipProviderContext(TOOLTIP_NAME,r.__scopeTooltip),u=usePopperScope(e),[c,p]=reactExports.useState(null),[_,m]=reactExports.useState(void 0),S=useId(),A=reactExports.useRef(0),h=o??d.disableHoverableContent,T=s??d.delayDuration,w=reactExports.useRef(!1),[b,N]=useControllableState({prop:n,defaultProp:a??!1,onChange:__name(v=>{v?(d.onOpen(),document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN))):d.onClose(),i?.(v)},"onChange"),caller:TOOLTIP_NAME}),O=reactExports.useMemo(()=>b?w.current?"delayed-open":"instant-open":"closed",[b]),X=reactExports.useCallback(()=>{window.clearTimeout(A.current),A.current=0,w.current=!1,N(!0)},[N]),ee=reactExports.useCallback(()=>{window.clearTimeout(A.current),A.current=0,N(!1)},[N]),V=reactExports.useCallback(()=>{window.clearTimeout(A.current),A.current=window.setTimeout(()=>{w.current=!0,N(!0),A.current=0},T)},[T,N]);reactExports.useEffect(()=>()=>{A.current&&(window.clearTimeout(A.current),A.current=0)},[]);const U=_??S;return jsxRuntimeExports.jsx(Root2,{...u,children:jsxRuntimeExports.jsx(TooltipContextProvider,{scope:e,contentId:U,setContentId:m,open:b,stateAttribute:O,trigger:c,onTriggerChange:p,onTriggerEnter:reactExports.useCallback(()=>{d.isOpenDelayedRef.current?V():X()},[d.isOpenDelayedRef,V,X]),onTriggerLeave:reactExports.useCallback(()=>{h?ee():(window.clearTimeout(A.current),A.current=0)},[ee,h]),onOpen:X,onClose:ee,disableHoverableContent:h,children:t})})},"Tooltip"),TRIGGER_NAME="TooltipTrigger",TooltipTrigger$1=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:n,...a}=e,i=useTooltipContext(TRIGGER_NAME,n),o=useTooltipProviderContext(TRIGGER_NAME,n),s=usePopperScope(n),d=reactExports.useRef(null),u=useComposedRefs(t,d,i.onTriggerChange),c=reactExports.useRef(!1),p=reactExports.useRef(!1),_=reactExports.useCallback(()=>c.current=!1,[]);return reactExports.useEffect(()=>()=>document.removeEventListener("pointerup",_),[_]),jsxRuntimeExports.jsx(Anchor,{asChild:!0,...s,children:jsxRuntimeExports.jsx(Primitive.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...a,ref:u,onPointerMove:composeEventHandlers(e.onPointerMove,m=>{m.pointerType!=="touch"&&!p.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),p.current=!0)}),onPointerLeave:composeEventHandlers(e.onPointerLeave,()=>{i.onTriggerLeave(),p.current=!1}),onPointerDown:composeEventHandlers(e.onPointerDown,()=>{i.open&&i.onClose(),c.current=!0,document.addEventListener("pointerup",_,{once:!0})}),onFocus:composeEventHandlers(e.onFocus,()=>{c.current||i.onOpen()}),onBlur:composeEventHandlers(e.onBlur,i.onClose),onClick:composeEventHandlers(e.onClick,i.onClose)})})},"TooltipTrigger")),PORTAL_NAME="TooltipPortal",[PortalProvider,usePortalContext]=createTooltipContext(PORTAL_NAME,{forceMount:void 0}),TooltipPortal$1=__name(r=>{const{__scopeTooltip:e,forceMount:t,children:n,container:a}=r,i=useTooltipContext(PORTAL_NAME,e);return jsxRuntimeExports.jsx(PortalProvider,{scope:e,forceMount:t,children:jsxRuntimeExports.jsx(Presence,{present:t||i.open,children:jsxRuntimeExports.jsx(Portal$1,{asChild:!0,container:a,children:n})})})},"TooltipPortal"),CONTENT_NAME="TooltipContent",TooltipContent$1=reactExports.forwardRef(__name(function(e,t){const n=usePortalContext(CONTENT_NAME,e.__scopeTooltip),{forceMount:a=n.forceMount,side:i="top",...o}=e,s=useTooltipContext(CONTENT_NAME,e.__scopeTooltip);return jsxRuntimeExports.jsx(Presence,{present:a||s.open,children:s.disableHoverableContent?jsxRuntimeExports.jsx(TooltipContentImpl,{side:i,...o,ref:t}):jsxRuntimeExports.jsx(TooltipContentHoverable,{side:i,...o,ref:t})})},"TooltipContent")),TooltipContentHoverable=reactExports.forwardRef(__name(function(e,t){const n=useTooltipContext(CONTENT_NAME,e.__scopeTooltip),a=useTooltipProviderContext(CONTENT_NAME,e.__scopeTooltip),i=reactExports.useRef(null),o=useComposedRefs(t,i),[s,d]=reactExports.useState(null),{trigger:u,onClose:c}=n,p=i.current,{onPointerInTransitChange:_}=a,m=reactExports.useCallback(()=>{d(null),_(!1)},[_]),S=reactExports.useCallback((A,h)=>{const T=A.currentTarget,w={x:A.clientX,y:A.clientY},b=getExitSideFromRect(w,T.getBoundingClientRect()),N=getPaddedExitPoints(w,b),O=getPointsFromRect(h.getBoundingClientRect()),X=getHull([...N,...O]);d(X),_(!0)},[_]);return reactExports.useEffect(()=>()=>m(),[m]),reactExports.useEffect(()=>{if(u&&p){const A=__name(T=>S(T,p),"handleTriggerLeave"),h=__name(T=>S(T,u),"handleContentLeave");return u.addEventListener("pointerleave",A),p.addEventListener("pointerleave",h),()=>{u.removeEventListener("pointerleave",A),p.removeEventListener("pointerleave",h)}}},[u,p,S,m]),reactExports.useEffect(()=>{if(s){const A=__name(h=>{const T=h.target,w={x:h.clientX,y:h.clientY},b=u?.contains(T)||p?.contains(T),N=!isPointInPolygon(w,s);b?m():N&&(m(),c())},"handleTrackPointerGrace");return document.addEventListener("pointermove",A),()=>document.removeEventListener("pointermove",A)}},[u,p,s,c,m]),jsxRuntimeExports.jsx(TooltipContentImpl,{...e,ref:o})},"TooltipContentHoverable")),Slottable=createSlottable("TooltipContent"),TooltipContentImpl=reactExports.forwardRef(__name(function(e,t){const{__scopeTooltip:n,children:a,"aria-label":i,id:o,onEscapeKeyDown:s,onPointerDownOutside:d,...u}=e,c=useTooltipContext(CONTENT_NAME,n),p=usePopperScope(n),{onClose:_}=c;reactExports.useEffect(()=>(document.addEventListener(TOOLTIP_OPEN,_),()=>document.removeEventListener(TOOLTIP_OPEN,_)),[_]),reactExports.useEffect(()=>{if(c.trigger){const S=__name(A=>{A.target instanceof Node&&A.target.contains(c.trigger)&&_()},"handleScroll");return window.addEventListener("scroll",S,{capture:!0}),()=>window.removeEventListener("scroll",S,{capture:!0})}},[c.trigger,_]);const{setContentId:m}=c;return useLayoutEffect2(()=>(m(o),()=>{m(void 0)}),[o,m]),jsxRuntimeExports.jsx(DismissableLayer,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:d,onFocusOutside:S=>S.preventDefault(),onDismiss:_,children:jsxRuntimeExports.jsxs(Content,{"data-state":c.stateAttribute,role:i?void 0:"tooltip",id:i?void 0:c.contentId,...p,...u,ref:t,style:{...u.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[jsxRuntimeExports.jsx(Slottable,{children:a}),i?jsxRuntimeExports.jsx(Root,{id:c.contentId,role:"tooltip",children:i}):null]})})},"TooltipContentImpl"));function getExitSideFromRect(r,e){const t=Math.abs(e.top-r.y),n=Math.abs(e.bottom-r.y),a=Math.abs(e.right-r.x),i=Math.abs(e.left-r.x);switch(Math.min(t,n,a,i)){case i:return"left";case a:return"right";case t:return"top";case n:return"bottom";default:throw new Error("unreachable")}}__name(getExitSideFromRect,"getExitSideFromRect");function getPaddedExitPoints(r,e,t=5){const n=[];switch(e){case"top":n.push({x:r.x-t,y:r.y+t},{x:r.x+t,y:r.y+t});break;case"bottom":n.push({x:r.x-t,y:r.y-t},{x:r.x+t,y:r.y-t});break;case"left":n.push({x:r.x+t,y:r.y-t},{x:r.x+t,y:r.y+t});break;case"right":n.push({x:r.x-t,y:r.y-t},{x:r.x-t,y:r.y+t});break}return n}__name(getPaddedExitPoints,"getPaddedExitPoints");function getPointsFromRect(r){const{top:e,right:t,bottom:n,left:a}=r;return[{x:a,y:e},{x:t,y:e},{x:t,y:n},{x:a,y:n}]}__name(getPointsFromRect,"getPointsFromRect");function isPointInPolygon(r,e){const{x:t,y:n}=r;let a=!1;for(let i=0,o=e.length-1;i<e.length;o=i++){const s=e[i],d=e[o],u=s.x,c=s.y,p=d.x,_=d.y;c>n!=_>n&&t<(p-u)*(n-c)/(_-c)+u&&(a=!a)}return a}__name(isPointInPolygon,"isPointInPolygon");function getHull(r){const e=r.slice();return e.sort((t,n)=>t.x<n.x?-1:t.x>n.x?1:t.y<n.y?-1:t.y>n.y?1:0),getHullPresorted(e)}__name(getHull,"getHull");function getHullPresorted(r){if(r.length<=1)return r.slice();const e=[];for(let n=0;n<r.length;n++){const a=r[n];for(;e.length>=2;){const i=e[e.length-1],o=e[e.length-2];if((i.x-o.x)*(a.y-o.y)>=(i.y-o.y)*(a.x-o.x))e.pop();else break}e.push(a)}e.pop();const t=[];for(let n=r.length-1;n>=0;n--){const a=r[n];for(;t.length>=2;){const i=t[t.length-1],o=t[t.length-2];if((i.x-o.x)*(a.y-o.y)>=(i.y-o.y)*(a.x-o.x))t.pop();else break}t.push(a)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}__name(getHullPresorted,"getHullPresorted");var Provider=TooltipProvider$1,Root3=Tooltip$1,Trigger=TooltipTrigger$1,Portal=TooltipPortal$1,Content2=TooltipContent$1;const TooltipProvider=Provider,Tooltip=Root3,TooltipTrigger=Trigger,TooltipPortal=Portal,TooltipContent=reactExports.forwardRef(({className:r,sideOffset:e=4,...t},n)=>jsxRuntimeExports.jsx(Content2,{ref:n,sideOffset:e,className:cn("z-[var(--layer-popover)] overflow-hidden rounded-md border border-border/50 bg-popover","px-2 py-1 text-xs text-popover-foreground shadow-md","animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2","data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r),...t}));TooltipContent.displayName=Content2.displayName;function BrandInfo({logo:r,info:e,infoLabel:t="Details",className:n}){const[a,i]=reactExports.useState(!1),o=reactExports.useRef(null);return jsxRuntimeExports.jsxs("div",{className:cn("inline-flex min-w-0 items-center gap-1",n),children:[r,e!=null&&e!==!1?jsxRuntimeExports.jsx(TooltipProvider,{delayDuration:150,children:jsxRuntimeExports.jsxs(Tooltip,{open:a,onOpenChange:i,children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("button",{ref:o,type:"button","aria-label":t,"aria-expanded":a,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-primary/10 hover:text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary",onPointerDown:s=>s.preventDefault(),onClick:s=>{s.preventDefault(),i(d=>!d)},children:jsxRuntimeExports.jsx(Info,{className:"h-4 w-4","aria-hidden":"true"})})}),jsxRuntimeExports.jsx(TooltipPortal,{children:jsxRuntimeExports.jsx(TooltipContent,{side:"bottom",align:"center",collisionPadding:12,onPointerDownOutside:s=>{s.target instanceof Node&&o.current?.contains(s.target)&&s.preventDefault()},className:"max-w-[min(320px,calc(100vw-24px))] space-y-2 p-3 text-left leading-relaxed [overflow-wrap:anywhere]",children:e})})]})}):null]})}const Checkbox=reactExports.forwardRef(({className:r,indeterminate:e=!1,...t},n)=>{const a=reactExports.useRef(null);return reactExports.useImperativeHandle(n,()=>a.current),reactExports.useEffect(()=>{a.current&&(a.current.indeterminate=e)}),jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0 items-center justify-center align-middle",children:[jsxRuntimeExports.jsx("input",{...t,ref:a,type:"checkbox",className:cn("peer m-0 h-4 w-4 shrink-0 appearance-none rounded border border-input bg-background checked:border-primary checked:bg-primary checked:bg-none indeterminate:border-primary indeterminate:bg-primary indeterminate:bg-none disabled:cursor-not-allowed disabled:opacity-50",controlFocusClass,r)}),jsxRuntimeExports.jsx(Check,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-checked:block peer-indeterminate:hidden peer-disabled:opacity-50",strokeWidth:3}),jsxRuntimeExports.jsx(Minus,{"aria-hidden":"true",className:"pointer-events-none absolute hidden h-3 w-3 text-primary-foreground peer-indeterminate:block peer-disabled:opacity-50",strokeWidth:3})]})});Checkbox.displayName="Checkbox";function FormField({label:r,error:e,hint:t,labelAside:n,children:a,className:i,...o}){const s=reactExports.useId(),d=`${s}-error`,u=`${s}-hint`,c=[e?d:void 0,t?u:void 0].filter(Boolean).join(" ")||void 0;return jsxRuntimeExports.jsxs("div",{...o,className:cn("flex flex-col gap-1.5",i),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("label",{htmlFor:s,className:"text-[13px] font-medium text-foreground",children:r}),n]}),a({id:s,...e?{"aria-invalid":!0}:{},"aria-describedby":c}),e?jsxRuntimeExports.jsx("p",{id:d,role:"alert",className:"text-[13px] text-destructive",children:e}):null,t?jsxRuntimeExports.jsx("div",{id:u,className:"text-[13px] text-muted-foreground",children:t}):null]})}const EmailInput=reactExports.forwardRef(({onInput:r,onChange:e,autoCapitalize:t="none",spellCheck:n=!1,...a},i)=>{const o=reactExports.useRef(null),s=reactExports.useRef(null);reactExports.useImperativeHandle(i,()=>o.current,[]);const d=reactExports.useCallback(c=>{const p=s.current??(s.current=c.ownerDocument.createElement("input"));p.type="email",p.multiple=c.multiple,p.required=c.required,p.value=c.value,c.setCustomValidity(p.validity.valid?"":p.validationMessage)},[]);reactExports.useLayoutEffect(()=>{o.current&&d(o.current)}),reactExports.useEffect(()=>{const c=o.current,p=c?.form;if(!c||!p)return;const _=()=>queueMicrotask(()=>d(c));return p.addEventListener("reset",_),()=>p.removeEventListener("reset",_)},[a.form,d]);const u=c=>{d(c),queueMicrotask(()=>d(c))};return jsxRuntimeExports.jsx(Input,{...a,ref:o,type:"text",inputMode:"email",autoCapitalize:t,spellCheck:n,onInput:c=>{u(c.currentTarget),r?.(c)},onChange:c=>{u(c.currentTarget),e?.(c)}})});EmailInput.displayName="EmailInput";const FOCUSABLE=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","summary",'[tabindex]:not([tabindex="-1"])'].join(","),PRIMARY_SELECTOR="[data-pod-sign-in-primary]";function isReachable(r){if(r.hidden||r.closest("[hidden]")||r.matches(":disabled"))return!1;const e=r.ownerDocument.defaultView?.getComputedStyle(r);if(e&&(e.display==="none"||e.visibility==="hidden"))return!1;for(let t=r.parentElement;t;t=t.parentElement){if(t.tagName!=="DETAILS"||t.open)continue;const n=Array.from(t.children).find(a=>a.tagName==="SUMMARY");if(!n||!(n===r||n.contains(r)))return!1}return!0}function useModalFocus(r,e){const t=reactExports.useRef(null),n=reactExports.useRef(e);return n.current=e,reactExports.useEffect(()=>{if(!r)return;const a=document.activeElement instanceof HTMLElement?document.activeElement:null;t.current?.focus();const i=o=>{if(o.key==="Escape"&&n.current){o.preventDefault(),n.current();return}if(o.key!=="Tab")return;const s=t.current;if(!s)return;const d=Array.from(s.querySelectorAll(FOCUSABLE)).filter(isReachable);if(d.length===0){o.preventDefault(),s.focus();return}const u=d.indexOf(document.activeElement);if(!o.shiftKey&&document.activeElement===s){const p=d.find(_=>_.matches(PRIMARY_SELECTOR));if(p){o.preventDefault(),p.focus();return}}const c=o.shiftKey?u<=0?d.length-1:u-1:u===d.length-1?0:u+1;o.preventDefault(),d[c]?.focus()};return document.addEventListener("keydown",i),()=>{document.removeEventListener("keydown",i),a?.focus()}},[r]),t}const bodyClass="flex min-h-0 w-full max-w-[480px] flex-1 flex-col";function PodSignInFrame({presentation:r,ariaLabel:e,appIntro:t,children:n,modal:a=!0,onClose:i,closeLabel:o,dataAttributes:s}){const d=r==="dialog"&&a,u=useModalFocus(d,i),c=t;if(r==="window")return jsxRuntimeExports.jsx("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"window",...s,className:"pod-sign-in flex h-full min-h-0 w-full min-w-0 justify-center overflow-hidden bg-background text-foreground",children:jsxRuntimeExports.jsx("div",{className:bodyClass,children:n})});if(r==="page")return jsxRuntimeExports.jsxs("div",{role:"region","aria-label":e,"data-pod-sign-in-frame":"page",...s,className:"pod-sign-in grid min-h-[100dvh] w-full bg-background text-foreground md:grid-cols-2",children:[c?jsxRuntimeExports.jsx("aside",{"data-pod-sign-in":"intro",className:"hidden flex-col justify-center gap-6 bg-[hsl(var(--sunken))] px-12 py-10 md:flex",children:c}):null,jsxRuntimeExports.jsx("div",{className:cn("flex min-w-0 items-center justify-center px-4 py-8",c?"":"md:col-span-2"),children:jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"min-h-[520px]"),children:n})})]});const p=jsxRuntimeExports.jsxs("div",{ref:u,role:d?"dialog":"region","aria-modal":d?!0:void 0,"aria-label":e,tabIndex:-1,"data-pod-sign-in-frame":"dialog",...s,className:cn("pod-sign-in relative flex min-h-[min(440px,90dvh)] max-h-[90dvh] w-[min(480px,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-lg focus:outline-none motion-safe:animate-in motion-safe:fade-in-0"),children:[d&&i&&o?jsxRuntimeExports.jsx("button",{type:"button","aria-label":o,className:"absolute right-2 top-2 flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",onClick:i,children:jsxRuntimeExports.jsx("span",{"aria-hidden":"true",children:"×"})}):null,jsxRuntimeExports.jsx("div",{className:cn(bodyClass,"mx-auto"),children:n})]});return d?jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[var(--layer-modal)] flex items-center justify-center bg-background/80 p-4",children:p}):jsxRuntimeExports.jsx("div",{className:"flex w-full items-center justify-center p-4",children:p})}function StorageBadge({kind:r,label:e}){const t=r==="cloud"?Cloud:Laptop;return jsxRuntimeExports.jsx("span",{role:"img","aria-label":e,title:e,"data-storage-kind":r,className:"flex h-[18px] w-[18px] items-center justify-center rounded-full border border-background bg-card text-foreground",children:jsxRuntimeExports.jsx(t,{"aria-hidden":"true",className:"h-3 w-3"})})}const zhCN={restoring:"正在恢复登录…",enterApp:"进入 {app}",reauthenticate:"重新登录",useAnother:"使用其他账号",expiredLine:"登录已过期,需要重新确认",chooseTitle:"登录",chooseLead:"用你的 WebID 账号登录,数据保存在你自己的 Pod 里",useXpod:"使用 Xpod 账号登录",useOtherSolid:"使用其他 Solid 账号",customLabel:"账号服务地址或 WebID",customPlaceholder:"https://example.com/",customSubmit:"继续",noAccount:"没有账号?",register:"注册 Xpod",noticeDetailsToggle:"详情",noticeCopy:"复制",noticeCopied:"已复制",whatIsPod:"什么是 Pod?",whatIsPodBody:"Pod 是保存你数据的个人空间。",whatIsWebId:"什么是 WebID?",whatIsWebIdBody:"WebID 是登录用的身份,它指向你的个人资料和 Pod。",signInWith:"使用 {service} 登录",select:"选择",selected:"已选择",choosePodTitle:"选择 Pod",choosePodLead:"选择要继续使用的 Pod",retry:"重试",goCreate:"去创建",refreshPage:"刷新页面",startAndEnter:"启动 Xpod 并进入",openXpod:"打开 Xpod",noticeUnreachable:"暂时连不上 Xpod,请稍后再试",noticeIncomplete:"登录没有完成,请再试一次",noticeNoWebId:"还没有 WebID",noticeCancelled:"登录已取消",noticeLocalStopped:"这台电脑上的 Xpod 没有运行",noticePending:"上次登录尚未结束",serviceLabel:"账号服务",signInTitle:"登录 {service}",returnToApp:"完成后回到 {app}",email:"邮箱",password:"密码",forgotPassword:"忘记密码?",rememberDevice:"在这台设备上保持登录",signIn:"登录",registerLink:"注册账号",registerTitle:"注册 {service}",username:"用户名",registerSubmit:"注册",haveAccount:"已有账号?登录",podElsewhereSummary:"想用你自己的独立部署存放 Pod?",podElsewhereBody:"注册后,可以在账号页的“存储”里把 Pod 建到你自己的独立部署上;它和当前账号服务是分开的,普通浏览器不会自动把 Pod 转到本机。",noWebIdTitle:"还没有 WebID",noWebIdLead:"新建一个 WebID 来登录 {app},数据存在它的 Pod 里",webIdName:"WebID 名称",noWebIdLocation:"存放在当前服务",createAndContinue:"创建并继续",chooseOtherLocation:"存到边缘设备(打开账号页)",consentTitle:"授权 {app}",unverifiedWarning:"未能验证这个应用的来源,请确认是你要使用的应用",chooseWebId:"用哪个 WebID 登录?",consentConsequence:"{app} 将以这个身份读写你的数据,之后可以在 Xpod 中收回。",requestDetails:"请求详情",scopes:"权限范围",clientId:"应用标识",webIdFull:"WebID",rememberChoice:"以后不再询问",manageAccount:"管理账号",switchAccount:"换一个账号",deny:"拒绝",allow:"允许",storageCloud:"数据存在 Xpod 云端",storageEdge:"数据存在边缘设备上",hostedStorage:"账号服务托管",independentStorage:"独立部署",identityAddress:"WebID(身份地址)",storageAddress:"Pod(存储地址)",showAddresses:"查看地址",webIdSectionTitle:"WebID",webIdEmpty:"还没有 WebID。新建一个,用它登录应用。",createWebId:"新建 WebID",linkExistingWebId:"关联已有 WebID",podOnDevice:"Pod 在 {device}",authorizedApps:"已授权 {count} 个应用",createStepName:"名称",createStepLocation:"存放在",createNameHint:"WebID 地址",changeDevice:"更换 ›",cannotChangeLater:"创建后不能直接更换,以后要换请使用迁移",createPod:"创建 WebID 和 Pod",startDeviceXpod:"启动这台设备上的 Xpod",creatingNote:"关闭页面不会中断创建",cancel:"取消",devicePickerTitle:"选择存放设备",addDevice:"+ 添加设备",deviceSectionTitle:"设备",deviceStatusOk:"正常",deviceStatusUnreachable:"⚠ 其他设备访问不到",deviceStatusStopped:"Xpod 已停止",deviceStatusOffline:"离线",deviceCloud:"Xpod 云端",deviceEdge:"边缘",podCount:"{count} 个 Pod",networkAction:"网络",fixAction:"处理",collapseAction:"收起",webIdSectionHint:"登录应用时使用的身份,数据存在它的 Pod 里",deviceSectionHint:"Pod 可以存放的地方,网络设置跟着设备走",credentialSectionHint:"让脚本或服务以某个 WebID 直接访问 Pod",startAction:"启动",networkTitle:"网络访问",probeLocal:"这台电脑",probeLan:"局域网",probeWan:"其他网络",probeIdle:"未检测",probeChecking:"检测中",probeOk:"可以访问",probeFailed:"不通",tunnelTitle:"选择隧道",enableAndRecheck:"开启并重新检测",enableAndCheck:"开启并检测",recheck:"重新检测",skipForNow:"跳过,稍后设置",reachableVia:"通过 {tunnel} 可以访问",networkFootnote:"只影响其他设备;这台电脑上照常可用",addDeviceTitle:"添加设备",stepInstall:"安装并登录",stepNetwork:"检查网络",stepDone:"完成",joinThisComputer:"把这台电脑加入",installOnOther:"在那台设备上安装 Xpod 边缘并登录本账号",waitingForDevice:"正在等待新设备上线,登录后这里会自动继续",deviceOnline:"已上线",finish:"完成",useThisDevice:"用这台设备",credentialSectionTitle:"密钥",credentialEmpty:"还没有密钥。",createCredential:"新建密钥",revokeCredential:"删除",resumeTitle:"{app} 正在等你完成授权",resumeWaiting:"在下面新建一个 WebID,完成后就能回去授权",resumeReady:"WebID 已就绪,可以回去授权了",resumeCancel:"取消授权",resumeContinue:"继续授权 {app}",close:"关闭"},en={restoring:"Restoring your sign-in…",enterApp:"Open {app}",reauthenticate:"Sign in again",useAnother:"Use another account",expiredLine:"Your sign-in expired. Please confirm again.",chooseTitle:"Sign in",chooseLead:"Sign in with your WebID account. Your data stays in your own Pod.",useXpod:"Sign in with Xpod",useOtherSolid:"Use another Solid account",customLabel:"Sign-in service address or WebID",customPlaceholder:"https://example.com/",customSubmit:"Continue",noAccount:"No account?",register:"Register for Xpod",noticeDetailsToggle:"Details",noticeCopy:"Copy",noticeCopied:"Copied",whatIsPod:"What is a Pod?",whatIsPodBody:"A Pod is a personal space that holds your data.",whatIsWebId:"What is a WebID?",whatIsWebIdBody:"A WebID is the identity you sign in with. It points to your profile and your Pod.",signInWith:"Sign in with {service}",select:"Select",selected:"Selected",choosePodTitle:"Choose a Pod",choosePodLead:"Choose the Pod to continue with",retry:"Retry",goCreate:"Create one",refreshPage:"Refresh page",startAndEnter:"Start Xpod and open",openXpod:"Open Xpod",noticeUnreachable:"Cannot reach Xpod right now. Please try again later.",noticeIncomplete:"Sign-in did not finish. Please try again.",noticeNoWebId:"No WebID yet",noticeCancelled:"Sign-in cancelled",noticeLocalStopped:"Xpod is not running on this computer",noticePending:"The previous sign-in has not finished",serviceLabel:"Sign-in service",signInTitle:"Sign in to {service}",returnToApp:"You will return to {app}",email:"Email",password:"Password",forgotPassword:"Forgot password?",rememberDevice:"Keep me signed in on this device",signIn:"Sign in",registerLink:"Register",registerTitle:"Register for {service}",username:"Username",registerSubmit:"Register",haveAccount:"Already have an account? Sign in",podElsewhereSummary:"Want it on your own standalone deployment?",podElsewhereBody:"After registering, create the Pod on your own standalone deployment under Storage on the account page; it is separate from this account service.",noWebIdTitle:"No WebID yet",noWebIdLead:"Create a WebID to sign in to {app}. Your data lives in its Pod.",webIdName:"WebID name",noWebIdLocation:"Stored on the current service",createAndContinue:"Create and continue",chooseOtherLocation:"Store on an edge device (open account page)",consentTitle:"Authorize {app}",unverifiedWarning:"We could not verify this application. Make sure it is the one you meant to use.",chooseWebId:"Which WebID do you sign in with?",consentConsequence:"{app} will read and write your data as this identity. You can revoke it later in Xpod.",requestDetails:"Request details",scopes:"Permissions",clientId:"Application ID",webIdFull:"WebID",rememberChoice:"Do not ask again",manageAccount:"Manage account",switchAccount:"Switch account",deny:"Deny",allow:"Allow",storageCloud:"Data is stored on Xpod Cloud",storageEdge:"Data is stored on an edge device",hostedStorage:"Hosted by account service",independentStorage:"Independent deployment",identityAddress:"WebID (identity address)",storageAddress:"Pod (storage address)",showAddresses:"View addresses",webIdSectionTitle:"WebID",webIdEmpty:"No WebID yet. Create one to sign in to applications.",createWebId:"New WebID",linkExistingWebId:"Link an existing WebID",podOnDevice:"Pod on {device}",authorizedApps:"{count} authorized apps",createStepName:"Name",createStepLocation:"Store on",createNameHint:"WebID address",changeDevice:"Change ›",cannotChangeLater:"It cannot be changed directly after creation. Use migration later.",createPod:"Create WebID and Pod",startDeviceXpod:"Start Xpod on this device",creatingNote:"Closing this page will not interrupt creation",cancel:"Cancel",devicePickerTitle:"Choose where to store",addDevice:"+ Add device",deviceSectionTitle:"Devices",deviceStatusOk:"Healthy",deviceStatusUnreachable:"⚠ Not reachable from other devices",deviceStatusStopped:"Xpod stopped",deviceStatusOffline:"Offline",deviceCloud:"Xpod Cloud",deviceEdge:"Edge",podCount:"{count} Pods",networkAction:"Network",fixAction:"Fix",collapseAction:"Collapse",webIdSectionHint:"The identity you sign in to apps with. Your data lives in its Pod.",deviceSectionHint:"Places a Pod can live. Network settings follow the device.",credentialSectionHint:"Let a script or service reach a Pod directly as one WebID.",startAction:"Start",networkTitle:"Network access",probeLocal:"This computer",probeLan:"Local network",probeWan:"Other networks",probeIdle:"Not checked",probeChecking:"Checking",probeOk:"Reachable",probeFailed:"Unreachable",tunnelTitle:"Choose a tunnel",enableAndRecheck:"Enable and recheck",enableAndCheck:"Enable and check",recheck:"Recheck",skipForNow:"Skip, set up later",reachableVia:"Reachable through {tunnel}",networkFootnote:"Only affects other devices. This computer keeps working as usual.",addDeviceTitle:"Add a device",stepInstall:"Install and sign in",stepNetwork:"Check network",stepDone:"Done",joinThisComputer:"Add this computer",installOnOther:"Install Xpod Edge on that device and sign in to this account",waitingForDevice:"Waiting for the new device to come online. This continues automatically after sign-in.",deviceOnline:"Online",finish:"Done",useThisDevice:"Use this device",credentialSectionTitle:"Credentials",credentialEmpty:"No credentials yet.",createCredential:"New credential",revokeCredential:"Delete",resumeTitle:"{app} is waiting for you to finish authorizing",resumeWaiting:"Create a WebID below, then you can go back and authorize",resumeReady:"Your WebID is ready. You can go back and authorize.",resumeCancel:"Cancel authorization",resumeContinue:"Continue authorizing {app}",close:"Close"},podSignInCopy={"zh-CN":zhCN,en};function resolvePodSignInCopy(r="zh-CN",e){return{...podSignInCopy[r],...e}}function formatCopy(r,e){return r.replace(/\{(\w+)\}/g,(t,n)=>{const a=e[n];return a===void 0?t:String(a)})}function IdpChrome({serviceName:r,serviceHost:e,icon:t,serviceLabel:n,locale:a}){const i=n??resolvePodSignInCopy(a).serviceLabel;return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"idp-chrome",className:"flex min-h-14 shrink-0 items-center gap-3 border-b border-border bg-[hsl(var(--sunken))] px-6 py-2 text-[13px] text-foreground min-[400px]:px-8",children:[jsxRuntimeExports.jsx("span",{className:"flex shrink-0 items-center justify-center",children:t??jsxRuntimeExports.jsx(XpodMark,{size:24})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 max-w-[50%] shrink-0 truncate font-medium",children:[r," · ",i]}),e?jsxRuntimeExports.jsx("span",{className:"ml-auto truncate font-mono text-xs text-muted-foreground",children:e}):null]})}const primaryButtonClass="h-auto min-h-12 w-full whitespace-normal break-normal rounded-lg py-2 text-base font-medium leading-snug",outlineButtonClass=primaryButtonClass,textButtonClass="h-9 rounded-lg px-2 text-sm font-medium",fieldClass="h-12 w-full rounded-lg border border-input bg-card px-4 text-base text-foreground placeholder:text-muted-foreground disabled:opacity-60";function Spinner({className:r}){return jsxRuntimeExports.jsx(LoaderCircle$1,{"aria-hidden":"true",className:cn("h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none",r)})}function ActionButton({busy:r=!1,children:e,disabled:t,...n}){return jsxRuntimeExports.jsxs(Button,{type:"button",...n,disabled:t||r,"aria-busy":r||void 0,children:[r?jsxRuntimeExports.jsx(Spinner,{className:"mr-2"}):null,e]})}function SourceMark({icon:r,name:e}){return jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"source",className:"flex h-6 items-center gap-2 text-[13px] text-muted-foreground",children:[r?jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"flex h-6 w-6 shrink-0 items-center justify-center overflow-hidden rounded-md",children:r}):null,jsxRuntimeExports.jsx("span",{className:"truncate",children:e})]})}function PodAvatar({name:r,avatarUrl:e,storage:t,size:n=56}){return jsxRuntimeExports.jsxs("span",{className:"relative inline-flex shrink-0",style:{width:n,height:n},"data-pod-sign-in":"avatar",children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-full w-full rounded-full","aria-hidden":"true",children:[e?jsxRuntimeExports.jsx(AvatarImage,{src:e,alt:""}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"text-base",children:Array.from(r.trim())[0]?.toUpperCase()??"?"})]}),t?jsxRuntimeExports.jsx("span",{className:"absolute -bottom-0.5 -right-0.5",children:jsxRuntimeExports.jsx(StorageBadge,{kind:t.kind,label:t.label})}):null]})}function Field(r){return jsxRuntimeExports.jsx(FormField,{...r,"data-pod-sign-in":"field"})}function Disclosure({summary:r,children:e,className:t}){return jsxRuntimeExports.jsxs("details",{className:cn("text-[13px] text-muted-foreground",t),children:[jsxRuntimeExports.jsx("summary",{className:"cursor-pointer select-none rounded py-1 text-[13px] font-medium text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",children:r}),jsxRuntimeExports.jsx("div",{className:"pt-1 leading-5",children:e})]})}function CheckboxRow({checked:r,onChange:e,label:t,disabled:n}){return jsxRuntimeExports.jsxs("label",{className:"flex min-h-9 cursor-pointer items-center gap-2 text-sm text-foreground",children:[jsxRuntimeExports.jsx(Checkbox,{checked:r,disabled:n,onChange:a=>e(a.target.checked)}),t]})}function usePastDelay(r){const[e,t]=reactExports.useState(!1);return reactExports.useEffect(()=>{const n=setTimeout(()=>t(!0),r);return()=>clearTimeout(n)},[r]),e}function ScreenLayout({chrome:r,children:e,actions:t,onSubmit:n,mainClassName:a,...i}){const o=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[r,jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"main",className:cn("flex min-h-0 flex-1 flex-col gap-7 overflow-y-auto px-6 pb-3 pt-7 min-[400px]:px-8 min-[400px]:pt-8",a),children:e}),t?jsxRuntimeExports.jsx("div",{"data-pod-sign-in":"actions",className:"flex shrink-0 flex-col gap-4 px-6 pb-7 pt-5 min-[400px]:px-8 min-[400px]:pb-8",children:t}):null]}),s="flex min-h-0 flex-1 flex-col";return n?jsxRuntimeExports.jsx("form",{...i,onSubmit:n,className:s,noValidate:!0,children:o}):jsxRuntimeExports.jsx("div",{...i,className:s,children:o})}function resolveIdpCopy({locale:r,copy:e}){return resolvePodSignInCopy(r,e)}function IdpFrameHeader({serviceName:r="Xpod",serviceHost:e,serviceIcon:t,locale:n,copy:a}){return jsxRuntimeExports.jsx(IdpChrome,{serviceName:r,serviceHost:e,icon:t,locale:n,serviceLabel:a?.serviceLabel})}const inputClass=fieldClass;function TextAction({href:r,onClick:e,disabled:t,className:n,children:a}){const i=cn(textButtonClass,"inline-flex shrink-0 items-center justify-center text-primary hover:underline",n);return r&&!t?jsxRuntimeExports.jsx("a",{href:r,className:i,children:a}):jsxRuntimeExports.jsx("button",{type:"button",className:i,disabled:t,onClick:e,children:a})}function IdpSignInView(r){const{serviceName:e,returnToAppName:t,error:n,fieldErrors:a,pending:i=!1,remember:o,defaultEmail:s="",defaultPassword:d="",onFieldChange:u,onRememberChange:c,onSubmit:p,onForgot:_,forgotHref:m,onRegister:S,registerHref:A,onUseOtherSolid:h}=r,T=resolveIdpCopy(r),[w,b]=reactExports.useState(s),[N,O]=reactExports.useState(d),X=ee=>{ee.preventDefault(),i||p({email:w.trim(),password:N})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-sign-in",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...r}),onSubmit:X,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[n?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:n}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:i,children:T.signIn}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[S||A?jsxRuntimeExports.jsxs("span",{className:"flex min-w-0 flex-wrap items-center gap-x-1 gap-y-0",children:[jsxRuntimeExports.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:T.noAccount}),jsxRuntimeExports.jsx(TextAction,{href:A,disabled:i,onClick:S,children:T.registerLink})]}):jsxRuntimeExports.jsx("span",{}),h?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"text-primary hover:underline"),disabled:i,onClick:h,children:T.useOtherSolid}):null]})]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(T.signInTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(T.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{"data-pod-sign-in":"fields",className:"flex flex-col gap-5",children:[jsxRuntimeExports.jsx(Field,{label:T.email,error:a?.email,children:ee=>jsxRuntimeExports.jsx(EmailInput,{...ee,name:"email",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:w,disabled:i,onChange:V=>{b(V.target.value),u?.("email",V.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:T.password,error:a?.password,labelAside:_||m?jsxRuntimeExports.jsx(TextAction,{className:"min-h-7 text-[13px]",href:m,onClick:_,children:T.forgotPassword}):void 0,children:ee=>jsxRuntimeExports.jsx(Input,{...ee,name:"password",type:"password",autoComplete:"current-password",className:inputClass,value:N,disabled:i,onChange:V=>{O(V.target.value),u?.("password",V.target.value)}})}),c?jsxRuntimeExports.jsx(CheckboxRow,{checked:o,onChange:c,label:T.rememberDevice,disabled:i}):null]})]})}function IdpRegisterView(r){const{serviceName:e,returnToAppName:t,usernamePreview:n,requireUsername:a,fieldErrors:i,error:o,pending:s=!1,defaultEmail:d="",defaultPassword:u="",defaultUsername:c="",onFieldChange:p,onSubmit:_,onSignIn:m}=r,S=resolveIdpCopy(r),[A,h]=reactExports.useState(c),[T,w]=reactExports.useState(d),[b,N]=reactExports.useState(u),O=X=>{X.preventDefault(),!s&&_({...a?{username:A.trim()}:{},email:T.trim(),password:b})};return jsxRuntimeExports.jsxs(ScreenLayout,{"data-pod-sign-in-state":"idp-register",chrome:jsxRuntimeExports.jsx(IdpFrameHeader,{...r}),onSubmit:O,actions:jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[o?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-[13px] text-destructive",children:o}):null,jsxRuntimeExports.jsx(ActionButton,{type:"submit",className:primaryButtonClass,busy:s,children:S.registerSubmit}),m?jsxRuntimeExports.jsx("button",{type:"button",className:cn(textButtonClass,"self-center text-primary hover:underline"),disabled:s,onClick:m,children:S.haveAccount}):null]}),children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:formatCopy(S.registerTitle,{service:e})}),t?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:formatCopy(S.returnToApp,{app:t})}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-5",children:[a?jsxRuntimeExports.jsx(Field,{label:S.username,error:i?.username,hint:n?jsxRuntimeExports.jsx("span",{role:"status",className:"font-mono text-xs",children:n}):void 0,children:X=>jsxRuntimeExports.jsx(Input,{...X,name:"username",type:"text",autoComplete:"username",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:A,disabled:s,onChange:ee=>{h(ee.target.value),p?.("username",ee.target.value)}})}):null,jsxRuntimeExports.jsx(Field,{label:S.email,error:i?.email,children:X=>jsxRuntimeExports.jsx(EmailInput,{...X,name:"email",autoComplete:"email",autoCapitalize:"none",spellCheck:!1,className:inputClass,value:T,disabled:s,onChange:ee=>{w(ee.target.value),p?.("email",ee.target.value)}})}),jsxRuntimeExports.jsx(Field,{label:S.password,error:i?.password,children:X=>jsxRuntimeExports.jsx(Input,{...X,name:"password",type:"password",autoComplete:"new-password",className:inputClass,value:b,disabled:s,onChange:ee=>{N(ee.target.value),p?.("password",ee.target.value)}})}),jsxRuntimeExports.jsx(Disclosure,{summary:S.podElsewhereSummary,children:S.podElsewhereBody})]})]})}const __iconNode$1=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],CircleAlert=createLucideIcon$1("circle-alert",__iconNode$1);const __iconNode=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon$1("loader-circle",__iconNode);function WebAccountLayout({title:r,description:e,children:t,host:n="document",bare:a=!1,intro:i,serviceIcon:o}){const s=reactExports.useId(),d=n==="window",u=d?"window":"page";return jsxRuntimeExports.jsx("main",{"data-testid":"web-account-page",className:d?"h-dvh w-full overflow-hidden":void 0,children:jsxRuntimeExports.jsx(PodSignInFrame,{presentation:d?"window":"page",ariaLabel:r,appIntro:i,dataAttributes:{"data-web-account-layout":u,"data-web-account-host":d?"window":"document"},children:jsxRuntimeExports.jsx("div",{"data-testid":"web-account-panel","data-web-account-layout":u,"data-web-account-host":d?"window":"document",className:"flex min-h-0 min-w-0 flex-1 flex-col",children:a?t:jsxRuntimeExports.jsxs(ScreenLayout,{chrome:jsxRuntimeExports.jsx(IdpChrome,{serviceName:"Xpod",serviceHost:window.location.host,icon:o}),children:[jsxRuntimeExports.jsxs("header",{className:"flex flex-col gap-1",children:[jsxRuntimeExports.jsx("h1",{id:s,className:"text-[17px] font-semibold text-foreground",children:r}),e?jsxRuntimeExports.jsx("p",{className:"text-sm leading-[22px] text-muted-foreground",children:e}):null]}),t]})})})})}const introCopy={"zh-CN":{name:"Xpod 账号服务",proposition:"一个账号,管理你的 WebID 和它背后的 Pod。",points:[{title:"WebID 是你的身份",detail:"登录应用时使用它;数据存在你自己的 Pod 里。"},{title:"Pod 存在哪里由你决定",detail:"Xpod 云端或你自己的设备,创建后可以在这里查看。"},{title:"密钥按需签发",detail:"为脚本或服务单独创建凭据,不再需要就撤销。"}]},en:{name:"Xpod accounts",proposition:"One account for your WebID and the Pod behind it.",points:[{title:"Your WebID is your identity",detail:"Apps sign you in with it; your data stays in your own Pod."},{title:"You choose where the Pod lives",detail:"Xpod cloud or your own device, reviewable here after creation."},{title:"Credentials on demand",detail:"Issue a key per script or service, and revoke it when it is done."}]}};function XpodAccountServiceIntro({serviceHost:r,locale:e="zh-CN"}){const t=introCopy[e];return jsxRuntimeExports.jsxs("div",{"data-testid":"web-account-introduction",className:"flex max-w-[460px] flex-col gap-7",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(XpodMark,{size:44}),jsxRuntimeExports.jsx("span",{className:"text-[22px] font-semibold leading-none text-foreground",children:t.name})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"m-0 text-[28px] font-semibold leading-[38px] text-foreground",children:t.proposition}),r?jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground",children:r}):null]}),jsxRuntimeExports.jsx("ul",{className:"m-0 flex list-none flex-col gap-4 p-0",children:t.points.map(n=>jsxRuntimeExports.jsxs("li",{className:"flex gap-3",children:[jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"mt-2 h-2 w-2 shrink-0 rounded-full bg-primary"}),jsxRuntimeExports.jsxs("span",{className:"flex flex-col gap-0.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[15px] font-semibold text-foreground",children:n.title}),jsxRuntimeExports.jsx("span",{className:"text-sm leading-[22px] text-muted-foreground",children:n.detail})]})]},n.title))})]})}function parseIdentity(r){if(!r||typeof r!="object")throw new Error("Missing deployment identity");const e=r;if(e.edition!=="cloud"&&e.edition!=="local"||typeof e.managed!="boolean")throw new Error("Invalid deployment identity");let t;if(e.edition==="local"&&e.managed&&typeof e.oidcIssuer=="string"){const a=new URL(e.oidcIssuer);if(!["http:","https:"].includes(a.protocol)||a.username||a.password||a.search||a.hash)throw new Error("Invalid account service");t=a.href.replace(/\/$/u,"")}let n;if(typeof e.publicUrl=="string"){const a=new URL(e.publicUrl);if(!["http:","https:"].includes(a.protocol)||a.username||a.password||a.search||a.hash)throw new Error("Invalid public service address");n=a.href}return{edition:e.edition,managed:e.managed,oidcIssuer:t,publicUrl:n}}function XpodDeploymentIdentity({renderLogo:r,className:e}={}){const[t,n]=reactExports.useState();reactExports.useEffect(()=>{const o=new AbortController;return(async()=>{try{const s=await fetch("/api/service-info",{headers:{accept:"application/json"},cache:"no-store",signal:o.signal});if(!s.ok)throw new Error("Deployment identity unavailable");const d=parseIdentity(await s.json());o.signal.aborted||n(d)}catch{o.signal.aborted||n(null)}})(),()=>o.abort()},[]);const a=t?t.edition==="cloud"?"云端":t.managed?"托管部署":"独立部署":t===null?"部署信息暂不可用":"正在识别部署…",i=r?r(a):jsxRuntimeExports.jsxs("span",{"data-testid":"xpod-deployment-logo",className:"inline-flex flex-col items-center gap-0.5",children:[jsxRuntimeExports.jsx(XpodMark,{size:24}),jsxRuntimeExports.jsx("span",{className:"text-[8px] font-medium leading-none text-primary",children:t?a:t===null?"未知":"…"}),t?null:jsxRuntimeExports.jsx("span",{className:"sr-only",children:a})]});return jsxRuntimeExports.jsx("div",{"data-testid":"xpod-deployment-identity",className:e,children:jsxRuntimeExports.jsx(BrandInfo,{logo:i,infoLabel:"部署详情",info:jsxRuntimeExports.jsxs("div",{className:"space-y-2 leading-relaxed",children:[jsxRuntimeExports.jsx("p",{className:"font-semibold",children:"部署详情"}),t?jsxRuntimeExports.jsxs("p",{children:["部署类型:",t.edition==="cloud"?"Cloud":t.managed?"Local · 云端托管":"Local · 独立部署"]}):jsxRuntimeExports.jsx("p",{children:a}),jsxRuntimeExports.jsxs("p",{children:["当前访问:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:window.location.origin})]}),t?jsxRuntimeExports.jsxs("p",{children:[t.edition==="local"?"节点地址":"服务地址",":",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.publicUrl??(t.managed?"尚未分配":"尚未配置")})]}):null,t?.oidcIssuer&&t.oidcIssuer!==window.location.origin?jsxRuntimeExports.jsxs("p",{children:["账号服务:",jsxRuntimeExports.jsx("span",{className:"font-mono",children:t.oidcIssuer})]}):null]})})})}function XpodAuthSurface(r){const e=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(e==="window"),jsxRuntimeExports.jsx(AuthSurface,{...r,presentation:"compact",host:e})}function XpodSignInFrame({ariaLabel:r,children:e}){const t=getXpodAuthSurfaceHost();return useXpodAuthWindowSurface(t==="window"),jsxRuntimeExports.jsx(PodSignInFrame,{presentation:t==="window"?"window":"page",ariaLabel:r,children:e})}function XpodAccountPageSurface({title:r,children:e,bare:t=!1,intro:n,presentation:a="compact"}){const i=getXpodAuthSurfaceHost(),o=a==="compact";return useXpodAuthWindowSurface(i==="window",o?"account":"workspace"),jsxRuntimeExports.jsx(WebAccountLayout,{title:r,host:o?i:"document",bare:t,intro:n??jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),children:e})}function credentialViewCopy(r){return{email:r.emailLabel,password:r.passwordLabel,username:r.usernameLabel,signIn:r.loginAction,registerSubmit:r.registerAction,rememberDevice:"记住账号"}}function XpodBlockingAccountCredentialsSurface(r){const e=getXpodAuthSurfaceHost(),t=r.mode!=="register";useXpodAuthWindowSurface(e==="window",t?"account":"workspace");const{mode:n,values:a,onChange:i,onSubmit:o,onFieldChange:s,onModeChange:d,rememberAccount:u=!0,onRememberAccountChange:c,pending:p=!1,errors:_,copy:m,surfaceTitle:S,footer:A,onForgot:h,onRegister:T,forgotHref:w,registerHref:b}=r,N={serviceName:"Xpod",serviceHost:window.location.host,serviceIcon:jsxRuntimeExports.jsx(XpodDeploymentIdentity,{}),copy:credentialViewCopy(m)},O=(X,ee)=>{i({...a,[X]:ee}),s?.(X,ee)};return jsxRuntimeExports.jsxs(WebAccountLayout,{title:S,host:t?e:"document",bare:!0,intro:jsxRuntimeExports.jsx(XpodAccountServiceIntro,{serviceHost:window.location.host}),children:[n==="register"?jsxRuntimeExports.jsx(IdpRegisterView,{...N,requireUsername:!1,pending:p,defaultEmail:a.email,defaultPassword:a.password,error:_?.form,fieldErrors:{email:_?.email,password:_?.password},onFieldChange:O,onSubmit:X=>{o({...a,...X})},onSignIn:d?()=>d("login"):void 0}):jsxRuntimeExports.jsx(IdpSignInView,{...N,pending:p,remember:u,defaultEmail:a.email,defaultPassword:a.password,error:_?.form,fieldErrors:{email:_?.email,password:_?.password},onFieldChange:O,onRememberChange:c,onSubmit:X=>{o({...a,...X})},onForgot:h,forgotHref:w,registerHref:b,onRegister:T??(d?()=>d("register"):void 0)}),A?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:A}):null]})}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(r=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(r));for(let n=0;n<r;n++)e+=urlAlphabet[t[n]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<r;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=r=>typeof r=="object"&&r!==null&&typeof r.value=="string",hasTermValue=r=>typeof r=="object"&&r!==null&&typeof r.term=="object"&&r.term!==null&&typeof r.term?.value=="string",resolveTermIri=r=>{if(typeof r=="string")return r;if(hasStringValue$2(r))return r.value;if(hasTermValue(r))return r.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is$1(r,e){if(!r||typeof r!="object")return!1;if(r instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=r.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:n,query:a}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:n,query:a,isExisting:!a,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,n,a=!1){this[SubqueryConfig]={sql:e,selection:t,alias:n,isWith:a}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const a=(is$1(e,Subquery)?e[SubqueryConfig].selection:is$1(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is$1(a,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!a.isSelectionField)return a.sql;const i=a.clone();return i.isSelectionField=!0,i}if(is$1(a,SQL)){if(this.config.sqlBehavior==="sql")return a;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is$1(a,Column)?this.config.alias?new Proxy(a,new ColumnAliasProxyHandler(new Proxy(a.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):a:typeof a!="object"||a===null?a:new Proxy(a,new SelectionProxyHandler(this.config))}}function orderSelectedFields(r,e){return Object.entries(r).reduce((t,[n,a])=>{if(typeof n!="string")return t;const i=e?[...e,n]:[n];return is$1(a,Column)||is$1(a,SQL)||is$1(a,SQL.Aliased)?t.push({path:i,field:a}):is$1(a,Table)?t.push(...orderSelectedFields(a[Table.Symbol.Columns],i)):t.push(...orderSelectedFields(a,i)),t},[])}function applyMixins(r,e){for(const t of e)for(const n of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(r.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)||Object.create(null))}function getTableLikeName(r){return is$1(r,Subquery)?r[SubqueryConfig].alias:is$1(r,View)?r[ViewBaseConfig].name:is$1(r,SQL)?void 0:r[Table.Symbol.IsAlias]?r[Table.Symbol.Name]:r[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,n){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=n}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(r,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:n,session:a,dialect:i,withList:o,distinct:s}){super(),this.config={withList:o,table:e,fields:{...t},distinct:s},this.isPartialSelect=n,this.session=a,this.dialect=i,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,n)=>{const a=this.tableName,i=getTableLikeName(t);if(typeof i=="string"&&this.config.joins?.some(o=>o.alias===i))throw new Error(`Alias "${i}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof a=="string"&&(this.config.fields={[a]:this.config.fields}),typeof i=="string"&&!is$1(t,SQL))){const o=is$1(t,Subquery)?t[SubqueryConfig].selection:is$1(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[i]=o}if(typeof n=="function"&&(n=n(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:t,joinType:e,alias:i}),typeof i=="string")switch(e){case"left":{this.joinsNotNullableMap[i]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[i]=!0;break}case"inner":{this.joinsNotNullableMap[i]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[i]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:n,dialect:a,joinsNotNullableMap:i}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const o=orderSelectedFields(n.fields),s=t.prepareQuery(a.sqlToQuery(this.getSQL()),o,e);return s.joinsNotNullableMap=i,s})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(r){return typeof r=="object"&&r!==null&&"getSQL"in r&&typeof r.getSQL=="function"}function mergeQueries(r){const e={sql:"",params:[]};for(const t of r)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,t){const n=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:a,escapeParam:i,prepareTyping:o,inlineParams:s,paramStartIndex:d}=n;return mergeQueries(e.map(u=>{if(is$1(u,StringChunk))return{sql:u.value.join(""),params:[]};if(is$1(u,Name))return{sql:a(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){const c=[new StringChunk("(")];for(const[p,_]of u.entries())c.push(_),p<u.length-1&&c.push(new StringChunk(", "));return c.push(new StringChunk(")")),this.buildQueryFromSourceParams(c,n)}if(is$1(u,SQL))return this.buildQueryFromSourceParams(u.queryChunks,{...n,inlineParams:s||u.shouldInlineParams});if(is$1(u,Table)){const c=u[Table.Symbol.Schema],p=u[Table.Symbol.Name];return{sql:c===void 0?a(p):a(c)+"."+a(p),params:[]}}if(is$1(u,Column))return{sql:a(u.table[Table.Symbol.Name])+"."+a(u.name),params:[]};if(is$1(u,View)){const c=u[ViewBaseConfig].schema,p=u[ViewBaseConfig].name;return{sql:c===void 0?a(p):a(c)+"."+a(p),params:[]}}if(is$1(u,Param)){const c=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(is$1(c,SQL))return this.buildQueryFromSourceParams([c],n);if(s)return{sql:this.mapInlineParam(c,n),params:[]};let p;return o!==void 0&&(p=[o(u.encoder)]),{sql:i(d.value++,c),params:[c],typings:p}}return is$1(u,Placeholder)?{sql:i(d.value++,u),params:[u]}:is$1(u,SQL.Aliased)&&u.fieldAlias!==void 0?{sql:a(u.fieldAlias),params:[]}:is$1(u,Subquery)?u[SubqueryConfig].isWith?{sql:a(u[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),u[SubqueryConfig].sql,new StringChunk(") "),new Name(u[SubqueryConfig].alias)],n):isSQLWrapper(u)?this.buildQueryFromSourceParams([new StringChunk("("),u.getSQL(),new StringChunk(")")],n):is$1(u,Relation)?this.buildQueryFromSourceParams([u.sourceTable,new StringChunk("."),sql.identifier(u.fieldName)],n):s?{sql:this.mapInlineParam(u,n),params:[]}:{sql:i(d.value++,u),params:[u]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const n=e.toString();return t(n==="[object Object]"?JSON.stringify(e):n)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:r=>r},noopEncoder={mapToDriverValue:r=>r};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(r,...e){const t=[];(e.length>0||r.length>0&&r[0]!=="")&&t.push(new StringChunk(r[0]));for(const[n,a]of e.entries())t.push(a,new StringChunk(r[n+1]));return new SQL(t)}(function(r){function e(){return new SQL([])}r.empty=e;function t(d){return new SQL(d)}r.fromList=t;function n(d){return new SQL([new StringChunk(d)])}r.raw=n;function a(d,u){const c=[];for(const[p,_]of d.entries())p>0&&u!==void 0&&c.push(u),c.push(_);return new SQL(c)}r.join=a;function i(d){return new Name(d)}r.identifier=i;function o(d){return new Placeholder(d)}r.placeholder=o;function s(d,u){return new Param(d,u)}r.param=s})(sql||(sql={}));(function(r){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(n,a){this.sql=n,this.fieldAlias=a}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}r.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const a=e[Table.Symbol.Columns];if(!a)return a;const i={};return Object.keys(a).map(o=>{i[o]=new Proxy(a[o],new ColumnAliasProxyHandler(new Proxy(e,this)))}),i}const n=e[t];return is$1(n,Column)?new Proxy(n,new ColumnAliasProxyHandler(new Proxy(e,this))):n}}var _a$b;class ColumnBuilder{constructor(e,t,n={},a,i){this.name=e,this.dataType=t,this.options={...n},this._predicateUri=a,this.elementType=i??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,n={},a){this.name=e,this.dataType=t,this.options=n,this.tableName=a}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,n={}){super(e,"array",n),this.elementType=t}}function boolean$2(r,e={}){return new ColumnBuilder(r,"boolean",e)}function timestamp(r,e={}){return new ColumnBuilder(r,"datetime",e)}function json(r,e={}){return new ColumnBuilder(r,"json",e)}function object$1(r,e={}){return new ColumnBuilder(r,"object",e)}function uri(r,e={}){return new ColumnBuilder(r,"uri",e)}function id(r="id",e={}){const t=new PodStringColumn(r,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(r,e={}){return new ColumnBuilder(r,"string",e)}function integer$1(r,e={}){return new ColumnBuilder(r,"integer",e)}function date$3(r,e={}){return new ColumnBuilder(r,"datetime",e)}function text(r,e={}){return new ColumnBuilder(r,"string",e)}function real(r,e={}){return new ColumnBuilder(r,"integer",e)}function validateColumnOverride(r,e,t){const n=r.getPredicateUri?.()??r.options?.predicate,a=e.options?.predicate;if(n&&a&&n!==a)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${a}",子 schema 尝试改为 "${n}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(r,e){const t={};for(const[n,a]of Object.entries(r.columns))t[n]=a;for(const[n,a]of Object.entries(e)){const i=r.columns[n];if(i&&!(a instanceof PodColumnBase)){validateColumnOverride(a,i,n);const o=a;!o.getPredicateUri?.()&&!o.options?.predicate&&(o.options={...o.options,predicate:i.options?.predicate})}t[n]=a}return t}function renderDefaultIdTemplate(r,e){if(!/\{[^{}]+\}/.test(r))return r;if(/\{\s*id\s*\}/.test(r))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},n=resolveDate(t,e.now),a={yyyy:String(n.getUTCFullYear()),MM:String(n.getUTCMonth()+1).padStart(2,"0"),dd:String(n.getUTCDate()).padStart(2,"0")};return r.replace(/\{([^{}]+)\}/g,(i,o)=>{const s=o.trim();if(s==="key")return e.key;if(s==="yyyy")return a.yyyy;if(s==="MM")return a.MM;if(s==="dd")return a.dd;const d=resolveExpression(s,t,e);return d==null?"":String(d)})}function resolveDate(r,e=new Date){const t=r.createdAt??r.favoredAt??r.indexedAt??e,n=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(n.getTime())?n:e}function resolveExpression(r,e,t){const n=parseExpression(r);let a=resolveTemplatePath(n.path,e,t);for(const i of n.transforms)a=applyTransform(a,i,n.path,t);return n.selector?applyPathSelector(a,n.selector):a}function parseExpression(r){const e=r.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():r,[n,...a]=t.split("|").map(i=>i.trim()).filter(Boolean);return{path:n??r,transforms:a,selector:e?.[2]?.trim()}}function resolveTemplatePath(r,e,t){const n=r.split("."),a=n[0];return n.reduce((i,o,s)=>{if(typeof i=="string")return a?resolveResourceProperty(i,a,o,t):void 0;if(!(!i||typeof i!="object"))return a&&isResourceProperty(o)&&!((o==="id"||o==="key")&&o in i)?resolveResourceProperty(i,a,o,t):s>0&&o==="id"&&readRef(i)?extractResourceId(i,a??"",t):i[o]},e)}function isResourceProperty(r){return r==="id"||r==="key"||r==="doc"||r==="document"||r==="dir"||r==="owner"}function resolveResourceProperty(r,e,t,n){if(t==="id")return extractResourceId(r,e,n);const a=extractResourceId(r,e,n);if(a){if(t==="key"){const i=extractTemplateValuesForField(r,e,n);return i?.key??i?.id??deriveResourceKey(a)}if(t==="doc"||t==="document")return resourceDocument(a);if(t==="dir"||t==="owner")return deriveOwnerDir(a)}}function applyTransform(r,e,t,n){if(e==="slug")return slugifyValue(String(r??""));const a=extractResourceId(r,t,n);if(e==="resource")return a;if(e==="document")return a?resourceDocument(a):"";if(e==="owner")return a?deriveOwnerDir(a):"";const i=extractTemplateValuesForField(r,t,n);return e==="id"?i?.id??i?.key??a??"":i?.[e]??""}function extractResourceId(r,e,t){const n=readRef(r);if(!n)return null;const a=resolveLinkedResource(e,t);if(!a)return normalizePodDataResourceId$1(n);if(!isCompleteResourceId$1(n))return renderLinkedResourceId(a,n);const i=relativeSubjectFromRef$1(a,n);return normalizePodDataResourceId$1(i??n)}function extractTemplateValuesForField(r,e,t){const n=readRef(r);if(!n)return null;const a=resolveLinkedResource(e,t);if(!a)return null;const i=relativeSubjectFromRef$1(a,n)??(isCompleteResourceId$1(n)?null:renderLinkedResourceId(a,n));if(!i)return null;const o=resourceTemplate(a);return o?extractVarsFromTemplate(normalizePodDataResourceId$1(i),o):{id:normalizePodDataResourceId$1(i)}}function resolveLinkedResource(r,e){const t=e.links?.[r];if(t)return t;const n=e.resource?.columns?.[r];return n?.getLinkTable?.()??n?.options?.linkTable??null}function resourceTemplate(r){const e=r.getSubjectTemplate?.()??r.config?.subjectTemplate;if(e)return e;const t=r.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(r,e){const t=resourceTemplate(r);if(!t)return e;const n=r.columns?.id?.options?.defaultValue;return typeof n=="function"?String(n(e,{})):t.replace(/\{([^}]+)\}/g,(a,i)=>{const o=parseTemplateField(i);return o==="id"||o==="key"?e:""})}function readRef(r){if(typeof r=="string"&&r.length>0)return r;if(!r||typeof r!="object")return null;const e=r,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(r){return normalizeResourcePath$1(r.getResourcePath?.()??r.config?.base??"")}function relativeSubjectFromRef$1(r,e){const t=resourcePath(r);if(!t)return normalizePodDataResourceId$1(e);const n=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const a of n){const i=e.indexOf(a);if(i<0)continue;let o=e.slice(i+a.length);return o.startsWith("/")&&(o=o.slice(1)),o.length>0?o:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(r,e){let t=0;const n=new Map,a=[];let i=0;for(const s of e.matchAll(/\{([^}]+)\}/g)){a.push(escapeRegExp$1(e.slice(i,s.index)));const d=`var${t++}`;n.set(d,parseTemplateField(s[1]??"")),a.push(`(?<${d}>.+?)`),i=s.index+s[0].length}a.push(escapeRegExp$1(e.slice(i)));const o=a.join("");try{const s=r.match(new RegExp(`^${o}$`));if(!s?.groups)return null;const d={};for(const[u,c]of Object.entries(s.groups)){const p=n.get(u);!p||c===void 0||(d[p]=decodeURIComponent(c))}return d}catch{return null}}function parseTemplateField(r){const e=r.split("|").map(n=>n.trim()).filter(Boolean)[0]??r,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(r){return r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(r,e){const t=splitResourcePath(r);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const n=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!n)throw new Error(`Invalid id default path selector [${e}]`);const a=n[1]===""?0:normalizeSliceIndex(Number(n[1]),t.length),i=n[2]===""?t.length:normalizeSliceIndex(Number(n[2]),t.length);return t.slice(a,i).join("/")}function splitResourcePath(r){const e=readRef(r);if(!e)return null;const t=normalizePodDataResourceId$1(e),[n,a]=t.split("#"),i=(n??t).split("/").filter(Boolean);return a&&i.push(a),i}function normalizePodDataResourceId$1(r){const e=r.indexOf("#"),[t,n=""]=e>=0?[r.slice(0,e),r.slice(e)]:[r,""],a=t.indexOf("/.data/");return`${a>=0?t.slice(a+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${n}`}function normalizeResourcePath$1(r){return r.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(r){return/^https?:\/\//u.test(r)||r.startsWith("/")||r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(r)}function deriveOwnerDir(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#"),n=t>=0?e.slice(0,t):e,a=t>=0?e.slice(t+1):"",i=n.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(i?.[1])return i[1];if(n==="task/index.ttl"&&a&&a!=="this")return`task/${a}`;const o=n.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(o?.[1])return o[1];const s=n.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(s?.[1])return s[1];const d=n.split("/").filter(Boolean);return d.length>1?d.slice(0,-1).join("/"):n}function resourceDocument(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(r){const e=normalizePodDataResourceId$1(r),t=e.indexOf("#");if(t>=0){const s=e.slice(t+1);if(s&&s!=="this"&&s!=="me"&&s!=="it")return s}const n=resourceDocument(e).replace(/\/+$/u,""),a=n.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(a?.[1])return a[1];const i=n.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(i?.[1])return i[1];const o=n.split("/").filter(Boolean);return o.length>0?o[o.length-1]:e}function slugifyValue(r){return r.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(r,e){return r<0?e+r:r}function normalizeSliceIndex(r,e){const t=r<0?e+r:r;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(r){const e=r.split("|").map(n=>n.trim()).filter(Boolean)[0]??r,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(r){return r.trim().replace(/^(\.\/)+/,"")}function podResourcePath(r){return normalizeResourcePath(r.getResourcePath?.()??r.config?.base??"")}function podResourceSubjectTemplate(r){return r.getSubjectTemplate?.()??r.config?.subjectTemplate}function podResourceIdDefaultTemplate(r){const e=r.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(r){const e=podResourcePath(r),t=normalizeResourcePath(r.getContainerPath?.()??r.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(r,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(r);return t?`${t}${e}`:e}function templateRelativeSubject(r,e){if((podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r))?.startsWith("#")&&!e.startsWith("#")){const n=e.indexOf("#");if(n>=0)return e.slice(n)}return e}function isBaseRelativeSubjectId$1(r){return!r||/^https?:\/\//.test(r)||r.startsWith("/")?!1:r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(r)}function isTemplateCompleteResourceId(r,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r);return t?extractTemplateValues(templateRelativeSubject(r,e),t)!==null:!1}function isResourceRelativeSubjectId(r,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(r,e)}function relativeSubjectFromRef(r,e){const t=podResourcePath(r);if(!t)return null;const n=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const a of n){const i=e.indexOf(a);if(i<0)continue;let o=e.slice(i+a.length);if(o.startsWith("/")&&(o=o.slice(1)),o.length>0)return o}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(r,e)?normalizeResourcePath(e):null}function extractTemplateValues(r,e){if(!e.includes("{"))return r===e?{}:null;let t=0;const n=new Map,a=[];let i=0;for(const s of e.matchAll(/\{([^}]+)\}/g)){a.push(escapeRegExp(e.slice(i,s.index)));const d=`var${t++}`;n.set(d,parseTemplateVariableField$1(s[1]??"")),a.push(`(?<${d}>.+?)`),i=s.index+s[0].length}a.push(escapeRegExp(e.slice(i)));const o=`^${a.join("")}$`;try{const s=r.match(new RegExp(o));if(!s?.groups)return null;const d={};for(const[u,c]of Object.entries(s.groups)){const p=n.get(u);if(!p||c===void 0)continue;const _=decodeURIComponent(c);if(p in d&&d[p]!==_)return null;d[p]=_}return d}catch{return null}}function escapeRegExp(r){return r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(r,e){if(!e)return null;const t=relativeSubjectFromRef(r,e);if(!t)return null;const n=qualifyFragmentResourceId(r,t),a=podResourceSubjectTemplate(r)??podResourceIdDefaultTemplate(r),i=a?extractTemplateValues(templateRelativeSubject(r,n),a):{id:decodeURIComponent(n)};return i?{resourceId:decodeURIComponent(n),templateValues:i}:null}function extractPodResourceTemplateValue(r,e,t="id"){return parsePodResourceRef(r,e)?.templateValues[t]??null}function resolvePodBaseUrl(r){const e=r.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(r){if(!r||typeof r!="object")return null;const e=r,t=typeof e.getDialect=="function"?e.getDialect():null,n=readPodUrl(t);if(n)return resolvePodBaseUrl(n);const a=typeof e.getSession=="function"?e.getSession():e.session,i=readPodUrl(a);if(i)return resolvePodBaseUrl(i);const o=readWebId(a);return o&&o.includes("/profile/card#me")?resolvePodBaseUrl(o):null}function normalizePodDataResourceId(r){const e=r.indexOf("#"),[t,n=""]=e>=0?[r.slice(0,e),r.slice(e)]:[r,""],a=t.indexOf("/.data/");return`${a>=0?t.slice(a+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${n}`}function resolvePodResourceId(r,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(r,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(r,e),normalizePodDataResourceId(e);const n=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!n)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(n)||isTemplateCompleteResourceId(r,n))return normalizePodDataResourceId(n);const a=resolveDefaultResourceId(r,n,e);if(a)return normalizePodDataResourceId(a);const i=podResourceSubjectTemplate(r);return normalizePodDataResourceId(i?renderSubjectTemplateResourceId(i,n,e):n)}function buildPodResourceIri(r,e){const t=resolvePodBaseUrl(r);if(!t||/^https?:\/\//u.test(e))return e;const n=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(n.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(r,e,t){const n=resolveKnownTargetIri(t);if(n)return n;const a=resolvePodRootTargetPath(t);if(a)return buildPodResourceIri(r,a);const i=resolvePodResourceId(e,t),o=isResourceRelativeSubjectId(e,i)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(i)}`:e.resolveUri?.(i)??`/.data/${normalizePodDataResourceId(i)}`;return buildPodResourceIri(r,o)}function buildPodResourceIriForDatabase(r,e,t){const n=resolvePodBaseUrlFromDatabase(r);if(!n)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(n,e,t)}function resolvePodResourceIriForDatabase(r,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(r,e,t)}catch{return null}}function resolveKnownTargetIri(r){if(typeof r=="string")return/^https?:\/\//u.test(r)?r:null;const e=r["@id"]??r.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(r){if(typeof r=="string")return r.startsWith("/")?r:null;const e=typeof r.id=="string"?r.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(r){return/^https?:\/\//u.test(r)||r.startsWith("/")||r.startsWith("#")||r.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(r)}function assertCompleteStringResourceId(r,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(r,e))return;const t=r.columns?.id?.options?.defaultValue!==void 0,n=podResourceSubjectTemplate(r);if(t||n)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(r,e,t){const n=r.columns?.id?.options?.defaultValue;if(n===void 0)return null;if(typeof n=="string")return renderDefaultIdTemplate(n,{key:e,row:t,resource:r});if(typeof n!="function")return String(n);const a=n;return a.length===0?String(a()):String(a(e,t))}function renderSubjectTemplateResourceId(r,e,t){const n=r.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(n,{key:encodeURIComponent(e),row:t})}function readPodUrl(r){if(!r||typeof r!="object")return null;const e=r,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(r){if(!r||typeof r!="object")return null;const e=r,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,n){this.initialized=!1;const a=n.type;if(!a)throw new Error("podTable requires a type (RDF class) via options.type");const i=n.typeIndex,o=i==="private"||i==="public",s=this.resolveBase(n.base,e);this.resourcePath=s.resourcePath,this.containerPath=s.containerPath;const d=this.resolveSubjectTemplate(n.subjectTemplate,s.resourcePath,s.containerPath,e);this.subjectTemplate=d.template,this.hasCustomSubjectTemplate=d.isCustom,this.resourceMode=n.resourceMode??(n.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=n.sparqlEndpoint,this.registerTypeIndexEnabled=o&&n.autoRegister!==!1,this.config={name:e,base:s.resourcePath,type:resolveTermIri(a),namespace:n.namespace,typeIndex:o?i:void 0,saiRegistryPath:n.saiRegistryPath,autoRegister:n.autoRegister,containerPath:s.containerPath,hooks:n.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(n.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let u=0;for(const c of Object.values(t))if(c.options.primaryKey&&u++,c.table=this,c.tableName=e,!c.options.predicate&&!c._virtualId&&!n.namespace)throw new Error(`Column "${c.name}" in table "${e}" is missing a predicate.`);if(u!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${u}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const n=t.replace(/\{id\}/g,e);return n.startsWith("#")?`${this.resourcePath}${n}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${n}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const n=this.normalizeBaseInput(e),a=this.normalizeResourcePath(n);if(a.endsWith("/")){const o=this.ensureTrailingSlash(a);return{resourcePath:o,containerPath:o}}const i=this.ensureTrailingSlash(this.deriveContainerPath(a));return{resourcePath:a,containerPath:i}}normalizeBaseInput(e){const t=e.trim(),n=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(n){const[,a,i]=n,o=a.toLowerCase(),s=i.trim();return o==="http"||o==="https"?`${o}://${s}`:s.startsWith("/")?s:`/${s}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const n=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return n.startsWith("/")?n:`/${n}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n===-1?"/":t.slice(0,n+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,n,a){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const n=(Array.isArray(e)?e:[e]).map(a=>resolveTermIri(a)).filter(a=>a&&a.length>0);return Array.from(new Set(n))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(r,e,t){const n={};for(const[a,i]of Object.entries(e)){if(i instanceof PodColumnBase){n[a]=i;continue}let o;switch(i.dataType){case"integer":o=new PodIntegerColumn(i.name,i.options);break;case"datetime":o=new PodDateTimeColumn(i.name,i.options);break;case"boolean":o=new PodBooleanColumn(i.name,i.options);break;case"json":o=new PodJsonColumn(i.name,i.options);break;case"object":o=new PodObjectColumn(i.name,i.options);break;case"array":{const d=i.elementType??i.options.baseType??"string";o=new PodArrayColumn(i.name,d,i.options);break}case"uri":o=new PodUriColumn(i.name,i.options);break;default:o=new PodStringColumn(i.name,i.options);break}const s=i.getPredicateUri?.();s&&o.predicate(s),n[a]=o}return new PodTable(r,n,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const n=mergeSchemaColumns(this,e),a=[this.type];return this.subClassOf&&a.push(...this.subClassOf),solidSchema(n,{...t,subClassOf:a})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(r,e){const t={};for(const[n,a]of Object.entries(r)){if(a instanceof PodColumnBase){t[n]=a;continue}let i;switch(a.dataType){case"integer":i=new PodIntegerColumn(a.name,a.options);break;case"datetime":i=new PodDateTimeColumn(a.name,a.options);break;case"boolean":i=new PodBooleanColumn(a.name,a.options);break;case"json":i=new PodJsonColumn(a.name,a.options);break;case"object":i=new PodObjectColumn(a.name,a.options);break;case"array":{const s=a.elementType??a.options.baseType??"string";i=new PodArrayColumn(a.name,s,a.options);break}case"uri":i=new PodUriColumn(a.name,a.options);break;default:i=new PodStringColumn(a.name,a.options);break}const o=a.getPredicateUri?.();o&&i.predicate(o),t[n]=i}return new SolidSchema(t,e)}function isSolidSchema(r){return r instanceof SolidSchema||r?.$kind==="SolidSchema"}const XSD$e="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(r,e){if(!r)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const a=e.getMapping()?.columns?.[r.name];if(a?.predicate)return a.predicate}if(typeof r.getPredicateUri=="function")return r.getPredicateUri();if(r._predicateUri)return r._predicateUri;if(r.predicate&&typeof r.predicate=="string")return r.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof r.getPredicate=="function")try{return r.getPredicate(t)}catch{}return r.options?.predicate?r.options.predicate:t?`${typeof t=="string"?t:t.uri}${r.name}`:(r.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",r),`http://example.org/${r.name}`)}function formatValue$1(r,e,t,n){return Array.isArray(r)?r.map(a=>formatSingleValue(a,e,t,n)):formatSingleValue(r,e,t,n)}function formatSingleValue(r,e,t,n){if(r==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const a=String(r);if(a.startsWith("<")&&a.endsWith(">")){const i=a.slice(1,-1);return t&&!t.isAbsoluteUri(i)?`<${t.resolveLink(i,e,n)}>`:a}return t?`<${t.resolveLink(a,e,n)}>`:a.startsWith("<")?a:`<${a}>`}return typeof r=="string"?!e&&(r.startsWith("http://")||r.startsWith("https://"))?`<${r}>`:`"${r.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof r=="number"?Number.isInteger(r)?String(r):`"${r}"^^<${XSD$e}decimal>`:typeof r=="boolean"?`"${r}"^^<${XSD$e}boolean>`:r instanceof Date?`"${r.toISOString()}"^^<${XSD$e}dateTime>`:`"${String(r)}"`}function resolveColumn(r,e){if(r&&typeof r=="object"&&r instanceof PodColumnBase)return r;if(r&&typeof r=="object"&&"name"in r){const t=r.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof r=="string"){const t=e.columns[r];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(r)}`)}function generateSubjectUri(r,e,t){const n=t.resolveSubject(e,r);if(!n)throw new Error("Failed to generate subject URI");return n}var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,n){super(),this.left=e,this.operator=t,this.right=n,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(r,e){return new BinaryExpression(r,"=",e)}function like(r,e){return new BinaryExpression(r,"LIKE",e)}function inArray(r,e){return new BinaryExpression(r,"IN",e)}function and(...r){return new LogicalExpression("AND",r.filter(Boolean))}function or(...r){return new LogicalExpression("OR",r.filter(Boolean))}function parseActivityStreamsMessage(r){const e=JSON.parse(r);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,n=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!n.ok)throw new Error(`SSE connection failed: ${n.status} ${n.statusText}`);if(!n.body)throw new Error("SSE response has no body");this.contentType=n.headers.get("content-type")||"",this._connected=!0,this.reader=n.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:n,value:a}=await this.reader.read();if(n){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const i=e.decode(a,{stream:!0});t+=i,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(n){n.name!=="AbortError"&&this.handleError(n)}}processTurtleBuffer(e){const t=e.split(`
|
|
3
3
|
`);let n="";for(let a=0;a<t.length;a++){const i=t[a];n+=i+`
|
|
4
4
|
`,i.trim().endsWith(".")&&(this.parseTurtleNotification(n.trim()),n="")}return n}processSSEBuffer(e){const t=e.split(`
|
|
5
5
|
|
|
@@ -30,7 +30,7 @@ import{c as createLucideIcon$1}from"./createLucideIcon-CacwLsmB.js";import{r as
|
|
|
30
30
|
FILTER(?typePredicate = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> && ?typeObject = <${e.config.type}> && CONTAINS(STR(?subject), "${escapeSparqlString(o)}"))`:`?subject ?predicate ?object .
|
|
31
31
|
FILTER(CONTAINS(STR(?subject), "${escapeSparqlString(o)}"))`}
|
|
32
32
|
}
|
|
33
|
-
LIMIT 50`,prefixes:{}},u=a.kind==="sparql"?await this.dialect.executeOnResource(a.resourceUrl,d,a.descriptor):await this.dialect.getSPARQLExecutor().queryContainer(a.resourceUrl,d),c=Array.from(new Set(u.map(p=>this.extractSubjectFromLookupRow(p)).filter(p=>!!p).filter(p=>this.subjectMatchesShortId(e,p,t,i))));if(c.length>1)throw new Error(`${n} found multiple resources for short id '${t}' in '${e.config?.name??"resource"}'. Use a base-relative resource id or full IRI to disambiguate.`);return c[0]??this.getIndexedSubject(e,t)}async resolveIdSubjectForExactOperation(e,t,n){return this.needsShortIdSubjectLookup(e,t)?await this.lookupSubjectIriByShortId(e,t,n):this.resolveIdSubject(e,t,n)}async findById(e,t){const n=await this.resolveIdSubjectForExactOperation(e,t,"findById");return n?await this.findByIri(e,n):null}async findByLocator(e,t){this.warnFindByLocatorDeprecation();const n=this.resolveLocatorSubject(e,t,"findByLocator");return await this.findByIri(e,n)}async findByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.findById(e,t);const n=this.resolveResourceTargetIri(e,t,"findByResource");return await this.findByIri(e,n)}async findByIri(e,t){if(!t||typeof t!="string")throw new Error("findByIri requires a valid IRI string");const n=await this.findByIriViaExactResource(e,t);return n!==void 0?n:(await this.session.select().from(e).whereByIri(t).limit(1))[0]??null}getColumnPredicate(e,t){return t.options?.predicate??t.getPredicate?.(e.config.namespace)}async findByIriViaExactResource(e,t){if(!isPodTable(e))return;const n=this.parseIri(t).documentUrl,a=await this.readPredicateObjectRowsFromDocument(n,t);if(a===null)return null;if(a!==void 0){const d=this.mapPredicateObjectRows(e,t,a);if(d!==void 0)return d}if(typeof this.dialect.executeOnResource!="function")return;const i={type:"SELECT",query:`SELECT ?p ?o WHERE { <${t}> ?p ?o . }`,prefixes:{}};let o;try{o=await this.dialect.executeOnResource(n,i)}catch(d){if(this.isMissingExactResourceError(d))return;throw d}const s=this.mapPredicateObjectRows(e,t,o);if(s!==void 0)return s}async readPredicateObjectRowsFromDocument(e,t){const n=this.dialect.getAuthenticatedFetch;if(typeof n!="function")return;let a;try{a=await n.call(this.dialect)(e,{method:"GET",headers:{Accept:"text/turtle, application/ld+json;q=0.8, */*;q=0.1"}})}catch(s){return this.isMissingExactResourceError(s)?null:void 0}if(a.status===404)return null;if(!a.ok)return;const i=a.headers.get("content-type")??"";if(i&&!i.includes("text/turtle")&&!i.includes("application/n-triples")&&!i.includes("application/trig")&&!i.includes("application/ld+json"))return;const o=await a.text();if(!o.trim())return null;try{return new N3Parser$7({baseIRI:e,format:i.includes("application/n-triples")?"N-Triples":"text/turtle"}).parse(o).filter(u=>u.subject.termType==="NamedNode"&&u.subject.value===t).map(u=>({p:u.predicate.value,o:this.convertRdfTermToValue(u.object)}))}catch{return}}convertRdfTermToValue(e){if(e.termType==="NamedNode")return e.value;if(e.termType==="BlankNode")return`_:${e.value}`;if(e.termType!=="Literal")return e.value;const t=e.datatype?.value??"";if(t.includes("#integer")||t.includes("#int"))return parseInt(e.value,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e.value);if(t.includes("#boolean"))return e.value==="true";if(t.includes("#dateTime"))return new Date(e.value);if(t.includes("#json"))try{return JSON.parse(e.value)}catch{return e.value}return e.value}isMissingExactResourceError(e){if(!isRecord$2(e))return!1;if((e.status??e.statusCode)===404)return!0;const n=e.message;return typeof n=="string"&&/\b(?:HTTP status )?404\b/.test(n)}mapPredicateObjectRows(e,t,n){if(!Array.isArray(n)||n.length===0)return null;const a={subject:t,"@id":t,uri:t},i=this.extractIdFromIri(e,t);i!==void 0&&(a.id=i);let o=!1,s=!1,d=!1;for(const u of n){if(!isRecord$2(u))continue;const c=u.p??u.predicate??u["?p"],p=u.o??u.object??u["?o"];if(typeof c=="string"){c==="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"&&p===e.config.type&&(o=!0);for(const[_,m]of Object.entries(e.columns??{})){if(m._virtualId)continue;const S=this.getColumnPredicate(e,m);if(!S||S==="@id"||S!==c)continue;if(m.options?.isArray||m.dataType==="array"){const h=Array.isArray(a[_])?a[_]:a[_]===void 0?[]:[a[_]];a[_]=[...h,p]}else a[_]===void 0&&(a[_]=p);m.dataType==="object"&&typeof p=="string"&&isAbsoluteIri(p)&&(d=!0),s=!0}}}if(!o&&!s)return null;if(!d)return a}extractIdFromIri(e,t){const n=parsePodResourceRef(e,t);if(n)return n.templateValues.id??n.resourceId;try{const s=this.dialect.getResolver(e).parseId(e,t);if(s)return s}catch{}const a=e.getSubjectTemplate?.()??e.config?.subjectTemplate;if(!a)return;if(a==="{id}.ttl"){const s=t.split("/").pop()??"";return s.endsWith(".ttl")?s.slice(0,-4):s||void 0}if(a==="{id}.ttl#it"){const d=t.split("#")[0].split("/").pop()??"";return d.endsWith(".ttl")?d.slice(0,-4):d||void 0}const i=t.indexOf("#");if(i>=0&&a.includes("{id}")&&a.startsWith("#"))return decodeURIComponent(t.slice(i+1));const o=t.split("#")[0].split("/").pop()??"";return o.endsWith(".ttl")?o.slice(0,-4):void 0}parseIri(e){const t=e.indexOf("#");return t>=0?{documentUrl:e.substring(0,t),fragment:e.substring(t+1)}:{documentUrl:e,fragment:null}}async subscribeByIri(e,t,n){if(!t||typeof t!="string")throw new Error("subscribeByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`subscribeByIri requires an absolute IRI, got: ${t}`);if(!this.notificationsClient){const o=this.dialect.getAuthenticatedFetch(),s={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(o,s)}const{documentUrl:a}=this.parseIri(t),i=await this.notificationsClient.subscribe(a,{channel:n.channel,features:n.features,onNotification:async o=>{try{if(o.type==="Update"){const s=await this.findByIri(e,t);s&&await n.onUpdate(s)}else o.type==="Delete"&&await n.onDelete?.()}catch(s){n.onError?.(s)}},onError:n.onError});return()=>i.unsubscribe()}async updateByIri(e,t,n){if(!t||typeof t!="string")throw new Error("updateByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`updateByIri requires an absolute IRI, got: ${t}`);const a=n;return await this.session.update(e).set(a).whereByIri(t),await this.findByIri(e,t)}async updateById(e,t,n){const a=await this.resolveIdSubjectForExactOperation(e,t,"updateById");return a?await this.updateByIri(e,a,n):null}async updateByLocator(e,t,n){const a=this.resolveLocatorSubject(e,t,"updateByLocator");return await this.updateByIri(e,a,n)}async updateByResource(e,t,n){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.updateById(e,t,n);const a=this.resolveResourceTargetIri(e,t,"updateByResource");return await this.updateByIri(e,a,n)}async deleteByIri(e,t){if(!t||typeof t!="string")throw new Error("deleteByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`deleteByIri requires an absolute IRI, got: ${t}`);return await this.findByIri(e,t)?(await this.session.delete(e).whereByIri(t),!0):!1}async deleteById(e,t){const n=await this.resolveIdSubjectForExactOperation(e,t,"deleteById");return n?await this.deleteByIri(e,n):!1}async deleteByLocator(e,t){const n=this.resolveLocatorSubject(e,t,"deleteByLocator");return await this.deleteByIri(e,n)}async deleteByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.deleteById(e,t);const n=this.resolveResourceTargetIri(e,t,"deleteByResource");return await this.deleteByIri(e,n)}async transaction(e){return await this.session.transaction(async t=>{const n=new PodDatabase(this.dialect,t,this.schema);return await e(n)})}getDialect(){return this.dialect}getSession(){return this.session}getSchema(){return this.schema}get discovery(){return this.dialect.getDiscovery()}async connect(){return await this.dialect.connect()}async disconnect(){return this.notificationsClient&&this.notificationsClient.unsubscribeAll(),await this.dialect.disconnect()}async subscribe(e,t){if(!this.notificationsClient){const i=this.dialect.getAuthenticatedFetch(),o={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(i,o)}const n=this.resolveResourceTopic(e,t.iri),a={channel:t.channel,features:t.features,onNotification:i=>{if(t.onNotification?.(i),!!(t.onCreate||t.onUpdate||t.onDelete||t.onAdd||t.onRemove)){const s={id:i.id,type:i.type,object:i.object,published:i.published,state:i.state};switch(i.type){case"Create":t.onCreate?.(s);break;case"Update":t.onUpdate?.(s);break;case"Delete":t.onDelete?.(s);break;case"Add":t.onAdd?.(s);break;case"Remove":t.onRemove?.(s);break}}},onError:t.onError,onClose:t.onClose};return this.notificationsClient.subscribe(n,a)}resolveResourceTopic(e,t){if(t){if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`iri must be an absolute URL, got: ${t}`);return t}const n=e.config.base||"";if(n.startsWith("http://")||n.startsWith("https://"))return n;const a=this.dialect.getPodUrl(),i=a.endsWith("/")?a:`${a}/`,o=n.startsWith("/")?n.slice(1):n;return`${i}${o}`}getConfig(){return this.dialect.getConfig()}async discoverTable(e){const t=await this.dialect.discoverDataLocations(e);if(t.length===0)return console.log(`[discoverTable] No data locations found for ${e}`),null;const n=t[0],a=n.shapes[0]?.url;if(console.log(`[discoverTable] Found location: ${n.container}, shape: ${a||"none"}`),a){const u=this.dialect.getShapeManager(),c=await u.loadShape(a,this.dialect.getAuthenticatedFetch());if(c){console.log(`[discoverTable] Loaded shape with ${c.properties.length} properties`);const p=u.shapeToTable(c,n.container);return await this.init(p.table),p.table}}console.log("[discoverTable] No shape available, creating basic table");const{podTable:i,string:o}=await __vitePreload(async()=>{const{podTable:u,string:c}=await import("./XpodShellApp-CsivHJl0.js").then(p=>p.E);return{podTable:u,string:c}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),s=this.extractClassName(e),d=i(s,{id:o("id").primaryKey()},{type:e,base:n.container});return await this.init(d),d}async discoverTables(e){const t=[];for(const n of e){const a=await this.discoverTable(n);a&&t.push(a)}return t}async discover(e,t){return this.dialect.discoverDataLocations(e,t)}async discoverAll(){return this.dialect.discoverAll()}async discoverByApp(e){return this.dialect.discoverByApp(e)}async locationToTable(e,t){const n=t??{};let a;if(n.shape)typeof n.shape=="string"?(a=e.shapes.find(u=>u.url===n.shape),a||(a={url:n.shape,source:"config"})):a=n.shape;else if(n.appId){if(a=e.shapes.find(u=>u.registeredBy===n.appId),!a)throw new Error(`[locationToTable] No shape found for appId: ${n.appId}`)}else a=e.shapes[0];if(a?.url){const u=this.dialect.getShapeManager(),c=await u.loadShape(a.url,this.dialect.getAuthenticatedFetch());if(c){console.log(`[locationToTable] Loaded shape: ${a.url} (${c.properties.length} properties)`),a.registeredBy&&console.log(`[locationToTable] -> registeredBy: ${a.registeredBy}`);const p=u.shapeToTable(c,e.container);return await this.init(p.table),p.table}}console.log(`[locationToTable] No shape available, creating basic table for container: ${e.container}`);const{podTable:i,string:o}=await __vitePreload(async()=>{const{podTable:u,string:c}=await import("./XpodShellApp-CsivHJl0.js").then(p=>p.E);return{podTable:u,string:c}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),s=this.extractContainerName(e.container),d=i(s,{id:o("id").primaryKey()},{type:"http://www.w3.org/2000/01/rdf-schema#Resource",base:e.container});return await this.init(d),d}extractContainerName(e){const t=e.replace(/\/$/,""),n=t.lastIndexOf("/");return n>=0&&t.substring(n+1).toLowerCase()||"data"}async discoverTablesFor(e,t,n){const a=await this.discover(e,t),i=[];for(const o of a){const s=await this.locationToTable(o,n);i.push(s)}return i}extractClassName(e){const t=e.lastIndexOf("#");if(t>=0)return e.substring(t+1).toLowerCase();const n=e.lastIndexOf("/");return n>=0?e.substring(n+1).toLowerCase():e.toLowerCase()}addSource(e){this.dialect.addSource(e)}removeSource(e){this.dialect.removeSource(e)}getSources(){return this.dialect.getSources()}async addSourcesFromTypeIndex(){return await this.dialect.addSourcesFromTypeIndex()}async init(...e){let t,n;const a=e[e.length-1];a&&typeof a=="object"&&!Array.isArray(a)&&!("columns"in a)?(t=a,n=e.slice(0,-1)):n=e;const i=[];for(const o of n)if(o)if(Array.isArray(o))for(const s of o)s&&i.push(s);else i.push(o);for(const o of i)if(typeof o.init=="function"?await o.init(this.dialect):await this.dialect.registerTable(o),t?.generateShape||t?.saveShape){const s=this.dialect.getShapeManager(),d=s.generateShape(o);if(t?.saveShape){const u=this.dialect.getPodUrl();let c=t.shapeLocation;c?c.startsWith("http")||(c=`${u}${c.replace(/^\//,"")}`):c=`${u}shapes/`,c.endsWith("/")||(c+="/");const p=`${c}${o.config.name}Shape.ttl`;try{await s.saveShape(d,p),console.log(`[init] Shape saved to: ${p}`)}catch(_){console.warn(`[init] Failed to save Shape to ${p}:`,_)}}}}get query(){return this.queryProxy||(this.queryProxy=this.buildQueryProxy()),this.queryProxy}buildQueryProxy(){const e=this.schema&&typeof this.schema=="object"?Object.entries(this.schema):[],t=new Map;for(const[i,o]of e)isPodTable(o)&&t.set(i,o);const n=(i,o)=>{const s=b=>{let N=null;const O=()=>(N||(N=b()),N);return{then:(X,ee)=>O().then(X,ee),catch:X=>O().catch(X),finally:X=>O().finally(X),[Symbol.toStringTag]:"Promise"}},d=(b,N,O)=>{const X={};for(const[ee,V]of Object.entries(N)){if(V instanceof PodColumnBase){X[ee]=b[V.name];continue}if(typeof V=="string"){X[ee]=b[V]??b[V.split(".").pop()??V];continue}const U=V?.name;if(typeof U=="string"){X[ee]=b[U];continue}X[ee]=b[ee]}if(O)for(const ee of Object.keys(O))X[ee]=b[ee]??[];return X},u=async b=>{this.clearFederatedErrors();let N=this.session.select().from(o);b?.where&&(N=N.where(b.where)),b?.orderBy&&(Array.isArray(b.orderBy)?b.orderBy:[b.orderBy]).forEach(V=>{N=N.orderBy(V.column,V.direction??"asc")}),typeof b?.limit=="number"&&(N=N.limit(b.limit)),typeof b?.offset=="number"&&(N=N.offset(b.offset));let O=await N;b?.with&&Object.keys(b.with).length>0&&(O=await this.eagerLoadWith(O,o,b.with,t));const X=b?.columns;return X&&(O=O.map(ee=>d(ee,X,b.with))),O},c=b=>s(()=>u(b)),p=async(b,N)=>{if(!b)return null;let O=[b];N?.with&&Object.keys(N.with).length>0&&(O=await this.eagerLoadWith(O,o,N.with,t));const X=N?.columns;return X&&(O=O.map(ee=>d(ee,X,N.with))),O[0]??null},_=b=>s(async()=>(await u({...b,limit:1}))[0]??null),m=b=>s(async()=>(await u({where:b?.where,columns:void 0,limit:void 0,offset:void 0})).length),S=()=>(b,N)=>s(async()=>await p(await this.findByLocator(o,b),N)),A=()=>(b,N)=>s(async()=>await p(await this.findById(o,b),N)),h=()=>(b,N)=>s(async()=>await p(await this.findByIri(o,b),N)),T=()=>(b,N)=>s(async()=>await p(await this.findByResource(o,b),N));return{findMany:c,findFirst:_,find:(b,N)=>T()(b,N),findById:A(),findByLocator:S(),findByIri:h(),findByResource:T(),count:m}},a={};return new Proxy(a,{get:(i,o)=>{if(typeof o!="string")return;const s=t.get(o);if(s)return n(o,s)}})}async eagerLoadWith(e,t,n,a){if(!e||e.length===0)return e;const i=this.dedupeBySubject(e);for(const[o,s]of Object.entries(n)){if(!s)continue;const d=t.relations?.[o],u=typeof s=="object"&&s.table?s.table:d?.table??a.get(o);if(!u)continue;if(isSolidSchema(u)||d?.isFederated){if(d&&d.discover)try{const V=await this.getFederatedExecutor().execute(i,{...d,relationName:o});V.errors&&V.errors.length>0&&this.lastFederatedErrors.push(...V.errors)}catch(ee){console.warn(`Federated relation "${o}" failed:`,ee),i.forEach(V=>{V[o]=[]})}else console.warn(`Federated relation "${o}" missing discover function, skipping.`),i.forEach(ee=>{ee[o]=[]});continue}const c=u,p=c.config.type,_=d?.fields&&d.fields.length>0?d.fields:Object.values(c.columns??{}),m=ee=>!!(ee&&(ee.options?.linkTarget===t.config.type||ee.options?.linkTable===t||ee.getLinkTable?.()===t)),S=ee=>!!(ee&&(ee.options?.linkTarget===p||ee.options?.linkTable===c||ee.getLinkTable?.()===c)),A=d?.fields&&d.fields.length>0?_:_.filter(ee=>m(ee)&&!ee.isInverse?.());if(A.length===0){const V=(d?.references??[]).filter(te=>!!(te&&typeof te.isInverse=="function"&&te.isInverse()&&S(te))),U=Object.values(t.columns??{}),v=(V.length>0?V:U).filter(te=>typeof te.isInverse=="function"&&te.isInverse()&&S(te));if(v.length===0)continue;const x=i.map(te=>this.collectInverseLinkValues(te,v)),I=Array.from(new Set(x.flat().filter(te=>typeof te=="string"&&te.length>0)));if(I.length===0){e.forEach(te=>{te[o]=[]});continue}let E=this.session.select().from(c);E=E.whereByIri(I);const Q=await E,K=this.groupRowsByIri(Q);i.forEach((te,se)=>{const D=x[se],ne=[];D.forEach(y=>{const C=K.get(y);C&&C.length>0&&ne.push(...C)}),te[o]=ne});continue}const h=A[0],T=d?.references&&d.references[0],w=h.isLink(),b=i.map(ee=>this.resolveParentKey(ee,T,w)).filter(ee=>typeof ee=="string"&&ee.length>0);if(b.length===0)continue;let N=this.session.select().from(c);w?N=N.where(inArray(h,b)):N=N.where({[h.name]:b});const O=await N,X=new Map;for(const ee of O){const V=ee[h.name],U=this.normalizeLiteralValue(V),v=w?this.collectLinkLookupKeys(V):U?[U]:[];for(const x of v){const I=X.get(x)??[];I.push(ee),X.set(x,I)}}i.forEach(ee=>{const V=w?Array.from(new Set([this.resolveParentKey(ee,T,!0),this.resolveIdFromRow(ee)].filter(v=>typeof v=="string"&&v.length>0))):[this.resolveParentKey(ee,T,!1)].filter(v=>typeof v=="string"&&v.length>0),U=[];for(const v of V){const x=X.get(v)??[];for(const I of x)U.includes(I)||U.push(I)}ee[o]=U})}return i}dedupeBySubject(e){const t=new Map,n=[];for(const a of e){const i=this.resolveIriFromRow(a)??this.resolveIdFromRow(a);if(!i){n.push(`__anon_${n.length}`),t.set(n[n.length-1],{...a});continue}if(!t.has(i)){t.set(i,{...a}),n.push(i);continue}const o=t.get(i);if(o)for(const[s,d]of Object.entries(a)){if(d===void 0)continue;const u=o[s];if(u===void 0){o[s]=d;continue}const c=Array.isArray(u)?u:[u],p=Array.isArray(d)?d:[d],_=[...c];for(const m of p)_.some(S=>S===m)||_.push(m);o[s]=_.length===1?_[0]:_}}return n.map(a=>t.get(a)).filter(a=>a!==void 0)}resolveIdFromRow(e){if(!e)return;if(typeof e.id=="string"&&e.id.length>0)return e.id;const t=typeof e["@id"]=="string"?e["@id"]:void 0;if(t)return this.extractFragment(t)}resolveParentKey(e,t,n){if(t){const a=e[t.name];return n?this.normalizeLinkValue(a):this.normalizeLiteralValue(a)}return n?this.resolveIriFromRow(e):this.resolveIdFromRow(e)}resolveIriFromRow(e){if(e){if(typeof e["@id"]=="string"&&e["@id"].length>0)return e["@id"];if(typeof e.subject=="string"&&e.subject.length>0)return e.subject}}collectLinkLookupKeys(e){const t=[],n=this.normalizeLinkValue(e)??this.normalizeLiteralValue(e);if(n){t.push(n);const a=this.extractFragment(n);a&&!t.includes(a)&&t.push(a)}return t}normalizeLinkValue(e){if(e){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}normalizeLiteralValue(e){if(e!=null){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}collectInverseLinkValues(e,t){if(!t.length)return[];const n=[];for(const a of t){const i=e[a.name];if(i==null)continue;const o=s=>{const d=this.normalizeLinkValue(s)??(typeof s=="string"?s:void 0);d&&n.push(d)};Array.isArray(i)?i.forEach(o):o(i)}return n}groupRowsByIri(e){const t=new Map;for(const n of e){const a=this.normalizeLinkValue(n["@id"])??this.normalizeLinkValue(n.uri)??(typeof n["@id"]=="string"?n["@id"]:void 0);if(!a)continue;const i=t.get(a)??[];i.push(n),t.set(a,i)}return t}extractFragment(e){const t=e.includes("#")?e.split("#").pop():void 0;return t&&t.length>0?t:e.split("/").pop()??e}}_a$8=entityKind;PodDatabase[_a$8]="PodDatabase";PodDatabase.findByLocatorDeprecationWarned=!1;function isAggregateExpression(r){return!!r&&typeof r=="object"&&r.kind==="aggregate"}function inferSPARQLQueryType(r){const n=r.replace(/^\s*#.*$/gm,"").trim().replace(/^(?:\s*(?:PREFIX|BASE)\s+[^\n]+\n)*/i,"").trim().match(/^(SELECT|ASK|INSERT|DELETE|UPDATE|WITH|LOAD|CLEAR|CREATE|DROP|COPY|MOVE|ADD|CONSTRUCT|DESCRIBE)\b/i)?.[1]?.toUpperCase();switch(n){case"SELECT":case"ASK":case"INSERT":case"DELETE":case"UPDATE":return n;case"WITH":case"LOAD":case"CLEAR":case"CREATE":case"DROP":case"COPY":case"MOVE":case"ADD":return"UPDATE";default:return}}function createLiteralCondition(r,e,t){const n=r?`${r}.${e}`:e;return t==null?new UnaryExpression("IS NULL",n):Array.isArray(t)?new BinaryExpression(n,"IN",t):new BinaryExpression(n,"=",t)}function buildConditionTreeFromObject(r,e){if(!r)return;const t=Object.entries(r);if(t.length===0)return;const n=t.map(([a,i])=>createLiteralCondition(e,a,i));return n.length===1?n[0]:new LogicalExpression("AND",n)}function resolveRowSubject(r){if(!(!r||typeof r!="object")){if(typeof r["@id"]=="string"&&r["@id"].length>0)return r["@id"];if(typeof r.subject=="string"&&r.subject.length>0)return r.subject;if(typeof r.uri=="string"&&r.uri.length>0)return r.uri;if(typeof r.source=="string"&&r.source.length>0)return r.source;if(typeof r.id=="string"&&r.id.length>0)return r.id}}function orderRowsBySubjects(r,e){if(!r.length||!e.length)return r;const t=new Map,n=[];for(const i of r){const o=resolveRowSubject(i);if(!o){n.push(i);continue}const s=t.get(o)??[];s.push(i),t.set(o,s)}const a=[];for(const i of e){const o=t.get(i);o?.length&&(a.push(...o),t.delete(i))}for(const i of t.values())a.push(...i);return a.push(...n),a}function isSelectFieldMap(r){return!!r&&typeof r=="object"&&!(r instanceof PodColumnBase)&&!(r instanceof PodTable)&&!("aggregateType"in r)}function resolveFieldBindingCandidates(r,e){const t=new Set;if(typeof e=="string"){if(t.add(e),e.includes(".")){const[n,a]=e.split(".",2);a&&(t.add(`${n}.${a}`),t.add(a))}}else e instanceof PodColumnBase&&(e.table?.config?.name&&t.add(`${e.table.config.name}.${e.name}`),t.add(e.name));return Array.from(t)}function isEmptyProjectedValue(r){if(r==null)return!0;if(Array.isArray(r))return r.length===0;if(typeof r=="object"){const e=Object.values(r);return e.length>0&&e.every(t=>isEmptyProjectedValue(t))}return!1}function projectTableRow(r,e){const t=e.config.name,n={};let a=!1;for(const i of Object.keys(e.columns)){const s=(t?[`${t}.${i}`,i]:[i]).find(d=>r[d]!==void 0);n[i]=s?r[s]:void 0,n[i]!==void 0&&(a=!0)}return a?n:null}function projectFieldValue(r,e,t){if(t instanceof PodTable)return projectTableRow(r,t);if(isSelectFieldMap(t)){const n={};for(const[a,i]of Object.entries(t))n[a]=projectFieldValue(r,a,i);return isEmptyProjectedValue(n)?null:n}for(const n of resolveFieldBindingCandidates(e,t))if(r[n]!==void 0)return r[n];return r[e]}function projectReturningRow(r,e){if(!e||e===!0)return r;const t={};for(const[n,a]of Object.entries(e))t[n]=projectFieldValue(r,n,a);return t}function projectReturningRows(r,e){return!e||e===!0?r:r.map(t=>projectReturningRow(t,e))}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,SINGLETON_FRAGMENTS=new Set(["#me","#this","#profile","#card"]);class UriResolverImpl{constructor(e=""){this.podUrl=e.replace(/\/$/,"")}setPodUrl(e){this.podUrl=e.replace(/\/$/,"")}resolveSubject(e,t,n,a){const i=a?.strict??!0,o=t["@id"]??t.id??t.uri;if(typeof o=="string"){if(this.isAbsoluteUri(o))return o;const c=this.resolveBaseRelativeSubjectId(e,o);if(c)return c;o.startsWith("#")&&this.acceptsFragmentOnlyResourceId(e)&&(t={...t,id:o.slice(1)})}const s=this.getEffectivePattern(e),d=this.getSubjectBaseUrl(e);if(this.isSingleton(e))return this.combineBaseAndPattern(d,s);const u=this.applyTemplate(s,t,n,e,i);return u===null?this.generateFallbackUri(d,s,n):this.isAbsoluteUri(u)?u:this.combineBaseAndPattern(d,u)}parseSubject(e,t){if(!e)return null;const n=e.indexOf("#"),a=n!==-1,i=a?e.slice(0,n):e,o=a?e.slice(n+1):void 0,s=this.extractPublicId(e,t),d=this.getResourceMode(t);return{uri:e,resourceUrl:i,fragment:o,id:s,mode:d}}getResourceUrl(e){const t=e.indexOf("#");return t!==-1?e.slice(0,t):e}getResourceMode(e){if(!(e.hasCustomTemplate?.()??!1)){const a=e.config?.base??"";return/\.(ttl|jsonld|json)$/i.test(a)?"fragment":"document"}return(e.config?.subjectTemplate??this.getDefaultPattern(e)).startsWith("#")?"fragment":"document"}getDefaultPattern(e){return"{id}"}resolveInlineChild(e,t,n,a){const i=n["@id"]??n.id;return typeof i=="string"?i:buildInlineChildUri(e,t,a)}isSingleton(e){const t=e.config?.subjectTemplate;return t?!!(SINGLETON_FRAGMENTS.has(t)||!t.includes("{")):!1}resolveLink(e,t,n){const a=String(e??""),i=n?.record&&typeof n.record=="object"?n.record:void 0;if(this.isAbsoluteUri(a))return a;if(a.startsWith("/")||a.startsWith("#")){const c=n?.baseUri||this.podUrl;if(c)try{return new URL(a,c).toString()}catch{}throw new Error(`Cannot resolve relative URI "${a}": no baseUri configured`)}const o=t.getLinkTable?.();if(o){const c=this.getTableUriInfo(o);if(c)return this.buildFullUri(a,c.baseUrl,c.subjectTemplate,o,n,i);throw new Error(`Cannot resolve URI "${a}": linked table "${o.config?.name}" has no base configured.`)}const s=t.getLinkTableName?.();if(s){if(n?.tableNameRegistry){const p=n.tableNameRegistry.get(s);if(p){const _=this.getTableUriInfo(p);if(_)return this.buildFullUri(a,_.baseUrl,_.subjectTemplate,p,n,i)}}const c=n?.tableNameRegistry?Array.from(n.tableNameRegistry.keys()).join(", "):"(no tables registered)";throw new Error(`Cannot resolve URI "${a}": table "${s}" not found in schema. Available tables: ${c}`)}const d=t.getLinkTarget?.();if(d){if(!n?.tableRegistry)throw new Error(`Cannot resolve URI "${a}" (links to ${d}): tableRegistry not configured. Ensure the schema is properly registered.`);const c=n.tableRegistry.get(d);if(c&&c.length>0){if(c.length>1){const m=c.map(S=>S.config?.name||"unknown").join(", ");throw new Error(`Ambiguous link target: class "${d}" has multiple tables [${m}]. Use .link('tableName') or .link(tableObject) to specify which table to use.`)}const p=c[0],_=this.getTableUriInfo(p);if(_)return this.buildFullUri(a,_.baseUrl,_.subjectTemplate,p,n,i)}throw new Error(`Cannot resolve URI "${a}": class "${d}" not found in tableRegistry. Available classes: ${Array.from(n.tableRegistry.keys()).join(", ")||"(none)"}`)}const u=n?.baseUri||this.podUrl;if(u&&this.isAbsoluteUri(u)){const c=u.endsWith("/")?u:`${u}/`;return this.buildFullUri(a,c)}throw new Error(`Cannot resolve URI "${a}". Either provide a full URI (https://...), or configure baseUri.`)}isAbsoluteUri(e){return!e||typeof e!="string"?!1:e.includes(":")&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("urn:")||e.startsWith("did:")||e.startsWith("mailto:")||e.startsWith("tel:")||e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))}isLinkColumn(e){return e?e.dataType==="uri"||e.isLink?.()||!!e.options?.linkTarget||!!e.options?.linkTableName||!!e.options?.linkTable:!1}findTargetTable(e,t){const n=e.getLinkTable?.()||e.options?.linkTable;if(n)return n;const a=e.getLinkTableName?.()||e.options?.linkTableName;if(a&&t?.tableNameRegistry){const o=t.tableNameRegistry.get(a);if(o)return o}const i=e.getLinkTarget?.()||e.options?.linkTarget;if(i&&t?.tableRegistry){const o=t.tableRegistry.get(i);if(o&&o.length===1)return o[0]}}extractLinkId(e,t,n){if(e?.startsWith("/")){const o=n?.baseUri||this.podUrl;if(o){const s=o.endsWith("/")?o:`${o}/`;e=new URL(e.replace(/^\/+/,""),s).toString()}}if(!e||!this.isAbsoluteUri(e))return e;const a=this.findTargetTable(t,n);if(!a)return e;const i=this.extractTemplateIdFromSubject(e,a);return i||e}getTableUriInfo(e){const t=e.config?.base;if(!t)return;const n=e.config?.subjectTemplate;return{baseUrl:this.toAbsoluteUrl(t),subjectTemplate:n}}buildFullUri(e,t,n,a,i,o){const s=String(e??"");if(!n){const _=this.combineBaseAndResourceId(t,s);return this.assertNoUnresolvedTemplate(_,void 0,a),_}if(!UUID_REGEX.test(s)&&s.includes("/")&&!s.includes("{")){const _=`${t}${s}`;return this.assertNoUnresolvedTemplate(_,n,a),_}const d=this.buildTemplateRecord(s,n,a,i,o),u=this.applyTemplate(n,d,void 0,a,!0,i);if(u===null)throw new Error(`[UriResolver] Failed to resolve URI template "${n}" for table "${a?.config?.name??"unknown"}"`);if(this.isAbsoluteUri(u))return this.assertNoUnresolvedTemplate(u,n,a),u;if(u.startsWith("#")){const m=`${t.endsWith("/")?t.slice(0,-1):t}${u}`;return this.assertNoUnresolvedTemplate(m,n,a),m}const p=`${t.endsWith("/")?t:`${t}/`}${u}`;return this.assertNoUnresolvedTemplate(p,n,a),p}buildTemplateRecord(e,t,n,a,i){const o={...i??{}};o.id=e;for(const s of t.matchAll(/\{([^}]+)\}/g)){const u=this.parseTemplateVariable(s[1]).field;if(u==="id"||u==="index"||u in o)continue;const c=this.resolveTemplateVariable(u,n,a,i);c!=null&&c!==""&&(o[u]=c)}return o}resolveTemplateVariable(e,t,n,a){if(!a||typeof a!="object")return;if(e in a){const d=t?.columns?.[e];return this.normalizeValue(a[e],d,n)}const i=`${e}Id`;if(i in a)return String(a[i]);const o=t?.columns?.[e],s=o?this.findTargetTable(o,n):void 0;if(s)for(const[d,u]of Object.entries(a)){const c=n?.currentTable?.columns?.[d];if((c?this.findTargetTable(c,n):void 0)===s)return this.normalizeValue(u,o,n)}}assertNoUnresolvedTemplate(e,t,n){if(/\{[^}]+\}/.test(e)){const a=n?.config?.name||"unknown";throw new Error(`[UriResolver] Unresolved URI template variable while resolving table "${a}" with template "${t??"<exact-id>"}": ${e}`)}}getEffectivePattern(e){if(e.hasCustomTemplate?.()??!1){const n=e.config?.subjectTemplate;if(n&&n.trim().length>0)return n}return this.getDefaultPattern(e)}getSubjectBaseUrl(e){const t=e.config?.base??"";return this.toAbsoluteUrl(t)}isBaseRelativeSubjectId(e){return!e||this.isAbsoluteUri(e)||e.startsWith("/")?!1:e.startsWith("#")||e.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(e)}acceptsFragmentOnlyResourceId(e){const t=e.config?.subjectTemplate;if(!t)return!1;const n=Array.from(t.matchAll(/\{([^}]+)\}/g)).map(a=>this.parseTemplateVariable(a[1]).field);return t==="#{id}"||t.startsWith("#")&&n.length===1&&n[0]==="id"}resolveBaseRelativeSubjectId(e,t){if(!this.isBaseRelativeSubjectId(t))return null;const n=this.getSubjectBaseUrl(e);if(t.startsWith("#"))return this.acceptsFragmentOnlyResourceId(e)?`${n}${t}`:null;if(n.endsWith("/"))return`${n}${t}`;const a=n.lastIndexOf("/");return`${a>=0?n.slice(0,a+1):`${n}/`}${t}`}toAbsoluteUrl(e){if(!e)return this.podUrl;if(this.isAbsoluteUri(e))return e;const t=e.startsWith("/")?e:`/${e}`;return`${this.podUrl}${t}`}combineBaseAndPattern(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:e.endsWith("/")?`${e}${t}`:(e.endsWith(".ttl")||e.endsWith(".jsonld"))&&t.startsWith("#")?`${e}${t}`:`${e}/${t}`}combineBaseAndResourceId(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:`${e.endsWith("/")?e:`${e}/`}${t}`}normalizeValue(e,t,n){return e==null?"":typeof e=="string"&&this.isAbsoluteUri(e)&&t&&this.isLinkColumn(t)?this.extractLinkId(e,t,n):String(e)}parseTemplateVariable(e){const[t,...n]=e.split("|").map(a=>a.trim()).filter(Boolean);return{raw:e,field:t||e,transforms:n}}slugifyValue(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu,"-").replace(/^-+|-+$/g,"")}applyTransforms(e,t,n,a){let i=this.normalizeValue(e,n,a);for(const o of t.transforms){if(o==="id"){i=n&&this.isLinkColumn(n)?this.extractLinkId(i,n,a):i;continue}o==="slug"&&(i=this.slugifyValue(i))}return i}applyTemplate(e,t,n,a,i=!0,o){if(!e.includes("{"))return e;const s=this.createTimeContext(t),d=[],u=e.replace(/(#?)\{([^}]+)\}/g,(c,p,_)=>{const m=this.parseTemplateVariable(_),S=m.field;if(S in s)return p+s[S];if(S==="index"&&n!==void 0)return p+String(n+1);let A=t[S];if(S==="id"&&A==null&&(A=t["@id"]??t.uri),A==null)return d.push(_),c;const h=a?.columns?.[S],T=o??(a?{tableRegistry:a[Symbol.for("drizzle:tableRegistry")],tableNameRegistry:a[Symbol.for("drizzle:tableNameRegistry")]}:void 0),w=this.applyTransforms(A,m,h,T);return p==="#"&&w.startsWith("#")?p+w.slice(1):p+w});if(d.length>0){if(i){const c=a?.config?.name||"unknown";throw new Error(`[UriResolver] Missing required fields for template "${e}" in table "${c}": [${d.join(", ")}]. Record keys: [${Object.keys(t).join(", ")}]. Record: ${JSON.stringify(t)}`)}return null}return u}createTimeContext(e){let t;const n=e.createdAt??e.created_at??e.dateCreated;n instanceof Date?t=n:typeof n=="string"||typeof n=="number"?t=new Date(n):t=new Date;const a=t.getUTCFullYear().toString(),i=(t.getUTCMonth()+1).toString().padStart(2,"0"),o=t.getUTCDate().toString().padStart(2,"0"),s=Math.floor(t.getTime()/1e3).toString();return{date:t,yyyy:a,MM:i,dd:o,timestamp:s}}generateFallbackUri(e,t,n){const a=n!==void 0?`row-${n+1}`:`row-${Date.now()}`;return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}#${a}`:`${e.endsWith("/")?e:`${e}/`}${a}.ttl`}extractRelativeSubjectId(e,t){const n=t.config?.base??"";let a="";if(n&&e.includes(n)){const i=e.indexOf(n);a=e.substring(i+n.length),a.startsWith("#")&&!(t.hasCustomTemplate?.()??!1)&&(a=`${n.split("/").filter(Boolean).pop()??""}${a}`),a.startsWith("/")&&(a=a.substring(1))}else if(!n)a=e;else return console.warn(`[UriResolver] Cannot extract ID: base "${n}" not found in URI "${e}"`),"";return a}extractPublicId(e,t){return this.extractTemplateIdFromSubject(e,t)??this.extractRelativeSubjectId(e,t)}extractTemplateIdFromSubject(e,t){const n=this.extractRelativeSubjectId(e,t),a=t.config?.subjectTemplate;return a?this.extractIdFromTemplate(n,a):n}extractIdFromTemplate(e,t){let n=t.replace(/[.+?^$[\]\\()]/g,"\\$&").replace(/\{id\}/g,"(?<id>.+?)").replace(/\{[^}]+\}/g,"(?:.+?)");n=`^${n}$`;try{const a=new RegExp(n),i=e.match(a);if(i&&i.groups?.id)return i.groups.id;if(i&&i[1])return i[1]}catch{}return null}}function buildInlineChildUri(r,e,t){const n=r.indexOf("#"),a=n>=0?r.slice(0,n):r,i=n>=0?r.slice(n+1):"",o=i?`${encodeURIComponent(i)}/`:"";return`${a}#${o}${encodeURIComponent(e)}-${t+1}`}function isOrderByExpression(r){if(!r||typeof r!="object")return!1;const e=r;return"column"in e&&(e.direction==="asc"||e.direction==="desc")}function isReservedIdentifierKey(r){return r==="id"||r==="@id"||r.endsWith(".id")||r.endsWith(".@id")}function isReservedIdentifierOperand(r){if(r instanceof PodColumnBase){const e=r;return r.name==="id"||r.options?.predicate==="@id"||e._virtualId===!0}return typeof r=="string"?isReservedIdentifierKey(r):!1}function conditionTargetsReservedIdentifier(r){return r.type==="binary_expr"?!!(isReservedIdentifierOperand(r.left)||isReservedIdentifierOperand(r.right)):r.type==="logical_expr"?r.expressions.some(e=>e!=null&&typeof e=="object"&&"type"in e&&conditionTargetsReservedIdentifier(e)):r.type==="unary_expr"?r.value!=null&&typeof r.value=="object"&&"type"in r.value&&conditionTargetsReservedIdentifier(r.value):!1}function createWhereIdentifierError(r){switch(r){case"select":return["Using 'id' or '@id' in where() is not supported.","Use findById(id) for base-relative resource ids,","or findByIri(iri) for full IRI exact lookups."].join(" ");case"update":return["Using 'id' or '@id' in where() is not supported.","Use updateById(id, data) for base-relative resource ids,","or updateByIri(iri, data) for full IRI exact updates."].join(" ");case"delete":return["Using 'id' or '@id' in where() is not supported.","Use deleteById(id) for base-relative resource ids,","or deleteByIri(iri) for full IRI exact deletes."].join(" ")}}function assertPublicWhereObject(r,e){if(e){for(const t of Object.keys(e))if(isReservedIdentifierKey(t))throw new Error(createWhereIdentifierError(r))}}function assertPublicWhereCondition(r,e){if(conditionTargetsReservedIdentifier(e))throw new Error(createWhereIdentifierError(r))}function assertPublicCursorCondition(r){let e=!1,t=!1;const n=a=>{if(a.type==="binary_expr"){if(isReservedIdentifierOperand(a.left)||isReservedIdentifierOperand(a.right)){if(![">",">=","<","<="].includes(a.operator))throw new Error("whereCursor() only supports range comparisons on 'id' or '@id'.");e=!0}else t=!0;return}if(a.type==="logical_expr"){for(const i of a.expressions)n(i);return}t=!0};if(n(r),!e||!t)throw new Error("whereCursor() requires a sort predicate plus an 'id' or '@id' range tie-breaker.")}var define_process_env_default$2={},_a$7;class SelectQueryBuilder{constructor(e,t){this.session=e,this.joins=[],this.orderByClauses=[],this.isDistinct=!1,this.tableAliases=new Map,this.aliasToTable=new Map,this.aliasUsage=new Map,this.joinFilters=[],this.groupByColumns=[],t&&this.setSelectedFields(t)}from(e){return this.selectedTable=e,this.primaryAlias=this.ensureAliasForTable(e),this}columns(e){return this.setSelectedFields(e),this}setSelectedFields(e){this.selectedFields={...e}}where(e){return e instanceof SQL?this.sql=e:this.isQueryCondition(e)?(assertPublicWhereCondition("select",e),this.processQueryCondition(e)):(assertPublicWhereObject("select",e),this.processWhereObject(e)),this}whereCursor(e){return assertPublicCursorCondition(e),this.processQueryCondition(e),this}whereByIri(e){return this.processWhereObject({"@id":e}),this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,n=e.right,a=e.operator,i=typeof t=="string"?t:t?.name;if(a==="="&&i&&n!==void 0)return{[i]:n}}if(e.type==="logical_expr"){const t=e.operator,n=e.expressions;if(t==="AND"&&n){const a={};for(const i of n){const o=this.convertQueryConditionToSimple(i);if(!o||Object.keys(o).length===0)return{};for(const[s,d]of Object.entries(o))a[s]=d}return a}}return{}}extractTableFromCondition(e){if(e.type==="binary_expr"){const t=e.left;if(t&&typeof t=="object"&&"table"in t){const n=t.table;if(n)return this.tableAliases.get(n)}if(typeof t=="string"&&t.includes("."))return t.split(".")[0]}}leftJoin(e,t){return this.addJoin("leftJoin",e,t)}rightJoin(e,t){return this.addJoin("rightJoin",e,t)}innerJoin(e,t){return this.addJoin("innerJoin",e,t)}fullJoin(e,t){return this.addJoin("fullJoin",e,t)}crossJoin(e){return this.addJoin("crossJoin",e)}groupBy(...e){const t=e.map(n=>this.resolveColumnReference(n));return this.groupByColumns.push(...t),this}having(e){return this.havingCondition=typeof e=="function"?e(this.createSelectedFieldAliases()):e,this}createSelectedFieldAliases(){const e={};for(const t of Object.keys(this.selectedFields??{}))e[t]=new SelectionAliasExpression(t);return e}addJoin(e,t,n){if(e==="rightJoin"||e==="fullJoin")throw new Error(`${e} is not yet supported in Solid dialect`);const a=this.ensureAliasForTable(t),i=e==="crossJoin"?void 0:this.resolveJoinConditions(n,a);return this.joins.push({type:e,table:t,alias:a,rawCondition:n,resolvedConditions:i}),this}ensureAliasForTable(e){const t=this.tableAliases.get(e);if(t)return t;const n=e.config.name||"table",a=this.aliasUsage.get(n)??0,i=a+1;this.aliasUsage.set(n,i);const o=a===0?n:`${n}_${i}`;return this.tableAliases.set(e,o),this.aliasToTable.set(o,e),o}resolveJoinConditions(e,t){if(this.isQueryCondition(e))return this.resolveJoinConditionExpression(e,t);if(!e||typeof e!="object")throw new Error("JOIN condition must be an equality expression or column mapping");const n=Object.entries(e);if(n.length===0)throw new Error("JOIN condition cannot be empty");return n.map(([a,i])=>{const o=this.resolveColumnReference(a),s=this.resolveColumnReference(i);if(o.alias!==t&&s.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return{left:o,right:s}})}resolveJoinConditionExpression(e,t){if(e.type==="logical_expr"){const i=(e.operator??"").toUpperCase(),o=e.expressions??[];if(i!=="AND"||o.length===0)throw new Error("JOIN condition only supports equality expressions combined with AND");return o.flatMap(s=>this.resolveJoinConditionExpression(s,t))}if(e.type!=="binary_expr"||e.operator!=="=")throw new Error("JOIN condition only supports equality expressions");const n=this.getConditionColumnReference(e.left),a=this.getConditionColumnReference(e.right);if(!n||!a)throw new Error("JOIN equality must compare two table columns");if(n.alias!==t&&a.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return[{left:n,right:a}]}getConditionColumnReference(e,t){if(e instanceof PodColumnBase)return this.resolveColumnReference(e,t);if(typeof e=="string"){if(e.includes("."))return this.resolveColumnReference(e,t);const n=t??this.primaryAlias,a=n?this.aliasToTable.get(n):void 0;if(a&&e in(a.columns??{}))return this.resolveColumnReference(e,t)}}resolveColumnReference(e,t){if(e instanceof PodColumnBase){const n=e.table;if(!n)throw new Error(`Column ${e.name} is not associated with a table`);const a=this.ensureAliasForTable(n);return{table:n,alias:a,column:e.name}}if(typeof e=="string"){const{alias:n,column:a}=this.parseColumnReferenceString(e),i=n??t??this.primaryAlias;if(!i)throw new Error(`Unable to resolve table alias for column reference "${e}"`);const o=this.aliasToTable.get(i);if(!o)throw new Error(`Unknown table alias "${i}" in column reference "${e}"`);return{table:o,alias:i,column:a}}throw new Error("Unsupported column link type")}parseColumnReferenceString(e){const t=e.trim();if(!t.includes("."))return{column:t};const[n,a]=t.split(".",2);return{alias:n,column:a}}processWhereObject(e){if(!e)return;const t={...this.whereConditions??{}};for(const[n,a]of Object.entries(e)){const{alias:i,column:o}=this.parseColumnReferenceString(n),s=i??this.primaryAlias;if(!s||s===this.primaryAlias||!this.aliasToTable.has(s)){t[o]=a;continue}this.joinFilters.push(createLiteralCondition(s,o,a))}this.whereConditions=Object.keys(t).length>0?t:void 0}processQueryCondition(e){const t=this.extractTableFromCondition(e);if(t&&t!==this.primaryAlias){this.joinFilters.push(e);return}this.conditionTree=e;const n=this.convertQueryConditionToSimple(e);Object.keys(n).length>0&&(this.whereConditions=n)}applyInternalQueryCondition(e){return this.processQueryCondition(e),this}normalizeWhereConditions(){if(this.conditionTree)return this.conditionTree;const e=this.primaryAlias??this.selectedTable?.config.name;return buildConditionTreeFromObject(this.whereConditions,e)}toIR(){const e=this.normalizeWhereConditions();return this.buildQueryPlan(e)}buildQueryPlan(e){if(!this.selectedTable)throw new Error("No table specified for SELECT query");const t=this.joins.map(n=>({type:n.type,table:n.table,alias:n.alias,conditions:(n.resolvedConditions??[]).map(({left:a,right:i})=>({left:a,right:i}))}));return{baseTable:this.selectedTable,baseAlias:this.primaryAlias??this.selectedTable.config.name,select:this.selectedFields,selectAll:!this.selectedFields,where:this.whereConditions,conditionTree:e,joins:t.length>0?t:void 0,joinFilters:this.joinFilters.length>0?[...this.joinFilters]:void 0,groupBy:this.groupByColumns.length>0?[...this.groupByColumns]:void 0,having:this.havingCondition,orderBy:this.orderByClauses.length>0?this.orderByClauses.map(n=>({rawColumn:n.column,direction:n.direction})):void 0,distinct:this.isDistinct||void 0,limit:this.limitCount,offset:this.offsetCount,aliasToTable:new Map(this.aliasToTable),tableToAlias:new Map(this.tableAliases)}}limit(e){if(!Number.isInteger(e)||e<0)throw new Error("LIMIT must be a non-negative integer");return this.limitCount=e,this}offset(e){if(!Number.isInteger(e)||e<0)throw new Error("OFFSET must be a non-negative integer");return this.offsetCount=e,this}addOrderByClause(e,t="asc"){const n=typeof e=="string"?e:e.name;if(!n)throw new Error("ORDER BY requires a valid column name");this.orderByClauses.push({column:n,direction:t})}orderBy(...e){if(e.length===0)throw new Error("ORDER BY requires at least one column or expression");if(e.length===2&&(e[0]instanceof PodColumnBase||typeof e[0]=="string")&&(e[1]==="asc"||e[1]==="desc"))return this.addOrderByClause(e[0],e[1]),this;for(const t of e){if(isOrderByExpression(t)){this.addOrderByClause(t.column,t.direction);continue}if(t instanceof PodColumnBase||typeof t=="string"){this.addOrderByClause(t,"asc");continue}throw new Error("ORDER BY received an unsupported argument")}return this}distinct(e=!0){return this.isDistinct=e,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const n=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(n);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:n,prefixes:{}}}if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.joins.length>0)throw new Error(`${e} is not yet supported for JOIN queries in Solid dialect`);if(this.shouldUseProjectionFallback())throw new Error(`${e} does not support structured selections in Solid dialect`);const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertSelectPlan(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.limitCount===0)return[];if(this.sql)return await this.session.executeSql(this.sql,this.selectedTable);{const e=this.toIR(),t=e.conditionTree,n=this.joins.length>0,a=this.shouldUseAggregateFallback(),i=this.shouldUseProjectionFallback(),o=n||a;(n||a||i)&&(e.select=void 0,e.selectAll=!0);const s=o?{...e,limit:void 0,offset:void 0,orderBy:void 0,...n?{joins:void 0,joinFilters:void 0}:{},...a?{groupBy:void 0,having:void 0}:{}}:n?{...e,joins:void 0,joinFilters:void 0}:e,d={type:"select",table:this.selectedTable,where:t,limit:o?void 0:this.limitCount,offset:o?void 0:this.offsetCount,orderBy:o||this.orderByClauses.length===0?void 0:this.orderByClauses,distinct:this.isDistinct||void 0};if(d.plan=s,this.groupByColumns.length===0&&this.hasMixedAggregateSelection())throw new Error("Mixed aggregate and non-aggregate selections require groupBy columns");let u;if(!n&&!a&&!i?(this.selectedFields&&(d.select=this.selectedFields),u=await this.session.execute(d),u=this.applySubjectMetadata(u)):(n?d.select=void 0:!a&&!i?d.select=this.selectedFields:d.select=void 0,u=await this.session.execute(d),n||(u=this.applySubjectMetadata(u)),n&&(u=this.normalizeBaseRows(u),u=this.mergeRowsBySubject(u),u=await this.applyJoinFallback(u),u=this.applyJoinFilters(u))),a){let p=this.handleAggregateFallback(u);return p=this.applyHavingFilter(p),o&&(p=this.applyDeferredOrderBy(p),p=this.applyDeferredOffsetAndLimit(p)),p}let c=u;return n||(c=this.mergeRowsBySubject(c)),this.selectedTable&&(c=await this.hydrateInlineColumns(c,this.selectedTable,!n)),n&&(c=this.applyDeferredOrderBy(c)),this.selectedFields&&(c=c.map(p=>this.projectSelectedRow(p))),c=this.applyDistinctRows(c),n||(c=this.mergeRowsBySubject(c)),n&&(c=this.applyDeferredOffsetAndLimit(c)),c}}projectSelectedRow(e){return this.selectedFields?this.projectFieldMap(e,this.selectedFields):e}projectFieldMap(e,t,n=!0){const a={};for(const[i,o]of Object.entries(t))a[i]=this.projectFieldValue(e,i,o,n);return a}projectFieldValue(e,t,n,a=!0){if(isAggregateExpression(n))return a?e[t]:void 0;if(n instanceof PodTable)return this.projectTableValue(e,n);if(this.isSelectFieldMap(n)){const i=this.collectSelectionAliases(n),o=i.size===1&&!i.has(this.primaryAlias??""),s=this.projectFieldMap(e,n,!o);if(i.size===1){const[d]=Array.from(i);if(d&&d!==this.primaryAlias&&this.isProjectedValueEmpty(s))return null}return s}for(const i of this.resolveFieldBindingCandidates(t,n))if(e[i]!==void 0)return e[i];return a?e[t]:void 0}projectTableValue(e,t){const n=this.tableAliases.get(t)??t.config.name,a={};let i=!1;for(const o of Object.keys(t.columns)){const d=(n===this.primaryAlias?[o,`${n}.${o}`]:[`${n}.${o}`]).find(u=>e[u]!==void 0);a[o]=d?e[d]:void 0,a[o]!==void 0&&(i=!0)}return n!==this.primaryAlias&&!i?null:a}isSelectFieldMap(e){return!!e&&typeof e=="object"&&!(e instanceof PodColumnBase)&&!(e instanceof PodTable)&&!isAggregateExpression(e)}collectSelectionAliases(e){if(typeof e=="string"){const{alias:n}=this.parseColumnReferenceString(e);return new Set(n?[n]:this.primaryAlias?[this.primaryAlias]:[])}if(e instanceof PodColumnBase)return new Set([this.resolveColumnReference(e).alias]);if(e instanceof PodTable)return new Set([this.tableAliases.get(e)??e.config.name]);if(!this.isSelectFieldMap(e))return new Set;const t=new Set;for(const n of Object.values(e))for(const a of this.collectSelectionAliases(n))t.add(a);return t}isProjectedValueEmpty(e){if(e==null)return!0;if(Array.isArray(e))return e.length===0;if(typeof e=="object"){const t=Object.values(e);return t.length>0&&t.every(n=>this.isProjectedValueEmpty(n))}return!1}resolveFieldBindingCandidates(e,t){const n=new Set;if(typeof t=="string"){const{alias:a,column:i}=this.parseColumnReferenceString(t);n.add(t),n.add(i),a&&n.add(`${a}.${i}`)}else if(t instanceof PodColumnBase){const a=this.resolveColumnReference(t);n.add(`${a.alias}.${a.column}`),(!a.alias||a.alias===this.primaryAlias)&&n.add(t.name)}else if(t&&typeof t=="object"){const a=t.name;typeof a=="string"&&n.add(a)}return Array.from(n)}shouldUseProjectionFallback(){if(!this.selectedFields)return!1;const e=t=>!!(t instanceof PodTable||this.isSelectFieldMap(t));return Object.values(this.selectedFields).some(t=>e(t))}shouldUseAggregateFallback(){if(this.havingCondition)return!0;if(this.joins.length>0)return this.groupByColumns.length>0||this.hasAggregateSelection();if(this.groupByColumns.length>0||!this.selectedFields)return!1;const e=Object.values(this.selectedFields);return e.length>0&&e.every(t=>isAggregateExpression(t))}buildAggregateRow(e){const t={};if(!this.selectedFields)return t;for(const[n,a]of Object.entries(this.selectedFields))isAggregateExpression(a)&&(t[n]=this.computeAggregateValue(a,e));return t}computeAggregateValue(e,t){const n=this.resolveAggregateColumnRef(e);if(!n)return e.func==="count"?e.distinct?this.countDistinctRows(t):t.length:null;switch(e.func){case"count":return this.collectValuesForCount(n,t,!!e.distinct).length;case"sum":{const a=this.collectNumericValues(n,t,!!e.distinct);return a.length===0?null:a.reduce((i,o)=>i+o,0)}case"avg":{const a=this.collectNumericValues(n,t,!!e.distinct);return a.length===0?null:a.reduce((o,s)=>o+s,0)/a.length}case"min":{const a=this.collectNumericValues(n,t,!!e.distinct);return a.length===0?null:Math.min(...a)}case"max":{const a=this.collectNumericValues(n,t,!!e.distinct);return a.length===0?null:Math.max(...a)}default:return null}}resolveAggregateColumnRef(e){const t=e.column;if(t){if(typeof t=="string")return this.resolveColumnReference(t);if(t instanceof PodColumnBase)return this.resolveColumnReference(t);if(typeof t=="object"&&"name"in t){const n=t.name;if(typeof n=="string")return this.resolveColumnReference(n)}}}collectValuesForCount(e,t,n){const a=t.map(s=>this.getRowValueForColumn(s,e)).filter(s=>s!=null);if(!n)return a;const i=new Set,o=[];for(const s of a){const d=this.serializeValueForKey(s);i.has(d)||(i.add(d),o.push(s))}return o}collectNumericValues(e,t,n){const a=[],i=new Set;for(const o of t){const s=this.getRowValueForColumn(o,e);if(s==null)continue;const d=Number(s);if(!Number.isNaN(d))if(n){const u=this.serializeValueForKey(d);i.has(u)||(i.add(u),a.push(d))}else a.push(d)}return a}countDistinctRows(e){const t=new Set;for(const n of e){const a=this.serializeValueForKey(n);t.add(a)}return t.size}handleAggregateFallback(e){if(!this.selectedFields){if(this.groupByColumns.length===0)return e;const t=new Map;for(const n of e){const a=this.groupByColumns.map(o=>this.serializeValueForKey(this.getRowValueForColumn(n,o))),i=JSON.stringify(a);t.has(i)||t.set(i,n)}return Array.from(t.values())}return this.groupByColumns.length===0?[this.buildAggregateRow(e)]:this.buildGroupedAggregateRows(e)}buildGroupedAggregateRows(e){if(!this.selectedFields)return e;this.ensureGroupByValidity();const t=new Map;for(const a of e){const i=this.groupByColumns.map(s=>this.serializeValueForKey(this.getRowValueForColumn(a,s))),o=JSON.stringify(i);t.has(o)||t.set(o,{rows:[],first:a}),t.get(o)?.rows.push(a)}const n=[];for(const{rows:a,first:i}of t.values()){const o=this.buildAggregateRow(a),s={};for(const[d,u]of Object.entries(this.selectedFields))if(isAggregateExpression(u))s[d]=o[d];else{const c=this.resolveSelectFieldColumn(u);s[d]=c?this.getRowValueForColumn(i,c):void 0}n.push(s)}return n}ensureGroupByValidity(){if(!this.selectedFields)return;const e=this.groupByColumns.map(t=>`${t.alias}.${t.column}`);for(const t of Object.values(this.selectedFields)){if(isAggregateExpression(t))continue;const n=this.resolveSelectFieldColumn(t);if(!n)continue;const a=`${n.alias}.${n.column}`;if(!e.includes(a))throw new Error(`Column ${a} must appear in GROUP BY clause when mixed with aggregates`)}}resolveSelectFieldColumn(e){if(e instanceof PodColumnBase)return this.resolveColumnReference(e);if(typeof e=="string")return this.resolveColumnReference(e)}hasAggregateSelection(){return this.selectedFields?Object.values(this.selectedFields).some(e=>isAggregateExpression(e)):!1}hasMixedAggregateSelection(){if(!this.selectedFields)return!1;const e=Object.values(this.selectedFields),t=e.some(a=>isAggregateExpression(a)),n=e.some(a=>!isAggregateExpression(a));return t&&n}applySubjectMetadata(e){return e.map(t=>this.attachSubjectMetadata(t))}extractSubjectValue(e){const t=e.subject??e["@id"]??e.uri;if(typeof t=="object"&&t&&"value"in t){const n=t.value;return typeof n=="string"&&n.length>0?n:void 0}if(typeof t=="string"&&t.length>0)return t}attachSubjectMetadata(e){const t=this.extractSubjectValue(e);if(typeof t=="string"&&t.length>0&&(e["@id"]===void 0&&(e["@id"]=t),e.uri===void 0&&(e.uri=t),e.id===void 0)){const n=this.extractIdFromSubject(t,this.selectedTable);n!==void 0&&(e.id=n)}return e}normalizeBaseRows(e){if(!e.length)return e;const t=this.primaryAlias||this.ensureAliasForTable(this.selectedTable);return e.map(n=>{const a={...n};for(const[o,s]of Object.entries(n))o!==`${t}.${o}`&&(a[`${t}.${o}`]=s);const i=this.extractSubjectValue(n);if(i){a.subject=i,a["@id"]=i,a.uri=i,a[`${t}.subject`]=i,a[`${t}.@id`]=i,a[`${t}.uri`]=i;const o=this.extractIdFromSubject(i,this.selectedTable);o!==void 0&&(a.id===void 0&&(a.id=o),(this.shouldUseSubjectIdentityColumn(this.selectedTable,"id")||a[`${t}.id`]===void 0)&&(a[`${t}.id`]=o))}return a})}async hydrateInlineColumns(e,t,n=!0){if(!e.length)return e;const a=Object.values(t.columns??{}).filter(h=>this.isInlineObjectColumn(h));if(a.length===0)return e;n&&(e=this.mergeRowsBySubject(e));const i=new Map;a.forEach(h=>{const T=h.getPredicate(t.config.namespace);i.set(T,h)});const o=Array.from(new Set(e.map(h=>this.normalizeInlineIri(h["@id"]??h.subject??h.uri??h.id)).filter(h=>!!h)));if(o.length===0||i.size===0)return e;const s=Array.from(i.keys()).map(h=>`<${h}>`).join(" "),d=this.session.getDialect().getSPARQLExecutor(),u=[],c=new Map;for(const h of o){const T=this.inferSourceFromChild(h,t),w=c.get(T)??[];w.push(h),c.set(T,w)}for(const[h,T]of c.entries()){const b={type:"SELECT",query:`SELECT ?parent ?linkPred ?child ?pred ?obj WHERE {
|
|
33
|
+
LIMIT 50`,prefixes:{}},u=a.kind==="sparql"?await this.dialect.executeOnResource(a.resourceUrl,d,a.descriptor):await this.dialect.getSPARQLExecutor().queryContainer(a.resourceUrl,d),c=Array.from(new Set(u.map(p=>this.extractSubjectFromLookupRow(p)).filter(p=>!!p).filter(p=>this.subjectMatchesShortId(e,p,t,i))));if(c.length>1)throw new Error(`${n} found multiple resources for short id '${t}' in '${e.config?.name??"resource"}'. Use a base-relative resource id or full IRI to disambiguate.`);return c[0]??this.getIndexedSubject(e,t)}async resolveIdSubjectForExactOperation(e,t,n){return this.needsShortIdSubjectLookup(e,t)?await this.lookupSubjectIriByShortId(e,t,n):this.resolveIdSubject(e,t,n)}async findById(e,t){const n=await this.resolveIdSubjectForExactOperation(e,t,"findById");return n?await this.findByIri(e,n):null}async findByLocator(e,t){this.warnFindByLocatorDeprecation();const n=this.resolveLocatorSubject(e,t,"findByLocator");return await this.findByIri(e,n)}async findByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.findById(e,t);const n=this.resolveResourceTargetIri(e,t,"findByResource");return await this.findByIri(e,n)}async findByIri(e,t){if(!t||typeof t!="string")throw new Error("findByIri requires a valid IRI string");const n=await this.findByIriViaExactResource(e,t);return n!==void 0?n:(await this.session.select().from(e).whereByIri(t).limit(1))[0]??null}getColumnPredicate(e,t){return t.options?.predicate??t.getPredicate?.(e.config.namespace)}async findByIriViaExactResource(e,t){if(!isPodTable(e))return;const n=this.parseIri(t).documentUrl,a=await this.readPredicateObjectRowsFromDocument(n,t);if(a===null)return null;if(a!==void 0){const d=this.mapPredicateObjectRows(e,t,a);if(d!==void 0)return d}if(typeof this.dialect.executeOnResource!="function")return;const i={type:"SELECT",query:`SELECT ?p ?o WHERE { <${t}> ?p ?o . }`,prefixes:{}};let o;try{o=await this.dialect.executeOnResource(n,i)}catch(d){if(this.isMissingExactResourceError(d))return;throw d}const s=this.mapPredicateObjectRows(e,t,o);if(s!==void 0)return s}async readPredicateObjectRowsFromDocument(e,t){const n=this.dialect.getAuthenticatedFetch;if(typeof n!="function")return;let a;try{a=await n.call(this.dialect)(e,{method:"GET",headers:{Accept:"text/turtle, application/ld+json;q=0.8, */*;q=0.1"}})}catch(s){return this.isMissingExactResourceError(s)?null:void 0}if(a.status===404)return null;if(!a.ok)return;const i=a.headers.get("content-type")??"";if(i&&!i.includes("text/turtle")&&!i.includes("application/n-triples")&&!i.includes("application/trig")&&!i.includes("application/ld+json"))return;const o=await a.text();if(!o.trim())return null;try{return new N3Parser$7({baseIRI:e,format:i.includes("application/n-triples")?"N-Triples":"text/turtle"}).parse(o).filter(u=>u.subject.termType==="NamedNode"&&u.subject.value===t).map(u=>({p:u.predicate.value,o:this.convertRdfTermToValue(u.object)}))}catch{return}}convertRdfTermToValue(e){if(e.termType==="NamedNode")return e.value;if(e.termType==="BlankNode")return`_:${e.value}`;if(e.termType!=="Literal")return e.value;const t=e.datatype?.value??"";if(t.includes("#integer")||t.includes("#int"))return parseInt(e.value,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e.value);if(t.includes("#boolean"))return e.value==="true";if(t.includes("#dateTime"))return new Date(e.value);if(t.includes("#json"))try{return JSON.parse(e.value)}catch{return e.value}return e.value}isMissingExactResourceError(e){if(!isRecord$2(e))return!1;if((e.status??e.statusCode)===404)return!0;const n=e.message;return typeof n=="string"&&/\b(?:HTTP status )?404\b/.test(n)}mapPredicateObjectRows(e,t,n){if(!Array.isArray(n)||n.length===0)return null;const a={subject:t,"@id":t,uri:t},i=this.extractIdFromIri(e,t);i!==void 0&&(a.id=i);let o=!1,s=!1,d=!1;for(const u of n){if(!isRecord$2(u))continue;const c=u.p??u.predicate??u["?p"],p=u.o??u.object??u["?o"];if(typeof c=="string"){c==="http://www.w3.org/1999/02/22-rdf-syntax-ns#type"&&p===e.config.type&&(o=!0);for(const[_,m]of Object.entries(e.columns??{})){if(m._virtualId)continue;const S=this.getColumnPredicate(e,m);if(!S||S==="@id"||S!==c)continue;if(m.options?.isArray||m.dataType==="array"){const h=Array.isArray(a[_])?a[_]:a[_]===void 0?[]:[a[_]];a[_]=[...h,p]}else a[_]===void 0&&(a[_]=p);m.dataType==="object"&&typeof p=="string"&&isAbsoluteIri(p)&&(d=!0),s=!0}}}if(!o&&!s)return null;if(!d)return a}extractIdFromIri(e,t){const n=parsePodResourceRef(e,t);if(n)return n.templateValues.id??n.resourceId;try{const s=this.dialect.getResolver(e).parseId(e,t);if(s)return s}catch{}const a=e.getSubjectTemplate?.()??e.config?.subjectTemplate;if(!a)return;if(a==="{id}.ttl"){const s=t.split("/").pop()??"";return s.endsWith(".ttl")?s.slice(0,-4):s||void 0}if(a==="{id}.ttl#it"){const d=t.split("#")[0].split("/").pop()??"";return d.endsWith(".ttl")?d.slice(0,-4):d||void 0}const i=t.indexOf("#");if(i>=0&&a.includes("{id}")&&a.startsWith("#"))return decodeURIComponent(t.slice(i+1));const o=t.split("#")[0].split("/").pop()??"";return o.endsWith(".ttl")?o.slice(0,-4):void 0}parseIri(e){const t=e.indexOf("#");return t>=0?{documentUrl:e.substring(0,t),fragment:e.substring(t+1)}:{documentUrl:e,fragment:null}}async subscribeByIri(e,t,n){if(!t||typeof t!="string")throw new Error("subscribeByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`subscribeByIri requires an absolute IRI, got: ${t}`);if(!this.notificationsClient){const o=this.dialect.getAuthenticatedFetch(),s={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(o,s)}const{documentUrl:a}=this.parseIri(t),i=await this.notificationsClient.subscribe(a,{channel:n.channel,features:n.features,onNotification:async o=>{try{if(o.type==="Update"){const s=await this.findByIri(e,t);s&&await n.onUpdate(s)}else o.type==="Delete"&&await n.onDelete?.()}catch(s){n.onError?.(s)}},onError:n.onError});return()=>i.unsubscribe()}async updateByIri(e,t,n){if(!t||typeof t!="string")throw new Error("updateByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`updateByIri requires an absolute IRI, got: ${t}`);const a=n;return await this.session.update(e).set(a).whereByIri(t),await this.findByIri(e,t)}async updateById(e,t,n){const a=await this.resolveIdSubjectForExactOperation(e,t,"updateById");return a?await this.updateByIri(e,a,n):null}async updateByLocator(e,t,n){const a=this.resolveLocatorSubject(e,t,"updateByLocator");return await this.updateByIri(e,a,n)}async updateByResource(e,t,n){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.updateById(e,t,n);const a=this.resolveResourceTargetIri(e,t,"updateByResource");return await this.updateByIri(e,a,n)}async deleteByIri(e,t){if(!t||typeof t!="string")throw new Error("deleteByIri requires a valid IRI string");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`deleteByIri requires an absolute IRI, got: ${t}`);return await this.findByIri(e,t)?(await this.session.delete(e).whereByIri(t),!0):!1}async deleteById(e,t){const n=await this.resolveIdSubjectForExactOperation(e,t,"deleteById");return n?await this.deleteByIri(e,n):!1}async deleteByLocator(e,t){const n=this.resolveLocatorSubject(e,t,"deleteByLocator");return await this.deleteByIri(e,n)}async deleteByResource(e,t){if(typeof t=="string"&&this.needsShortIdSubjectLookup(e,t))return await this.deleteById(e,t);const n=this.resolveResourceTargetIri(e,t,"deleteByResource");return await this.deleteByIri(e,n)}async transaction(e){return await this.session.transaction(async t=>{const n=new PodDatabase(this.dialect,t,this.schema);return await e(n)})}getDialect(){return this.dialect}getSession(){return this.session}getSchema(){return this.schema}get discovery(){return this.dialect.getDiscovery()}async connect(){return await this.dialect.connect()}async disconnect(){return this.notificationsClient&&this.notificationsClient.unsubscribeAll(),await this.dialect.disconnect()}async subscribe(e,t){if(!this.notificationsClient){const i=this.dialect.getAuthenticatedFetch(),o={preferredChannels:this.dialect.config.preferredChannels??["streaming-http","websocket"]};this.notificationsClient=new NotificationsClient(i,o)}const n=this.resolveResourceTopic(e,t.iri),a={channel:t.channel,features:t.features,onNotification:i=>{if(t.onNotification?.(i),!!(t.onCreate||t.onUpdate||t.onDelete||t.onAdd||t.onRemove)){const s={id:i.id,type:i.type,object:i.object,published:i.published,state:i.state};switch(i.type){case"Create":t.onCreate?.(s);break;case"Update":t.onUpdate?.(s);break;case"Delete":t.onDelete?.(s);break;case"Add":t.onAdd?.(s);break;case"Remove":t.onRemove?.(s);break}}},onError:t.onError,onClose:t.onClose};return this.notificationsClient.subscribe(n,a)}resolveResourceTopic(e,t){if(t){if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`iri must be an absolute URL, got: ${t}`);return t}const n=e.config.base||"";if(n.startsWith("http://")||n.startsWith("https://"))return n;const a=this.dialect.getPodUrl(),i=a.endsWith("/")?a:`${a}/`,o=n.startsWith("/")?n.slice(1):n;return`${i}${o}`}getConfig(){return this.dialect.getConfig()}async discoverTable(e){const t=await this.dialect.discoverDataLocations(e);if(t.length===0)return console.log(`[discoverTable] No data locations found for ${e}`),null;const n=t[0],a=n.shapes[0]?.url;if(console.log(`[discoverTable] Found location: ${n.container}, shape: ${a||"none"}`),a){const u=this.dialect.getShapeManager(),c=await u.loadShape(a,this.dialect.getAuthenticatedFetch());if(c){console.log(`[discoverTable] Loaded shape with ${c.properties.length} properties`);const p=u.shapeToTable(c,n.container);return await this.init(p.table),p.table}}console.log("[discoverTable] No shape available, creating basic table");const{podTable:i,string:o}=await __vitePreload(async()=>{const{podTable:u,string:c}=await import("./XpodShellApp-D1b3kqD0.js").then(p=>p.F);return{podTable:u,string:c}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),s=this.extractClassName(e),d=i(s,{id:o("id").primaryKey()},{type:e,base:n.container});return await this.init(d),d}async discoverTables(e){const t=[];for(const n of e){const a=await this.discoverTable(n);a&&t.push(a)}return t}async discover(e,t){return this.dialect.discoverDataLocations(e,t)}async discoverAll(){return this.dialect.discoverAll()}async discoverByApp(e){return this.dialect.discoverByApp(e)}async locationToTable(e,t){const n=t??{};let a;if(n.shape)typeof n.shape=="string"?(a=e.shapes.find(u=>u.url===n.shape),a||(a={url:n.shape,source:"config"})):a=n.shape;else if(n.appId){if(a=e.shapes.find(u=>u.registeredBy===n.appId),!a)throw new Error(`[locationToTable] No shape found for appId: ${n.appId}`)}else a=e.shapes[0];if(a?.url){const u=this.dialect.getShapeManager(),c=await u.loadShape(a.url,this.dialect.getAuthenticatedFetch());if(c){console.log(`[locationToTable] Loaded shape: ${a.url} (${c.properties.length} properties)`),a.registeredBy&&console.log(`[locationToTable] -> registeredBy: ${a.registeredBy}`);const p=u.shapeToTable(c,e.container);return await this.init(p.table),p.table}}console.log(`[locationToTable] No shape available, creating basic table for container: ${e.container}`);const{podTable:i,string:o}=await __vitePreload(async()=>{const{podTable:u,string:c}=await import("./XpodShellApp-D1b3kqD0.js").then(p=>p.F);return{podTable:u,string:c}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),s=this.extractContainerName(e.container),d=i(s,{id:o("id").primaryKey()},{type:"http://www.w3.org/2000/01/rdf-schema#Resource",base:e.container});return await this.init(d),d}extractContainerName(e){const t=e.replace(/\/$/,""),n=t.lastIndexOf("/");return n>=0&&t.substring(n+1).toLowerCase()||"data"}async discoverTablesFor(e,t,n){const a=await this.discover(e,t),i=[];for(const o of a){const s=await this.locationToTable(o,n);i.push(s)}return i}extractClassName(e){const t=e.lastIndexOf("#");if(t>=0)return e.substring(t+1).toLowerCase();const n=e.lastIndexOf("/");return n>=0?e.substring(n+1).toLowerCase():e.toLowerCase()}addSource(e){this.dialect.addSource(e)}removeSource(e){this.dialect.removeSource(e)}getSources(){return this.dialect.getSources()}async addSourcesFromTypeIndex(){return await this.dialect.addSourcesFromTypeIndex()}async init(...e){let t,n;const a=e[e.length-1];a&&typeof a=="object"&&!Array.isArray(a)&&!("columns"in a)?(t=a,n=e.slice(0,-1)):n=e;const i=[];for(const o of n)if(o)if(Array.isArray(o))for(const s of o)s&&i.push(s);else i.push(o);for(const o of i)if(typeof o.init=="function"?await o.init(this.dialect):await this.dialect.registerTable(o),t?.generateShape||t?.saveShape){const s=this.dialect.getShapeManager(),d=s.generateShape(o);if(t?.saveShape){const u=this.dialect.getPodUrl();let c=t.shapeLocation;c?c.startsWith("http")||(c=`${u}${c.replace(/^\//,"")}`):c=`${u}shapes/`,c.endsWith("/")||(c+="/");const p=`${c}${o.config.name}Shape.ttl`;try{await s.saveShape(d,p),console.log(`[init] Shape saved to: ${p}`)}catch(_){console.warn(`[init] Failed to save Shape to ${p}:`,_)}}}}get query(){return this.queryProxy||(this.queryProxy=this.buildQueryProxy()),this.queryProxy}buildQueryProxy(){const e=this.schema&&typeof this.schema=="object"?Object.entries(this.schema):[],t=new Map;for(const[i,o]of e)isPodTable(o)&&t.set(i,o);const n=(i,o)=>{const s=b=>{let N=null;const O=()=>(N||(N=b()),N);return{then:(X,ee)=>O().then(X,ee),catch:X=>O().catch(X),finally:X=>O().finally(X),[Symbol.toStringTag]:"Promise"}},d=(b,N,O)=>{const X={};for(const[ee,V]of Object.entries(N)){if(V instanceof PodColumnBase){X[ee]=b[V.name];continue}if(typeof V=="string"){X[ee]=b[V]??b[V.split(".").pop()??V];continue}const U=V?.name;if(typeof U=="string"){X[ee]=b[U];continue}X[ee]=b[ee]}if(O)for(const ee of Object.keys(O))X[ee]=b[ee]??[];return X},u=async b=>{this.clearFederatedErrors();let N=this.session.select().from(o);b?.where&&(N=N.where(b.where)),b?.orderBy&&(Array.isArray(b.orderBy)?b.orderBy:[b.orderBy]).forEach(V=>{N=N.orderBy(V.column,V.direction??"asc")}),typeof b?.limit=="number"&&(N=N.limit(b.limit)),typeof b?.offset=="number"&&(N=N.offset(b.offset));let O=await N;b?.with&&Object.keys(b.with).length>0&&(O=await this.eagerLoadWith(O,o,b.with,t));const X=b?.columns;return X&&(O=O.map(ee=>d(ee,X,b.with))),O},c=b=>s(()=>u(b)),p=async(b,N)=>{if(!b)return null;let O=[b];N?.with&&Object.keys(N.with).length>0&&(O=await this.eagerLoadWith(O,o,N.with,t));const X=N?.columns;return X&&(O=O.map(ee=>d(ee,X,N.with))),O[0]??null},_=b=>s(async()=>(await u({...b,limit:1}))[0]??null),m=b=>s(async()=>(await u({where:b?.where,columns:void 0,limit:void 0,offset:void 0})).length),S=()=>(b,N)=>s(async()=>await p(await this.findByLocator(o,b),N)),A=()=>(b,N)=>s(async()=>await p(await this.findById(o,b),N)),h=()=>(b,N)=>s(async()=>await p(await this.findByIri(o,b),N)),T=()=>(b,N)=>s(async()=>await p(await this.findByResource(o,b),N));return{findMany:c,findFirst:_,find:(b,N)=>T()(b,N),findById:A(),findByLocator:S(),findByIri:h(),findByResource:T(),count:m}},a={};return new Proxy(a,{get:(i,o)=>{if(typeof o!="string")return;const s=t.get(o);if(s)return n(o,s)}})}async eagerLoadWith(e,t,n,a){if(!e||e.length===0)return e;const i=this.dedupeBySubject(e);for(const[o,s]of Object.entries(n)){if(!s)continue;const d=t.relations?.[o],u=typeof s=="object"&&s.table?s.table:d?.table??a.get(o);if(!u)continue;if(isSolidSchema(u)||d?.isFederated){if(d&&d.discover)try{const V=await this.getFederatedExecutor().execute(i,{...d,relationName:o});V.errors&&V.errors.length>0&&this.lastFederatedErrors.push(...V.errors)}catch(ee){console.warn(`Federated relation "${o}" failed:`,ee),i.forEach(V=>{V[o]=[]})}else console.warn(`Federated relation "${o}" missing discover function, skipping.`),i.forEach(ee=>{ee[o]=[]});continue}const c=u,p=c.config.type,_=d?.fields&&d.fields.length>0?d.fields:Object.values(c.columns??{}),m=ee=>!!(ee&&(ee.options?.linkTarget===t.config.type||ee.options?.linkTable===t||ee.getLinkTable?.()===t)),S=ee=>!!(ee&&(ee.options?.linkTarget===p||ee.options?.linkTable===c||ee.getLinkTable?.()===c)),A=d?.fields&&d.fields.length>0?_:_.filter(ee=>m(ee)&&!ee.isInverse?.());if(A.length===0){const V=(d?.references??[]).filter(te=>!!(te&&typeof te.isInverse=="function"&&te.isInverse()&&S(te))),U=Object.values(t.columns??{}),v=(V.length>0?V:U).filter(te=>typeof te.isInverse=="function"&&te.isInverse()&&S(te));if(v.length===0)continue;const x=i.map(te=>this.collectInverseLinkValues(te,v)),I=Array.from(new Set(x.flat().filter(te=>typeof te=="string"&&te.length>0)));if(I.length===0){e.forEach(te=>{te[o]=[]});continue}let E=this.session.select().from(c);E=E.whereByIri(I);const Q=await E,K=this.groupRowsByIri(Q);i.forEach((te,se)=>{const D=x[se],ne=[];D.forEach(y=>{const C=K.get(y);C&&C.length>0&&ne.push(...C)}),te[o]=ne});continue}const h=A[0],T=d?.references&&d.references[0],w=h.isLink(),b=i.map(ee=>this.resolveParentKey(ee,T,w)).filter(ee=>typeof ee=="string"&&ee.length>0);if(b.length===0)continue;let N=this.session.select().from(c);w?N=N.where(inArray(h,b)):N=N.where({[h.name]:b});const O=await N,X=new Map;for(const ee of O){const V=ee[h.name],U=this.normalizeLiteralValue(V),v=w?this.collectLinkLookupKeys(V):U?[U]:[];for(const x of v){const I=X.get(x)??[];I.push(ee),X.set(x,I)}}i.forEach(ee=>{const V=w?Array.from(new Set([this.resolveParentKey(ee,T,!0),this.resolveIdFromRow(ee)].filter(v=>typeof v=="string"&&v.length>0))):[this.resolveParentKey(ee,T,!1)].filter(v=>typeof v=="string"&&v.length>0),U=[];for(const v of V){const x=X.get(v)??[];for(const I of x)U.includes(I)||U.push(I)}ee[o]=U})}return i}dedupeBySubject(e){const t=new Map,n=[];for(const a of e){const i=this.resolveIriFromRow(a)??this.resolveIdFromRow(a);if(!i){n.push(`__anon_${n.length}`),t.set(n[n.length-1],{...a});continue}if(!t.has(i)){t.set(i,{...a}),n.push(i);continue}const o=t.get(i);if(o)for(const[s,d]of Object.entries(a)){if(d===void 0)continue;const u=o[s];if(u===void 0){o[s]=d;continue}const c=Array.isArray(u)?u:[u],p=Array.isArray(d)?d:[d],_=[...c];for(const m of p)_.some(S=>S===m)||_.push(m);o[s]=_.length===1?_[0]:_}}return n.map(a=>t.get(a)).filter(a=>a!==void 0)}resolveIdFromRow(e){if(!e)return;if(typeof e.id=="string"&&e.id.length>0)return e.id;const t=typeof e["@id"]=="string"?e["@id"]:void 0;if(t)return this.extractFragment(t)}resolveParentKey(e,t,n){if(t){const a=e[t.name];return n?this.normalizeLinkValue(a):this.normalizeLiteralValue(a)}return n?this.resolveIriFromRow(e):this.resolveIdFromRow(e)}resolveIriFromRow(e){if(e){if(typeof e["@id"]=="string"&&e["@id"].length>0)return e["@id"];if(typeof e.subject=="string"&&e.subject.length>0)return e.subject}}collectLinkLookupKeys(e){const t=[],n=this.normalizeLinkValue(e)??this.normalizeLiteralValue(e);if(n){t.push(n);const a=this.extractFragment(n);a&&!t.includes(a)&&t.push(a)}return t}normalizeLinkValue(e){if(e){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}normalizeLiteralValue(e){if(e!=null){if(typeof e=="string")return e;if(hasStringValue$1(e))return e.value}}collectInverseLinkValues(e,t){if(!t.length)return[];const n=[];for(const a of t){const i=e[a.name];if(i==null)continue;const o=s=>{const d=this.normalizeLinkValue(s)??(typeof s=="string"?s:void 0);d&&n.push(d)};Array.isArray(i)?i.forEach(o):o(i)}return n}groupRowsByIri(e){const t=new Map;for(const n of e){const a=this.normalizeLinkValue(n["@id"])??this.normalizeLinkValue(n.uri)??(typeof n["@id"]=="string"?n["@id"]:void 0);if(!a)continue;const i=t.get(a)??[];i.push(n),t.set(a,i)}return t}extractFragment(e){const t=e.includes("#")?e.split("#").pop():void 0;return t&&t.length>0?t:e.split("/").pop()??e}}_a$8=entityKind;PodDatabase[_a$8]="PodDatabase";PodDatabase.findByLocatorDeprecationWarned=!1;function isAggregateExpression(r){return!!r&&typeof r=="object"&&r.kind==="aggregate"}function inferSPARQLQueryType(r){const n=r.replace(/^\s*#.*$/gm,"").trim().replace(/^(?:\s*(?:PREFIX|BASE)\s+[^\n]+\n)*/i,"").trim().match(/^(SELECT|ASK|INSERT|DELETE|UPDATE|WITH|LOAD|CLEAR|CREATE|DROP|COPY|MOVE|ADD|CONSTRUCT|DESCRIBE)\b/i)?.[1]?.toUpperCase();switch(n){case"SELECT":case"ASK":case"INSERT":case"DELETE":case"UPDATE":return n;case"WITH":case"LOAD":case"CLEAR":case"CREATE":case"DROP":case"COPY":case"MOVE":case"ADD":return"UPDATE";default:return}}function createLiteralCondition(r,e,t){const n=r?`${r}.${e}`:e;return t==null?new UnaryExpression("IS NULL",n):Array.isArray(t)?new BinaryExpression(n,"IN",t):new BinaryExpression(n,"=",t)}function buildConditionTreeFromObject(r,e){if(!r)return;const t=Object.entries(r);if(t.length===0)return;const n=t.map(([a,i])=>createLiteralCondition(e,a,i));return n.length===1?n[0]:new LogicalExpression("AND",n)}function resolveRowSubject(r){if(!(!r||typeof r!="object")){if(typeof r["@id"]=="string"&&r["@id"].length>0)return r["@id"];if(typeof r.subject=="string"&&r.subject.length>0)return r.subject;if(typeof r.uri=="string"&&r.uri.length>0)return r.uri;if(typeof r.source=="string"&&r.source.length>0)return r.source;if(typeof r.id=="string"&&r.id.length>0)return r.id}}function orderRowsBySubjects(r,e){if(!r.length||!e.length)return r;const t=new Map,n=[];for(const i of r){const o=resolveRowSubject(i);if(!o){n.push(i);continue}const s=t.get(o)??[];s.push(i),t.set(o,s)}const a=[];for(const i of e){const o=t.get(i);o?.length&&(a.push(...o),t.delete(i))}for(const i of t.values())a.push(...i);return a.push(...n),a}function isSelectFieldMap(r){return!!r&&typeof r=="object"&&!(r instanceof PodColumnBase)&&!(r instanceof PodTable)&&!("aggregateType"in r)}function resolveFieldBindingCandidates(r,e){const t=new Set;if(typeof e=="string"){if(t.add(e),e.includes(".")){const[n,a]=e.split(".",2);a&&(t.add(`${n}.${a}`),t.add(a))}}else e instanceof PodColumnBase&&(e.table?.config?.name&&t.add(`${e.table.config.name}.${e.name}`),t.add(e.name));return Array.from(t)}function isEmptyProjectedValue(r){if(r==null)return!0;if(Array.isArray(r))return r.length===0;if(typeof r=="object"){const e=Object.values(r);return e.length>0&&e.every(t=>isEmptyProjectedValue(t))}return!1}function projectTableRow(r,e){const t=e.config.name,n={};let a=!1;for(const i of Object.keys(e.columns)){const s=(t?[`${t}.${i}`,i]:[i]).find(d=>r[d]!==void 0);n[i]=s?r[s]:void 0,n[i]!==void 0&&(a=!0)}return a?n:null}function projectFieldValue(r,e,t){if(t instanceof PodTable)return projectTableRow(r,t);if(isSelectFieldMap(t)){const n={};for(const[a,i]of Object.entries(t))n[a]=projectFieldValue(r,a,i);return isEmptyProjectedValue(n)?null:n}for(const n of resolveFieldBindingCandidates(e,t))if(r[n]!==void 0)return r[n];return r[e]}function projectReturningRow(r,e){if(!e||e===!0)return r;const t={};for(const[n,a]of Object.entries(e))t[n]=projectFieldValue(r,n,a);return t}function projectReturningRows(r,e){return!e||e===!0?r:r.map(t=>projectReturningRow(t,e))}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,SINGLETON_FRAGMENTS=new Set(["#me","#this","#profile","#card"]);class UriResolverImpl{constructor(e=""){this.podUrl=e.replace(/\/$/,"")}setPodUrl(e){this.podUrl=e.replace(/\/$/,"")}resolveSubject(e,t,n,a){const i=a?.strict??!0,o=t["@id"]??t.id??t.uri;if(typeof o=="string"){if(this.isAbsoluteUri(o))return o;const c=this.resolveBaseRelativeSubjectId(e,o);if(c)return c;o.startsWith("#")&&this.acceptsFragmentOnlyResourceId(e)&&(t={...t,id:o.slice(1)})}const s=this.getEffectivePattern(e),d=this.getSubjectBaseUrl(e);if(this.isSingleton(e))return this.combineBaseAndPattern(d,s);const u=this.applyTemplate(s,t,n,e,i);return u===null?this.generateFallbackUri(d,s,n):this.isAbsoluteUri(u)?u:this.combineBaseAndPattern(d,u)}parseSubject(e,t){if(!e)return null;const n=e.indexOf("#"),a=n!==-1,i=a?e.slice(0,n):e,o=a?e.slice(n+1):void 0,s=this.extractPublicId(e,t),d=this.getResourceMode(t);return{uri:e,resourceUrl:i,fragment:o,id:s,mode:d}}getResourceUrl(e){const t=e.indexOf("#");return t!==-1?e.slice(0,t):e}getResourceMode(e){if(!(e.hasCustomTemplate?.()??!1)){const a=e.config?.base??"";return/\.(ttl|jsonld|json)$/i.test(a)?"fragment":"document"}return(e.config?.subjectTemplate??this.getDefaultPattern(e)).startsWith("#")?"fragment":"document"}getDefaultPattern(e){return"{id}"}resolveInlineChild(e,t,n,a){const i=n["@id"]??n.id;return typeof i=="string"?i:buildInlineChildUri(e,t,a)}isSingleton(e){const t=e.config?.subjectTemplate;return t?!!(SINGLETON_FRAGMENTS.has(t)||!t.includes("{")):!1}resolveLink(e,t,n){const a=String(e??""),i=n?.record&&typeof n.record=="object"?n.record:void 0;if(this.isAbsoluteUri(a))return a;if(a.startsWith("/")||a.startsWith("#")){const c=n?.baseUri||this.podUrl;if(c)try{return new URL(a,c).toString()}catch{}throw new Error(`Cannot resolve relative URI "${a}": no baseUri configured`)}const o=t.getLinkTable?.();if(o){const c=this.getTableUriInfo(o);if(c)return this.buildFullUri(a,c.baseUrl,c.subjectTemplate,o,n,i);throw new Error(`Cannot resolve URI "${a}": linked table "${o.config?.name}" has no base configured.`)}const s=t.getLinkTableName?.();if(s){if(n?.tableNameRegistry){const p=n.tableNameRegistry.get(s);if(p){const _=this.getTableUriInfo(p);if(_)return this.buildFullUri(a,_.baseUrl,_.subjectTemplate,p,n,i)}}const c=n?.tableNameRegistry?Array.from(n.tableNameRegistry.keys()).join(", "):"(no tables registered)";throw new Error(`Cannot resolve URI "${a}": table "${s}" not found in schema. Available tables: ${c}`)}const d=t.getLinkTarget?.();if(d){if(!n?.tableRegistry)throw new Error(`Cannot resolve URI "${a}" (links to ${d}): tableRegistry not configured. Ensure the schema is properly registered.`);const c=n.tableRegistry.get(d);if(c&&c.length>0){if(c.length>1){const m=c.map(S=>S.config?.name||"unknown").join(", ");throw new Error(`Ambiguous link target: class "${d}" has multiple tables [${m}]. Use .link('tableName') or .link(tableObject) to specify which table to use.`)}const p=c[0],_=this.getTableUriInfo(p);if(_)return this.buildFullUri(a,_.baseUrl,_.subjectTemplate,p,n,i)}throw new Error(`Cannot resolve URI "${a}": class "${d}" not found in tableRegistry. Available classes: ${Array.from(n.tableRegistry.keys()).join(", ")||"(none)"}`)}const u=n?.baseUri||this.podUrl;if(u&&this.isAbsoluteUri(u)){const c=u.endsWith("/")?u:`${u}/`;return this.buildFullUri(a,c)}throw new Error(`Cannot resolve URI "${a}". Either provide a full URI (https://...), or configure baseUri.`)}isAbsoluteUri(e){return!e||typeof e!="string"?!1:e.includes(":")&&(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("urn:")||e.startsWith("did:")||e.startsWith("mailto:")||e.startsWith("tel:")||e.startsWith("file://")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))}isLinkColumn(e){return e?e.dataType==="uri"||e.isLink?.()||!!e.options?.linkTarget||!!e.options?.linkTableName||!!e.options?.linkTable:!1}findTargetTable(e,t){const n=e.getLinkTable?.()||e.options?.linkTable;if(n)return n;const a=e.getLinkTableName?.()||e.options?.linkTableName;if(a&&t?.tableNameRegistry){const o=t.tableNameRegistry.get(a);if(o)return o}const i=e.getLinkTarget?.()||e.options?.linkTarget;if(i&&t?.tableRegistry){const o=t.tableRegistry.get(i);if(o&&o.length===1)return o[0]}}extractLinkId(e,t,n){if(e?.startsWith("/")){const o=n?.baseUri||this.podUrl;if(o){const s=o.endsWith("/")?o:`${o}/`;e=new URL(e.replace(/^\/+/,""),s).toString()}}if(!e||!this.isAbsoluteUri(e))return e;const a=this.findTargetTable(t,n);if(!a)return e;const i=this.extractTemplateIdFromSubject(e,a);return i||e}getTableUriInfo(e){const t=e.config?.base;if(!t)return;const n=e.config?.subjectTemplate;return{baseUrl:this.toAbsoluteUrl(t),subjectTemplate:n}}buildFullUri(e,t,n,a,i,o){const s=String(e??"");if(!n){const _=this.combineBaseAndResourceId(t,s);return this.assertNoUnresolvedTemplate(_,void 0,a),_}if(!UUID_REGEX.test(s)&&s.includes("/")&&!s.includes("{")){const _=`${t}${s}`;return this.assertNoUnresolvedTemplate(_,n,a),_}const d=this.buildTemplateRecord(s,n,a,i,o),u=this.applyTemplate(n,d,void 0,a,!0,i);if(u===null)throw new Error(`[UriResolver] Failed to resolve URI template "${n}" for table "${a?.config?.name??"unknown"}"`);if(this.isAbsoluteUri(u))return this.assertNoUnresolvedTemplate(u,n,a),u;if(u.startsWith("#")){const m=`${t.endsWith("/")?t.slice(0,-1):t}${u}`;return this.assertNoUnresolvedTemplate(m,n,a),m}const p=`${t.endsWith("/")?t:`${t}/`}${u}`;return this.assertNoUnresolvedTemplate(p,n,a),p}buildTemplateRecord(e,t,n,a,i){const o={...i??{}};o.id=e;for(const s of t.matchAll(/\{([^}]+)\}/g)){const u=this.parseTemplateVariable(s[1]).field;if(u==="id"||u==="index"||u in o)continue;const c=this.resolveTemplateVariable(u,n,a,i);c!=null&&c!==""&&(o[u]=c)}return o}resolveTemplateVariable(e,t,n,a){if(!a||typeof a!="object")return;if(e in a){const d=t?.columns?.[e];return this.normalizeValue(a[e],d,n)}const i=`${e}Id`;if(i in a)return String(a[i]);const o=t?.columns?.[e],s=o?this.findTargetTable(o,n):void 0;if(s)for(const[d,u]of Object.entries(a)){const c=n?.currentTable?.columns?.[d];if((c?this.findTargetTable(c,n):void 0)===s)return this.normalizeValue(u,o,n)}}assertNoUnresolvedTemplate(e,t,n){if(/\{[^}]+\}/.test(e)){const a=n?.config?.name||"unknown";throw new Error(`[UriResolver] Unresolved URI template variable while resolving table "${a}" with template "${t??"<exact-id>"}": ${e}`)}}getEffectivePattern(e){if(e.hasCustomTemplate?.()??!1){const n=e.config?.subjectTemplate;if(n&&n.trim().length>0)return n}return this.getDefaultPattern(e)}getSubjectBaseUrl(e){const t=e.config?.base??"";return this.toAbsoluteUrl(t)}isBaseRelativeSubjectId(e){return!e||this.isAbsoluteUri(e)||e.startsWith("/")?!1:e.startsWith("#")||e.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(e)}acceptsFragmentOnlyResourceId(e){const t=e.config?.subjectTemplate;if(!t)return!1;const n=Array.from(t.matchAll(/\{([^}]+)\}/g)).map(a=>this.parseTemplateVariable(a[1]).field);return t==="#{id}"||t.startsWith("#")&&n.length===1&&n[0]==="id"}resolveBaseRelativeSubjectId(e,t){if(!this.isBaseRelativeSubjectId(t))return null;const n=this.getSubjectBaseUrl(e);if(t.startsWith("#"))return this.acceptsFragmentOnlyResourceId(e)?`${n}${t}`:null;if(n.endsWith("/"))return`${n}${t}`;const a=n.lastIndexOf("/");return`${a>=0?n.slice(0,a+1):`${n}/`}${t}`}toAbsoluteUrl(e){if(!e)return this.podUrl;if(this.isAbsoluteUri(e))return e;const t=e.startsWith("/")?e:`/${e}`;return`${this.podUrl}${t}`}combineBaseAndPattern(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:e.endsWith("/")?`${e}${t}`:(e.endsWith(".ttl")||e.endsWith(".jsonld"))&&t.startsWith("#")?`${e}${t}`:`${e}/${t}`}combineBaseAndResourceId(e,t){return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}${t}`:`${e.endsWith("/")?e:`${e}/`}${t}`}normalizeValue(e,t,n){return e==null?"":typeof e=="string"&&this.isAbsoluteUri(e)&&t&&this.isLinkColumn(t)?this.extractLinkId(e,t,n):String(e)}parseTemplateVariable(e){const[t,...n]=e.split("|").map(a=>a.trim()).filter(Boolean);return{raw:e,field:t||e,transforms:n}}slugifyValue(e){return e.normalize("NFKC").toLowerCase().replace(/[^\p{Letter}\p{Number}]+/gu,"-").replace(/^-+|-+$/g,"")}applyTransforms(e,t,n,a){let i=this.normalizeValue(e,n,a);for(const o of t.transforms){if(o==="id"){i=n&&this.isLinkColumn(n)?this.extractLinkId(i,n,a):i;continue}o==="slug"&&(i=this.slugifyValue(i))}return i}applyTemplate(e,t,n,a,i=!0,o){if(!e.includes("{"))return e;const s=this.createTimeContext(t),d=[],u=e.replace(/(#?)\{([^}]+)\}/g,(c,p,_)=>{const m=this.parseTemplateVariable(_),S=m.field;if(S in s)return p+s[S];if(S==="index"&&n!==void 0)return p+String(n+1);let A=t[S];if(S==="id"&&A==null&&(A=t["@id"]??t.uri),A==null)return d.push(_),c;const h=a?.columns?.[S],T=o??(a?{tableRegistry:a[Symbol.for("drizzle:tableRegistry")],tableNameRegistry:a[Symbol.for("drizzle:tableNameRegistry")]}:void 0),w=this.applyTransforms(A,m,h,T);return p==="#"&&w.startsWith("#")?p+w.slice(1):p+w});if(d.length>0){if(i){const c=a?.config?.name||"unknown";throw new Error(`[UriResolver] Missing required fields for template "${e}" in table "${c}": [${d.join(", ")}]. Record keys: [${Object.keys(t).join(", ")}]. Record: ${JSON.stringify(t)}`)}return null}return u}createTimeContext(e){let t;const n=e.createdAt??e.created_at??e.dateCreated;n instanceof Date?t=n:typeof n=="string"||typeof n=="number"?t=new Date(n):t=new Date;const a=t.getUTCFullYear().toString(),i=(t.getUTCMonth()+1).toString().padStart(2,"0"),o=t.getUTCDate().toString().padStart(2,"0"),s=Math.floor(t.getTime()/1e3).toString();return{date:t,yyyy:a,MM:i,dd:o,timestamp:s}}generateFallbackUri(e,t,n){const a=n!==void 0?`row-${n+1}`:`row-${Date.now()}`;return t.startsWith("#")?`${e.endsWith("/")?e.slice(0,-1):e}#${a}`:`${e.endsWith("/")?e:`${e}/`}${a}.ttl`}extractRelativeSubjectId(e,t){const n=t.config?.base??"";let a="";if(n&&e.includes(n)){const i=e.indexOf(n);a=e.substring(i+n.length),a.startsWith("#")&&!(t.hasCustomTemplate?.()??!1)&&(a=`${n.split("/").filter(Boolean).pop()??""}${a}`),a.startsWith("/")&&(a=a.substring(1))}else if(!n)a=e;else return console.warn(`[UriResolver] Cannot extract ID: base "${n}" not found in URI "${e}"`),"";return a}extractPublicId(e,t){return this.extractTemplateIdFromSubject(e,t)??this.extractRelativeSubjectId(e,t)}extractTemplateIdFromSubject(e,t){const n=this.extractRelativeSubjectId(e,t),a=t.config?.subjectTemplate;return a?this.extractIdFromTemplate(n,a):n}extractIdFromTemplate(e,t){let n=t.replace(/[.+?^$[\]\\()]/g,"\\$&").replace(/\{id\}/g,"(?<id>.+?)").replace(/\{[^}]+\}/g,"(?:.+?)");n=`^${n}$`;try{const a=new RegExp(n),i=e.match(a);if(i&&i.groups?.id)return i.groups.id;if(i&&i[1])return i[1]}catch{}return null}}function buildInlineChildUri(r,e,t){const n=r.indexOf("#"),a=n>=0?r.slice(0,n):r,i=n>=0?r.slice(n+1):"",o=i?`${encodeURIComponent(i)}/`:"";return`${a}#${o}${encodeURIComponent(e)}-${t+1}`}function isOrderByExpression(r){if(!r||typeof r!="object")return!1;const e=r;return"column"in e&&(e.direction==="asc"||e.direction==="desc")}function isReservedIdentifierKey(r){return r==="id"||r==="@id"||r.endsWith(".id")||r.endsWith(".@id")}function isReservedIdentifierOperand(r){if(r instanceof PodColumnBase){const e=r;return r.name==="id"||r.options?.predicate==="@id"||e._virtualId===!0}return typeof r=="string"?isReservedIdentifierKey(r):!1}function conditionTargetsReservedIdentifier(r){return r.type==="binary_expr"?!!(isReservedIdentifierOperand(r.left)||isReservedIdentifierOperand(r.right)):r.type==="logical_expr"?r.expressions.some(e=>e!=null&&typeof e=="object"&&"type"in e&&conditionTargetsReservedIdentifier(e)):r.type==="unary_expr"?r.value!=null&&typeof r.value=="object"&&"type"in r.value&&conditionTargetsReservedIdentifier(r.value):!1}function createWhereIdentifierError(r){switch(r){case"select":return["Using 'id' or '@id' in where() is not supported.","Use findById(id) for base-relative resource ids,","or findByIri(iri) for full IRI exact lookups."].join(" ");case"update":return["Using 'id' or '@id' in where() is not supported.","Use updateById(id, data) for base-relative resource ids,","or updateByIri(iri, data) for full IRI exact updates."].join(" ");case"delete":return["Using 'id' or '@id' in where() is not supported.","Use deleteById(id) for base-relative resource ids,","or deleteByIri(iri) for full IRI exact deletes."].join(" ")}}function assertPublicWhereObject(r,e){if(e){for(const t of Object.keys(e))if(isReservedIdentifierKey(t))throw new Error(createWhereIdentifierError(r))}}function assertPublicWhereCondition(r,e){if(conditionTargetsReservedIdentifier(e))throw new Error(createWhereIdentifierError(r))}function assertPublicCursorCondition(r){let e=!1,t=!1;const n=a=>{if(a.type==="binary_expr"){if(isReservedIdentifierOperand(a.left)||isReservedIdentifierOperand(a.right)){if(![">",">=","<","<="].includes(a.operator))throw new Error("whereCursor() only supports range comparisons on 'id' or '@id'.");e=!0}else t=!0;return}if(a.type==="logical_expr"){for(const i of a.expressions)n(i);return}t=!0};if(n(r),!e||!t)throw new Error("whereCursor() requires a sort predicate plus an 'id' or '@id' range tie-breaker.")}var define_process_env_default$2={},_a$7;class SelectQueryBuilder{constructor(e,t){this.session=e,this.joins=[],this.orderByClauses=[],this.isDistinct=!1,this.tableAliases=new Map,this.aliasToTable=new Map,this.aliasUsage=new Map,this.joinFilters=[],this.groupByColumns=[],t&&this.setSelectedFields(t)}from(e){return this.selectedTable=e,this.primaryAlias=this.ensureAliasForTable(e),this}columns(e){return this.setSelectedFields(e),this}setSelectedFields(e){this.selectedFields={...e}}where(e){return e instanceof SQL?this.sql=e:this.isQueryCondition(e)?(assertPublicWhereCondition("select",e),this.processQueryCondition(e)):(assertPublicWhereObject("select",e),this.processWhereObject(e)),this}whereCursor(e){return assertPublicCursorCondition(e),this.processQueryCondition(e),this}whereByIri(e){return this.processWhereObject({"@id":e}),this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,n=e.right,a=e.operator,i=typeof t=="string"?t:t?.name;if(a==="="&&i&&n!==void 0)return{[i]:n}}if(e.type==="logical_expr"){const t=e.operator,n=e.expressions;if(t==="AND"&&n){const a={};for(const i of n){const o=this.convertQueryConditionToSimple(i);if(!o||Object.keys(o).length===0)return{};for(const[s,d]of Object.entries(o))a[s]=d}return a}}return{}}extractTableFromCondition(e){if(e.type==="binary_expr"){const t=e.left;if(t&&typeof t=="object"&&"table"in t){const n=t.table;if(n)return this.tableAliases.get(n)}if(typeof t=="string"&&t.includes("."))return t.split(".")[0]}}leftJoin(e,t){return this.addJoin("leftJoin",e,t)}rightJoin(e,t){return this.addJoin("rightJoin",e,t)}innerJoin(e,t){return this.addJoin("innerJoin",e,t)}fullJoin(e,t){return this.addJoin("fullJoin",e,t)}crossJoin(e){return this.addJoin("crossJoin",e)}groupBy(...e){const t=e.map(n=>this.resolveColumnReference(n));return this.groupByColumns.push(...t),this}having(e){return this.havingCondition=typeof e=="function"?e(this.createSelectedFieldAliases()):e,this}createSelectedFieldAliases(){const e={};for(const t of Object.keys(this.selectedFields??{}))e[t]=new SelectionAliasExpression(t);return e}addJoin(e,t,n){if(e==="rightJoin"||e==="fullJoin")throw new Error(`${e} is not yet supported in Solid dialect`);const a=this.ensureAliasForTable(t),i=e==="crossJoin"?void 0:this.resolveJoinConditions(n,a);return this.joins.push({type:e,table:t,alias:a,rawCondition:n,resolvedConditions:i}),this}ensureAliasForTable(e){const t=this.tableAliases.get(e);if(t)return t;const n=e.config.name||"table",a=this.aliasUsage.get(n)??0,i=a+1;this.aliasUsage.set(n,i);const o=a===0?n:`${n}_${i}`;return this.tableAliases.set(e,o),this.aliasToTable.set(o,e),o}resolveJoinConditions(e,t){if(this.isQueryCondition(e))return this.resolveJoinConditionExpression(e,t);if(!e||typeof e!="object")throw new Error("JOIN condition must be an equality expression or column mapping");const n=Object.entries(e);if(n.length===0)throw new Error("JOIN condition cannot be empty");return n.map(([a,i])=>{const o=this.resolveColumnReference(a),s=this.resolveColumnReference(i);if(o.alias!==t&&s.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return{left:o,right:s}})}resolveJoinConditionExpression(e,t){if(e.type==="logical_expr"){const i=(e.operator??"").toUpperCase(),o=e.expressions??[];if(i!=="AND"||o.length===0)throw new Error("JOIN condition only supports equality expressions combined with AND");return o.flatMap(s=>this.resolveJoinConditionExpression(s,t))}if(e.type!=="binary_expr"||e.operator!=="=")throw new Error("JOIN condition only supports equality expressions");const n=this.getConditionColumnReference(e.left),a=this.getConditionColumnReference(e.right);if(!n||!a)throw new Error("JOIN equality must compare two table columns");if(n.alias!==t&&a.alias!==t)throw new Error("JOIN condition must reference the joined table in at least one side");return[{left:n,right:a}]}getConditionColumnReference(e,t){if(e instanceof PodColumnBase)return this.resolveColumnReference(e,t);if(typeof e=="string"){if(e.includes("."))return this.resolveColumnReference(e,t);const n=t??this.primaryAlias,a=n?this.aliasToTable.get(n):void 0;if(a&&e in(a.columns??{}))return this.resolveColumnReference(e,t)}}resolveColumnReference(e,t){if(e instanceof PodColumnBase){const n=e.table;if(!n)throw new Error(`Column ${e.name} is not associated with a table`);const a=this.ensureAliasForTable(n);return{table:n,alias:a,column:e.name}}if(typeof e=="string"){const{alias:n,column:a}=this.parseColumnReferenceString(e),i=n??t??this.primaryAlias;if(!i)throw new Error(`Unable to resolve table alias for column reference "${e}"`);const o=this.aliasToTable.get(i);if(!o)throw new Error(`Unknown table alias "${i}" in column reference "${e}"`);return{table:o,alias:i,column:a}}throw new Error("Unsupported column link type")}parseColumnReferenceString(e){const t=e.trim();if(!t.includes("."))return{column:t};const[n,a]=t.split(".",2);return{alias:n,column:a}}processWhereObject(e){if(!e)return;const t={...this.whereConditions??{}};for(const[n,a]of Object.entries(e)){const{alias:i,column:o}=this.parseColumnReferenceString(n),s=i??this.primaryAlias;if(!s||s===this.primaryAlias||!this.aliasToTable.has(s)){t[o]=a;continue}this.joinFilters.push(createLiteralCondition(s,o,a))}this.whereConditions=Object.keys(t).length>0?t:void 0}processQueryCondition(e){const t=this.extractTableFromCondition(e);if(t&&t!==this.primaryAlias){this.joinFilters.push(e);return}this.conditionTree=e;const n=this.convertQueryConditionToSimple(e);Object.keys(n).length>0&&(this.whereConditions=n)}applyInternalQueryCondition(e){return this.processQueryCondition(e),this}normalizeWhereConditions(){if(this.conditionTree)return this.conditionTree;const e=this.primaryAlias??this.selectedTable?.config.name;return buildConditionTreeFromObject(this.whereConditions,e)}toIR(){const e=this.normalizeWhereConditions();return this.buildQueryPlan(e)}buildQueryPlan(e){if(!this.selectedTable)throw new Error("No table specified for SELECT query");const t=this.joins.map(n=>({type:n.type,table:n.table,alias:n.alias,conditions:(n.resolvedConditions??[]).map(({left:a,right:i})=>({left:a,right:i}))}));return{baseTable:this.selectedTable,baseAlias:this.primaryAlias??this.selectedTable.config.name,select:this.selectedFields,selectAll:!this.selectedFields,where:this.whereConditions,conditionTree:e,joins:t.length>0?t:void 0,joinFilters:this.joinFilters.length>0?[...this.joinFilters]:void 0,groupBy:this.groupByColumns.length>0?[...this.groupByColumns]:void 0,having:this.havingCondition,orderBy:this.orderByClauses.length>0?this.orderByClauses.map(n=>({rawColumn:n.column,direction:n.direction})):void 0,distinct:this.isDistinct||void 0,limit:this.limitCount,offset:this.offsetCount,aliasToTable:new Map(this.aliasToTable),tableToAlias:new Map(this.tableAliases)}}limit(e){if(!Number.isInteger(e)||e<0)throw new Error("LIMIT must be a non-negative integer");return this.limitCount=e,this}offset(e){if(!Number.isInteger(e)||e<0)throw new Error("OFFSET must be a non-negative integer");return this.offsetCount=e,this}addOrderByClause(e,t="asc"){const n=typeof e=="string"?e:e.name;if(!n)throw new Error("ORDER BY requires a valid column name");this.orderByClauses.push({column:n,direction:t})}orderBy(...e){if(e.length===0)throw new Error("ORDER BY requires at least one column or expression");if(e.length===2&&(e[0]instanceof PodColumnBase||typeof e[0]=="string")&&(e[1]==="asc"||e[1]==="desc"))return this.addOrderByClause(e[0],e[1]),this;for(const t of e){if(isOrderByExpression(t)){this.addOrderByClause(t.column,t.direction);continue}if(t instanceof PodColumnBase||typeof t=="string"){this.addOrderByClause(t,"asc");continue}throw new Error("ORDER BY received an unsupported argument")}return this}distinct(e=!0){return this.isDistinct=e,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const n=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(n);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:n,prefixes:{}}}if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.joins.length>0)throw new Error(`${e} is not yet supported for JOIN queries in Solid dialect`);if(this.shouldUseProjectionFallback())throw new Error(`${e} does not support structured selections in Solid dialect`);const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertSelectPlan(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(!this.selectedTable)throw new Error("No table specified for SELECT query");if(this.limitCount===0)return[];if(this.sql)return await this.session.executeSql(this.sql,this.selectedTable);{const e=this.toIR(),t=e.conditionTree,n=this.joins.length>0,a=this.shouldUseAggregateFallback(),i=this.shouldUseProjectionFallback(),o=n||a;(n||a||i)&&(e.select=void 0,e.selectAll=!0);const s=o?{...e,limit:void 0,offset:void 0,orderBy:void 0,...n?{joins:void 0,joinFilters:void 0}:{},...a?{groupBy:void 0,having:void 0}:{}}:n?{...e,joins:void 0,joinFilters:void 0}:e,d={type:"select",table:this.selectedTable,where:t,limit:o?void 0:this.limitCount,offset:o?void 0:this.offsetCount,orderBy:o||this.orderByClauses.length===0?void 0:this.orderByClauses,distinct:this.isDistinct||void 0};if(d.plan=s,this.groupByColumns.length===0&&this.hasMixedAggregateSelection())throw new Error("Mixed aggregate and non-aggregate selections require groupBy columns");let u;if(!n&&!a&&!i?(this.selectedFields&&(d.select=this.selectedFields),u=await this.session.execute(d),u=this.applySubjectMetadata(u)):(n?d.select=void 0:!a&&!i?d.select=this.selectedFields:d.select=void 0,u=await this.session.execute(d),n||(u=this.applySubjectMetadata(u)),n&&(u=this.normalizeBaseRows(u),u=this.mergeRowsBySubject(u),u=await this.applyJoinFallback(u),u=this.applyJoinFilters(u))),a){let p=this.handleAggregateFallback(u);return p=this.applyHavingFilter(p),o&&(p=this.applyDeferredOrderBy(p),p=this.applyDeferredOffsetAndLimit(p)),p}let c=u;return n||(c=this.mergeRowsBySubject(c)),this.selectedTable&&(c=await this.hydrateInlineColumns(c,this.selectedTable,!n)),n&&(c=this.applyDeferredOrderBy(c)),this.selectedFields&&(c=c.map(p=>this.projectSelectedRow(p))),c=this.applyDistinctRows(c),n||(c=this.mergeRowsBySubject(c)),n&&(c=this.applyDeferredOffsetAndLimit(c)),c}}projectSelectedRow(e){return this.selectedFields?this.projectFieldMap(e,this.selectedFields):e}projectFieldMap(e,t,n=!0){const a={};for(const[i,o]of Object.entries(t))a[i]=this.projectFieldValue(e,i,o,n);return a}projectFieldValue(e,t,n,a=!0){if(isAggregateExpression(n))return a?e[t]:void 0;if(n instanceof PodTable)return this.projectTableValue(e,n);if(this.isSelectFieldMap(n)){const i=this.collectSelectionAliases(n),o=i.size===1&&!i.has(this.primaryAlias??""),s=this.projectFieldMap(e,n,!o);if(i.size===1){const[d]=Array.from(i);if(d&&d!==this.primaryAlias&&this.isProjectedValueEmpty(s))return null}return s}for(const i of this.resolveFieldBindingCandidates(t,n))if(e[i]!==void 0)return e[i];return a?e[t]:void 0}projectTableValue(e,t){const n=this.tableAliases.get(t)??t.config.name,a={};let i=!1;for(const o of Object.keys(t.columns)){const d=(n===this.primaryAlias?[o,`${n}.${o}`]:[`${n}.${o}`]).find(u=>e[u]!==void 0);a[o]=d?e[d]:void 0,a[o]!==void 0&&(i=!0)}return n!==this.primaryAlias&&!i?null:a}isSelectFieldMap(e){return!!e&&typeof e=="object"&&!(e instanceof PodColumnBase)&&!(e instanceof PodTable)&&!isAggregateExpression(e)}collectSelectionAliases(e){if(typeof e=="string"){const{alias:n}=this.parseColumnReferenceString(e);return new Set(n?[n]:this.primaryAlias?[this.primaryAlias]:[])}if(e instanceof PodColumnBase)return new Set([this.resolveColumnReference(e).alias]);if(e instanceof PodTable)return new Set([this.tableAliases.get(e)??e.config.name]);if(!this.isSelectFieldMap(e))return new Set;const t=new Set;for(const n of Object.values(e))for(const a of this.collectSelectionAliases(n))t.add(a);return t}isProjectedValueEmpty(e){if(e==null)return!0;if(Array.isArray(e))return e.length===0;if(typeof e=="object"){const t=Object.values(e);return t.length>0&&t.every(n=>this.isProjectedValueEmpty(n))}return!1}resolveFieldBindingCandidates(e,t){const n=new Set;if(typeof t=="string"){const{alias:a,column:i}=this.parseColumnReferenceString(t);n.add(t),n.add(i),a&&n.add(`${a}.${i}`)}else if(t instanceof PodColumnBase){const a=this.resolveColumnReference(t);n.add(`${a.alias}.${a.column}`),(!a.alias||a.alias===this.primaryAlias)&&n.add(t.name)}else if(t&&typeof t=="object"){const a=t.name;typeof a=="string"&&n.add(a)}return Array.from(n)}shouldUseProjectionFallback(){if(!this.selectedFields)return!1;const e=t=>!!(t instanceof PodTable||this.isSelectFieldMap(t));return Object.values(this.selectedFields).some(t=>e(t))}shouldUseAggregateFallback(){if(this.havingCondition)return!0;if(this.joins.length>0)return this.groupByColumns.length>0||this.hasAggregateSelection();if(this.groupByColumns.length>0||!this.selectedFields)return!1;const e=Object.values(this.selectedFields);return e.length>0&&e.every(t=>isAggregateExpression(t))}buildAggregateRow(e){const t={};if(!this.selectedFields)return t;for(const[n,a]of Object.entries(this.selectedFields))isAggregateExpression(a)&&(t[n]=this.computeAggregateValue(a,e));return t}computeAggregateValue(e,t){const n=this.resolveAggregateColumnRef(e);if(!n)return e.func==="count"?e.distinct?this.countDistinctRows(t):t.length:null;switch(e.func){case"count":return this.collectValuesForCount(n,t,!!e.distinct).length;case"sum":{const a=this.collectNumericValues(n,t,!!e.distinct);return a.length===0?null:a.reduce((i,o)=>i+o,0)}case"avg":{const a=this.collectNumericValues(n,t,!!e.distinct);return a.length===0?null:a.reduce((o,s)=>o+s,0)/a.length}case"min":{const a=this.collectNumericValues(n,t,!!e.distinct);return a.length===0?null:Math.min(...a)}case"max":{const a=this.collectNumericValues(n,t,!!e.distinct);return a.length===0?null:Math.max(...a)}default:return null}}resolveAggregateColumnRef(e){const t=e.column;if(t){if(typeof t=="string")return this.resolveColumnReference(t);if(t instanceof PodColumnBase)return this.resolveColumnReference(t);if(typeof t=="object"&&"name"in t){const n=t.name;if(typeof n=="string")return this.resolveColumnReference(n)}}}collectValuesForCount(e,t,n){const a=t.map(s=>this.getRowValueForColumn(s,e)).filter(s=>s!=null);if(!n)return a;const i=new Set,o=[];for(const s of a){const d=this.serializeValueForKey(s);i.has(d)||(i.add(d),o.push(s))}return o}collectNumericValues(e,t,n){const a=[],i=new Set;for(const o of t){const s=this.getRowValueForColumn(o,e);if(s==null)continue;const d=Number(s);if(!Number.isNaN(d))if(n){const u=this.serializeValueForKey(d);i.has(u)||(i.add(u),a.push(d))}else a.push(d)}return a}countDistinctRows(e){const t=new Set;for(const n of e){const a=this.serializeValueForKey(n);t.add(a)}return t.size}handleAggregateFallback(e){if(!this.selectedFields){if(this.groupByColumns.length===0)return e;const t=new Map;for(const n of e){const a=this.groupByColumns.map(o=>this.serializeValueForKey(this.getRowValueForColumn(n,o))),i=JSON.stringify(a);t.has(i)||t.set(i,n)}return Array.from(t.values())}return this.groupByColumns.length===0?[this.buildAggregateRow(e)]:this.buildGroupedAggregateRows(e)}buildGroupedAggregateRows(e){if(!this.selectedFields)return e;this.ensureGroupByValidity();const t=new Map;for(const a of e){const i=this.groupByColumns.map(s=>this.serializeValueForKey(this.getRowValueForColumn(a,s))),o=JSON.stringify(i);t.has(o)||t.set(o,{rows:[],first:a}),t.get(o)?.rows.push(a)}const n=[];for(const{rows:a,first:i}of t.values()){const o=this.buildAggregateRow(a),s={};for(const[d,u]of Object.entries(this.selectedFields))if(isAggregateExpression(u))s[d]=o[d];else{const c=this.resolveSelectFieldColumn(u);s[d]=c?this.getRowValueForColumn(i,c):void 0}n.push(s)}return n}ensureGroupByValidity(){if(!this.selectedFields)return;const e=this.groupByColumns.map(t=>`${t.alias}.${t.column}`);for(const t of Object.values(this.selectedFields)){if(isAggregateExpression(t))continue;const n=this.resolveSelectFieldColumn(t);if(!n)continue;const a=`${n.alias}.${n.column}`;if(!e.includes(a))throw new Error(`Column ${a} must appear in GROUP BY clause when mixed with aggregates`)}}resolveSelectFieldColumn(e){if(e instanceof PodColumnBase)return this.resolveColumnReference(e);if(typeof e=="string")return this.resolveColumnReference(e)}hasAggregateSelection(){return this.selectedFields?Object.values(this.selectedFields).some(e=>isAggregateExpression(e)):!1}hasMixedAggregateSelection(){if(!this.selectedFields)return!1;const e=Object.values(this.selectedFields),t=e.some(a=>isAggregateExpression(a)),n=e.some(a=>!isAggregateExpression(a));return t&&n}applySubjectMetadata(e){return e.map(t=>this.attachSubjectMetadata(t))}extractSubjectValue(e){const t=e.subject??e["@id"]??e.uri;if(typeof t=="object"&&t&&"value"in t){const n=t.value;return typeof n=="string"&&n.length>0?n:void 0}if(typeof t=="string"&&t.length>0)return t}attachSubjectMetadata(e){const t=this.extractSubjectValue(e);if(typeof t=="string"&&t.length>0&&(e["@id"]===void 0&&(e["@id"]=t),e.uri===void 0&&(e.uri=t),e.id===void 0)){const n=this.extractIdFromSubject(t,this.selectedTable);n!==void 0&&(e.id=n)}return e}normalizeBaseRows(e){if(!e.length)return e;const t=this.primaryAlias||this.ensureAliasForTable(this.selectedTable);return e.map(n=>{const a={...n};for(const[o,s]of Object.entries(n))o!==`${t}.${o}`&&(a[`${t}.${o}`]=s);const i=this.extractSubjectValue(n);if(i){a.subject=i,a["@id"]=i,a.uri=i,a[`${t}.subject`]=i,a[`${t}.@id`]=i,a[`${t}.uri`]=i;const o=this.extractIdFromSubject(i,this.selectedTable);o!==void 0&&(a.id===void 0&&(a.id=o),(this.shouldUseSubjectIdentityColumn(this.selectedTable,"id")||a[`${t}.id`]===void 0)&&(a[`${t}.id`]=o))}return a})}async hydrateInlineColumns(e,t,n=!0){if(!e.length)return e;const a=Object.values(t.columns??{}).filter(h=>this.isInlineObjectColumn(h));if(a.length===0)return e;n&&(e=this.mergeRowsBySubject(e));const i=new Map;a.forEach(h=>{const T=h.getPredicate(t.config.namespace);i.set(T,h)});const o=Array.from(new Set(e.map(h=>this.normalizeInlineIri(h["@id"]??h.subject??h.uri??h.id)).filter(h=>!!h)));if(o.length===0||i.size===0)return e;const s=Array.from(i.keys()).map(h=>`<${h}>`).join(" "),d=this.session.getDialect().getSPARQLExecutor(),u=[],c=new Map;for(const h of o){const T=this.inferSourceFromChild(h,t),w=c.get(T)??[];w.push(h),c.set(T,w)}for(const[h,T]of c.entries()){const b={type:"SELECT",query:`SELECT ?parent ?linkPred ?child ?pred ?obj WHERE {
|
|
34
34
|
VALUES ?parent { ${T.map(O=>`<${O}>`).join(" ")} }
|
|
35
35
|
VALUES ?linkPred { ${s} }
|
|
36
36
|
?parent ?linkPred ?child .
|
|
@@ -564,4 +564,4 @@ ${T}`);return this.handleDereferenceErrors(u,w,_.headers,A)}}const h=i.exec(_.he
|
|
|
564
564
|
`},typeof de=="string"&&(de.indexOf("-----BEGIN")!=-1?this.readCertPEM(de):me.lang.String.isHex(de)&&this.readCertHex(de))}he.prototype.sign=function(de,ce){var ye=(function(Re){return me.crypto.Util.hashString(Re,ce)})(de);return this.signWithMessageHash(ye,ce)},he.prototype.signWithMessageHash=function(de,ce){var ye=fe(me.crypto.Util.getPaddedDigestInfoHex(de,ce,this.n.bitLength()),16);return ve(this.doPrivate(ye).toString(16),this.n.bitLength())},he.prototype.signPSS=function(de,ce,ye){var _e=(function(Ie){return me.crypto.Util.hashHex(Ie,ce)})(et(de));return ye===void 0&&(ye=-1),this.signWithMessageHashPSS(_e,ce,ye)},he.prototype.signWithMessageHashPSS=function(de,ce,ye){var _e,Re=at(de),Ie=Re.length,Pe=this.n.bitLength()-1,Be=Math.ceil(Pe/8),Me=function(Fe){return me.crypto.Util.hashHex(Fe,ce)};if(ye===-1||ye===void 0)ye=Ie;else if(ye===-2)ye=Be-Ie-2;else if(ye<-2)throw new Error("invalid salt length");if(Be<Ie+ye+2)throw new Error("data too long");var Ue="";ye>0&&(Ue=new Array(ye),new L().nextBytes(Ue),Ue=String.fromCharCode.apply(String,Ue));var ke=at(Me(et("\0\0\0\0\0\0\0\0"+Re+Ue))),Ge=[];for(_e=0;_e<Be-ye-Ie-2;_e+=1)Ge[_e]=0;var Xe=String.fromCharCode.apply(String,Ge)+""+Ue,tt=Rt(ke,Xe.length,Me),nt=[];for(_e=0;_e<Xe.length;_e+=1)nt[_e]=Xe.charCodeAt(_e)^tt.charCodeAt(_e);var ht=65280>>8*Be-Pe&255;for(nt[0]&=~ht,_e=0;_e<Ie;_e++)nt.push(ke.charCodeAt(_e));return nt.push(188),ve(this.doPrivate(new v(nt)).toString(16),this.n.bitLength())},he.prototype.verify=function(de,ce){if((ce=ce.toLowerCase()).match(/^[0-9a-f]+$/)==null)return!1;var ye=fe(ce,16),_e=this.n.bitLength();if(ye.bitLength()>_e)return!1;var Re=this.doPublic(ye).toString(16);if(Re.length+3!=_e/4)return!1;var Ie=Tt(Re.replace(/^1f+00/,""));if(Ie.length==0)return!1;var Pe=Ie[0];return Ie[1]==(function(Me){return me.crypto.Util.hashString(Me,Pe)})(de)},he.prototype.verifyWithMessageHash=function(de,ce){if(ce.length!=Math.ceil(this.n.bitLength()/4))return!1;var ye=fe(ce,16);if(ye.bitLength()>this.n.bitLength())return 0;var _e=Tt(this.doPublic(ye).toString(16).replace(/^1f+00/,""));return _e.length==0?!1:(_e[0],_e[1]==de)},he.prototype.verifyPSS=function(de,ce,ye,_e){var Re=(function(Pe){return me.crypto.Util.hashHex(Pe,ye)})(et(de));return _e===void 0&&(_e=-1),this.verifyWithMessageHashPSS(Re,ce,ye,_e)},he.prototype.verifyWithMessageHashPSS=function(de,ce,ye,_e){if(ce.length!=Math.ceil(this.n.bitLength()/4))return!1;var Re,Ie=new v(ce,16),Pe=function(ze){return me.crypto.Util.hashHex(ze,ye)},Be=at(de),Me=Be.length,Ue=this.n.bitLength()-1,ke=Math.ceil(Ue/8);if(_e===-1||_e===void 0)_e=Me;else if(_e===-2)_e=ke-Me-2;else if(_e<-2)throw new Error("invalid salt length");if(ke<Me+_e+2)throw new Error("data too long");var Ge=this.doPublic(Ie).toByteArray();for(Re=0;Re<Ge.length;Re+=1)Ge[Re]&=255;for(;Ge.length<ke;)Ge.unshift(0);if(Ge[ke-1]!==188)throw new Error("encoded message does not end in 0xbc");var Xe=(Ge=String.fromCharCode.apply(String,Ge)).substr(0,ke-Me-1),tt=Ge.substr(Xe.length,Me),nt=65280>>8*ke-Ue&255;if((Xe.charCodeAt(0)&nt)!=0)throw new Error("bits beyond keysize not zero");var ht=Rt(tt,Xe.length,Pe),bt=[];for(Re=0;Re<Xe.length;Re+=1)bt[Re]=Xe.charCodeAt(Re)^ht.charCodeAt(Re);bt[0]&=~nt;var Fe=ke-Me-_e-2;for(Re=0;Re<Fe;Re+=1)if(bt[Re]!==0)throw new Error("leftmost octets not zero");if(bt[Fe]!==1)throw new Error("0x01 marker not found");return tt===at(Pe(et("\0\0\0\0\0\0\0\0"+Be+String.fromCharCode.apply(String,bt.slice(-_e)))))},he.SALT_LEN_HLEN=-1,he.SALT_LEN_MAX=-2,he.SALT_LEN_RECOVER=-2,xt.hex2dn=function(de,ce){ce===void 0&&(ce=0);var ye=new xt;return Le.getTLV(de,ce),ye.getX500Name(de).str},xt.hex2rdn=function(de,ce){if(ce===void 0&&(ce=0),de.substr(ce,2)!=="31")throw new Error("malformed RDN");for(var ye=new Array,_e=Le.getChildIdx(de,ce),Re=0;Re<_e.length;Re++)ye.push(xt.hex2attrTypeValue(de,_e[Re]));return(ye=ye.map((function(Ie){return Ie.replace("+","\\+")}))).join("+")},xt.hex2attrTypeValue=function(de,ce){var ye=Le,_e=ye.getV;if(ce===void 0&&(ce=0),de.substr(ce,2)!=="30")throw new Error("malformed attribute type and value");var Re=ye.getChildIdx(de,ce);Re.length!==2||de.substr(Re[0],2);var Ie=_e(de,Re[0]),Pe=me.asn1.ASN1Util.oidHexToInt(Ie);return me.asn1.x509.OID.oid2atype(Pe)+"="+at(_e(de,Re[1]))},xt.getPublicKeyFromCertHex=function(de){var ce=new xt;return ce.readCertHex(de),ce.getPublicKey()},xt.getPublicKeyFromCertPEM=function(de){var ce=new xt;return ce.readCertPEM(de),ce.getPublicKey()},xt.getPublicKeyInfoPropOfCertPEM=function(de){var ce,ye,_e=Le.getVbyList,Re={};return Re.algparam=null,(ce=new xt).readCertPEM(de),ye=ce.getPublicKeyHex(),Re.keyhex=_e(ye,0,[1],"03").substr(2),Re.algoid=_e(ye,0,[0,0],"06"),Re.algoid==="2a8648ce3d0201"&&(Re.algparam=_e(ye,0,[0,1],"06")),Re},xt.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],me!==void 0&&me||(n.KJUR=me={}),me.jws!==void 0&&me.jws||(me.jws={}),me.jws.JWS=function(){var de=me.jws.JWS.isSafeJSONString;this.parseJWS=function(ce,ye){if(this.parsedJWS===void 0||!ye&&this.parsedJWS.sigvalH===void 0){var _e=ce.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(_e==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var Re=_e[1],Ie=_e[2],Pe=_e[3],Be=Re+"."+Ie;if(this.parsedJWS={},this.parsedJWS.headB64U=Re,this.parsedJWS.payloadB64U=Ie,this.parsedJWS.sigvalB64U=Pe,this.parsedJWS.si=Be,!ye){var Me=Ve(Pe),Ue=fe(Me,16);this.parsedJWS.sigvalH=Me,this.parsedJWS.sigvalBI=Ue}var ke=We(Re),Ge=We(Ie);if(this.parsedJWS.headS=ke,this.parsedJWS.payloadS=Ge,!de(ke,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+ke}}},me.jws.JWS.sign=function(de,ce,ye,_e,Re){var Ie,Pe,Be,Me=me,Ue=Me.jws.JWS,ke=Ue.readSafeJSONString,Ge=Ue.isSafeJSONString,Xe=Me.crypto,tt=(Xe.ECDSA,Xe.Mac),nt=Xe.Signature,ht=JSON;if(typeof ce!="string"&&(ce===void 0?"undefined":T(ce))!="object")throw"spHeader must be JSON string or object: "+ce;if((ce===void 0?"undefined":T(ce))=="object"&&(Pe=ce,Ie=ht.stringify(Pe)),typeof ce=="string"){if(!Ge(Ie=ce))throw"JWS Head is not safe JSON string: "+Ie;Pe=ke(Ie)}if(Be=ye,(ye===void 0?"undefined":T(ye))=="object"&&(Be=ht.stringify(ye)),de!=""&&de!=null||Pe.alg===void 0||(de=Pe.alg),de!=""&&de!=null&&Pe.alg===void 0&&(Pe.alg=de,Ie=ht.stringify(Pe)),de!==Pe.alg)throw"alg and sHeader.alg doesn't match: "+de+"!="+Pe.alg;var bt=null;if(Ue.jwsalg2sigalg[de]===void 0)throw"unsupported alg name: "+de;bt=Ue.jwsalg2sigalg[de];var Fe=we(Ie)+"."+we(Be),Qe="";if(bt.substr(0,4)=="Hmac"){if(_e===void 0)throw"mac key shall be specified for HS* alg";var ze=new tt({alg:bt,prov:"cryptojs",pass:_e});ze.updateString(Fe),Qe=ze.doFinal()}else if(bt.indexOf("withECDSA")!=-1){(it=new nt({alg:bt})).init(_e,Re),it.updateString(Fe);var Ke=it.sign();Qe=me.crypto.ECDSA.asn1SigToConcatSig(Ke)}else{var it;bt!="none"&&((it=new nt({alg:bt})).init(_e,Re),it.updateString(Fe),Qe=it.sign())}return Fe+"."+Ce(Qe)},me.jws.JWS.verify=function(de,ce,ye){var _e,Re=me,Ie=Re.jws.JWS,Pe=Ie.readSafeJSONString,Be=Re.crypto,Me=Be.ECDSA,Ue=Be.Mac,ke=Be.Signature;T(he)!==void 0&&(_e=he);var Ge=de.split(".");if(Ge.length!==3)return!1;var Xe=Ge[0]+"."+Ge[1],tt=Ve(Ge[2]),nt=Pe(We(Ge[0])),ht=null,bt=null;if(nt.alg===void 0)throw"algorithm not specified in header";if(bt=(ht=nt.alg).substr(0,2),ye!=null&&Object.prototype.toString.call(ye)==="[object Array]"&&ye.length>0&&(":"+ye.join(":")+":").indexOf(":"+ht+":")==-1)throw"algorithm '"+ht+"' not accepted in the list";if(ht!="none"&&ce===null)throw"key shall be specified to verify.";if(typeof ce=="string"&&ce.indexOf("-----BEGIN ")!=-1&&(ce=qe.getKey(ce)),!(bt!="RS"&&bt!="PS"||ce instanceof _e))throw"key shall be a RSAKey obj for RS* and PS* algs";if(bt=="ES"&&!(ce instanceof Me))throw"key shall be a ECDSA obj for ES* algs";var Fe=null;if(Ie.jwsalg2sigalg[nt.alg]===void 0)throw"unsupported alg name: "+ht;if((Fe=Ie.jwsalg2sigalg[ht])=="none")throw"not supported";if(Fe.substr(0,4)=="Hmac"){if(ce===void 0)throw"hexadecimal key shall be specified for HMAC";var Qe=new Ue({alg:Fe,pass:ce});return Qe.updateString(Xe),tt==Qe.doFinal()}if(Fe.indexOf("withECDSA")!=-1){var ze,Ke=null;try{Ke=Me.concatSigToASN1Sig(tt)}catch{return!1}return(ze=new ke({alg:Fe})).init(ce),ze.updateString(Xe),ze.verify(Ke)}return(ze=new ke({alg:Fe})).init(ce),ze.updateString(Xe),ze.verify(tt)},me.jws.JWS.parse=function(de){var ce,ye,_e,Re=de.split("."),Ie={};if(Re.length!=2&&Re.length!=3)throw"malformed sJWS: wrong number of '.' splitted elements";return ce=Re[0],ye=Re[1],Re.length==3&&(_e=Re[2]),Ie.headerObj=me.jws.JWS.readSafeJSONString(We(ce)),Ie.payloadObj=me.jws.JWS.readSafeJSONString(We(ye)),Ie.headerPP=JSON.stringify(Ie.headerObj,null," "),Ie.payloadObj==null?Ie.payloadPP=We(ye):Ie.payloadPP=JSON.stringify(Ie.payloadObj,null," "),_e!==void 0&&(Ie.sigHex=Ve(_e)),Ie},me.jws.JWS.verifyJWT=function(de,ce,ye){var _e=me.jws,Re=_e.JWS,Ie=Re.readSafeJSONString,Pe=Re.inArray,Be=Re.includedArray,Me=de.split("."),Ue=Me[0],ke=Me[1],Ge=(Ve(Me[2]),Ie(We(Ue))),Xe=Ie(We(ke));if(Ge.alg===void 0)return!1;if(ye.alg===void 0)throw"acceptField.alg shall be specified";if(!Pe(Ge.alg,ye.alg)||Xe.iss!==void 0&&T(ye.iss)==="object"&&!Pe(Xe.iss,ye.iss)||Xe.sub!==void 0&&T(ye.sub)==="object"&&!Pe(Xe.sub,ye.sub))return!1;if(Xe.aud!==void 0&&T(ye.aud)==="object"){if(typeof Xe.aud=="string"){if(!Pe(Xe.aud,ye.aud))return!1}else if(T(Xe.aud)=="object"&&!Be(Xe.aud,ye.aud))return!1}var tt=_e.IntDate.getNow();return ye.verifyAt!==void 0&&typeof ye.verifyAt=="number"&&(tt=ye.verifyAt),ye.gracePeriod!==void 0&&typeof ye.gracePeriod=="number"||(ye.gracePeriod=0),!(Xe.exp!==void 0&&typeof Xe.exp=="number"&&Xe.exp+ye.gracePeriod<tt)&&!(Xe.nbf!==void 0&&typeof Xe.nbf=="number"&&tt<Xe.nbf-ye.gracePeriod)&&!(Xe.iat!==void 0&&typeof Xe.iat=="number"&&tt<Xe.iat-ye.gracePeriod)&&(Xe.jti===void 0||ye.jti===void 0||Xe.jti===ye.jti)&&!!Re.verify(de,ce,ye.alg)},me.jws.JWS.includedArray=function(de,ce){var ye=me.jws.JWS.inArray;if(de===null||(de===void 0?"undefined":T(de))!=="object"||typeof de.length!="number")return!1;for(var _e=0;_e<de.length;_e++)if(!ye(de[_e],ce))return!1;return!0},me.jws.JWS.inArray=function(de,ce){if(ce===null||(ce===void 0?"undefined":T(ce))!=="object"||typeof ce.length!="number")return!1;for(var ye=0;ye<ce.length;ye++)if(ce[ye]==de)return!0;return!1},me.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},me.jws.JWS.isSafeJSONString=function(de,ce,ye){var _e=null;try{return((_e=ge(de))===void 0?"undefined":T(_e))!="object"||_e.constructor===Array?0:(ce&&(ce[ye]=_e),1)}catch{return 0}},me.jws.JWS.readSafeJSONString=function(de){var ce=null;try{return((ce=ge(de))===void 0?"undefined":T(ce))!="object"||ce.constructor===Array?null:ce}catch{return null}},me.jws.JWS.getEncodedSignatureValueFromJWS=function(de){var ce=de.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(ce==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return ce[1]},me.jws.JWS.getJWKthumbprint=function(de){if(de.kty!=="RSA"&&de.kty!=="EC"&&de.kty!=="oct")throw"unsupported algorithm for JWK Thumprint";var ce="{";if(de.kty==="RSA"){if(typeof de.n!="string"||typeof de.e!="string")throw"wrong n and e value for RSA key";ce+='"e":"'+de.e+'",',ce+='"kty":"'+de.kty+'",',ce+='"n":"'+de.n+'"}'}else if(de.kty==="EC"){if(typeof de.crv!="string"||typeof de.x!="string"||typeof de.y!="string")throw"wrong crv, x and y value for EC key";ce+='"crv":"'+de.crv+'",',ce+='"kty":"'+de.kty+'",',ce+='"x":"'+de.x+'",',ce+='"y":"'+de.y+'"}'}else if(de.kty==="oct"){if(typeof de.k!="string")throw"wrong k value for oct(symmetric) key";ce+='"kty":"'+de.kty+'",',ce+='"k":"'+de.k+'"}'}var ye=et(ce);return Ce(me.crypto.Util.hashHex(ye,"sha256"))},me.jws.IntDate={},me.jws.IntDate.get=function(de){var ce=me.jws.IntDate,ye=ce.getNow,_e=ce.getZulu;if(de=="now")return ye();if(de=="now + 1hour")return ye()+3600;if(de=="now + 1day")return ye()+86400;if(de=="now + 1month")return ye()+2592e3;if(de=="now + 1year")return ye()+31536e3;if(de.match(/Z$/))return _e(de);if(de.match(/^[0-9]+$/))return parseInt(de);throw"unsupported format: "+de},me.jws.IntDate.getZulu=function(de){return $e(de)},me.jws.IntDate.getNow=function(){return~~(new Date/1e3)},me.jws.IntDate.intDate2UTCString=function(de){return new Date(1e3*de).toUTCString()},me.jws.IntDate.intDate2Zulu=function(de){var ce=new Date(1e3*de);return("0000"+ce.getUTCFullYear()).slice(-4)+("00"+(ce.getUTCMonth()+1)).slice(-2)+("00"+ce.getUTCDate()).slice(-2)+("00"+ce.getUTCHours()).slice(-2)+("00"+ce.getUTCMinutes()).slice(-2)+("00"+ce.getUTCSeconds()).slice(-2)+"Z"},n.SecureRandom=L,n.rng_seed_time=B,n.BigInteger=v,n.RSAKey=he;var Vt=me.crypto.EDSA;n.EDSA=Vt;var Ut=me.crypto.DSA;n.DSA=Ut;var Nr=me.crypto.Signature;n.Signature=Nr;var cr=me.crypto.MessageDigest;n.MessageDigest=cr;var kt=me.crypto.Mac;n.Mac=kt;var pr=me.crypto.Cipher;n.Cipher=pr,n.KEYUTIL=qe,n.ASN1HEX=Le,n.X509=xt,n.CryptoJS=N,n.b64tohex=V,n.b64toBA=U,n.stoBA=Je,n.BAtos=ct,n.BAtohex=st,n.stohex=pt,n.stob64=function(ce){return ee(pt(ce))},n.stob64u=function(ce){return Se(ee(pt(ce)))},n.b64utos=function(ce){return ct(U(Ne(ce)))},n.b64tob64u=Se,n.b64utob64=Ne,n.hex2b64=ee,n.hextob64u=Ce,n.b64utohex=Ve,n.utf8tob64u=we,n.b64utoutf8=We,n.utf8tob64=function(ce){return ee(Ee(ot(ce)))},n.b64toutf8=function(ce){return decodeURIComponent(ft(V(ce)))},n.utf8tohex=He,n.hextoutf8=ut,n.hextorstr=at,n.rstrtohex=et,n.hextob64=dt,n.hextob64nl=l,n.b64nltohex=f,n.hextopem=J,n.pemtohex=Y,n.hextoArrayBuffer=function(ce){if(ce.length%2!=0)throw"input is not even length";if(ce.match(/^[0-9A-Fa-f]+$/)==null)throw"input is not hexadecimal";for(var ye=new ArrayBuffer(ce.length/2),_e=new DataView(ye),Re=0;Re<ce.length/2;Re++)_e.setUint8(Re,parseInt(ce.substr(2*Re,2),16));return ye},n.ArrayBuffertohex=function(ce){for(var ye="",_e=new DataView(ce),Re=0;Re<ce.byteLength;Re++)ye+=("00"+_e.getUint8(Re).toString(16)).slice(-2);return ye},n.zulutomsec=ae,n.zulutosec=$e,n.zulutodate=function(ce){return new Date(ae(ce))},n.datetozulu=function(ce,ye,_e){var Re,Ie=ce.getUTCFullYear();if(ye){if(Ie<1950||2049<Ie)throw"not proper year for UTCTime: "+Ie;Re=(""+Ie).slice(-2)}else Re=("000"+Ie).slice(-4);if(Re+=("0"+(ce.getUTCMonth()+1)).slice(-2),Re+=("0"+ce.getUTCDate()).slice(-2),Re+=("0"+ce.getUTCHours()).slice(-2),Re+=("0"+ce.getUTCMinutes()).slice(-2),Re+=("0"+ce.getUTCSeconds()).slice(-2),_e){var Pe=ce.getUTCMilliseconds();Pe!==0&&(Re+="."+(Pe=(Pe=("00"+Pe).slice(-3)).replace(/0+$/g,"")))}return Re+="Z"},n.uricmptohex=Ee,n.hextouricmp=ft,n.ipv6tohex=De,n.hextoipv6=rt,n.hextoip=mt,n.iptohex=function(ce){var ye="malformed IP address";if(!(ce=ce.toLowerCase(ce)).match(/^[0-9.]+$/)){if(ce.match(/^[0-9a-f:]+$/)&&ce.indexOf(":")!==-1)return De(ce);throw ye}var _e=ce.split(".");if(_e.length!==4)throw ye;var Re="";try{for(var Ie=0;Ie<4;Ie++)Re+=("0"+parseInt(_e[Ie]).toString(16)).slice(-2);return Re}catch{throw ye}},n.encodeURIComponentAll=ot,n.newline_toUnix=function(ce){return ce=ce.replace(/\r\n/gm,`
|
|
565
565
|
`)},n.newline_toDos=function(ce){return ce=(ce=ce.replace(/\r\n/gm,`
|
|
566
566
|
`)).replace(/\n/gm,`\r
|
|
567
|
-
`)},n.hextoposhex=lt,n.intarystrtohex=function(ce){ce=(ce=(ce=ce.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return ce.split(/,/).map((function(ye,_e,Re){var Ie=parseInt(ye);if(Ie<0||255<Ie)throw"integer not in range 0-255";return("00"+Ie.toString(16)).slice(-2)})).join("")}catch(ye){throw"malformed integer array string: "+ye}},n.strdiffidx=function(ce,ye){var _e=ce.length;ce.length>ye.length&&(_e=ye.length);for(var Re=0;Re<_e;Re++)if(ce.charCodeAt(Re)!=ye.charCodeAt(Re))return Re;return ce.length!=ye.length?_e:-1},n.KJUR=me;var Yt=me.crypto;n.crypto=Yt;var gr=me.asn1;n.asn1=gr;var Zt=me.jws;n.jws=Zt;var kr=me.lang;n.lang=kr}).call(this,a(28).Buffer)},function(t,n,a){(function(i){var o=a(30),s=a(31),d=a(32);function u(){return p.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function c(z,G){if(u()<G)throw new RangeError("Invalid typed array length");return p.TYPED_ARRAY_SUPPORT?(z=new Uint8Array(G)).__proto__=p.prototype:(z===null&&(z=new p(G)),z.length=G),z}function p(z,G,g){if(!(p.TYPED_ARRAY_SUPPORT||this instanceof p))return new p(z,G,g);if(typeof z=="number"){if(typeof G=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,z)}return _(this,z,G,g)}function _(z,G,g,R){if(typeof G=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&G instanceof ArrayBuffer?(function(B,k,W,$){if(k.byteLength,W<0||k.byteLength<W)throw new RangeError("'offset' is out of bounds");if(k.byteLength<W+($||0))throw new RangeError("'length' is out of bounds");return k=W===void 0&&$===void 0?new Uint8Array(k):$===void 0?new Uint8Array(k,W):new Uint8Array(k,W,$),p.TYPED_ARRAY_SUPPORT?(B=k).__proto__=p.prototype:B=A(B,k),B})(z,G,g,R):typeof G=="string"?(function(B,k,W){if(typeof W=="string"&&W!==""||(W="utf8"),!p.isEncoding(W))throw new TypeError('"encoding" must be a valid string encoding');var $=0|T(k,W),j=(B=c(B,$)).write(k,W);return j!==$&&(B=B.slice(0,j)),B})(z,G,g):(function(B,k){if(p.isBuffer(k)){var W=0|h(k.length);return(B=c(B,W)).length===0||k.copy(B,0,0,W),B}if(k){if(typeof ArrayBuffer<"u"&&k.buffer instanceof ArrayBuffer||"length"in k)return typeof k.length!="number"||(function(j){return j!=j})(k.length)?c(B,0):A(B,k);if(k.type==="Buffer"&&d(k.data))return A(B,k.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(z,G)}function m(z){if(typeof z!="number")throw new TypeError('"size" argument must be a number');if(z<0)throw new RangeError('"size" argument must not be negative')}function S(z,G){if(m(G),z=c(z,G<0?0:0|h(G)),!p.TYPED_ARRAY_SUPPORT)for(var g=0;g<G;++g)z[g]=0;return z}function A(z,G){var g=G.length<0?0:0|h(G.length);z=c(z,g);for(var R=0;R<g;R+=1)z[R]=255&G[R];return z}function h(z){if(z>=u())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+u().toString(16)+" bytes");return 0|z}function T(z,G){if(p.isBuffer(z))return z.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(z)||z instanceof ArrayBuffer))return z.byteLength;typeof z!="string"&&(z=""+z);var g=z.length;if(g===0)return 0;for(var R=!1;;)switch(G){case"ascii":case"latin1":case"binary":return g;case"utf8":case"utf-8":case void 0:return P(z).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*g;case"hex":return g>>>1;case"base64":return M(z).length;default:if(R)return P(z).length;G=(""+G).toLowerCase(),R=!0}}function w(z,G,g){var R=!1;if((G===void 0||G<0)&&(G=0),G>this.length||((g===void 0||g>this.length)&&(g=this.length),g<=0)||(g>>>=0)<=(G>>>=0))return"";for(z||(z="utf8");;)switch(z){case"hex":return se(this,G,g);case"utf8":case"utf-8":return E(this,G,g);case"ascii":return K(this,G,g);case"latin1":case"binary":return te(this,G,g);case"base64":return I(this,G,g);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,G,g);default:if(R)throw new TypeError("Unknown encoding: "+z);z=(z+"").toLowerCase(),R=!0}}function b(z,G,g){var R=z[G];z[G]=z[g],z[g]=R}function N(z,G,g,R,q){if(z.length===0)return-1;if(typeof g=="string"?(R=g,g=0):g>2147483647?g=2147483647:g<-2147483648&&(g=-2147483648),g=+g,isNaN(g)&&(g=q?0:z.length-1),g<0&&(g=z.length+g),g>=z.length){if(q)return-1;g=z.length-1}else if(g<0){if(!q)return-1;g=0}if(typeof G=="string"&&(G=p.from(G,R)),p.isBuffer(G))return G.length===0?-1:O(z,G,g,R,q);if(typeof G=="number")return G&=255,p.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?q?Uint8Array.prototype.indexOf.call(z,G,g):Uint8Array.prototype.lastIndexOf.call(z,G,g):O(z,[G],g,R,q);throw new TypeError("val must be string, number or Buffer")}function O(z,G,g,R,q){var B,k=1,W=z.length,$=G.length;if(R!==void 0&&((R=String(R).toLowerCase())==="ucs2"||R==="ucs-2"||R==="utf16le"||R==="utf-16le")){if(z.length<2||G.length<2)return-1;k=2,W/=2,$/=2,g/=2}function j(Ae,he){return k===1?Ae[he]:Ae.readUInt16BE(he*k)}if(q){var H=-1;for(B=g;B<W;B++)if(j(z,B)===j(G,H===-1?0:B-H)){if(H===-1&&(H=B),B-H+1===$)return H*k}else H!==-1&&(B-=B-H),H=-1}else for(g+$>W&&(g=W-$),B=g;B>=0;B--){for(var L=!0,fe=0;fe<$;fe++)if(j(z,B+fe)!==j(G,fe)){L=!1;break}if(L)return B}return-1}function X(z,G,g,R){g=Number(g)||0;var q=z.length-g;R?(R=Number(R))>q&&(R=q):R=q;var B=G.length;if(B%2!=0)throw new TypeError("Invalid hex string");R>B/2&&(R=B/2);for(var k=0;k<R;++k){var W=parseInt(G.substr(2*k,2),16);if(isNaN(W))return k;z[g+k]=W}return k}function ee(z,G,g,R){return Z(P(G,z.length-g),z,g,R)}function V(z,G,g,R){return Z((function(B){for(var k=[],W=0;W<B.length;++W)k.push(255&B.charCodeAt(W));return k})(G),z,g,R)}function U(z,G,g,R){return V(z,G,g,R)}function v(z,G,g,R){return Z(M(G),z,g,R)}function x(z,G,g,R){return Z((function(B,k){for(var W,$,j,H=[],L=0;L<B.length&&!((k-=2)<0);++L)$=(W=B.charCodeAt(L))>>8,j=W%256,H.push(j),H.push($);return H})(G,z.length-g),z,g,R)}function I(z,G,g){return G===0&&g===z.length?o.fromByteArray(z):o.fromByteArray(z.slice(G,g))}function E(z,G,g){g=Math.min(z.length,g);for(var R=[],q=G;q<g;){var B,k,W,$,j=z[q],H=null,L=j>239?4:j>223?3:j>191?2:1;if(q+L<=g)switch(L){case 1:j<128&&(H=j);break;case 2:(192&(B=z[q+1]))==128&&($=(31&j)<<6|63&B)>127&&(H=$);break;case 3:B=z[q+1],k=z[q+2],(192&B)==128&&(192&k)==128&&($=(15&j)<<12|(63&B)<<6|63&k)>2047&&($<55296||$>57343)&&(H=$);break;case 4:B=z[q+1],k=z[q+2],W=z[q+3],(192&B)==128&&(192&k)==128&&(192&W)==128&&($=(15&j)<<18|(63&B)<<12|(63&k)<<6|63&W)>65535&&$<1114112&&(H=$)}H===null?(H=65533,L=1):H>65535&&(H-=65536,R.push(H>>>10&1023|55296),H=56320|1023&H),R.push(H),q+=L}return(function(Ae){var he=Ae.length;if(he<=Q)return String.fromCharCode.apply(String,Ae);for(var Te="",be=0;be<he;)Te+=String.fromCharCode.apply(String,Ae.slice(be,be+=Q));return Te})(R)}n.Buffer=p,n.SlowBuffer=function(G){return+G!=G&&(G=0),p.alloc(+G)},n.INSPECT_MAX_BYTES=50,p.TYPED_ARRAY_SUPPORT=i.TYPED_ARRAY_SUPPORT!==void 0?i.TYPED_ARRAY_SUPPORT:(function(){try{var G=new Uint8Array(1);return G.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},G.foo()===42&&typeof G.subarray=="function"&&G.subarray(1,1).byteLength===0}catch{return!1}})(),n.kMaxLength=u(),p.poolSize=8192,p._augment=function(z){return z.__proto__=p.prototype,z},p.from=function(z,G,g){return _(null,z,G,g)},p.TYPED_ARRAY_SUPPORT&&(p.prototype.__proto__=Uint8Array.prototype,p.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&p[Symbol.species]===p&&Object.defineProperty(p,Symbol.species,{value:null,configurable:!0})),p.alloc=function(z,G,g){return(function(q,B,k,W){return m(B),B<=0?c(q,B):k!==void 0?typeof W=="string"?c(q,B).fill(k,W):c(q,B).fill(k):c(q,B)})(null,z,G,g)},p.allocUnsafe=function(z){return S(null,z)},p.allocUnsafeSlow=function(z){return S(null,z)},p.isBuffer=function(G){return!(G==null||!G._isBuffer)},p.compare=function(G,g){if(!p.isBuffer(G)||!p.isBuffer(g))throw new TypeError("Arguments must be Buffers");if(G===g)return 0;for(var R=G.length,q=g.length,B=0,k=Math.min(R,q);B<k;++B)if(G[B]!==g[B]){R=G[B],q=g[B];break}return R<q?-1:q<R?1:0},p.isEncoding=function(G){switch(String(G).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},p.concat=function(G,g){if(!d(G))throw new TypeError('"list" argument must be an Array of Buffers');if(G.length===0)return p.alloc(0);var R;if(g===void 0)for(g=0,R=0;R<G.length;++R)g+=G[R].length;var q=p.allocUnsafe(g),B=0;for(R=0;R<G.length;++R){var k=G[R];if(!p.isBuffer(k))throw new TypeError('"list" argument must be an Array of Buffers');k.copy(q,B),B+=k.length}return q},p.byteLength=T,p.prototype._isBuffer=!0,p.prototype.swap16=function(){var G=this.length;if(G%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var g=0;g<G;g+=2)b(this,g,g+1);return this},p.prototype.swap32=function(){var G=this.length;if(G%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var g=0;g<G;g+=4)b(this,g,g+3),b(this,g+1,g+2);return this},p.prototype.swap64=function(){var G=this.length;if(G%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var g=0;g<G;g+=8)b(this,g,g+7),b(this,g+1,g+6),b(this,g+2,g+5),b(this,g+3,g+4);return this},p.prototype.toString=function(){var G=0|this.length;return G===0?"":arguments.length===0?E(this,0,G):w.apply(this,arguments)},p.prototype.equals=function(G){if(!p.isBuffer(G))throw new TypeError("Argument must be a Buffer");return this===G||p.compare(this,G)===0},p.prototype.inspect=function(){var G="",g=n.INSPECT_MAX_BYTES;return this.length>0&&(G=this.toString("hex",0,g).match(/.{2}/g).join(" "),this.length>g&&(G+=" ... ")),"<Buffer "+G+">"},p.prototype.compare=function(G,g,R,q,B){if(!p.isBuffer(G))throw new TypeError("Argument must be a Buffer");if(g===void 0&&(g=0),R===void 0&&(R=G?G.length:0),q===void 0&&(q=0),B===void 0&&(B=this.length),g<0||R>G.length||q<0||B>this.length)throw new RangeError("out of range index");if(q>=B&&g>=R)return 0;if(q>=B)return-1;if(g>=R)return 1;if(this===G)return 0;for(var k=(B>>>=0)-(q>>>=0),W=(R>>>=0)-(g>>>=0),$=Math.min(k,W),j=this.slice(q,B),H=G.slice(g,R),L=0;L<$;++L)if(j[L]!==H[L]){k=j[L],W=H[L];break}return k<W?-1:W<k?1:0},p.prototype.includes=function(G,g,R){return this.indexOf(G,g,R)!==-1},p.prototype.indexOf=function(G,g,R){return N(this,G,g,R,!0)},p.prototype.lastIndexOf=function(G,g,R){return N(this,G,g,R,!1)},p.prototype.write=function(G,g,R,q){if(g===void 0)q="utf8",R=this.length,g=0;else if(R===void 0&&typeof g=="string")q=g,R=this.length,g=0;else{if(!isFinite(g))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");g|=0,isFinite(R)?(R|=0,q===void 0&&(q="utf8")):(q=R,R=void 0)}var B=this.length-g;if((R===void 0||R>B)&&(R=B),G.length>0&&(R<0||g<0)||g>this.length)throw new RangeError("Attempt to write outside buffer bounds");q||(q="utf8");for(var k=!1;;)switch(q){case"hex":return X(this,G,g,R);case"utf8":case"utf-8":return ee(this,G,g,R);case"ascii":return V(this,G,g,R);case"latin1":case"binary":return U(this,G,g,R);case"base64":return v(this,G,g,R);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,G,g,R);default:if(k)throw new TypeError("Unknown encoding: "+q);q=(""+q).toLowerCase(),k=!0}},p.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;function K(z,G,g){var R="";g=Math.min(z.length,g);for(var q=G;q<g;++q)R+=String.fromCharCode(127&z[q]);return R}function te(z,G,g){var R="";g=Math.min(z.length,g);for(var q=G;q<g;++q)R+=String.fromCharCode(z[q]);return R}function se(z,G,g){var R=z.length;(!G||G<0)&&(G=0),(!g||g<0||g>R)&&(g=R);for(var q="",B=G;B<g;++B)q+=ue(z[B]);return q}function D(z,G,g){for(var R=z.slice(G,g),q="",B=0;B<R.length;B+=2)q+=String.fromCharCode(R[B]+256*R[B+1]);return q}function ne(z,G,g){if(z%1!=0||z<0)throw new RangeError("offset is not uint");if(z+G>g)throw new RangeError("Trying to access beyond buffer length")}function y(z,G,g,R,q,B){if(!p.isBuffer(z))throw new TypeError('"buffer" argument must be a Buffer instance');if(G>q||G<B)throw new RangeError('"value" argument is out of bounds');if(g+R>z.length)throw new RangeError("Index out of range")}function C(z,G,g,R){G<0&&(G=65535+G+1);for(var q=0,B=Math.min(z.length-g,2);q<B;++q)z[g+q]=(G&255<<8*(R?q:1-q))>>>8*(R?q:1-q)}function re(z,G,g,R){G<0&&(G=4294967295+G+1);for(var q=0,B=Math.min(z.length-g,4);q<B;++q)z[g+q]=G>>>8*(R?q:3-q)&255}function F(z,G,g,R,q,B){if(g+R>z.length)throw new RangeError("Index out of range");if(g<0)throw new RangeError("Index out of range")}function ie(z,G,g,R,q){return q||F(z,0,g,4),s.write(z,G,g,R,23,4),g+4}function oe(z,G,g,R,q){return q||F(z,0,g,8),s.write(z,G,g,R,52,8),g+8}p.prototype.slice=function(G,g){var R,q=this.length;if((G=~~G)<0?(G+=q)<0&&(G=0):G>q&&(G=q),(g=g===void 0?q:~~g)<0?(g+=q)<0&&(g=0):g>q&&(g=q),g<G&&(g=G),p.TYPED_ARRAY_SUPPORT)(R=this.subarray(G,g)).__proto__=p.prototype;else{var B=g-G;R=new p(B,void 0);for(var k=0;k<B;++k)R[k]=this[k+G]}return R},p.prototype.readUIntLE=function(G,g,R){G|=0,g|=0,R||ne(G,g,this.length);for(var q=this[G],B=1,k=0;++k<g&&(B*=256);)q+=this[G+k]*B;return q},p.prototype.readUIntBE=function(G,g,R){G|=0,g|=0,R||ne(G,g,this.length);for(var q=this[G+--g],B=1;g>0&&(B*=256);)q+=this[G+--g]*B;return q},p.prototype.readUInt8=function(G,g){return g||ne(G,1,this.length),this[G]},p.prototype.readUInt16LE=function(G,g){return g||ne(G,2,this.length),this[G]|this[G+1]<<8},p.prototype.readUInt16BE=function(G,g){return g||ne(G,2,this.length),this[G]<<8|this[G+1]},p.prototype.readUInt32LE=function(G,g){return g||ne(G,4,this.length),(this[G]|this[G+1]<<8|this[G+2]<<16)+16777216*this[G+3]},p.prototype.readUInt32BE=function(G,g){return g||ne(G,4,this.length),16777216*this[G]+(this[G+1]<<16|this[G+2]<<8|this[G+3])},p.prototype.readIntLE=function(G,g,R){G|=0,g|=0,R||ne(G,g,this.length);for(var q=this[G],B=1,k=0;++k<g&&(B*=256);)q+=this[G+k]*B;return q>=(B*=128)&&(q-=Math.pow(2,8*g)),q},p.prototype.readIntBE=function(G,g,R){G|=0,g|=0,R||ne(G,g,this.length);for(var q=g,B=1,k=this[G+--q];q>0&&(B*=256);)k+=this[G+--q]*B;return k>=(B*=128)&&(k-=Math.pow(2,8*g)),k},p.prototype.readInt8=function(G,g){return g||ne(G,1,this.length),128&this[G]?-1*(255-this[G]+1):this[G]},p.prototype.readInt16LE=function(G,g){g||ne(G,2,this.length);var R=this[G]|this[G+1]<<8;return 32768&R?4294901760|R:R},p.prototype.readInt16BE=function(G,g){g||ne(G,2,this.length);var R=this[G+1]|this[G]<<8;return 32768&R?4294901760|R:R},p.prototype.readInt32LE=function(G,g){return g||ne(G,4,this.length),this[G]|this[G+1]<<8|this[G+2]<<16|this[G+3]<<24},p.prototype.readInt32BE=function(G,g){return g||ne(G,4,this.length),this[G]<<24|this[G+1]<<16|this[G+2]<<8|this[G+3]},p.prototype.readFloatLE=function(G,g){return g||ne(G,4,this.length),s.read(this,G,!0,23,4)},p.prototype.readFloatBE=function(G,g){return g||ne(G,4,this.length),s.read(this,G,!1,23,4)},p.prototype.readDoubleLE=function(G,g){return g||ne(G,8,this.length),s.read(this,G,!0,52,8)},p.prototype.readDoubleBE=function(G,g){return g||ne(G,8,this.length),s.read(this,G,!1,52,8)},p.prototype.writeUIntLE=function(G,g,R,q){G=+G,g|=0,R|=0,q||y(this,G,g,R,Math.pow(2,8*R)-1,0);var B=1,k=0;for(this[g]=255&G;++k<R&&(B*=256);)this[g+k]=G/B&255;return g+R},p.prototype.writeUIntBE=function(G,g,R,q){G=+G,g|=0,R|=0,q||y(this,G,g,R,Math.pow(2,8*R)-1,0);var B=R-1,k=1;for(this[g+B]=255&G;--B>=0&&(k*=256);)this[g+B]=G/k&255;return g+R},p.prototype.writeUInt8=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,1,255,0),p.TYPED_ARRAY_SUPPORT||(G=Math.floor(G)),this[g]=255&G,g+1},p.prototype.writeUInt16LE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,2,65535,0),p.TYPED_ARRAY_SUPPORT?(this[g]=255&G,this[g+1]=G>>>8):C(this,G,g,!0),g+2},p.prototype.writeUInt16BE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,2,65535,0),p.TYPED_ARRAY_SUPPORT?(this[g]=G>>>8,this[g+1]=255&G):C(this,G,g,!1),g+2},p.prototype.writeUInt32LE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,4,4294967295,0),p.TYPED_ARRAY_SUPPORT?(this[g+3]=G>>>24,this[g+2]=G>>>16,this[g+1]=G>>>8,this[g]=255&G):re(this,G,g,!0),g+4},p.prototype.writeUInt32BE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,4,4294967295,0),p.TYPED_ARRAY_SUPPORT?(this[g]=G>>>24,this[g+1]=G>>>16,this[g+2]=G>>>8,this[g+3]=255&G):re(this,G,g,!1),g+4},p.prototype.writeIntLE=function(G,g,R,q){if(G=+G,g|=0,!q){var B=Math.pow(2,8*R-1);y(this,G,g,R,B-1,-B)}var k=0,W=1,$=0;for(this[g]=255&G;++k<R&&(W*=256);)G<0&&$===0&&this[g+k-1]!==0&&($=1),this[g+k]=(G/W>>0)-$&255;return g+R},p.prototype.writeIntBE=function(G,g,R,q){if(G=+G,g|=0,!q){var B=Math.pow(2,8*R-1);y(this,G,g,R,B-1,-B)}var k=R-1,W=1,$=0;for(this[g+k]=255&G;--k>=0&&(W*=256);)G<0&&$===0&&this[g+k+1]!==0&&($=1),this[g+k]=(G/W>>0)-$&255;return g+R},p.prototype.writeInt8=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,1,127,-128),p.TYPED_ARRAY_SUPPORT||(G=Math.floor(G)),G<0&&(G=255+G+1),this[g]=255&G,g+1},p.prototype.writeInt16LE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,2,32767,-32768),p.TYPED_ARRAY_SUPPORT?(this[g]=255&G,this[g+1]=G>>>8):C(this,G,g,!0),g+2},p.prototype.writeInt16BE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,2,32767,-32768),p.TYPED_ARRAY_SUPPORT?(this[g]=G>>>8,this[g+1]=255&G):C(this,G,g,!1),g+2},p.prototype.writeInt32LE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,4,2147483647,-2147483648),p.TYPED_ARRAY_SUPPORT?(this[g]=255&G,this[g+1]=G>>>8,this[g+2]=G>>>16,this[g+3]=G>>>24):re(this,G,g,!0),g+4},p.prototype.writeInt32BE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,4,2147483647,-2147483648),G<0&&(G=4294967295+G+1),p.TYPED_ARRAY_SUPPORT?(this[g]=G>>>24,this[g+1]=G>>>16,this[g+2]=G>>>8,this[g+3]=255&G):re(this,G,g,!1),g+4},p.prototype.writeFloatLE=function(G,g,R){return ie(this,G,g,!0,R)},p.prototype.writeFloatBE=function(G,g,R){return ie(this,G,g,!1,R)},p.prototype.writeDoubleLE=function(G,g,R){return oe(this,G,g,!0,R)},p.prototype.writeDoubleBE=function(G,g,R){return oe(this,G,g,!1,R)},p.prototype.copy=function(G,g,R,q){if(R||(R=0),q||q===0||(q=this.length),g>=G.length&&(g=G.length),g||(g=0),q>0&&q<R&&(q=R),q===R||G.length===0||this.length===0)return 0;if(g<0)throw new RangeError("targetStart out of bounds");if(R<0||R>=this.length)throw new RangeError("sourceStart out of bounds");if(q<0)throw new RangeError("sourceEnd out of bounds");q>this.length&&(q=this.length),G.length-g<q-R&&(q=G.length-g+R);var B,k=q-R;if(this===G&&R<g&&g<q)for(B=k-1;B>=0;--B)G[B+g]=this[B+R];else if(k<1e3||!p.TYPED_ARRAY_SUPPORT)for(B=0;B<k;++B)G[B+g]=this[B+R];else Uint8Array.prototype.set.call(G,this.subarray(R,R+k),g);return k},p.prototype.fill=function(G,g,R,q){if(typeof G=="string"){if(typeof g=="string"?(q=g,g=0,R=this.length):typeof R=="string"&&(q=R,R=this.length),G.length===1){var B=G.charCodeAt(0);B<256&&(G=B)}if(q!==void 0&&typeof q!="string")throw new TypeError("encoding must be a string");if(typeof q=="string"&&!p.isEncoding(q))throw new TypeError("Unknown encoding: "+q)}else typeof G=="number"&&(G&=255);if(g<0||this.length<g||this.length<R)throw new RangeError("Out of range index");if(R<=g)return this;var k;if(g>>>=0,R=R===void 0?this.length:R>>>0,G||(G=0),typeof G=="number")for(k=g;k<R;++k)this[k]=G;else{var W=p.isBuffer(G)?G:P(new p(G,q).toString()),$=W.length;for(k=0;k<R-g;++k)this[k+g]=W[k%$]}return this};var le=/[^+\/0-9A-Za-z-_]/g;function ue(z){return z<16?"0"+z.toString(16):z.toString(16)}function P(z,G){var g;G=G||1/0;for(var R=z.length,q=null,B=[],k=0;k<R;++k){if((g=z.charCodeAt(k))>55295&&g<57344){if(!q){if(g>56319){(G-=3)>-1&&B.push(239,191,189);continue}if(k+1===R){(G-=3)>-1&&B.push(239,191,189);continue}q=g;continue}if(g<56320){(G-=3)>-1&&B.push(239,191,189),q=g;continue}g=65536+(q-55296<<10|g-56320)}else q&&(G-=3)>-1&&B.push(239,191,189);if(q=null,g<128){if((G-=1)<0)break;B.push(g)}else if(g<2048){if((G-=2)<0)break;B.push(g>>6|192,63&g|128)}else if(g<65536){if((G-=3)<0)break;B.push(g>>12|224,g>>6&63|128,63&g|128)}else{if(!(g<1114112))throw new Error("Invalid code point");if((G-=4)<0)break;B.push(g>>18|240,g>>12&63|128,g>>6&63|128,63&g|128)}}return B}function M(z){return o.toByteArray((function(g){if((g=(function(q){return q.trim?q.trim():q.replace(/^\s+|\s+$/g,"")})(g).replace(le,"")).length<2)return"";for(;g.length%4!=0;)g+="=";return g})(z))}function Z(z,G,g,R){for(var q=0;q<R&&!(q+g>=G.length||q>=z.length);++q)G[q+g]=z[q];return q}}).call(this,a(29))},function(t,n){var a;a=(function(){return this})();try{a=a||new Function("return this")()}catch{typeof window=="object"&&(a=window)}t.exports=a},function(t,n,a){n.byteLength=function(S){var A=p(S),h=A[0],T=A[1];return 3*(h+T)/4-T},n.toByteArray=function(S){var A,h,T=p(S),w=T[0],b=T[1],N=new s((function(V,U,v){return 3*(U+v)/4-v})(0,w,b)),O=0,X=b>0?w-4:w;for(h=0;h<X;h+=4)A=o[S.charCodeAt(h)]<<18|o[S.charCodeAt(h+1)]<<12|o[S.charCodeAt(h+2)]<<6|o[S.charCodeAt(h+3)],N[O++]=A>>16&255,N[O++]=A>>8&255,N[O++]=255&A;return b===2&&(A=o[S.charCodeAt(h)]<<2|o[S.charCodeAt(h+1)]>>4,N[O++]=255&A),b===1&&(A=o[S.charCodeAt(h)]<<10|o[S.charCodeAt(h+1)]<<4|o[S.charCodeAt(h+2)]>>2,N[O++]=A>>8&255,N[O++]=255&A),N},n.fromByteArray=function(S){for(var A,h=S.length,T=h%3,w=[],b=16383,N=0,O=h-T;N<O;N+=b)w.push(_(S,N,N+b>O?O:N+b));return T===1?(A=S[h-1],w.push(i[A>>2]+i[A<<4&63]+"==")):T===2&&(A=(S[h-2]<<8)+S[h-1],w.push(i[A>>10]+i[A>>4&63]+i[A<<2&63]+"=")),w.join("")};for(var i=[],o=[],s=typeof Uint8Array<"u"?Uint8Array:Array,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,c=d.length;u<c;++u)i[u]=d[u],o[d.charCodeAt(u)]=u;function p(m){var S=m.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var A=m.indexOf("=");return A===-1&&(A=S),[A,A===S?0:4-A%4]}function _(m,S,A){for(var h,T,w=[],b=S;b<A;b+=3)h=(m[b]<<16&16711680)+(m[b+1]<<8&65280)+(255&m[b+2]),w.push(i[(T=h)>>18&63]+i[T>>12&63]+i[T>>6&63]+i[63&T]);return w.join("")}o[45]=62,o[95]=63},function(t,n){n.read=function(a,i,o,s,d){var u,c,p=8*d-s-1,_=(1<<p)-1,m=_>>1,S=-7,A=o?d-1:0,h=o?-1:1,T=a[i+A];for(A+=h,u=T&(1<<-S)-1,T>>=-S,S+=p;S>0;u=256*u+a[i+A],A+=h,S-=8);for(c=u&(1<<-S)-1,u>>=-S,S+=s;S>0;c=256*c+a[i+A],A+=h,S-=8);if(u===0)u=1-m;else{if(u===_)return c?NaN:1/0*(T?-1:1);c+=Math.pow(2,s),u-=m}return(T?-1:1)*c*Math.pow(2,u-s)},n.write=function(a,i,o,s,d,u){var c,p,_,m=8*u-d-1,S=(1<<m)-1,A=S>>1,h=d===23?Math.pow(2,-24)-Math.pow(2,-77):0,T=s?0:u-1,w=s?1:-1,b=i<0||i===0&&1/i<0?1:0;for(i=Math.abs(i),isNaN(i)||i===1/0?(p=isNaN(i)?1:0,c=S):(c=Math.floor(Math.log(i)/Math.LN2),i*(_=Math.pow(2,-c))<1&&(c--,_*=2),(i+=c+A>=1?h/_:h*Math.pow(2,1-A))*_>=2&&(c++,_/=2),c+A>=S?(p=0,c=S):c+A>=1?(p=(i*_-1)*Math.pow(2,d),c+=A):(p=i*Math.pow(2,A-1)*Math.pow(2,d),c=0));d>=8;a[o+T]=255&p,T+=w,p/=256,d-=8);for(c=c<<d|p,m+=d;m>0;a[o+T]=255&c,T+=w,c/=256,m-=8);a[o+T-w]|=128*b}},function(t,n){var a={}.toString;t.exports=Array.isArray||function(i){return a.call(i)=="[object Array]"}},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.default=function(s){var d=s.jws,u=s.KeyUtil,c=s.X509,p=s.crypto,_=s.hextob64u,m=s.b64tohex,S=s.AllowedSigningAlgs;return(function(){function A(){(function(T,w){if(!(T instanceof w))throw new TypeError("Cannot call a class as a function")})(this,A)}return A.parseJwt=function(T){i.Log.debug("JoseUtil.parseJwt");try{var w=d.JWS.parse(T);return{header:w.headerObj,payload:w.payloadObj}}catch(b){i.Log.error(b)}},A.validateJwt=function(T,w,b,N,O,X,ee){i.Log.debug("JoseUtil.validateJwt");try{if(w.kty==="RSA")if(w.e&&w.n)w=u.getKey(w);else{if(!w.x5c||!w.x5c.length)return i.Log.error("JoseUtil.validateJwt: RSA key missing key material",w),Promise.reject(new Error("RSA key missing key material"));var V=m(w.x5c[0]);w=c.getPublicKeyFromCertHex(V)}else{if(w.kty!=="EC")return i.Log.error("JoseUtil.validateJwt: Unsupported key type",w&&w.kty),Promise.reject(new Error(w.kty));if(!(w.crv&&w.x&&w.y))return i.Log.error("JoseUtil.validateJwt: EC key missing key material",w),Promise.reject(new Error("EC key missing key material"));w=u.getKey(w)}return A._validateJwt(T,w,b,N,O,X,ee)}catch(U){return i.Log.error(U&&U.message||U),Promise.reject("JWT validation failed")}},A.validateJwtAttributes=function(T,w,b,N,O,X){N||(N=0),O||(O=parseInt(Date.now()/1e3));var ee=A.parseJwt(T).payload;if(!ee.iss)return i.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(ee.iss!==w)return i.Log.error("JoseUtil._validateJwt: Invalid issuer in token",ee.iss),Promise.reject(new Error("Invalid issuer in token: "+ee.iss));if(!ee.aud)return i.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(ee.aud===b||Array.isArray(ee.aud)&&ee.aud.indexOf(b)>=0))return i.Log.error("JoseUtil._validateJwt: Invalid audience in token",ee.aud),Promise.reject(new Error("Invalid audience in token: "+ee.aud));if(ee.azp&&ee.azp!==b)return i.Log.error("JoseUtil._validateJwt: Invalid azp in token",ee.azp),Promise.reject(new Error("Invalid azp in token: "+ee.azp));if(!X){var V=O+N,U=O-N;if(!ee.iat)return i.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(V<ee.iat)return i.Log.error("JoseUtil._validateJwt: iat is in the future",ee.iat),Promise.reject(new Error("iat is in the future: "+ee.iat));if(ee.nbf&&V<ee.nbf)return i.Log.error("JoseUtil._validateJwt: nbf is in the future",ee.nbf),Promise.reject(new Error("nbf is in the future: "+ee.nbf));if(!ee.exp)return i.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(ee.exp<U)return i.Log.error("JoseUtil._validateJwt: exp is in the past",ee.exp),Promise.reject(new Error("exp is in the past:"+ee.exp))}return Promise.resolve(ee)},A._validateJwt=function(T,w,b,N,O,X,ee){return A.validateJwtAttributes(T,b,N,O,X,ee).then((function(V){try{return d.JWS.verify(T,w,S)?V:(i.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(U){return i.Log.error(U&&U.message||U),Promise.reject(new Error("signature validation failed"))}}))},A.hashString=function(T,w){try{return p.Util.hashString(T,w)}catch(b){i.Log.error(b)}},A.hexToBase64Url=function(T){try{return _(T)}catch(w){i.Log.error(w)}},A})()};var i=a(0);t.exports=n.default},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.SigninResponse=void 0;var i=(function(){function d(u,c){for(var p=0;p<c.length;p++){var _=c[p];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(u,_.key,_)}}return function(u,c,p){return c&&d(u.prototype,c),p&&d(u,p),u}})(),o=a(3);function s(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}n.SigninResponse=(function(){function d(u){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";s(this,d);var p=o.UrlUtility.parseUrlFragment(u,c);this.error=p.error,this.error_description=p.error_description,this.error_uri=p.error_uri,this.code=p.code,this.state=p.state,this.id_token=p.id_token,this.session_state=p.session_state,this.access_token=p.access_token,this.token_type=p.token_type,this.scope=p.scope,this.profile=void 0,this.expires_in=p.expires_in}return i(d,[{key:"expires_in",get:function(){if(this.expires_at){var c=parseInt(Date.now()/1e3);return this.expires_at-c}},set:function(c){var p=parseInt(c);if(typeof p=="number"&&p>0){var _=parseInt(Date.now()/1e3);this.expires_at=_+p}}},{key:"expired",get:function(){var c=this.expires_in;if(c!==void 0)return c<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),d})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.SignoutRequest=void 0;var i=a(0),o=a(3),s=a(9);n.SignoutRequest=function d(u){var c=u.url,p=u.id_token_hint,_=u.post_logout_redirect_uri,m=u.data,S=u.extraQueryParams,A=u.request_type;if((function(w,b){if(!(w instanceof b))throw new TypeError("Cannot call a class as a function")})(this,d),!c)throw i.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var h in p&&(c=o.UrlUtility.addQueryParam(c,"id_token_hint",p)),_&&(c=o.UrlUtility.addQueryParam(c,"post_logout_redirect_uri",_),m&&(this.state=new s.State({data:m,request_type:A}),c=o.UrlUtility.addQueryParam(c,"state",this.state.id))),S)c=o.UrlUtility.addQueryParam(c,h,S[h]);this.url=c}},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.SignoutResponse=void 0;var i=a(3);n.SignoutResponse=function o(s){(function(c,p){if(!(c instanceof p))throw new TypeError("Cannot call a class as a function")})(this,o);var d=i.UrlUtility.parseUrlFragment(s,"?");this.error=d.error,this.error_description=d.error_description,this.error_uri=d.error_uri,this.state=d.state}},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.InMemoryWebStorage=void 0;var i=(function(){function s(d,u){for(var c=0;c<u.length;c++){var p=u[c];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(d,p.key,p)}}return function(d,u,c){return u&&s(d.prototype,u),c&&s(d,c),d}})(),o=a(0);n.InMemoryWebStorage=(function(){function s(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,s),this._data={}}return s.prototype.getItem=function(u){return o.Log.debug("InMemoryWebStorage.getItem",u),this._data[u]},s.prototype.setItem=function(u,c){o.Log.debug("InMemoryWebStorage.setItem",u),this._data[u]=c},s.prototype.removeItem=function(u){o.Log.debug("InMemoryWebStorage.removeItem",u),delete this._data[u]},s.prototype.key=function(u){return Object.getOwnPropertyNames(this._data)[u]},i(s,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.UserManager=void 0;var i=(function(){function b(N,O){for(var X=0;X<O.length;X++){var ee=O[X];ee.enumerable=ee.enumerable||!1,ee.configurable=!0,"value"in ee&&(ee.writable=!0),Object.defineProperty(N,ee.key,ee)}}return function(N,O,X){return O&&b(N.prototype,O),X&&b(N,X),N}})(),o=a(0),s=a(10),d=a(39),u=a(15),c=a(45),p=a(47),_=a(18),m=a(8),S=a(20),A=a(11),h=a(4);function T(b,N){if(!(b instanceof N))throw new TypeError("Cannot call a class as a function")}function w(b,N){if(!b)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!N||typeof N!="object"&&typeof N!="function"?b:N}n.UserManager=(function(b){function N(){var O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},X=arguments.length>1&&arguments[1]!==void 0?arguments[1]:p.SilentRenewService,ee=arguments.length>2&&arguments[2]!==void 0?arguments[2]:_.SessionMonitor,V=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,U=arguments.length>4&&arguments[4]!==void 0?arguments[4]:A.TokenClient,v=arguments.length>5&&arguments[5]!==void 0?arguments[5]:h.JoseUtil;T(this,N),O instanceof d.UserManagerSettings||(O=new d.UserManagerSettings(O));var x=w(this,b.call(this,O));return x._events=new c.UserManagerEvents(O),x._silentRenewService=new X(x),x.settings.automaticSilentRenew&&(o.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),x.startSilentRenew()),x.settings.monitorSession&&(o.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),x._sessionMonitor=new ee(x)),x._tokenRevocationClient=new V(x._settings),x._tokenClient=new U(x._settings),x._joseUtil=v,x}return(function(X,ee){if(typeof ee!="function"&&ee!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof ee);X.prototype=Object.create(ee&&ee.prototype,{constructor:{value:X,enumerable:!1,writable:!0,configurable:!0}}),ee&&(Object.setPrototypeOf?Object.setPrototypeOf(X,ee):X.__proto__=ee)})(N,b),N.prototype.getUser=function(){var X=this;return this._loadUser().then((function(ee){return ee?(o.Log.info("UserManager.getUser: user loaded"),X._events.load(ee,!1),ee):(o.Log.info("UserManager.getUser: user not found in storage"),null)}))},N.prototype.removeUser=function(){var X=this;return this.storeUser(null).then((function(){o.Log.info("UserManager.removeUser: user removed from storage"),X._events.unload()}))},N.prototype.signinRedirect=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(X=Object.assign({},X)).request_type="si:r";var ee={useReplaceToNavigate:X.useReplaceToNavigate};return this._signinStart(X,this._redirectNavigator,ee).then((function(){o.Log.info("UserManager.signinRedirect: successful")}))},N.prototype.signinRedirectCallback=function(X){return this._signinEnd(X||this._redirectNavigator.url).then((function(ee){return ee.profile&&ee.profile.sub?o.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",ee.profile.sub):o.Log.info("UserManager.signinRedirectCallback: no sub"),ee}))},N.prototype.signinPopup=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(X=Object.assign({},X)).request_type="si:p";var ee=X.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return ee?(X.redirect_uri=ee,X.display="popup",this._signin(X,this._popupNavigator,{startUrl:ee,popupWindowFeatures:X.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:X.popupWindowTarget||this.settings.popupWindowTarget}).then((function(V){return V&&(V.profile&&V.profile.sub?o.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",V.profile.sub):o.Log.info("UserManager.signinPopup: no sub")),V}))):(o.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},N.prototype.signinPopupCallback=function(X){return this._signinCallback(X,this._popupNavigator).then((function(ee){return ee&&(ee.profile&&ee.profile.sub?o.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",ee.profile.sub):o.Log.info("UserManager.signinPopupCallback: no sub")),ee})).catch((function(ee){o.Log.error(ee.message)}))},N.prototype.signinSilent=function(){var X=this,ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return ee=Object.assign({},ee),this._loadUser().then((function(V){return V&&V.refresh_token?(ee.refresh_token=V.refresh_token,X._useRefreshToken(ee)):(ee.request_type="si:s",ee.id_token_hint=ee.id_token_hint||X.settings.includeIdTokenInSilentRenew&&V&&V.id_token,V&&X._settings.validateSubOnSilentRenew&&(o.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",V.profile.sub),ee.current_sub=V.profile.sub),X._signinSilentIframe(ee))}))},N.prototype._useRefreshToken=function(){var X=this,ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(ee).then((function(V){return V?V.access_token?X._loadUser().then((function(U){if(U){var v=Promise.resolve();return V.id_token&&(v=X._validateIdTokenFromTokenRefreshToken(U.profile,V.id_token)),v.then((function(){return o.Log.debug("UserManager._useRefreshToken: refresh token response success"),U.id_token=V.id_token||U.id_token,U.access_token=V.access_token,U.refresh_token=V.refresh_token||U.refresh_token,U.expires_in=V.expires_in,X.storeUser(U).then((function(){return X._events.load(U),U}))}))}return null})):(o.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(o.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},N.prototype._validateIdTokenFromTokenRefreshToken=function(X,ee){var V=this;return this._metadataService.getIssuer().then((function(U){return V.settings.getEpochTime().then((function(v){return V._joseUtil.validateJwtAttributes(ee,U,V._settings.client_id,V._settings.clockSkew,v).then((function(x){return x?x.sub!==X.sub?(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):x.auth_time&&x.auth_time!==X.auth_time?(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):x.azp&&x.azp!==X.azp?(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!x.azp&&X.azp?(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},N.prototype._signinSilentIframe=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ee=X.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return ee?(X.redirect_uri=ee,X.prompt=X.prompt||"none",this._signin(X,this._iframeNavigator,{startUrl:ee,silentRequestTimeout:X.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(V){return V&&(V.profile&&V.profile.sub?o.Log.info("UserManager.signinSilent: successful, signed in sub: ",V.profile.sub):o.Log.info("UserManager.signinSilent: no sub")),V}))):(o.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},N.prototype.signinSilentCallback=function(X){return this._signinCallback(X,this._iframeNavigator).then((function(ee){return ee&&(ee.profile&&ee.profile.sub?o.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",ee.profile.sub):o.Log.info("UserManager.signinSilentCallback: no sub")),ee}))},N.prototype.signinCallback=function(X){var ee=this;return this.readSigninResponseState(X).then((function(V){var U=V.state;return V.response,U.request_type==="si:r"?ee.signinRedirectCallback(X):U.request_type==="si:p"?ee.signinPopupCallback(X):U.request_type==="si:s"?ee.signinSilentCallback(X):Promise.reject(new Error("invalid response_type in state"))}))},N.prototype.signoutCallback=function(X,ee){var V=this;return this.readSignoutResponseState(X).then((function(U){var v=U.state,x=U.response;return v?v.request_type==="so:r"?V.signoutRedirectCallback(X):v.request_type==="so:p"?V.signoutPopupCallback(X,ee):Promise.reject(new Error("invalid response_type in state")):x}))},N.prototype.querySessionStatus=function(){var X=this,ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(ee=Object.assign({},ee)).request_type="si:s";var V=ee.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return V?(ee.redirect_uri=V,ee.prompt="none",ee.response_type=ee.response_type||this.settings.query_status_response_type,ee.scope=ee.scope||"openid",ee.skipUserInfo=!0,this._signinStart(ee,this._iframeNavigator,{startUrl:V,silentRequestTimeout:ee.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(U){return X.processSigninResponse(U.url).then((function(v){if(o.Log.debug("UserManager.querySessionStatus: got signin response"),v.session_state&&v.profile.sub)return o.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",v.profile.sub),{session_state:v.session_state,sub:v.profile.sub,sid:v.profile.sid};o.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(v){if(v.session_state&&X.settings.monitorAnonymousSession&&(v.message=="login_required"||v.message=="consent_required"||v.message=="interaction_required"||v.message=="account_selection_required"))return o.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:v.session_state};throw v}))}))):(o.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},N.prototype._signin=function(X,ee){var V=this,U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(X,ee,U).then((function(v){return V._signinEnd(v.url,X)}))},N.prototype._signinStart=function(X,ee){var V=this,U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return ee.prepare(U).then((function(v){return o.Log.debug("UserManager._signinStart: got navigator window handle"),V.createSigninRequest(X).then((function(x){return o.Log.debug("UserManager._signinStart: got signin request"),U.url=x.url,U.id=x.state.id,v.navigate(U)})).catch((function(x){throw v.close&&(o.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),v.close()),x}))}))},N.prototype._signinEnd=function(X){var ee=this,V=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(X).then((function(U){o.Log.debug("UserManager._signinEnd: got signin response");var v=new u.User(U);if(V.current_sub){if(V.current_sub!==v.profile.sub)return o.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",v.profile.sub),Promise.reject(new Error("login_required"));o.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return ee.storeUser(v).then((function(){return o.Log.debug("UserManager._signinEnd: user stored"),ee._events.load(v),v}))}))},N.prototype._signinCallback=function(X,ee){o.Log.debug("UserManager._signinCallback");var V=this._settings.response_mode==="query"||!this._settings.response_mode&&m.SigninRequest.isCode(this._settings.response_type)?"?":"#";return ee.callback(X,void 0,V)},N.prototype.signoutRedirect=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(X=Object.assign({},X)).request_type="so:r";var ee=X.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;ee&&(X.post_logout_redirect_uri=ee);var V={useReplaceToNavigate:X.useReplaceToNavigate};return this._signoutStart(X,this._redirectNavigator,V).then((function(){o.Log.info("UserManager.signoutRedirect: successful")}))},N.prototype.signoutRedirectCallback=function(X){return this._signoutEnd(X||this._redirectNavigator.url).then((function(ee){return o.Log.info("UserManager.signoutRedirectCallback: successful"),ee}))},N.prototype.signoutPopup=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(X=Object.assign({},X)).request_type="so:p";var ee=X.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return X.post_logout_redirect_uri=ee,X.display="popup",X.post_logout_redirect_uri&&(X.state=X.state||{}),this._signout(X,this._popupNavigator,{startUrl:ee,popupWindowFeatures:X.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:X.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){o.Log.info("UserManager.signoutPopup: successful")}))},N.prototype.signoutPopupCallback=function(X,ee){return ee===void 0&&typeof X=="boolean"&&(ee=X,X=null),this._popupNavigator.callback(X,ee,"?").then((function(){o.Log.info("UserManager.signoutPopupCallback: successful")}))},N.prototype._signout=function(X,ee){var V=this,U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(X,ee,U).then((function(v){return V._signoutEnd(v.url)}))},N.prototype._signoutStart=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ee=this,V=arguments[1],U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return V.prepare(U).then((function(v){return o.Log.debug("UserManager._signoutStart: got navigator window handle"),ee._loadUser().then((function(x){return o.Log.debug("UserManager._signoutStart: loaded current user from storage"),(ee._settings.revokeAccessTokenOnSignout?ee._revokeInternal(x):Promise.resolve()).then((function(){var I=X.id_token_hint||x&&x.id_token;return I&&(o.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),X.id_token_hint=I),ee.removeUser().then((function(){return o.Log.debug("UserManager._signoutStart: user removed, creating signout request"),ee.createSignoutRequest(X).then((function(E){return o.Log.debug("UserManager._signoutStart: got signout request"),U.url=E.url,E.state&&(U.id=E.state.id),v.navigate(U)}))}))}))})).catch((function(x){throw v.close&&(o.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),v.close()),x}))}))},N.prototype._signoutEnd=function(X){return this.processSignoutResponse(X).then((function(ee){return o.Log.debug("UserManager._signoutEnd: got signout response"),ee}))},N.prototype.revokeAccessToken=function(){var X=this;return this._loadUser().then((function(ee){return X._revokeInternal(ee,!0).then((function(V){if(V)return o.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),ee.access_token=null,ee.refresh_token=null,ee.expires_at=null,ee.token_type=null,X.storeUser(ee).then((function(){o.Log.debug("UserManager.revokeAccessToken: user stored"),X._events.load(ee)}))}))})).then((function(){o.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},N.prototype._revokeInternal=function(X,ee){var V=this;if(X){var U=X.access_token,v=X.refresh_token;return this._revokeAccessTokenInternal(U,ee).then((function(x){return V._revokeRefreshTokenInternal(v,ee).then((function(I){return x||I||o.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),x||I}))}))}return Promise.resolve(!1)},N.prototype._revokeAccessTokenInternal=function(X,ee){return!X||X.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(X,ee).then((function(){return!0}))},N.prototype._revokeRefreshTokenInternal=function(X,ee){return X?this._tokenRevocationClient.revoke(X,ee,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},N.prototype.startSilentRenew=function(){this._silentRenewService.start()},N.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},N.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(X){return X?(o.Log.debug("UserManager._loadUser: user storageString loaded"),u.User.fromStorageString(X)):(o.Log.debug("UserManager._loadUser: no user storageString"),null)}))},N.prototype.storeUser=function(X){if(X){o.Log.debug("UserManager.storeUser: storing user");var ee=X.toStorageString();return this._userStore.set(this._userStoreKey,ee)}return o.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},i(N,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),N})(s.OidcClient)},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.UserManagerSettings=void 0;var i=(function(){function A(h,T){for(var w=0;w<T.length;w++){var b=T[w];b.enumerable=b.enumerable||!1,b.configurable=!0,"value"in b&&(b.writable=!0),Object.defineProperty(h,b.key,b)}}return function(h,T,w){return T&&A(h.prototype,T),w&&A(h,w),h}})(),o=(a(0),a(5)),s=a(40),d=a(41),u=a(43),c=a(6),p=a(1),_=a(8);function m(A,h){if(!(A instanceof h))throw new TypeError("Cannot call a class as a function")}function S(A,h){if(!A)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!h||typeof h!="object"&&typeof h!="function"?A:h}n.UserManagerSettings=(function(A){function h(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},w=T.popup_redirect_uri,b=T.popup_post_logout_redirect_uri,N=T.popupWindowFeatures,O=T.popupWindowTarget,X=T.silent_redirect_uri,ee=T.silentRequestTimeout,V=T.automaticSilentRenew,U=V!==void 0&&V,v=T.validateSubOnSilentRenew,x=v!==void 0&&v,I=T.includeIdTokenInSilentRenew,E=I===void 0||I,Q=T.monitorSession,K=Q===void 0||Q,te=T.monitorAnonymousSession,se=te!==void 0&&te,D=T.checkSessionInterval,ne=D===void 0?2e3:D,y=T.stopCheckSessionOnError,C=y===void 0||y,re=T.query_status_response_type,F=T.revokeAccessTokenOnSignout,ie=F!==void 0&&F,oe=T.accessTokenExpiringNotificationTime,le=oe===void 0?60:oe,ue=T.redirectNavigator,P=ue===void 0?new s.RedirectNavigator:ue,M=T.popupNavigator,Z=M===void 0?new d.PopupNavigator:M,z=T.iframeNavigator,G=z===void 0?new u.IFrameNavigator:z,g=T.userStore,R=g===void 0?new c.WebStorageStateStore({store:p.Global.sessionStorage}):g;m(this,h);var q=S(this,A.call(this,arguments[0]));return q._popup_redirect_uri=w,q._popup_post_logout_redirect_uri=b,q._popupWindowFeatures=N,q._popupWindowTarget=O,q._silent_redirect_uri=X,q._silentRequestTimeout=ee,q._automaticSilentRenew=U,q._validateSubOnSilentRenew=x,q._includeIdTokenInSilentRenew=E,q._accessTokenExpiringNotificationTime=le,q._monitorSession=K,q._monitorAnonymousSession=se,q._checkSessionInterval=ne,q._stopCheckSessionOnError=C,re?q._query_status_response_type=re:arguments[0]&&arguments[0].response_type?q._query_status_response_type=_.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":q._query_status_response_type="id_token",q._revokeAccessTokenOnSignout=ie,q._redirectNavigator=P,q._popupNavigator=Z,q._iframeNavigator=G,q._userStore=R,q}return(function(w,b){if(typeof b!="function"&&b!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof b);w.prototype=Object.create(b&&b.prototype,{constructor:{value:w,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(w,b):w.__proto__=b)})(h,A),i(h,[{key:"popup_redirect_uri",get:function(){return this._popup_redirect_uri}},{key:"popup_post_logout_redirect_uri",get:function(){return this._popup_post_logout_redirect_uri}},{key:"popupWindowFeatures",get:function(){return this._popupWindowFeatures}},{key:"popupWindowTarget",get:function(){return this._popupWindowTarget}},{key:"silent_redirect_uri",get:function(){return this._silent_redirect_uri}},{key:"silentRequestTimeout",get:function(){return this._silentRequestTimeout}},{key:"automaticSilentRenew",get:function(){return this._automaticSilentRenew}},{key:"validateSubOnSilentRenew",get:function(){return this._validateSubOnSilentRenew}},{key:"includeIdTokenInSilentRenew",get:function(){return this._includeIdTokenInSilentRenew}},{key:"accessTokenExpiringNotificationTime",get:function(){return this._accessTokenExpiringNotificationTime}},{key:"monitorSession",get:function(){return this._monitorSession}},{key:"monitorAnonymousSession",get:function(){return this._monitorAnonymousSession}},{key:"checkSessionInterval",get:function(){return this._checkSessionInterval}},{key:"stopCheckSessionOnError",get:function(){return this._stopCheckSessionOnError}},{key:"query_status_response_type",get:function(){return this._query_status_response_type}},{key:"revokeAccessTokenOnSignout",get:function(){return this._revokeAccessTokenOnSignout}},{key:"redirectNavigator",get:function(){return this._redirectNavigator}},{key:"popupNavigator",get:function(){return this._popupNavigator}},{key:"iframeNavigator",get:function(){return this._iframeNavigator}},{key:"userStore",get:function(){return this._userStore}}]),h})(o.OidcClientSettings)},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.RedirectNavigator=void 0;var i=(function(){function s(d,u){for(var c=0;c<u.length;c++){var p=u[c];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(d,p.key,p)}}return function(d,u,c){return u&&s(d.prototype,u),c&&s(d,c),d}})(),o=a(0);n.RedirectNavigator=(function(){function s(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,s)}return s.prototype.prepare=function(){return Promise.resolve(this)},s.prototype.navigate=function(u){return u&&u.url?(u.useReplaceToNavigate?window.location.replace(u.url):window.location=u.url,Promise.resolve()):(o.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},i(s,[{key:"url",get:function(){return window.location.href}}]),s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.PopupNavigator=void 0;var i=a(0),o=a(42);n.PopupNavigator=(function(){function s(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,s)}return s.prototype.prepare=function(u){var c=new o.PopupWindow(u);return Promise.resolve(c)},s.prototype.callback=function(u,c,p){i.Log.debug("PopupNavigator.callback");try{return o.PopupWindow.notifyOpener(u,c,p),Promise.resolve()}catch(_){return Promise.reject(_)}},s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.PopupWindow=void 0;var i=(function(){function d(u,c){for(var p=0;p<c.length;p++){var _=c[p];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(u,_.key,_)}}return function(u,c,p){return c&&d(u.prototype,c),p&&d(u,p),u}})(),o=a(0),s=a(3);n.PopupWindow=(function(){function d(u){var c=this;(function(S,A){if(!(S instanceof A))throw new TypeError("Cannot call a class as a function")})(this,d),this._promise=new Promise((function(m,S){c._resolve=m,c._reject=S}));var p=u.popupWindowTarget||"_blank",_=u.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",p,_),this._popup&&(o.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return d.prototype.navigate=function(c){return this._popup?c&&c.url?(o.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=c.id,this._id&&(window["popupCallback_"+c.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=c.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},d.prototype._success=function(c){o.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(c)},d.prototype._error=function(c){o.Log.error("PopupWindow.error: ",c),this._cleanup(),this._reject(new Error(c))},d.prototype.close=function(){this._cleanup(!1)},d.prototype._cleanup=function(c){o.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!c&&this._popup.close(),this._popup=null},d.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},d.prototype._callback=function(c,p){this._cleanup(p),c?(o.Log.debug("PopupWindow.callback success"),this._success({url:c})):(o.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},d.notifyOpener=function(c,p,_){if(window.opener){if(c=c||window.location.href){var m=s.UrlUtility.parseUrlFragment(c,_);if(m.state){var S="popupCallback_"+m.state,A=window.opener[S];A?(o.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),A(c,p)):o.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else o.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else o.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},i(d,[{key:"promise",get:function(){return this._promise}}]),d})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.IFrameNavigator=void 0;var i=a(0),o=a(44);n.IFrameNavigator=(function(){function s(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,s)}return s.prototype.prepare=function(u){var c=new o.IFrameWindow(u);return Promise.resolve(c)},s.prototype.callback=function(u){i.Log.debug("IFrameNavigator.callback");try{return o.IFrameWindow.notifyParent(u),Promise.resolve()}catch(c){return Promise.reject(c)}},s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.IFrameWindow=void 0;var i=(function(){function s(d,u){for(var c=0;c<u.length;c++){var p=u[c];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(d,p.key,p)}}return function(d,u,c){return u&&s(d.prototype,u),c&&s(d,c),d}})(),o=a(0);n.IFrameWindow=(function(){function s(d){var u=this;(function(p,_){if(!(p instanceof _))throw new TypeError("Cannot call a class as a function")})(this,s),this._promise=new Promise((function(c,p){u._resolve=c,u._reject=p})),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.width=0,this._frame.height=0,window.document.body.appendChild(this._frame)}return s.prototype.navigate=function(u){if(u&&u.url){var c=u.silentRequestTimeout||1e4;o.Log.debug("IFrameWindow.navigate: Using timeout of:",c),this._timer=window.setTimeout(this._timeout.bind(this),c),this._frame.src=u.url}else this._error("No url provided");return this.promise},s.prototype._success=function(u){this._cleanup(),o.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(u)},s.prototype._error=function(u){this._cleanup(),o.Log.error(u),this._reject(new Error(u))},s.prototype.close=function(){this._cleanup()},s.prototype._cleanup=function(){this._frame&&(o.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},s.prototype._timeout=function(){o.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},s.prototype._message=function(u){if(o.Log.debug("IFrameWindow.message"),this._timer&&u.origin===this._origin&&u.source===this._frame.contentWindow&&typeof u.data=="string"&&(u.data.startsWith("http://")||u.data.startsWith("https://"))){var c=u.data;c?this._success({url:c}):this._error("Invalid response from frame")}},s.notifyParent=function(u){o.Log.debug("IFrameWindow.notifyParent"),(u=u||window.location.href)&&(o.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(u,location.protocol+"//"+location.host))},i(s,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.UserManagerEvents=void 0;var i=a(0),o=a(16),s=a(17);n.UserManagerEvents=(function(d){function u(c){(function(m,S){if(!(m instanceof S))throw new TypeError("Cannot call a class as a function")})(this,u);var p=(function(m,S){if(!m)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?m:S})(this,d.call(this,c));return p._userLoaded=new s.Event("User loaded"),p._userUnloaded=new s.Event("User unloaded"),p._silentRenewError=new s.Event("Silent renew error"),p._userSignedIn=new s.Event("User signed in"),p._userSignedOut=new s.Event("User signed out"),p._userSessionChanged=new s.Event("User session changed"),p}return(function(p,_){if(typeof _!="function"&&_!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof _);p.prototype=Object.create(_&&_.prototype,{constructor:{value:p,enumerable:!1,writable:!0,configurable:!0}}),_&&(Object.setPrototypeOf?Object.setPrototypeOf(p,_):p.__proto__=_)})(u,d),u.prototype.load=function(p){var _=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];i.Log.debug("UserManagerEvents.load"),d.prototype.load.call(this,p),_&&this._userLoaded.raise(p)},u.prototype.unload=function(){i.Log.debug("UserManagerEvents.unload"),d.prototype.unload.call(this),this._userUnloaded.raise()},u.prototype.addUserLoaded=function(p){this._userLoaded.addHandler(p)},u.prototype.removeUserLoaded=function(p){this._userLoaded.removeHandler(p)},u.prototype.addUserUnloaded=function(p){this._userUnloaded.addHandler(p)},u.prototype.removeUserUnloaded=function(p){this._userUnloaded.removeHandler(p)},u.prototype.addSilentRenewError=function(p){this._silentRenewError.addHandler(p)},u.prototype.removeSilentRenewError=function(p){this._silentRenewError.removeHandler(p)},u.prototype._raiseSilentRenewError=function(p){i.Log.debug("UserManagerEvents._raiseSilentRenewError",p.message),this._silentRenewError.raise(p)},u.prototype.addUserSignedIn=function(p){this._userSignedIn.addHandler(p)},u.prototype.removeUserSignedIn=function(p){this._userSignedIn.removeHandler(p)},u.prototype._raiseUserSignedIn=function(){i.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},u.prototype.addUserSignedOut=function(p){this._userSignedOut.addHandler(p)},u.prototype.removeUserSignedOut=function(p){this._userSignedOut.removeHandler(p)},u.prototype._raiseUserSignedOut=function(){i.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},u.prototype.addUserSessionChanged=function(p){this._userSessionChanged.addHandler(p)},u.prototype.removeUserSessionChanged=function(p){this._userSessionChanged.removeHandler(p)},u.prototype._raiseUserSessionChanged=function(){i.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},u})(o.AccessTokenEvents)},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.Timer=void 0;var i=(function(){function p(_,m){for(var S=0;S<m.length;S++){var A=m[S];A.enumerable=A.enumerable||!1,A.configurable=!0,"value"in A&&(A.writable=!0),Object.defineProperty(_,A.key,A)}}return function(_,m,S){return m&&p(_.prototype,m),S&&p(_,S),_}})(),o=a(0),s=a(1),d=a(17);function u(p,_){if(!(p instanceof _))throw new TypeError("Cannot call a class as a function")}function c(p,_){if(!p)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!_||typeof _!="object"&&typeof _!="function"?p:_}n.Timer=(function(p){function _(m){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:s.Global.timer,A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;u(this,_);var h=c(this,p.call(this,m));return h._timer=S,h._nowFunc=A||function(){return Date.now()/1e3},h}return(function(S,A){if(typeof A!="function"&&A!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof A);S.prototype=Object.create(A&&A.prototype,{constructor:{value:S,enumerable:!1,writable:!0,configurable:!0}}),A&&(Object.setPrototypeOf?Object.setPrototypeOf(S,A):S.__proto__=A)})(_,p),_.prototype.init=function(S){S<=0&&(S=1),S=parseInt(S);var A=this.now+S;if(this.expiration===A&&this._timerHandle)o.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),o.Log.debug("Timer.init timer "+this._name+" for duration:",S),this._expiration=A;var h=5;S<h&&(h=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*h)}},_.prototype.cancel=function(){this._timerHandle&&(o.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},_.prototype._callback=function(){var S=this._expiration-this.now;o.Log.debug("Timer.callback; "+this._name+" timer expires in:",S),this._expiration<=this.now&&(this.cancel(),p.prototype.raise.call(this))},i(_,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),_})(d.Event)},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.SilentRenewService=void 0;var i=a(0);n.SilentRenewService=(function(){function o(s){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,o),this._userManager=s}return o.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(d){})).catch((function(d){i.Log.error("SilentRenewService.start: Error from getUser:",d.message)})))},o.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},o.prototype._tokenExpiring=function(){var d=this;this._userManager.signinSilent().then((function(u){i.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(u){i.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",u.message),d._userManager.events._raiseSilentRenewError(u)}))},o})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.CordovaPopupNavigator=void 0;var i=a(21);n.CordovaPopupNavigator=(function(){function o(){(function(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")})(this,o)}return o.prototype.prepare=function(d){var u=new i.CordovaPopupWindow(d);return Promise.resolve(u)},o})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.CordovaIFrameNavigator=void 0;var i=a(21);n.CordovaIFrameNavigator=(function(){function o(){(function(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")})(this,o)}return o.prototype.prepare=function(d){d.popupWindowFeatures="hidden=yes";var u=new i.CordovaPopupWindow(d);return Promise.resolve(u)},o})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.Version="1.11.6"}])}))})(oidcClient_min$1)),oidcClient_min$1.exports}var oidcClient_minExports=requireOidcClient_min();function processErrorResponse(r,e){throw r.error==="invalid_redirect_uri"?new Error(`Dynamic client registration failed: the provided redirect uri [${e.redirectUrl?.toString()}] is invalid - ${r.error_description??""}`):r.error==="invalid_client_metadata"?new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(e)} is invalid - ${r.error_description??""}`):new Error(`Dynamic client registration failed: ${r.error} - ${r.error_description??""}`)}function hasClientId(r){return typeof r.client_id=="string"}function hasRedirectUri(r){return Array.isArray(r.redirect_uris)&&r.redirect_uris.every(e=>typeof e=="string")}function validateRegistrationResponse(r,e){if(!hasClientId(r))throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(r)}`);if(e.redirectUrl&&hasRedirectUri(r)&&r.redirect_uris[0]!==e.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(r.redirect_uris)} don't match the provided ${JSON.stringify([e.redirectUrl.toString()])}`);return!0}async function registerClient(r,e){if(!e.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(e.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const t=determineSigningAlg(e.idTokenSigningAlgValuesSupported,PREFERRED_SIGNING_ALG),n={client_name:r.clientName,application_type:"web",redirect_uris:[r.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:t,grant_types:["authorization_code","refresh_token"]},a={"Content-Type":"application/json"},i=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:a,body:JSON.stringify(n)});if(i.ok){const o=await i.json();return validateRegistrationResponse(o,r),{clientId:o.client_id,clientSecret:o.client_secret,expiresAt:o.client_secret_expires_at,idTokenSignedResponseAlg:o.id_token_signed_response_alg,clientType:"dynamic"}}throw i.status===400&&processErrorResponse(await i.json(),r),new Error(`Dynamic client registration failed: the server returned ${i.status} ${i.statusText} - ${await i.text()}`)}function hasError(r){return r.error!==void 0&&typeof r.error=="string"}function hasErrorDescription(r){return r.error_description!==void 0&&typeof r.error_description=="string"}function hasErrorUri(r){return r.error_uri!==void 0&&typeof r.error_uri=="string"}function hasAccessToken(r){return r.access_token!==void 0&&typeof r.access_token=="string"}function hasIdToken(r){return r.id_token!==void 0&&typeof r.id_token=="string"}function hasRefreshToken(r){return r.refresh_token!==void 0&&typeof r.refresh_token=="string"}function hasTokenType(r){return r.token_type!==void 0&&typeof r.token_type=="string"}function hasExpiresIn(r){return r.expires_in===void 0||typeof r.expires_in=="number"}function validatePreconditions(r,e){if(e.grantType&&(!r.grantTypesSupported||!r.grantTypesSupported.includes(e.grantType)))throw new Error(`The issuer [${r.issuer}] does not support the [${e.grantType}] grant`);if(!r.tokenEndpoint)throw new Error(`This issuer [${r.issuer}] does not have a token endpoint`)}function validateTokenEndpointResponse(r,e){if(hasError(r))throw new OidcProviderError(`Token endpoint returned error [${r.error}]${hasErrorDescription(r)?`: ${r.error_description}`:""}${hasErrorUri(r)?` (see ${r.error_uri})`:""}`,r.error,hasErrorDescription(r)?r.error_description:void 0);if(!hasAccessToken(r))throw new InvalidResponseError(["access_token"]);if(!hasIdToken(r))throw new InvalidResponseError(["id_token"]);if(!hasTokenType(r))throw new InvalidResponseError(["token_type"]);if(!hasExpiresIn(r))throw new InvalidResponseError(["expires_in"]);if(!e&&r.token_type.toLowerCase()!=="bearer")throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${r.token_type}].`);return r}async function getTokens(r,e,t,n){validatePreconditions(r,t);const a={"content-type":"application/x-www-form-urlencoded"};let i;n&&(i=await generateDpopKeyPair(),a.DPoP=await createDpopHeader(r.tokenEndpoint,"POST",i)),e.clientSecret&&(a.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const o={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},s={method:"POST",headers:a,body:new URLSearchParams(o).toString()},u=await(await fetch(r.tokenEndpoint,s)).json(),c=validateTokenEndpointResponse(u,n),{webId:p,clientId:_}=await getWebidFromTokenPayload(c.id_token,r.jwksUri,r.issuer,e.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:hasRefreshToken(c)?c.refresh_token:void 0,webId:p,clientId:_,dpopKey:i,expiresIn:c.expires_in}}const isValidUrl=r=>{try{return new URL(r),!0}catch{return!1}};async function refresh(r,e,t,n){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const a={grant_type:"refresh_token",refresh_token:r};let i={};n!==void 0&&(i={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",n)});let o={};t.clientSecret!==void 0?o={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(a.client_id=t.clientId);const s=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(a).toString(),headers:{...i,...o,"Content-Type":"application/x-www-form-urlencoded"}});let d;try{d=await s.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const u=validateTokenEndpointResponse(d,n!==void 0),{webId:c}=await getWebidFromTokenPayload(u.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:typeof u.refresh_token=="string"?u.refresh_token:void 0,webId:c,dpopKey:n,expiresIn:u.expires_in}}function normalizeCallbackUrl(r){const e=removeOpenIdParams(r);return e.hash="",r.includes(`${e.origin}/`)?e.href:`${e.origin}${e.href.substring(e.origin.length+1)}`}async function clearOidcPersistentStorage(){await new oidcClient_minExports.OidcClient({response_mode:"query"}).clearStaleState(new oidcClient_minExports.WebStorageStateStore({}));const e=window.localStorage,t=[];for(let n=0;n<=e.length;n+=1){const a=e.key(n);a&&(a.match(/^oidc\..+$/)||a.match(/^solidClientAuthenticationUser:.+$/))&&t.push(a)}t.forEach(n=>e.removeItem(n))}class StorageUtilityBrowser extends StorageUtility{constructor(e,t){super(e,t)}}class ClientAuthentication extends ClientAuthentication$1{login=async(e,t)=>{e.prompt!=="none"&&await this.sessionInfoManager.clear(e.sessionId);const n=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(n))throw new Error(`${n} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:n,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return t===void 0||t.clientAppId===void 0||t.issuer===void 0?null:t};handleIncomingRedirect=async(e,t)=>{try{const n=await this.redirectHandler.handle(e,t,void 0);return this.fetch=n.fetch.bind(window),this.boundLogout=n.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:n.isLoggedIn,webId:n.webId,sessionId:n.sessionId,expirationDate:n.expirationDate,clientAppId:n.clientAppId}}catch(n){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",n);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(n=>{setTimeout(()=>n(),1)})}}function hasIssuer(r){return typeof r.oidcIssuer=="string"}function hasRedirectUrl(r){return typeof r.redirectUrl=="string"}class OidcLoginHandler{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,n,a){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=n,this.clientRegistrar=a,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=n,this.clientRegistrar=a}async canHandle(e){return hasIssuer(e)&&hasRedirectUrl(e)}async handle(e){if(!hasIssuer(e))throw new ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!hasRedirectUrl(e))throw new ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),n=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),a={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:n,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(a)}}class AuthorizationCodeWithPkceOidcHandler extends AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},n=new oidcClient_minExports.OidcClient(t);try{const a=await n.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:a.state._id,codeVerifier:a.state._code_verifier,targetUrl:a.url.toString()})}catch(a){console.error(a)}}}const WELL_KNOWN_OPENID_CONFIG=".well-known/openid-configuration",issuerConfigKeyMap={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};function processConfig(r){const e={};return Object.keys(r).forEach(t=>{issuerConfigKeyMap[t]&&(e[issuerConfigKeyMap[t].toKey]=r[t])}),Array.isArray(e.scopesSupported)||(e.scopesSupported=["openid"]),e}class IssuerConfigFetcher{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const n=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,a=await fetch(n);try{t=processConfig(await a.json())}catch(i){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${i.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function clear(r,e){await clear$1(r,e),await clearOidcPersistentStorage()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,n,a,i,o,s,d,u]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if(typeof o=="string"&&!isValidRedirectUrl(o)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(u!==void 0&&!isSupportedTokenType(u))throw new Error(`Tokens of type [${u}] are not supported.`);if(!(a===void 0&&t===void 0&&n===void 0&&s===void 0))return{sessionId:e,webId:n,isLoggedIn:t==="true",redirectUrl:o,refreshToken:s,issuer:d,clientAppId:a,clientAppSecret:i,tokenType:u??"DPoP"}}async clear(e){return clear(e,this.storageUtility)}}class FallbackRedirectHandler{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return getUnauthenticatedSession()}}class AuthCodeRedirectHandler{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;fetch;constructor(e,t,n,a,i,o){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=n,this.clientRegistrar=a,this.tokerRefresher=i,this.fetch=o,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=n,this.clientRegistrar=a,this.tokerRefresher=i}async canHandle(e){try{const t=new URL(e);return t.searchParams.get("code")!==null&&t.searchParams.get("state")!==null}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const n=new URL(e),a=n.searchParams.get("state"),i=await this.storageUtility.getForUser(a,"sessionId",{errorIfNull:!0}),{issuerConfig:o,codeVerifier:s,redirectUrl:d,dpop:u}=await loadOidcContextFromStorage(i,this.storageUtility,this.issuerConfigFetcher),c=n.searchParams.get("iss");if(typeof c=="string"&&c!==o.issuer)throw new Error(`The value of the iss parameter (${c}) does not match the issuer identifier of the authorization server (${o.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(s===void 0)throw new Error(`The code verifier for session ${i} is missing from storage.`);if(d===void 0)throw new Error(`The redirect URL for session ${i} is missing from storage.`);const p=await this.clientRegistrar.getClient({sessionId:i},o),_=Date.now(),m=await getTokens(o,p,{grantType:"authorization_code",code:n.searchParams.get("code"),codeVerifier:s,redirectUrl:d},u);window.localStorage.removeItem(`oidc.${a}`);let S;m.refreshToken!==void 0&&(S={sessionId:i,refreshToken:m.refreshToken,tokenRefresher:this.tokerRefresher});const A=buildAuthenticatedFetch(m.accessToken,{dpopKey:m.dpopKey,refreshOptions:S,eventEmitter:t,expiresIn:m.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,i,m.webId,m.clientId,"true",void 0,!0);const h=await this.sessionInfoManager.get(i);if(!h)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(h,{fetch:A,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:m.idToken,endSessionEndpoint:o.endSessionEndpoint}),expirationDate:typeof m.expiresIn=="number"?_+m.expiresIn*1e3:void 0})}}class AggregateRedirectHandler extends AggregateHandler{constructor(e){super(e)}}class BrowserStorage{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class Redirector{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class ClientRegistrar{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[n,a,i,o,s]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),d=i!==void 0?Number.parseInt(i,10):-1,u=a!==void 0&&d!==0&&Math.floor(Date.now()/1e3)>d;if(n&&isKnownClientType(s)&&!u)return a!==void 0?{clientId:n,clientSecret:a,clientName:o,clientType:"dynamic",expiresAt:d}:{clientId:n,clientName:o,clientType:s};try{const c=await registerClient(e,t),p={clientId:c.clientId,clientType:"dynamic"};return c.clientSecret!==void 0&&(p.clientSecret=c.clientSecret,p.expiresAt=String(c.expiresAt)),c.idTokenSignedResponseAlg&&(p.idTokenSignedResponseAlg=c.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,p,{secure:!1}),c}catch(c){throw new Error("Client registration failed.",{cause:c})}}}class ErrorOidcHandler{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(t!==void 0){const n=new URL(e),a=n.searchParams.get("error"),i=n.searchParams.get("error_description");t.emit(EVENTS.ERROR,a,i)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,n){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=n,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=n}async refresh(e,t,n,a){const i=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),o=await this.clientRegistrar.getClient({sessionId:e},i.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(i.dpop&&n===void 0)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const s=await refresh(t,i.issuerConfig,o,n);return s.refreshToken!==void 0&&a?.emit(EVENTS.NEW_REFRESH_TOKEN,s.refreshToken),s}}function getClientAuthenticationWithDependencies(r){const e=new InMemoryStorage,t=r.secureStorage||e,n=r.insecureStorage||new BrowserStorage,a=new StorageUtilityBrowser(t,n),i=new IssuerConfigFetcher(a),o=new ClientRegistrar(a),s=new SessionInfoManager(a),d=new TokenRefresher(a,i,o),u=new Redirector,c=new OidcLoginHandler(a,new AuthorizationCodeWithPkceOidcHandler(a,u),i,o),p=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(a,s,i,o,d,r.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(c,p,new IWaterfallLogoutHandler(s,u),s,i)}const KEY_CURRENT_SESSION=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,KEY_CURRENT_URL=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;async function silentlyAuthenticate(r,e,t){const n=await e.validateCurrentSession(r);return n!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:r,prompt:"none",oidcIssuer:n.issuer,redirectUrl:n.redirectUrl,clientId:n.clientAppId,clientSecret:n.clientAppSecret,tokenType:n.tokenType??"DPoP"},t.events),!0):!1}function isLoggedIn(r){return!!r?.isLoggedIn}class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;xpodErrorLogout=Promise.resolve();constructor(e={},t=void 0){this.events=new EventEmitter,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=getClientAuthenticationWithDependencies({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage,fetch:e.fetch}):this.clientAuthentication=getClientAuthenticationWithDependencies({fetch:e.fetch}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??v4$1(),isLoggedIn:!1},this.events.on(EVENTS.LOGIN,()=>window.localStorage.setItem(KEY_CURRENT_SESSION,this.info.sessionId)),this.events.on(EVENTS.SESSION_EXPIRED,()=>this.internalLogout(!1)),this.events.on(EVENTS.ERROR,()=>{this.xpodErrorLogout=this.xpodErrorLogout.then(()=>this.internalLogout(!1),()=>this.internalLogout(!1)),this.xpodErrorLogout.catch(()=>{})})}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(KEY_CURRENT_SESSION),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(EVENTS.LOGOUT)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t=typeof e=="string"?{url:e}:e,n=t.url??window.location.href;this.tokenRequestInProgress=!0;const a=await this.clientAuthentication.handleIncomingRedirect(n,this.events);try{await this.xpodErrorLogout}catch(i){throw this.tokenRequestInProgress=!1,i}if(isLoggedIn(a)){this.setSessionInfo(a);const i=window.localStorage.getItem(KEY_CURRENT_URL);i===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,i))}else if(t.restorePreviousSession===!0){const i=window.localStorage.getItem(KEY_CURRENT_SESSION);if(i!==null&&await silentlyAuthenticate(i,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,a};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(EVENTS.SESSION_EXTENDED,t=>{this.info.expirationDate=Date.now()+t*1e3})}}async function chooseAccessRoute(r,e={}){const t=usableRoutes(r,e.managedClient??!0,e.allowLocalOnlyRoutes??!1);if(t.length===0)return null;const n=t[0];if(isSelfProvenRoute(n))return n;const a=e.probe??defaultProbe,i=e.probeTimeoutMs??1e3;return(await Promise.all(t.map(async s=>({route:s,ok:isSelfProvenRoute(s)||await probeWithTimeout(s,a,i)})))).find(s=>s.ok)?.route??null}function isSelfProvenRoute(r){return r.health==="healthy"}function usableRoutes(r,e,t){return r.routes.filter(n=>n.health!=="unreachable").filter(n=>e||!n.requiresManagedClient).filter(n=>t||n.visibility!=="local-only").slice().sort((n,a)=>n.priority-a.priority||n.id.localeCompare(a.id))}function createSolidAccessRouteFetch(r){const e=r.managedClient??!0;let t;const n=async d=>{const u=r.routes(),c=d===void 0?u:u.filter(m=>routeKey(m)!==d),p={canonicalUrl:c[0]?.canonicalUrl??"",routes:c},_=await chooseAccessRoute(p,{managedClient:e,...r.allowLocalOnlyRoutes===void 0?{}:{allowLocalOnlyRoutes:r.allowLocalOnlyRoutes},...r.probeTimeoutMs===void 0?{}:{probeTimeoutMs:r.probeTimeoutMs},...r.probe===void 0?{}:{probe:r.probe}});return t=_??void 0,_},a=async()=>t&&r.routes().some(d=>d.id===t?.id&&d.targetUrl===t?.targetUrl)?t:await n()??void 0,i=d=>createSolidLocalRouteFetch({fetch:r.fetch,routes:()=>[{canonicalBaseUrl:d.canonicalUrl,localBaseUrl:d.targetUrl}]}),o=d=>!!resolveSolidLocalRouteUrl(d,r.routes().map(toLocalRoute$1)),s=d=>{const u=requestUrl(d);if(!u||!o(u))return;const c=r.routes(),p=usableRoutes({canonicalUrl:c[0]?.canonicalUrl??"",routes:c},e,r.allowLocalOnlyRoutes??!1)[0];if(!(!p||sameOrigin(p.targetUrl,u)))return u};return async(d,u)=>{const c=requestUrl(d);if(!c||!o(c))return u===void 0?r.fetch.call(globalThis,d):r.fetch.call(globalThis,d,u);const p=await a();if(!p){const _=s(d);if(_)throw new NoUsableAccessRouteError(_.href,r.routes());return u===void 0?r.fetch.call(globalThis,d):r.fetch.call(globalThis,d,u)}try{return await i(p)(d,u)}catch(_){t=void 0;const m=(u?.method??(d instanceof Request?d.method:"GET")).toUpperCase();if(!["GET","HEAD","OPTIONS"].includes(m))throw _;await r.refreshRoutes?.();const S=await n(routeKey(p));if(S&&routeKey(S)!==routeKey(p))return i(S)(d,u);const A=requestUrl(d);throw A&&o(A)?new NoUsableAccessRouteError(A.href,r.routes(),_):_}}}function routeKey(r){return`${r.id}|${r.targetUrl}`}class NoUsableAccessRouteError extends Error{constructor(e,t,n){super(`No usable access route can reach ${e}`),this.url=e,this.routes=t,this.reason=n,this.name="NoUsableAccessRouteError"}}function toLocalRoute$1(r){return{canonicalBaseUrl:r.canonicalUrl,localBaseUrl:r.targetUrl}}function sameOrigin(r,e){try{return new URL(r).origin===e.origin}catch{return!1}}function requestUrl(r){if(r instanceof Request)try{return new URL(r.url)}catch{return}try{return new URL(String(r))}catch{return}}async function probeWithTimeout(r,e,t){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{return await Promise.resolve(e(r,n.signal))}catch{return!1}finally{clearTimeout(a)}}function answersAccessRoute(r){return r.status<500}async function defaultProbe(r,e){if(!r.targetUrl.startsWith("http://")&&!r.targetUrl.startsWith("https://"))return r.health==="healthy";const t=await fetch(new URL("/.well-known/solid",r.targetUrl),{method:"HEAD",signal:e});return answersAccessRoute(t)}function snapshotFromSessionInfo(r){return r?.isLoggedIn&&r.webId?{status:"authenticated",webId:r.webId}:{status:"anonymous"}}function normalizeError(r){return r instanceof Error?r:new Error(String(r))}function snapshotFromSessionError(r,e){return{status:"error",webId:e.webId,error:normalizeError(r)}}function snapshotFromSessionExpired(r){return{status:"expired",...r.webId===void 0?{}:{webId:r.webId}}}function areSnapshotsEqual(r,e){return!r||r.status!==e.status||r.webId!==e.webId?!1:r.status==="error"&&e.status==="error"?r.error===e.error:!0}function createSolidSessionRuntime(r={}){const e=r.session??new Session,t=new Set;let n={status:"initializing"},a,i,o,s,d=!1,u=!1,c,p=!1,_=0,m=!1,S=0,A=0,h;const T=()=>{_+=1,m=!0},w=U=>{if(p||((U.status!=="authenticated"||n.status!=="authenticated"||n.webId!==U.webId)&&T(),U.status==="authenticated"&&(m=!1),n=U,areSnapshotsEqual(a,n)))return n;a=n;for(const v of t)v(n);return n},b=()=>{if(h){if(h.generation!==A||h.eventWebId&&h.eventWebId!==e.info.webId)return n;h.eventWebId=e.info.webId}return T(),a=void 0,w(snapshotFromSessionInfo(e.info))},N=()=>(A+=1,w({status:"anonymous"})),O=()=>(A+=1,w(snapshotFromSessionExpired(e.info))),X=(U,v)=>{if(h&&h.generation!==A)return;A+=1;const x=snapshotFromSessionError(v??U??"Solid session error",e.info);u&&(c=x),w(x)};e.events.on(EVENTS.LOGIN,b),e.events.on(EVENTS.SESSION_RESTORED,b),e.events.on(EVENTS.LOGOUT,N),e.events.on(EVENTS.SESSION_EXPIRED,O);const ee=e.events;ee.on(EVENTS.ERROR,X);const V=(U,v)=>{const x=new Promise((I,E)=>{s=()=>I(n),o=setTimeout(()=>{if(o=void 0,!p&&v.generation===A&&(A+=1,n.status==="initializing")){const K=new Error("Previous login is still completing. Reload before reconnecting.");K.name="SolidSessionPendingError",w(snapshotFromSessionError(K,e.info))}I(n)},15e3);const Q=()=>{i===x&&(clearTimeout(o),o=void 0,s=void 0,h===v&&(h=void 0),i=void 0,u=!1,c=void 0)};U.then(K=>{Q(),I(K)},K=>{Q(),E(K)})});return x};return{fetch:e.fetch,createAuthenticatedFetch(U){const v=_,x=()=>{if(p||S>0||m||v!==_||n.status!=="authenticated"||n.webId!==U||!e.info.isLoggedIn||e.info.webId!==U){const I=new Error("Authenticated session is no longer current");throw I.name="AbortError",I}};return async(I,E)=>{x();const Q=await(E===void 0?e.fetch(I):e.fetch(I,E));try{x()}catch(K){throw Q.body?.cancel().catch(()=>{}),K}return Q}},getSnapshot(){return n},initialize(U={}){if(i)return i;if(d||p)return Promise.resolve(n);const v={generation:++A,eventWebId:void 0};h=v;const x=E=>!p&&v.generation===A&&(!E?.isLoggedIn||!v.eventWebId||v.eventWebId===E.webId);u=!0,c=void 0,w({status:"initializing"});const I=e.handleIncomingRedirect({restorePreviousSession:U.restorePreviousSession??!0}).then(E=>{if(!x(E??e.info))return n;const Q=snapshotFromSessionInfo(E??e.info);return Q.status==="anonymous"&&c?.status==="error"?c:(d=!0,w(Q))}).catch(E=>x()?w(snapshotFromSessionError(E,e.info)):n);return i=V(I,v),i},handleIncomingRedirect(U){if(i)return i;if(p)return Promise.resolve(n);const v={generation:++A,eventWebId:void 0};h=v;const x=E=>!p&&v.generation===A&&(!E?.isLoggedIn||!v.eventWebId||v.eventWebId===E.webId);u=!0,c=void 0,w({status:"initializing"});const I=e.handleIncomingRedirect(U).then(E=>{if(!x(E??e.info))return n;const Q=snapshotFromSessionInfo(E??e.info);return Q.status==="anonymous"&&c?.status==="error"?c:(d=!0,w(Q))}).catch(E=>x()?w(snapshotFromSessionError(E,e.info)):n);return i=V(I,v),i},async login(U){A+=1,T(),S+=1;try{if(i){const v=new Error("Previous login is still completing. Reload before reconnecting.");throw v.name="SolidSessionPendingError",v}if(p)throw new Error("Solid session runtime is disposed");await e.login(U)}catch(v){throw w(snapshotFromSessionError(v,e.info)),v}finally{S-=1}},async logout(U){A+=1,T(),S+=1;try{await e.logout(U),w({status:"anonymous"})}catch(v){throw w(snapshotFromSessionError(v,e.info)),v}finally{S-=1}},subscribe(U){return t.add(U),()=>{t.delete(U)}},dispose(){clearTimeout(o),A+=1,T(),p=!0,s?.(),s=void 0,t.clear(),e.events.off(EVENTS.LOGIN,b),e.events.off(EVENTS.SESSION_RESTORED,b),e.events.off(EVENTS.LOGOUT,N),e.events.off(EVENTS.SESSION_EXPIRED,O),ee.off(EVENTS.ERROR,X)}}}const ENDPOINT_PROTOCOLS=new Set(["http:","https:"]),RESERVED_AUTHORIZATION_PARAMETERS=new Set(["state","redirect_uri","client_id","response_type","code_challenge","code_challenge_method"]);function normalizeEndpoint(r,e){if(!r||typeof r.url!="string"||r.url.trim()==="")throw new TypeError(`${e}.url must be a non-empty absolute URL`);if(typeof r.label!="string")throw new TypeError(`${e}.label must be a string`);let t;try{t=new URL(r.url.trim())}catch{throw new TypeError(`${e}.url must be a valid absolute URL`)}if(!ENDPOINT_PROTOCOLS.has(t.protocol))throw new TypeError(`${e}.url must use http or https`);if(t.username||t.password)throw new TypeError(`${e}.url must not contain credentials`);if(t.hash)throw new TypeError(`${e}.url must not contain a fragment`);return{url:t.href,label:r.label}}function validateWebId(r){if(typeof r!="string"||r===""||/[\s\u0000-\u001f\u007f-\u009f]/u.test(r))throw new TypeError("webId must be a non-empty identifier without whitespace or control characters");return r}function normalizeStorageBinding(r){if(!r||typeof r.storageUrl!="string"||r.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");validateWebId(r.webId);let e;try{e=new URL(r.storageUrl.trim())}catch{throw new TypeError("selectedStorage.storageUrl must be a valid absolute URL")}if(!ENDPOINT_PROTOCOLS.has(e.protocol))throw new TypeError("selectedStorage.storageUrl must use http or https");if(e.username||e.password)throw new TypeError("selectedStorage.storageUrl must not contain credentials");if(e.hash)throw new TypeError("selectedStorage.storageUrl must not contain a fragment");return{storageUrl:e.href,webId:r.webId,...r.label===void 0?{}:{label:r.label}}}function ensureEnum(r,e,t){if(!e.includes(r))throw new TypeError(`${t} has an unsupported value`);return r}function normalizeWebIdLoginRoute(r){if(!r||typeof r.id!="string"||r.id.trim()==="")throw new TypeError("route.id must be a non-empty opaque identifier");if(typeof r.label!="string")throw new TypeError("route.label must be a string");return{id:r.id.trim(),label:r.label,...r.description===void 0?{}:{description:r.description},...r.badge===void 0?{}:{badge:{label:r.badge.label,tone:ensureEnum(r.badge.tone,["neutral","primary","success","warning","danger"],"route.badge.tone")}},identityProvider:normalizeEndpoint(r.identityProvider,"route.identityProvider"),...r.storageProvider===void 0?{}:{storageProvider:normalizeEndpoint(r.storageProvider,"route.storageProvider")},availability:ensureEnum(r.availability,["ready","starting","unavailable"],"route.availability"),...r.unavailableReason===void 0?{}:{unavailableReason:r.unavailableReason}}}function decodeForValidation$1(r){let e=r;for(let t=0;t<4;t+=1){let n;try{n=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(n===e)return e;e=n}return e}function matchesAllowedPrefix(r,e){return e.some(t=>{if(t==="/")return r.startsWith("/");const n=t.endsWith("/")?t.slice(0,-1):t;return r===n||r.startsWith(`${n}/`)})}function normalizeApplicationReturnTo(r,e){if(r===void 0)return;if(typeof r!="string"||r.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const t=r.trim(),n=decodeForValidation$1(t),a=n.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||n.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(n)||n.startsWith("//")||a.split("/").some(i=>i==="..")||!matchesAllowedPrefix(a,e))throw new TypeError("returnTo must be a safe path within the application allow-list");return t}function normalizeWebIdLoginTransaction(r){if(!r||typeof r.id!="string"||r.id.trim()==="")throw new TypeError("transaction.id must be a non-empty opaque identifier");const e=r.authorizationParameters===void 0?void 0:{...r.authorizationParameters};if(e){for(const n of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(n.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${n}`)}const t=r.prompt===void 0?void 0:ensureEnum(r.prompt,["login","consent","select_account"],"transaction.prompt");return{id:r.id,route:normalizeWebIdLoginRoute(r.route),...r.selectedStorage===void 0?{}:{selectedStorage:normalizeStorageBinding(r.selectedStorage)},authorizationSurface:ensureEnum(r.authorizationSurface,["redirect","popup","embedded","external"],"transaction.authorizationSurface"),...t===void 0?{}:{prompt:t},discovery:ensureEnum(r.discovery,["standard","strict"],"transaction.discovery"),...e===void 0?{}:{authorizationParameters:e},...r.returnTo===void 0?{}:{returnTo:normalizeApplicationReturnTo(r.returnTo,["/"])}}}const KEY_SEPARATOR="\0";function normalizePodUrl(r){if(typeof r!="string"||r.trim()==="")throw new TypeError("podUrl must be a non-empty absolute URL");let e;try{e=new URL(r.trim())}catch{throw new TypeError("podUrl must be a valid absolute URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("podUrl must use http or https");if(e.username||e.password||e.hash)throw new TypeError("podUrl must not contain credentials or a fragment");return e.href}function compositeKey(r,e){return`${r}${KEY_SEPARATOR}${e}`}function nextGeneration(r,e){const t=(r.get(e)??0)+1;return r.set(e,t),t}function createAbortedOpenError(){const r=new Error("Pod open aborted because the runtime identity changed");return r.name="AbortError",r}function createPodRuntime(r){const{adapter:e}=r,t=new Map,n=new Map,a=new Map,i=new Map,o=new Map,s=new Map,d=(p,_)=>{const m=validateWebId(p);if(_!==void 0){const h=normalizePodUrl(_),T=compositeKey(p,h);nextGeneration(s,T),i.get(T)?.controller.abort(),i.delete(T),n.delete(T);const w=t.get(m);w&&compositeKey(w.webId,w.podUrl)===T&&t.delete(m);return}nextGeneration(o,m),a.get(m)?.controller.abort(),a.delete(m);const S=t.get(m);S&&n.delete(compositeKey(S.webId,S.podUrl)),t.delete(m);const A=`${m}${KEY_SEPARATOR}`;for(const h of[...n.keys()])h.startsWith(A)&&n.delete(h);for(const[h,T]of[...i.entries()])h.startsWith(A)&&(nextGeneration(s,h),T.controller.abort(),i.delete(h))},u=p=>{if(p===void 0){t.clear(),n.clear();for(const _ of a.values())_.controller.abort();for(const _ of i.values())_.controller.abort();a.clear(),i.clear();for(const _ of o.keys())nextGeneration(o,_);for(const _ of s.keys())nextGeneration(s,_);return}if(typeof p=="string"){d(p);return}d(p.webId,p.podUrl)};return{open(p){const _=validateWebId(p.webId),m=p.podUrl===void 0?void 0:normalizePodUrl(p.podUrl);if(m!==void 0){const X=compositeKey(p.webId,m),ee=n.get(X);if(ee)return Promise.resolve(ee);const V=i.get(X);if(V)return V.promise;const U=s.get(X)??0;s.set(X,U);const v=new AbortController,x=()=>!v.signal.aborted&&(s.get(X)??0)===U,I=()=>{if(!x())throw createAbortedOpenError()},E=c({webId:p.webId,podUrl:m,fetch:p.fetch,signal:v.signal,isCurrent:x,assertCurrent:I});i.set(X,{generation:U,promise:E,controller:v});const Q=()=>{const K=i.get(X);K?.generation===U&&K.promise===E&&i.delete(X)};return E.then(Q,Q),E}const S=t.get(_);if(S)return Promise.resolve(S);const A=a.get(_);if(A)return A.promise;const h=o.get(_)??0;o.set(_,h);const T=new AbortController,w=()=>!T.signal.aborted&&(o.get(_)??0)===h,b=()=>{if(!w())throw createAbortedOpenError()},N=(async()=>{const X=await e.discoverPod({webId:p.webId,fetch:p.fetch,signal:T.signal,isCurrent:w});return b(),c({webId:p.webId,podUrl:normalizePodUrl(X),fetch:p.fetch,signal:T.signal,isCurrent:w,assertCurrent:b,generation:h,webIdKey:_,discovered:!0})})();a.set(_,{generation:h,promise:N,controller:T});const O=()=>{const X=a.get(_);X?.generation===h&&X.promise===N&&a.delete(_)};return N.then(O,O),N},clear:u,dispose(){u()}};async function c(p){const _=compositeKey(p.webId,p.podUrl),m=n.get(_);if(m)return p.discovered&&p.webIdKey&&p.isCurrent()&&t.set(p.webIdKey,m),m;const S=await e.openDatabase({webId:p.webId,podUrl:p.podUrl,fetch:p.fetch,signal:p.signal,isCurrent:p.isCurrent});p.assertCurrent(),await e.hydrateCollections({webId:p.webId,podUrl:p.podUrl,database:S,signal:p.signal,isCurrent:p.isCurrent}),p.assertCurrent();const A={webId:p.webId,podUrl:p.podUrl,database:S,collections:"ready"};return p.isCurrent()&&(n.set(_,A),p.discovered&&p.webIdKey&&t.set(p.webIdKey,A)),A}}SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,RDF$6.type,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt,UDFS.disabledAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;RDF$6.type,UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$6.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),offeringId:string$2("offeringId").predicate(UDFS.offeringId),service:string$2("service").predicate(UDFS.service).notNull().default("ai"),status:string$2("status").predicate(UDFS.status).notNull().default("active"),apiKey:string$2("apiKey").predicate(UDFS.apiKey),storageMode:string$2("storageMode").predicate(UDFS.storageMode),secretPayload:string$2("secretPayload").predicate(UDFS.secretPayload),encryptedSecret:string$2("encryptedSecret").predicate(UDFS.encryptedSecret),wrappedDataKey:string$2("wrappedDataKey").predicate(UDFS.wrappedDataKey),encryptionAlgorithm:string$2("encryptionAlgorithm").predicate(UDFS.encryptionAlgorithm),keyVersion:string$2("keyVersion").predicate(UDFS.keyVersion),scopes:text("scopes").array().predicate(UDFS.scopes),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),accountLabel:string$2("accountLabel").predicate(UDFS.accountLabel),lastRefreshAt:timestamp("lastRefreshAt").predicate(UDFS.lastRefreshAt),reauthRequired:boolean$2("reauthRequired").predicate(UDFS.reauthRequired).default(!1),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),label:string$2("label").predicate(UDFS.label),isDefault:boolean$2("isDefault").predicate(UDFS.isDefault).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).defaultNow(),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),clientCredentialId:string$2("clientCredentialId").predicate(UDFS.clientCredentialId),appliedTo:string$2("appliedTo").predicate(UDFS.appliedTo),appliedOn:string$2("appliedOn").predicate(UDFS.appliedOn),appliedAt:timestamp("appliedAt").predicate(UDFS.appliedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),lastFailureCode:string$2("lastFailureCode").predicate(UDFS.lastFailureCode),lastFailureAt:timestamp("lastFailureAt").predicate(UDFS.lastFailureAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId),metadata:json("metadata").predicate(UDFS.metadata)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(r,e){return r&&r.length>0?r:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(r){return taskDir(r)??runDir(r)??deliveryDir(r)??issueDir(r)??threadDir(r)??chatDir(r)??aboutDir(r)}function chatDir(r){const e=typeof r?.chat=="string"?r.chat:void 0;if(!e)return null;const n=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return n?.[1]?`chat/${n[1]}`:null}function threadDir(r){const e=typeof r?.thread=="string"?r.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(r){const e=typeof r?.task=="string"?r.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const n=t.match(/^task\/index\.ttl#([^#/]+)$/);if(n?.[1])return`task/${n[1]}`;const a=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return a?.[1]?`task/${a[1]}`:null}function issueDir(r){const e=typeof r?.issue=="string"?r.issue:void 0;if(!e)return null;const n=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return n?.[1]?`issues/${n[1]}`:null}function deliveryDir(r){const e=typeof r?.delivery=="string"?r.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(r){const e=typeof r?.run=="string"?r.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(r){const e=typeof r?.about=="string"?r.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((r,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(r,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((r,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(r,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(r,e){return e===void 0?void 0:eq(exactFilterColumns[r],e)}function messageListFilter(r){if(!r)return;const e=[exactFilter$1("parent",r.parent),exactFilter$1("chat",r.chat),exactFilter$1("thread",r.thread),exactFilter$1("maker",r.maker),exactFilter$1("role",r.role),exactFilter$1("status",r.status),exactFilter$1("toolName",r.toolName),exactFilter$1("toolCallId",r.toolCallId),exactFilter$1("coordinationId",r.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:r})=>messageListFilter(r)});function chatProjectMemoryResourceId(r){return r.endsWith(".ttl")?r:`${encodeURIComponent(r)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(r=>r?chatProjectMemoryResourceId(r):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:r})=>r?.workspace?eq(chatProjectContextResource.workspace,r.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:r})=>r?.workspace?eq(chatProjectMemoryResource.workspace,r.workspace):void 0});function conversationShareResourceId(r){return r.endsWith(".ttl")?r:`${encodeURIComponent(r)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(r=>r?conversationShareResourceId(r):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:r})=>r?.thread?eq(conversationShareResource.thread,r.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),dueAt:timestamp("dueAt").predicate(UDFS.dueAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),notes:text("notes").predicate(DCTerms.description),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((r,e)=>{const t=resourceKey(r,"report"),n=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${n}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(r){r.UNKNOWN="unknown",r.MAIN_TEXT="main_text",r.THINKING="thinking",r.IMAGE="image",r.CODE="code",r.TOOL="tool",r.TOOL_APPROVAL="tool_approval",r.TASK_PROGRESS="task_progress",r.FILE="file",r.ERROR="error",r.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(r){r.PENDING="pending",r.PROCESSING="processing",r.STREAMING="streaming",r.SUCCESS="success",r.ERROR="error",r.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$6.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(r,e,t){const{rdfType:n,sourceModule:a,extractor:i}=e,o=t["@id"]||t.id;if(!o){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const s=i.getTitle(t),d={id:crypto.randomUUID(),targetType:n,target:o,title:s,snapshotContent:i.getContent?.(t),snapshotAuthor:i.getAuthor?.(t),sourceModule:a,searchText:i.getSearchText?.(t)??s,snapshotMeta:i.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(u){console.error("[StarredSync] Failed to create favorite:",u)}}async function deleteFavorite(r,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(r){return{afterUpdate:async(e,t,n)=>{if(!("starred"in n))return;const a=t.starred,i=t["@id"]||t.id;a?await createFavorite(e,r,t):await deleteFavorite(e,i)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:r=>r.title||"未命名对话",getContent:r=>r.lastMessagePreview},threadSnapshotExtractor={getTitle:r=>r.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(r,e,t){return t===void 0?void 0:eq(r[e],t)}function combineFilters(r){const e=r.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(r){if(r)return combineFilters([exactFilter(candidateExactFilterColumns,"source",r.source),exactFilter(candidateExactFilterColumns,"suggestedType",r.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",r.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",r.status),exactFilter(candidateExactFilterColumns,"chat",r.chat),exactFilter(candidateExactFilterColumns,"thread",r.thread),exactFilter(candidateExactFilterColumns,"task",r.task),exactFilter(candidateExactFilterColumns,"run",r.run)])}function captureEventListFilter(r){if(r)return combineFilters([exactFilter(eventExactFilterColumns,"source",r.source),exactFilter(eventExactFilterColumns,"captureCandidate",r.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",r.targetResource),exactFilter(eventExactFilterColumns,"decision",r.decision),exactFilter(eventExactFilterColumns,"approval",r.approval),exactFilter(eventExactFilterColumns,"inputRequest",r.inputRequest),exactFilter(eventExactFilterColumns,"chat",r.chat),exactFilter(eventExactFilterColumns,"thread",r.thread),exactFilter(eventExactFilterColumns,"task",r.task),exactFilter(eventExactFilterColumns,"run",r.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:r})=>captureCandidateListFilter(r)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:r})=>captureEventListFilter(r)});podTable("settings",{id:id("id").default((r,e)=>{const t=typeof e?.key=="string"?e.key:r;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$6.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});const inboxNotificationResource=podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$6.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(r){r.assertEqual=a=>{};function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t,r.arrayToEnum=a=>{const i={};for(const o of a)i[o]=o;return i},r.getValidEnumValues=a=>{const i=r.objectKeys(a).filter(s=>typeof a[a[s]]!="number"),o={};for(const s of i)o[s]=a[s];return r.objectValues(o)},r.objectValues=a=>r.objectKeys(a).map(function(i){return a[i]}),r.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const i=[];for(const o in a)Object.prototype.hasOwnProperty.call(a,o)&&i.push(o);return i},r.find=(a,i)=>{for(const o of a)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,i=" | "){return a.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(a,i)=>typeof i=="bigint"?i.toString():i})(util||(util={}));var objectUtil;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=r=>{switch(typeof r){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(r)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(r)?ZodParsedType.array:r===null?ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?ZodParsedType.map:typeof Set<"u"&&r instanceof Set?ZodParsedType.set:typeof Date<"u"&&r instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},n={_errors:[]},a=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(a);else if(o.code==="invalid_return_type")a(o.returnTypeError);else if(o.code==="invalid_arguments")a(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let s=n,d=0;for(;d<o.path.length;){const u=o.path[d];d===o.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(t(o))):s[u]=s[u]||{_errors:[]},s=s[u],d++}}};return a(this),n}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const a of this.issues)if(a.path.length>0){const i=a.path[0];t[i]=t[i]||[],t[i].push(e(a))}else n.push(e(a));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=r=>new ZodError(r);const errorMap=(r,e)=>{let t;switch(r.code){case ZodIssueCode.invalid_type:r.received===ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(r.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(r.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(r.options)}, received '${r.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(r)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=r=>{const{data:e,path:t,errorMaps:n,issueData:a}=r,i=[...t,...a.path||[]],o={...a,path:i};if(a.message!==void 0)return{...a,path:i,message:a.message};let s="";const d=n.filter(u=>!!u).slice().reverse();for(const u of d)s=u(o,{data:e,defaultError:s}).message;return{...a,path:i,message:s}};function addIssueToContext(r,e){const t=getErrorMap(),n=makeIssue({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(a=>!!a)});r.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const a of t){if(a.status==="aborted")return INVALID;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const a of t){const i=await a.key,o=await a.value;n.push({key:i,value:o})}return ParseStatus.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const a of t){const{key:i,value:o}=a;if(i.status==="aborted"||o.status==="aborted")return INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||a.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=r=>({status:"dirty",value:r}),OK=r=>({status:"valid",value:r}),isAborted=r=>r.status==="aborted",isDirty=r=>r.status==="dirty",isValid=r=>r.status==="valid",isAsync=r=>typeof Promise<"u"&&r instanceof Promise;var errorUtil;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,n,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(r,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(r.common.issues);return this._error=t,this._error}}};function processCreateParams(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:a}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(o,s)=>{const{message:d}=r;return o.code==="invalid_enum_value"?{message:d??s.defaultError}:typeof s.data>"u"?{message:d??n??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:d??t??s.defaultError}},description:a}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},a=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return isValid(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>isValid(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},a=this._parse({data:e,path:n.path,parent:n}),i=await(isAsync(a)?a:Promise.resolve(a));return handleResult(n,i)}refine(e,t){const n=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,i)=>{const o=e(a),s=()=>i.addIssue({code:ZodIssueCode.custom,...n(a)});return typeof Promise<"u"&&o instanceof Promise?o.then(d=>d?!0:(s(),!1)):o?!0:(s(),!1)})}refinement(e,t){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof t=="function"?t(n,a):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(r){return new RegExp(`^${timeRegexSource(r)}$`)}function datetimeRegex(r){let e=`${dateRegexSource}T${timeRegexSource(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(r,e){return!!((e==="v4"||!e)&&ipv4Regex.test(r)||(e==="v6"||!e)&&ipv6Regex.test(r))}function isValidJWT(r,e){if(!jwtRegex.test(r))return!1;try{const[t]=r.split(".");if(!t)return!1;const n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function isValidCidr(r,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(r)||(e==="v6"||!e)&&ipv6CidrRegex.test(r))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:i.parsedType}),INVALID}const n=new ParseStatus;let a;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,s=e.data.length<i.value;(o||s)&&(a=this._getOrReturnCtx(e,a),o?addIssueToContext(a,{code:ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&addIssueToContext(a,{code:ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")emailRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"email",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"emoji",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")uuidRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"uuid",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")nanoidRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")cuidRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"cuid",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")cuid2Regex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")ulidRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"ulid",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"url",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"regex",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?datetimeRegex(i).test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?dateRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?timeRegex(i).test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?durationRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"duration",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?isValidIP(e.data,i.version)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"ip",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?isValidJWT(e.data,i.alg)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"jwt",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?isValidCidr(e.data,i.version)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"cidr",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?base64Regex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"base64",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?base64urlRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"base64url",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(a=>e.test(a),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=r=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:r?.coerce??!1,...processCreateParams(r)});function floatSafeRemainder(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=t>n?t:n,i=Number.parseInt(r.toFixed(a).replace(".","")),o=Number.parseInt(e.toFixed(a).replace(".",""));return i%o/10**a}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:i.parsedType}),INVALID}let n;const a=new ParseStatus;for(const i of this._def.checks)i.kind==="int"?util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),a.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="multipleOf"?floatSafeRemainder(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_finite,message:i.message}),a.dirty()):util.assertNever(i);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,n,a){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:errorUtil.toString(a)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=r=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:r?.coerce||!1,...processCreateParams(r)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let n;const a=new ParseStatus;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):util.assertNever(i);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,n,a){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:errorUtil.toString(a)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=r=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:r?.coerce??!1,...processCreateParams(r)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=r=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:r?.coerce||!1,...processCreateParams(r)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:i.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_date}),INVALID}const n=new ParseStatus;let a;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=r=>new ZodDate({checks:[],coerce:r?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(r)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=r=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(r)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=r=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(r)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=r=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(r)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=r=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(r)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=r=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(r)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=r=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(r)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=r=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(r)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),a=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(a.exactLength!==null){const o=t.data.length>a.exactLength.value,s=t.data.length<a.exactLength.value;(o||s)&&(addIssueToContext(t,{code:o?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:s?a.exactLength.value:void 0,maximum:o?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),n.dirty())}if(a.minLength!==null&&t.data.length<a.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,s)=>a.type._parseAsync(new ParseInputLazyPath(t,o,t.path,s)))).then(o=>ParseStatus.mergeArray(n,o));const i=[...t.data].map((o,s)=>a.type._parseSync(new ParseInputLazyPath(t,o,t.path,s)));return ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(r,e)=>new ZodArray({type:r,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(r){if(r instanceof ZodObject){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...r._def,shape:()=>e})}else return r instanceof ZodArray?new ZodArray({...r._def,type:deepPartialify(r.element)}):r instanceof ZodOptional?ZodOptional.create(deepPartialify(r.unwrap())):r instanceof ZodNullable?ZodNullable.create(deepPartialify(r.unwrap())):r instanceof ZodTuple?ZodTuple.create(r.items.map(e=>deepPartialify(e))):r}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const u=this._getOrReturnCtx(e);return addIssueToContext(u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:u.parsedType}),INVALID}const{status:n,ctx:a}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const u in a.data)o.includes(u)||s.push(u);const d=[];for(const u of o){const c=i[u],p=a.data[u];d.push({key:{status:"valid",value:u},value:c._parse(new ParseInputLazyPath(a,p,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof ZodNever){const u=this._def.unknownKeys;if(u==="passthrough")for(const c of s)d.push({key:{status:"valid",value:c},value:{status:"valid",value:a.data[c]}});else if(u==="strict")s.length>0&&(addIssueToContext(a,{code:ZodIssueCode.unrecognized_keys,keys:s}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const c of s){const p=a.data[c];d.push({key:{status:"valid",value:c},value:u._parse(new ParseInputLazyPath(a,p,a.path,c)),alwaysSet:c in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const u=[];for(const c of d){const p=await c.key,_=await c.value;u.push({key:p,value:_,alwaysSet:c.alwaysSet})}return u}).then(u=>ParseStatus.mergeObjectSync(n,u)):ParseStatus.mergeObjectSync(n,d)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{const a=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const n of util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const n of util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const n of util.objectKeys(this.shape)){const a=this.shape[n];e&&!e[n]?t[n]=a:t[n]=a.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const n of util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ZodOptional;)i=i._def.innerType;t[n]=i}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(r,e)=>new ZodObject({shape:()=>r,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(r,e)=>new ZodObject({shape:()=>r,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(r,e)=>new ZodObject({shape:r,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function a(i){for(const s of i)if(s.result.status==="valid")return s.result;for(const s of i)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;const o=i.map(s=>new ZodError(s.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}if(t.common.async)return Promise.all(n.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(a);{let i;const o=[];for(const d of n){const u={...t,common:{...t.common,issues:[]},parent:null},c=d._parseSync({data:t.data,path:t.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!i&&(i={result:c,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const s=o.map(d=>new ZodError(d));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(r,e)=>new ZodUnion({options:r,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(r,e){const t=getParsedType(r),n=getParsedType(e);if(r===e)return{valid:!0,data:r};if(t===ZodParsedType.object&&n===ZodParsedType.object){const a=util.objectKeys(e),i=util.objectKeys(r).filter(s=>a.indexOf(s)!==-1),o={...r,...e};for(const s of i){const d=mergeValues(r[s],e[s]);if(!d.valid)return{valid:!1};o[s]=d.data}return{valid:!0,data:o}}else if(t===ZodParsedType.array&&n===ZodParsedType.array){if(r.length!==e.length)return{valid:!1};const a=[];for(let i=0;i<r.length;i++){const o=r[i],s=e[i],d=mergeValues(o,s);if(!d.valid)return{valid:!1};a.push(d.data)}return{valid:!0,data:a}}else return t===ZodParsedType.date&&n===ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),a=(i,o)=>{if(isAborted(i)||isAborted(o))return INVALID;const s=mergeValues(i.value,o.value);return s.valid?((isDirty(i)||isDirty(o))&&t.dirty(),{status:t.value,value:s.data}):(addIssueToContext(n,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>a(i,o)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ZodIntersection.create=(r,e,t)=>new ZodIntersection({left:r,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((o,s)=>{const d=this._def.items[s]||this._def.rest;return d?d._parse(new ParseInputLazyPath(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ParseStatus.mergeArray(t,o)):ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:r,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.object)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:n.parsedType}),INVALID;const a=[],i=this._def.keyType,o=this._def.valueType;for(const s in n.data)a.push({key:i._parse(new ParseInputLazyPath(n,s,n.path,s)),value:o._parse(new ParseInputLazyPath(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?ParseStatus.mergeObjectAsync(t,a):ParseStatus.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(n)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.map)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:n.parsedType}),INVALID;const a=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([s,d],u)=>({key:a._parse(new ParseInputLazyPath(n,s,n.path,[u,"key"])),value:i._parse(new ParseInputLazyPath(n,d,n.path,[u,"value"]))}));if(n.common.async){const s=new Map;return Promise.resolve().then(async()=>{for(const d of o){const u=await d.key,c=await d.value;if(u.status==="aborted"||c.status==="aborted")return INVALID;(u.status==="dirty"||c.status==="dirty")&&t.dirty(),s.set(u.value,c.value)}return{status:t.value,value:s}})}else{const s=new Map;for(const d of o){const u=d.key,c=d.value;if(u.status==="aborted"||c.status==="aborted")return INVALID;(u.status==="dirty"||c.status==="dirty")&&t.dirty(),s.set(u.value,c.value)}return{status:t.value,value:s}}}}ZodMap.create=(r,e,t)=>new ZodMap({valueType:e,keyType:r,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.set)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:n.parsedType}),INVALID;const a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const i=this._def.valueType;function o(d){const u=new Set;for(const c of d){if(c.status==="aborted")return INVALID;c.status==="dirty"&&t.dirty(),u.add(c.value)}return{status:t.value,value:u}}const s=[...n.data.values()].map((d,u)=>i._parse(new ParseInputLazyPath(n,d,n.path,u)));return n.common.async?Promise.all(s).then(d=>o(d)):o(s)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(r,e)=>new ZodSet({valueType:r,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(r,e)=>new ZodLazy({getter:r,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(r,e)=>new ZodLiteral({value:r,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(r,e){return new ZodEnum({values:r,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{expected:util.joinValues(n),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:n}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ZodParsedType.string&&n.parsedType!==ZodParsedType.number){const a=util.objectValues(t);return addIssueToContext(n,{expected:util.joinValues(a),received:n.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=util.objectValues(t);return addIssueToContext(n,{received:n.data,code:ZodIssueCode.invalid_enum_value,options:a}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(r,e)=>new ZodNativeEnum({values:r,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const n=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(n.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(r,e)=>new ZodPromise({type:r,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:o=>{addIssueToContext(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),a.type==="preprocess"){const o=a.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async s=>{if(t.value==="aborted")return INVALID;const d=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return d.status==="aborted"?INVALID:d.status==="dirty"||t.value==="dirty"?DIRTY(d.value):d});{if(t.value==="aborted")return INVALID;const s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?INVALID:s.status==="dirty"||t.value==="dirty"?DIRTY(s.value):s}}if(a.type==="refinement"){const o=s=>{const d=a.refinement(s,i);if(n.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?INVALID:(s.status==="dirty"&&t.dirty(),o(s.value),{status:t.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?INVALID:(s.status==="dirty"&&t.dirty(),o(s.value).then(()=>({status:t.value,value:s.value}))))}if(a.type==="transform")if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(o))return INVALID;const s=a.transform(o.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>isValid(o)?Promise.resolve(a.transform(o.value,i)).then(s=>({status:t.value,value:s})):INVALID);util.assertNever(a)}}ZodEffects.create=(r,e,t)=>new ZodEffects({schema:r,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(r,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:r},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(r,e)=>new ZodOptional({innerType:r,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(r,e)=>new ZodNullable({innerType:r,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(r,e)=>new ZodDefault({innerType:r,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(a)?a.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(r,e)=>new ZodCatch({innerType:r,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=r=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(r)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?INVALID:i.status==="dirty"?(t.dirty(),DIRTY(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?INVALID:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),n=a=>(isValid(a)&&(a.value=Object.freeze(a.value)),a);return isAsync(t)?t.then(a=>n(a)):n(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(r,e)=>new ZodReadonly({innerType:r,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$6.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel},modelClassAliases={chat:"chat",language:"chat",embedding:"embedding",embeddings:"embedding",document_understanding:"document_understanding",rerank:"reranking",reranker:"reranking",reranking:"reranking",image:"image_generation",image_generation:"image_generation",transcription:"speech_recognition",speech_recognition:"speech_recognition",text_to_speech:"speech_synthesis",speech_synthesis:"speech_synthesis",video:"video_generation",video_generation:"video_generation"},AI_MODEL_CLASS_DEFAULT_CAPABILITY={[AI_MODEL_CLASS.chat]:AI_MODEL_CAPABILITY.chat,[AI_MODEL_CLASS.embedding]:AI_MODEL_CAPABILITY.embedding,[AI_MODEL_CLASS.document_understanding]:AI_MODEL_CAPABILITY.document_understanding,[AI_MODEL_CLASS.reranking]:AI_MODEL_CAPABILITY.reranking,[AI_MODEL_CLASS.image_generation]:AI_MODEL_CAPABILITY.image_generation,[AI_MODEL_CLASS.speech_recognition]:AI_MODEL_CAPABILITY.speech_recognition,[AI_MODEL_CLASS.speech_synthesis]:AI_MODEL_CAPABILITY.speech_synthesis,[AI_MODEL_CLASS.video_generation]:AI_MODEL_CAPABILITY.video_generation};new Set(AI_MODEL_MODALITIES);const capabilitySet=new Set(AI_MODEL_CAPABILITIES),capabilityUriSet=new Set(Object.values(AI_MODEL_CAPABILITY)),capabilityNameByUri=new Map(Object.entries(AI_MODEL_CAPABILITY).map(([r,e])=>[e,r])),classNameByUri=new Map(Object.entries(AI_MODEL_CLASS).map(([r,e])=>[e,r])),legacyCapabilityAliases={function_calling:"tool_call",function_call:"tool_call",rerank:"reranking",document:"document_understanding","document-parse":"document_understanding"};function toAIModelClassUri(r){if(r==null)return AI_MODEL_CLASS.chat;if(typeof r=="string"&&Object.values(AI_MODEL_CLASS).includes(r))return r;const e=typeof r=="string"?modelClassAliases[r.trim().toLowerCase()]:void 0;return e?AI_MODEL_CLASS[e]:void 0}function isAIModelCapability(r){return typeof r=="string"&&capabilitySet.has(r)}function isAIModelCapabilityUri(r){return typeof r=="string"&&capabilityUriSet.has(r)}function toAIModelCapabilityUri(r){if(isAIModelCapabilityUri(r))return r;if(typeof r!="string")return;const e=legacyCapabilityAliases[r]??r;return isAIModelCapability(e)?AI_MODEL_CAPABILITY[e]:void 0}function toAIModelCapabilityName(r){return typeof r=="string"?capabilityNameByUri.get(r):void 0}function toAIModelClassName(r){const e=Array.isArray(r)?r:[r];for(const t of e){if(typeof t!="string")continue;const n=classNameByUri.get(t);if(n)return n}return"chat"}function filterAIModelCapabilityUris(r){return Array.isArray(r)?[...new Set(r.map(toAIModelCapabilityUri).filter(e=>!!e))]:[]}function withAIModelClassDefaultCapabilities(r){const e=Array.isArray(r.rdfType)?r.rdfType:[r.rdfType],t=filterAIModelCapabilityUris(r.capabilities);for(const n of e){if(typeof n!="string")continue;const a=AI_MODEL_CLASS_DEFAULT_CAPABILITY[n];a&&t.push(a)}return{...r,capabilities:[...new Set(t)]}}podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(r){const e=r;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const n of Object.values(t??{}))typeof n.options?.predicate=="string"&&(n.getPredicate=()=>n.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(r=>[r.id,r]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(r){return r.trim().toLowerCase()}function normalizeAIConfigResourceId(r){if(!r)return"";const e=r.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),n=t.split("/").pop()||t;return n.endsWith(".ttl")?n.slice(0,-4):n}function aiConfigResourceRefToModelId(r,e){return normalizeAIConfigModelId(r,e)}function normalizeAIConfigModelId(r,e){const t=normalizeAIConfigResourceId(r);if(!t.includes("/"))return t;const[n,...a]=t.split("/");return a.length===0||!e?t:normalizeAIConfigProviderId(n)===normalizeAIConfigProviderId(e)?a.join("/"):t}function normalizeAIConfigProviderId(r){const e=normalizeText(normalizeAIConfigResourceId(r));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(r,e){return aiConfigResourceRefToModelId(r,e)}function buildAIConfigModelStorageId(r,e){return aiModelResource.buildId({id:e,isProvidedBy:aiConfigProviderRef(r)})}function aiConfigProviderRef(r){const e=normalizeAIConfigProviderId(r);return e&&`settings/providers/${aiProviderResource.buildId({id:e})}`}function aiConfigModelRef(r,e){if(e===void 0)return normalizeAIConfigResourceId(r);const t=normalizeAIConfigProviderId(r),n=normalizeAIConfigModelStorageId(e,t);return t&&n?`settings/providers/${buildAIConfigModelStorageId(t,n)}`:n}function definePodModelDescriptor(r){return r}const credentialDescriptor={uri:UDFS.Credential,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Credential,resourceKind:"credential",description:"Generic credential material required by runtimes, tools, MCP servers, and providers.",storage:{base:"/settings/credentials.ttl",resourceIdPattern:"#{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative credential row id. Every credential in a provider pool keeps its own id."},provider:{type:"uri",predicate:UDFS.provider,references:{resource:"provider",key:"id"},description:"Provider resource URI this credential connects through, as a URI relation to the provider row."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},offeringId:{type:"string",predicate:UDFS.offeringId,description:"Offering id this credential connects through. Offerings are catalog content, so this stays a plain attribute, not a relation."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},storageMode:{type:"string",predicate:UDFS.storageMode,description:"Credential storage format, for example plaintext-v1 or secret-cell-v1."},secretPayload:{type:"string",predicate:UDFS.secretPayload,secret:!0,description:"Storage-mode-specific credential payload. plaintext-v1 stores a JSON payload here."},encryptedSecret:{type:"string",predicate:UDFS.encryptedSecret,secret:!0,description:"Encrypted credential payload stored in the Pod."},wrappedDataKey:{type:"string",predicate:UDFS.wrappedDataKey,secret:!0,description:"Wrapped data-encryption key for encrypted credential payloads."},encryptionAlgorithm:{type:"string",predicate:UDFS.encryptionAlgorithm,description:"Credential encryption algorithm identifier."},keyVersion:{type:"string",predicate:UDFS.keyVersion,description:"Key-management version used to encrypt the credential."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Credential scopes granted by the provider."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Credential expiry timestamp."},accountLabel:{type:"string",predicate:UDFS.accountLabel,description:"Provider account label associated with the credential."},lastRefreshAt:{type:"timestamp",predicate:UDFS.lastRefreshAt,description:"Last successful credential refresh timestamp."},reauthRequired:{type:"boolean",predicate:UDFS.reauthRequired,description:"Whether this credential requires user reauthentication."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL recorded on the credential."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for requests made with this credential."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},isDefault:{type:"boolean",predicate:UDFS.isDefault,description:"Whether this credential is the default credential for its provider."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp, set by the store."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful use timestamp."},clientCredentialId:{type:"string",predicate:UDFS.clientCredentialId,description:"Client the issued credential belongs to. An external runtime identifier, not an RDF link."},appliedTo:{type:"string",predicate:UDFS.appliedTo,description:"Client application id the credential is in effect for. A runtime identifier, not an RDF link."},appliedOn:{type:"string",predicate:UDFS.appliedOn,description:"Device id that wrote the applied configuration. A runtime identifier, not an RDF link."},appliedAt:{type:"timestamp",predicate:UDFS.appliedAt,description:"Timestamp when the credential was applied."},failCount:{type:"number",predicate:UDFS.failCount,description:"Failed use count recorded for the credential."},rateLimitResetAt:{type:"timestamp",predicate:UDFS.rateLimitResetAt,description:"Timestamp when the provider rate limit is expected to reset."},lastFailureCode:{type:"string",predicate:UDFS.lastFailureCode,description:"Stable credential failure category. No upstream response body or secret."},lastFailureAt:{type:"timestamp",predicate:UDFS.lastFailureAt,description:"Time when the most recent credential failure was observed."},oauthRefreshToken:{type:"string",predicate:UDFS.oauthRefreshToken,secret:!0,description:"OAuth refresh token."},oauthAccessToken:{type:"string",predicate:UDFS.oauthAccessToken,secret:!0,description:"OAuth access token."},oauthExpiresAt:{type:"timestamp",predicate:UDFS.oauthExpiresAt,description:"OAuth access token expiry timestamp."},projectId:{type:"string",predicate:UDFS.projectId,description:"Provider project identifier recorded for the credential."},organizationId:{type:"string",predicate:UDFS.organizationId,description:"Provider organization identifier recorded for the credential."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata bag; shared relations must be explicit fields."}},uniqueBy:["id"],writableFields:["provider","authMode","offeringId","service","status","apiKey","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","baseUrl","proxyUrl","label","isDefault","lastUsedAt","clientCredentialId","appliedTo","appliedOn","appliedAt","failCount","rateLimitResetAt","lastFailureCode","lastFailureAt","oauthRefreshToken","oauthAccessToken","oauthExpiresAt","projectId","organizationId","metadata"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{id:"cloudflare-5f2c9a1e"}},{request:"保存 OpenAI API key",match:{id:"openai-2b7d4e10"}}]},gatewayAccessKeyDescriptor={uri:UDFS.GatewayAccessKey,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.GatewayAccessKey,resourceKind:"gateway-access-key",description:"Control-primary Pod AI Gateway access key. The key owner is a semantic WebID/URI relation, while the secret itself is represented only by a hash.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/access-keys.ttl#key_1."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID or principal URI that owns this Gateway access key."},secretHash:{type:"string",predicate:UDFS.secretHash,required:!0,secret:!0,description:"Hash of the Gateway secret. Raw access key material must not be stored here."},name:{type:"string",predicate:UDFS.name,description:"User-visible label for distinguishing this Gateway access key."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment target: local or cloud."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Gateway scopes granted to this key."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Key expiry timestamp."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful Gateway use timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp. Presence means the key is no longer valid."},disabledAt:{type:"timestamp",predicate:UDFS.disabledAt,description:"Temporary disable timestamp. Clear it to enable the key again."}},uniqueBy:["id"],writableFields:["owner","secretHash","name","deployment","scopes","createdAt","expiresAt","lastUsedAt","revokedAt","disabledAt"],mergePolicy:"upsert",examples:[{request:"Create a local Gateway access key for a user",match:{id:"ai/gateway/access-keys.ttl#key_1"}}]},quotaSnapshotDescriptor={uri:UDFS.QuotaSnapshot,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.QuotaSnapshot,resourceKind:"quota-snapshot",description:"Observed Pod AI Gateway quota state for a provider credential. The credential field is a semantic URI relation, and normalized windows are stored as a serialized literal.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/quota.ttl#quota_1."},credential:{type:"uri",predicate:UDFS.credential,references:{resource:"credential",key:"id"},required:!0,description:"Credential resource URI this quota snapshot describes."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID that owns the credential and quota snapshot."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment scope: local or cloud."},provider:{type:"string",predicate:UDFS.provider,required:!0,description:"Normalized provider id for the quota snapshot."},status:{type:"string",predicate:UDFS.status,required:!0,description:"Quota availability status: available, unsupported, or error."},balance:{type:"number",predicate:UDFS.balance,description:"Normalized remaining quota balance when the provider exposes one."},windows:{type:"text",predicate:UDFS.windows,description:"Serialized normalized quota windows literal, for example JSON produced by Gateway normalization."},observedAt:{type:"timestamp",predicate:UDFS.observedAt,description:"Observation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Snapshot freshness expiry timestamp."},source:{type:"string",predicate:UDFS.source,description:"Observation source such as provider, gateway-cache, or manual."}},uniqueBy:["id"],writableFields:["credential","status","balance","windows","observedAt","expiresAt","source"],mergePolicy:"upsert",examples:[{request:"Record a fresh quota snapshot for a provider credential",match:{id:"ai/gateway/quota.ttl#quota_1"}}]},aiProviderDescriptor={uri:UDFS.Provider,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Provider,resourceKind:"provider",description:"AI provider endpoint configured in the Pod: endpoint, proxy, console entry, backend support, and the models it exposes. Its model rows live in the same provider document and are linked from here through hasModel.",storage:{base:"/settings/providers/",resourceIdPattern:"{key}.ttl"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative provider row id, for example openai.ttl."},displayName:{type:"string",predicate:UDFS.displayName,description:"Provider display name stored on the provider row."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for provider requests."},homepage:{type:"string",predicate:UDFS.homepage,description:"Provider homepage URL."},apiKeyUrl:{type:"string",predicate:UDFS.apiKeyUrl,description:"URL where a user creates an API key for this provider."},connectMode:{type:"string",predicate:UDFS.connectMode,description:"Connection mode recorded for the provider authorization method."},hasModel:{type:"uri",predicate:UDFS.hasModel,references:{resource:"ai-model",key:"id"},array:!0,description:"Model rows this provider exposes, as subjects inside the provider document."},defaultModel:{type:"uri",predicate:UDFS.defaultModel,references:{resource:"ai-model",key:"id"},description:"Default model for this provider when a request does not select one."},supportsBackend:{type:"string",predicate:UDFS.supportsBackend,description:"Backends this provider can serve, read as a backend list by the AI config selector."},capabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Provider capability tags."},rotationPolicy:{type:"string",predicate:UDFS.rotationPolicy,description:"Credential rotation policy recorded for the provider."}},uniqueBy:["id"],writableFields:["displayName","baseUrl","proxyUrl","homepage","apiKeyUrl","connectMode","hasModel","defaultModel","supportsBackend","capabilities","rotationPolicy"],mergePolicy:"upsert",examples:[{request:"Describe the provider document a Pod AI connection writes",match:{id:"openai.ttl"}}]},aiModelDescriptor={uri:UDFS.AIModel,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AIModel,resourceKind:"ai-model",description:"AI model exposed by a provider, stored as a subject inside that provider document. The provider relation and model capabilities are URI facts, while pricing and modality facts stay literals.",storage:{base:"/settings/providers/",resourceIdPattern:"{isProvidedBy.doc}#{key}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative model row id: provider document plus model key, for example openai.ttl#gpt-4o."},rdfType:{type:"uri",predicate:RDF$6.type,array:!0,description:"RDF class of the model row. The base table defaults to AIModel, and subclass tables narrow it."},displayName:{type:"string",predicate:UDFS.displayName,description:"Model display name stored on the model row."},isProvidedBy:{type:"uri",predicate:UDFS.isProvidedBy,references:{resource:"provider",key:"id"},description:"Provider document this model row belongs to, as a URI relation to the provider row."},inputModalities:{type:"text",predicate:UDFS.inputModality,array:!0,description:"Input modalities the model accepts."},outputModalities:{type:"text",predicate:UDFS.outputModality,array:!0,description:"Output modalities the model produces."},runtimeCapabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Adapter/runtime endpoint capabilities, kept separate from semantic model capabilities."},capabilities:{type:"uri",predicate:UDFS.hasCapability,array:!0,description:"Semantic capabilities of the model, as URIs."},pricingInput:{type:"number",predicate:UDFS.pricingInput,description:"Input token price recorded for the model."},pricingOutput:{type:"number",predicate:UDFS.pricingOutput,description:"Output token price recorded for the model."},status:{type:"string",predicate:UDFS.status,description:"Model availability status."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp, set by the store."},updatedAt:{type:"timestamp",predicate:UDFS.updatedAt,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["displayName","isProvidedBy","inputModalities","outputModalities","runtimeCapabilities","capabilities","pricingInput","pricingOutput","status","updatedAt"],mergePolicy:"upsert",examples:[{request:"Describe a model row inside a provider document",match:{id:"openai.ttl#gpt-4o"}}]},approvalDescriptor={uri:UDFS.ApprovalRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ApprovalRequest,resourceKind:"approval",description:"Durable approval request control item. Solid inbox notifications may point at this resource, but lifecycle and claim state live here.",storage:{base:"/.data/approvals/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Approval request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource that requested approval."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},toolCallId:{type:"string",predicate:UDFS.toolCallId,required:!0,description:"Opaque runtime tool-call identifier; not an RDF resource link."},toolName:{type:"string",predicate:UDFS.toolName,required:!0,description:"Runtime tool name that requires approval."},target:{type:"uri",predicate:ODRL.target,required:!0,description:"Target resource for the requested action. Schema field uses ODRL target in the executable resource."},action:{type:"uri",predicate:ODRL.action,required:!0,description:"Requested action URI. Schema field uses ODRL action in the executable resource."},risk:{type:"string",predicate:UDFS.risk,required:!0,description:"Risk level assigned by the runtime or policy layer."},status:{type:"string",predicate:UDFS.status,description:"Approval lifecycle status such as pending, handling, approved, rejected, resolved, or expired."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/approval handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to decide the request."},decisionBy:{type:"uri",predicate:UDFS.decisionBy,description:"WebID or agent resource that made the decision."},decisionRole:{type:"string",predicate:UDFS.decisionRole,description:"Role of the decision maker, for example human or secretary."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the decision applies."},reason:{type:"text",predicate:UDFS.reason,description:"Decision reason or policy explanation."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},approvalOptions:{type:"text",predicate:UDFS.approvalOptions,description:"Serialized approval options offered by the runtime."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version used to create or resolve this approval."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Decision timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","toolCallId","toolName","target","action","risk","status","leaseOwner","leaseExpiresAt","assignedTo","decisionBy","decisionRole","onBehalfOf","reason","context","approvalOptions","policyVersion","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending approval from Inbox subscription",match:{id:"2026/06/12.ttl#approval_1"}}]},inputRequestDescriptor={uri:UDFS.InputRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.InputRequest,resourceKind:"input-request",description:"Durable input request control item. It asks for missing information or a choice; approval/authority decisions remain ApprovalRequest.",storage:{base:"/.data/input-requests/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Input request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource waiting for input."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(r="/.data/"){return{base:r,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that created the candidate."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["source","summary","suggestedType","suggestedTarget","confidence","reason","status","sourceHash","chat","thread","task","run","actor","metadata","updatedAt"],mergePolicy:"upsert",examples:[{request:"Create a capture candidate from an observed chat message",match:{id:"candidates/2026/06/16.ttl#candidate_1"}}]},captureEventDescriptor={uri:UDFS.CaptureEvent,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureEvent,resourceKind:"capture-event",description:"Append-only capture decision ledger. It records direct commits, optimistic commits, candidate creation, promotion, rejection, correction, rollback, duplicate detection, and ignored decisions.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource considered by capture."},captureCandidate:{type:"uri",predicate:UDFS.captureCandidate,references:{resource:"capture-candidate",key:"id"},description:"Candidate resource involved in this event, when applicable."},targetResource:{type:"uri",predicate:UDFS.targetResource,description:"Formal resource affected by this capture decision."},decision:{type:"string",predicate:UDFS.captureDecision,required:!0,description:"Decision such as direct_commit, optimistic_commit, candidate_created, promoted, rejected, corrected, rollback, duplicate, or ignored."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Type suggested at decision time."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Target suggested at decision time."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence at decision time."},reason:{type:"text",predicate:UDFS.reason,description:"Explanation for the capture decision."},userCorrection:{type:"text",predicate:UDFS.userCorrection,description:"User correction to type, target, title, summary, or content."},approval:{type:"uri",predicate:UDFS.approval,references:{resource:"approval",key:"id"},description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,references:{resource:"input-request",key:"id"},description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$6.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,references:{resource:"contact",key:"id"},description:"Optional counterpart/contact represented by this channel."},participants:{type:"uri",predicate:WF.participant,array:!0,description:"Participant resource URIs."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},lastActiveAt:{type:"timestamp",predicate:UDFS.lastActiveAt,description:"Last activity timestamp."},lastMessage:{type:"uri",predicate:UDFS.lastMessage,description:"Latest message pointer."},lastMessagePreview:{type:"text",predicate:SCHEMA.text,description:"Latest message preview."}},uniqueBy:["id"],writableFields:["title","description","avatarUrl","author","status","starred","muted","unreadCount","contact","participants","metadata","lastActiveAt","lastMessage","lastMessagePreview"],mergePolicy:"upsert",examples:[{request:"Create a team chat surface",match:{id:"team/index.ttl#this"}}]},threadDescriptor={uri:SIOC.Thread,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:SIOC.Thread,resourceKind:"thread",description:"Concrete timeline/place under one parent command surface. Ownership is thread.parent via sioc:has_parent.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container."},title:{type:"string",predicate:DCTerms.title,description:"Thread title."},status:{type:"string",predicate:UDFS.status,description:"Thread lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},workspace:{type:"uri",predicate:UDFS.workspace,description:"Storage-layer workspace/container URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."}},uniqueBy:["id"],writableFields:["parent","title","status","starred","workspace","metadata"],mergePolicy:"upsert",examples:[{request:"Create a thread under a chat surface",match:{id:"chat/team/index.ttl#thread"}}]},messageDescriptor={uri:MEETING.Message,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.Message,resourceKind:"message",description:"Human/runtime communication item under one parent command surface and optionally a concrete thread timeline.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container URI."},chat:{type:"uri",predicate:WF.message,references:{resource:"chat",key:"id"},description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,references:{resource:"thread",key:"id"},description:"Thread containment relation."},maker:{type:"uri",predicate:FOAF.maker,description:"Author resource IRI."},role:{type:"string",predicate:UDFS.messageType,description:"Message role."},content:{type:"text",predicate:SIOC.content,required:!0,description:"Plain text content."},richContent:{type:"text",predicate:SIOC.richContent,description:"Structured/rich content payload."},status:{type:"string",predicate:UDFS.messageStatus,description:"Message lifecycle status."},toolName:{type:"string",predicate:UDFS.toolName,description:"Tool name for tool messages."},toolCallId:{type:"string",predicate:UDFS.toolCallId,description:"Opaque tool call id; not a resource relation."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},replacedBy:{type:"string",predicate:DCTerms.isReplacedBy,description:"Replacement message reference."},deletedAt:{type:"timestamp",predicate:SCHEMA.dateDeleted,description:"Deletion timestamp."},senderName:{type:"string",predicate:UDFS.senderName,description:"Display sender name."},senderAvatarUrl:{type:"uri",predicate:UDFS.senderAvatarUrl,description:"Display sender avatar."},mentions:{type:"uri",predicate:UDFS.mentions,array:!0,description:"Mentioned resource URIs."},replyTo:{type:"uri",predicate:UDFS.replyTo,description:"Original message URI."},routedBy:{type:"uri",predicate:UDFS.routedBy,description:"Routing agent URI."},routeTargetAgent:{type:"uri",predicate:UDFS.routeTargetAgent,description:"Target agent URI."},coordinationId:{type:"string",predicate:UDFS.coordinationId,description:"Opaque multi-agent coordination id."}},uniqueBy:["id"],writableFields:["parent","chat","thread","maker","role","content","richContent","status","toolName","toolCallId","metadata","replacedBy","deletedAt","senderName","senderAvatarUrl","mentions","replyTo","routedBy","routeTargetAgent","coordinationId"],mergePolicy:"append",examples:[{request:"Append a message under a team chat",match:{id:"chat/team/2026/06/14/messages.ttl#msg_1"}}]},chatProjectContextDescriptor={uri:UDFS.ChatProjectContext,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ChatProjectContext,resourceKind:"chat-project-context",description:"Workspace-scoped instructions and explicit memory-use preference shared by related chat threads.",storage:exactIdStorage("/.data/chat-projects/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this context."},instructions:{type:"text",predicate:UDFS.systemMessage,description:"User-maintained project instructions."},memoryEnabled:{type:"boolean",predicate:UDFS.memoryEnabled,description:"Whether explicit project memories may be injected into model context."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","instructions","memoryEnabled","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Save shared instructions for a workspace",match:{id:"workspace-key.ttl"}}]},chatProjectMemoryDescriptor={uri:UDFS.ProjectMemory,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ProjectMemory,resourceKind:"chat-project-memory",description:"One user-approved, workspace-scoped memory entry with optional message provenance.",storage:exactIdStorage("/.data/chat-project-memories/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this memory."},text:{type:"text",predicate:SCHEMA.text,required:!0,description:"Explicit memory text."},sourceMessage:{type:"uri",predicate:UDFS.sourceMessage,description:"Optional source message URI."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","text","sourceMessage","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Remember an explicit project fact",match:{id:"memory-id.ttl"}}]},conversationShareDescriptor={uri:UDFS.ConversationShare,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ConversationShare,resourceKind:"conversation-share",description:"Revocable metadata record for a sanitized, read-only conversation export.",storage:exactIdStorage("/.data/chat-shares/"),fields:{id:idField,thread:{type:"uri",predicate:UDFS.targetThread,required:!0,description:"Shared thread URI."},resourceUrl:{type:"uri",predicate:SCHEMA.url,required:!0,description:"Public read-only HTML resource URL."},includeToolDetails:{type:"boolean",predicate:UDFS.includeToolDetails,description:"Whether sanitized tool details were included."},excludedMessageIds:{type:"string",predicate:UDFS.excludedMessage,array:!0,description:"Messages excluded by the user before sharing."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp."}},uniqueBy:["id"],writableFields:["thread","resourceUrl","includeToolDetails","excludedMessageIds","createdAt","revokedAt"],mergePolicy:"upsert",examples:[{request:"Record a read-only conversation share",match:{id:"share-id.ttl"}}]},ideaDescriptor={uri:UDFS.Idea,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Idea,resourceKind:"idea",description:"File-primary candidate extracted from conversation before it is promoted to committed work. The document owns human-readable content; meta owns status and routing facts.",storage:exactIdStorage("/.data/ideas/"),fields:{id:idField,summary:{type:"string",predicate:DCTerms.abstract,required:!0,description:"Short summary of the idea."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the idea body."},input:{type:"text",predicate:DCTerms.description,description:"Original or synthesized input text."},status:{type:"string",predicate:UDFS.status,description:"Idea lifecycle status."},commitment:{type:"string",predicate:UDFS.commitment,description:"Commitment level such as thought, direction, tentative_decision, or committed."},affectedArea:{type:"string",predicate:UDFS.affectedArea,description:"System or product area the idea may affect."},currentUnderstanding:{type:"text",predicate:UDFS.currentUnderstanding,description:"Current synthesized understanding."},openQuestions:{type:"text",predicate:UDFS.openQuestions,array:!0,description:"Open questions before promotion."},related:{type:"uri",predicate:DCTerms.relation,array:!0,description:"Related control records or resources."},conflicts:{type:"text",predicate:UDFS.conflicts,array:!0,description:"Potential semantic conflicts."},nextStep:{type:"text",predicate:UDFS.nextStep,description:"Suggested next action."},promotedTo:{type:"uri",predicate:UDFS.promotedTo,description:"Committed resource created from the idea."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},sourceMessages:{type:"uri",predicate:DCTerms.source,array:!0,description:"Source messages."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["summary","document","input","status","commitment","affectedArea","currentUnderstanding","openQuestions","related","conflicts","nextStep","promotedTo","chat","thread","sourceMessages","createdBy","metadata"],mergePolicy:"upsert",examples:[{request:"Capture a fragmented product idea for later triage",match:{id:"2026/05/28.ttl#idea_symphony_quality_metrics"}}]},issueDescriptor={uri:UDFS.Issue,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Issue,resourceKind:"issue",description:"File-primary user-facing work item for a requirement, bug, support item, investigation, or feature request. The document owns human-readable content; meta owns status and routing facts.",storage:{base:"/.data/issues/",resourceIdPattern:"{id}"},fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Compact issue label for list/search surfaces; the file owns the full title/body."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the issue body."},description:{type:"text",predicate:DCTerms.description,description:"Issue description."},status:{type:"string",predicate:UDFS.status,description:"Issue lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Issue priority."},labels:{type:"text",predicate:UDFS.tags,array:!0,description:"Tags or labels."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,references:{resource:"issue",key:"id"},description:"Parent issue."},tasks:{type:"uri",predicate:UDFS.task,array:!0,description:"Executable task slices."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},closedAt:{type:"timestamp",predicate:UDFS.closedAt,description:"Closure timestamp."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."}},uniqueBy:["id"],writableFields:["title","document","description","status","priority","labels","chat","thread","parentIssue","tasks","createdBy","assignedTo","closedAt","deletedAt"],mergePolicy:"upsert",examples:[{request:"Create a Symphony issue for a delegated implementation slice",match:{id:"issue_symphony_runtime_projection.ttl"}}]},taskDescriptor={uri:UDFS.Task,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Task,resourceKind:"task",description:"Durable executable work unit. Scheduling, runner selection, and concrete attempts live outside Task.",storage:exactIdStorage("/.data/task/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,description:"Task title."},instruction:{type:"text",predicate:UDFS.instruction,required:!0,description:"Executable instruction."},prompt:{type:"text",predicate:UDFS.prompt,description:"Runtime prompt projection."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},dueAt:{type:"timestamp",predicate:UDFS.dueAt,description:"Deadline, independent of execution scheduling."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Time the task was completed."},notes:{type:"text",predicate:DCTerms.description,description:"User notes about the task."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","dueAt","completedAt","notes","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},required:!0,description:"Scheduled task."},status:{type:"string",predicate:UDFS.status,description:"Schedule lifecycle status."},scheduleKind:{type:"string",predicate:UDFS.scheduleKind,description:"Schedule kind: once, interval, or cron."},cron:{type:"string",predicate:UDFS.cron,description:"Cron expression."},intervalSeconds:{type:"number",predicate:UDFS.intervalSeconds,description:"Interval in seconds."},timezone:{type:"string",predicate:UDFS.timezone,description:"Timezone."},startsAt:{type:"timestamp",predicate:UDFS.startsAt,description:"Start timestamp."},nextRunAt:{type:"timestamp",predicate:UDFS.nextRunAt,description:"Next run timestamp."},lastRunAt:{type:"timestamp",predicate:UDFS.lastRunAt,description:"Last run timestamp."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["task","status","scheduleKind","cron","intervalSeconds","timezone","startsAt","nextRunAt","lastRunAt","metadata"],mergePolicy:"upsert",examples:[{request:"Create a time trigger for a task",match:{id:"schedules/schedule_1.ttl"}}]},automationRuleDescriptor={uri:UDFS.AutomationRule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AutomationRule,resourceKind:"automation_rule",description:"Policy, condition, and action wiring that can dispatch tasks or scheduled work.",storage:exactIdStorage(),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Rule title."},description:{type:"text",predicate:DCTerms.description,description:"Rule description."},status:{type:"string",predicate:UDFS.status,description:"Rule lifecycle status."},ruleKind:{type:"string",predicate:UDFS.ruleKind,description:"Rule kind: event, schedule, or manual."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,references:{resource:"schedule",key:"id"},description:"Schedule that triggers this rule."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},condition:{type:"json",predicate:UDFS.condition,description:"Structured condition."},actions:{type:"json",predicate:UDFS.actions,description:"Structured actions."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},lastTriggeredAt:{type:"timestamp",predicate:UDFS.lastTriggeredAt,description:"Last trigger timestamp."},lastRunStatus:{type:"string",predicate:UDFS.lastRunStatus,description:"Last run status."}},uniqueBy:["id"],writableFields:["title","description","status","ruleKind","task","schedule","source","target","condition","actions","metadata","lastTriggeredAt","lastRunStatus"],mergePolicy:"upsert",examples:[{request:"Create an automation rule that dispatches a task",match:{id:"automation/rule_1.ttl"}}]},deliveryDescriptor={uri:UDFS.Delivery,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Delivery,resourceKind:"delivery",description:"Internal handoff envelope between threads, sessions, agents, and runtimes.",storage:exactIdStorage(),fields:{id:idField,kind:{type:"string",predicate:UDFS.deliveryKind,description:"Delivery kind."},status:{type:"string",predicate:UDFS.status,description:"Delivery lifecycle status."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being delivered."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,references:{resource:"thread",key:"id"},description:"Target thread."},targetSession:{type:"uri",predicate:UDFS.targetSession,description:"Target session."},actor:{type:"uri",predicate:AS.actor,description:"Actor."},object:{type:"uri",predicate:AS.object,description:"Object resource."},objective:{type:"text",predicate:UDFS.objective,description:"Short objective."},payload:{type:"json",predicate:UDFS.payload,description:"Structured payload."},projection:{type:"json",predicate:UDFS.projection,description:"Runtime projection."},projectedRole:{type:"string",predicate:UDFS.projectedRole,description:"Projected runtime role."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},error:{type:"text",predicate:UDFS.error,description:"Failure detail."},dispatchedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Dispatch timestamp."},consumedAt:{type:"timestamp",predicate:UDFS.consumedAt,description:"Consumption timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["kind","status","task","source","target","chat","thread","targetThread","targetSession","actor","object","objective","payload","projection","projectedRole","metadata","error","dispatchedAt","consumedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Create a worker delivery package",match:{id:"task/symphony/2026/05/28/deliveries.ttl#delivery_1"}}]},runDescriptor={uri:UDFS.Run,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Run,resourceKind:"run",description:"One concrete execution attempt by an agent runtime.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Delivery that caused or carries this run."},trigger:{type:"uri",predicate:UDFS.trigger,description:"Resource that triggered the run."},input:{type:"uri",predicate:UDFS.input,description:"Concrete input/context projection resource."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},required:!0,description:"Runtime thread."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Run lifecycle status."},runner:{type:"string",predicate:UDFS.runner,required:!0,description:"Runtime implementation."},prompt:{type:"string",predicate:UDFS.prompt,description:"Prompt or prompt version."},externalRunId:{type:"string",predicate:UDFS.externalRunId,description:"Opaque external runtime id; not a resource relation."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Lease owner."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Lease expiration timestamp."},heartbeatAt:{type:"timestamp",predicate:UDFS.heartbeatAt,description:"Heartbeat timestamp."},cancelRequestedAt:{type:"timestamp",predicate:UDFS.cancelRequestedAt,description:"Cancel request timestamp."},error:{type:"string",predicate:UDFS.error,description:"Failure detail."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},startedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Start timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["task","delivery","trigger","input","thread","workspace","status","runner","prompt","externalRunId","leaseOwner","leaseExpiresAt","heartbeatAt","cancelRequestedAt","error","metadata","startedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Record a runtime execution attempt",match:{id:"task/symphony/2026/05/28/runs.ttl#run_1"}}]},runStepDescriptor={uri:UDFS.RunStep,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.RunStep,resourceKind:"run_step",description:"Append-only execution fact emitted while a run executes.",storage:exactIdStorage(),fields:{id:idField,run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},required:!0,description:"Run this step belongs to."},stepType:{type:"string",predicate:UDFS.stepType,required:!0,description:"RunStep event type."},message:{type:"string",predicate:DCTerms.description,description:"Human-readable step message."},payload:{type:"json",predicate:UDFS.payload,description:"Structured step payload."}},uniqueBy:["id"],writableFields:["run","stepType","message","payload"],mergePolicy:"append",examples:[{request:"Append a runtime tool call step",match:{id:"task/symphony/2026/05/28/runs.ttl#run-step_1"}}]},evidenceDescriptor={uri:UDFS.Evidence,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Evidence,resourceKind:"evidence",description:"Append-only proof or finding for a workflow control object.",storage:exactIdStorage(),fields:{id:idField,evidenceKind:{type:"string",predicate:UDFS.evidenceKind,required:!0,description:"Evidence kind."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object this evidence supports."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},summary:{type:"text",predicate:DCTerms.abstract,description:"Evidence summary."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the evidence."},outcome:{type:"string",predicate:UDFS.outcome,description:"Evidence outcome."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["evidenceKind","about","issue","task","delivery","run","thread","summary","source","actor","outcome","metadata"],mergePolicy:"append",examples:[{request:"Record test evidence for a task",match:{id:"task/symphony/2026/05/28/evidence.ttl#evidence_1"}}]},reportDescriptor={uri:UDFS.Report,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Report,resourceKind:"report",description:"Closure, review, handoff, status, or quality summary for a control object.",storage:exactIdStorage(),fields:{id:idField,reportKind:{type:"string",predicate:UDFS.reportKind,required:!0,description:"Report kind."},status:{type:"string",predicate:UDFS.status,description:"Report lifecycle status."},outcome:{type:"string",predicate:UDFS.outcome,description:"Reported outcome."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object being summarized."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,references:{resource:"evidence",key:"id"},array:!0,description:"Evidence summarized by this report."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Report summary."},reviewer:{type:"uri",predicate:SCHEMA.reviewedBy,description:"Reviewer."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the report."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},metricFacts:{type:"json",predicate:UDFS.metricFacts,description:"Structured metric facts."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},publishedAt:{type:"timestamp",predicate:DCTerms.issued,description:"Publication timestamp."}},uniqueBy:["id"],writableFields:["reportKind","status","outcome","about","issue","task","delivery","run","thread","evidence","summary","reviewer","actor","source","metricFacts","metadata","publishedAt"],mergePolicy:"upsert",examples:[{request:"Publish a worker handoff report",match:{id:"task/symphony/2026/05/28/reports.ttl#report_1"}}]},sessionDescriptor={uri:UDFS.term("Session"),version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.term("Session"),resourceKind:"session",description:"Runtime or collaboration session lifecycle projection for a concrete thread.",storage:exactIdStorage("/.data/sessions/"),fields:{id:idField,owner:{type:"uri",predicate:UDFS.actor,required:!0,description:"Session owner."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},status:{type:"string",predicate:UDFS.sessionStatus,description:"Session lifecycle status."},tool:{type:"string",predicate:UDFS.sessionTool,description:"Runtime tool or backend."},tokenUsage:{type:"number",predicate:UDFS.tokenUsage,description:"Token usage."},messages:{type:"uri",predicate:UDFS.message,array:!0,description:"Messages in this session."},policy:{type:"uri",predicate:UDFS.policy,description:"Policy resource."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},archivedAt:{type:"timestamp",predicate:UDFS.archivedAt,description:"Archive timestamp."}},uniqueBy:["id"],writableFields:["owner","chat","thread","status","tool","tokenUsage","messages","policy","policyVersion","metadata","archivedAt"],mergePolicy:"upsert",examples:[{request:"Record a worker runtime session",match:{id:"2026/05/28/sess_1.ttl"}}]},officialPodModelDescriptors=[credentialDescriptor,gatewayAccessKeyDescriptor,quotaSnapshotDescriptor,aiProviderDescriptor,aiModelDescriptor,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(r=officialPodModelDescriptors){const e=new Map(r.map(t=>[t.uri,t]));return{list(t={}){return r.filter(n=>!(t.source&&n.source!==t.source||t.resourceKind&&n.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(r=createPodModelDescriptorRegistry()){const e=(t={})=>{const n=t.uri??t.schemaUri;if(!n)return r.list();const a=r.describe(n);return a?[a]:[]};return{list:r.list,describe(t){const n=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return r.describe(n)},classes(t={}){return e(t).map(n=>({schemaUri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description}))},search(t){const n=normalizeSearchTerms(t.query);return n.length===0?[]:r.list({source:t.source,resourceKind:t.resourceKind}).map(a=>scoreDescriptorSearch(a,n)).filter(a=>a!==null).sort((a,i)=>i.score-a.score||a.uri.localeCompare(i.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(n=>Object.entries(n.fields).filter(([a])=>!t.field||a===t.field).map(([a,i])=>({schemaUri:n.uri,field:a,predicate:i.predicate,type:i.type,required:!!i.required,secret:!!i.secret,array:!!i.array,description:i.description})))}}}function normalizeSearchTerms(r){return r.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(r,e){const t=new Set;let n=0;const a=(i,o,s)=>{if(!o)return;const d=o.toLowerCase();for(const u of e)d.includes(u)&&(t.add(i),n+=s)};a("uri",r.uri,10),a("class",r.class,10),a("namespace",r.namespace,4),a("resourceKind",r.resourceKind,8),a("description",r.description,4),a("storage",`${r.storage.base}${r.storage.resourceIdPattern}`,3);for(const[i,o]of Object.entries(r.fields))a(`field:${i}`,i,6),a(`predicate:${i}`,o.predicate,6),a(`description:${i}`,o.description,3);for(const i of r.examples){a("example",i.request,3);for(const[o,s]of Object.entries(i.match))a(`example:${o}`,String(s),3)}return n<=0?null:{uri:r.uri,resourceKind:r.resourceKind,class:r.class,namespace:r.namespace,source:r.source,trustLevel:r.trustLevel,description:r.description,score:n,matchedFields:[...t].sort()}}async function filterWebIdsByStorageRoot(r,e,t){const n=normalizeStorageRoot(t);if(!n)return[];const a=Array.from(new Set(e.filter(o=>typeof o=="string"&&o.length>0)));return(await Promise.all(a.map(async o=>{const d=(await fetchProfileStorageUrls(r,o)).find(u=>storageUrlBelongsToRoot(u,n));return d?{webId:o,storageUrl:ensureTrailingSlash$1(d)}:void 0}))).filter(o=>!!o)}function storageUrlBelongsToRoot(r,e){const t=normalizeStorageUrl(r),n=normalizeStorageRoot(e);return!!(t&&n&&t.startsWith(n))}function normalizeStorageRoot(r){if(r)try{return ensureTrailingSlash$1(new URL(r).toString())}catch{return}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(r,e){const t=await r(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const n=t.headers?.get?.("content-type")??"",a=await t.text().catch(()=>"");if(!a)return[];if(n.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(a)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(a))}function extractStorageUrlsFromTurtle(r){return Array.from(r.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(r){const e=new Set,t=new WeakSet,n=(a,i=!1)=>{if(typeof a=="string"){i&&e.add(a);return}if(!(!a||typeof a!="object")&&!t.has(a)){if(t.add(a),Array.isArray(a)){for(const o of a)n(o,i);return}for(const[o,s]of Object.entries(a)){const d=SOLID_STORAGE_KEYS.has(o);if(i&&o==="@id"){n(s,!0);continue}n(s,i||d)}}};return n(r),Array.from(e)}function normalizeStorageUrl(r){try{return ensureTrailingSlash$1(new URL(r).toString())}catch{return}}function uniqueNormalizedStorageUrls(r){const e=new Set;for(const t of r){const n=normalizeStorageUrl(t);n&&e.add(n)}return Array.from(e)}function ensureTrailingSlash$1(r){return r.replace(/\/+$/u,"")+"/"}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections","/tasks","/pod","/device","/inbox","/notifications"],desktopPages=new Set(["/tasks","/pod","/pod/models","/pod/search","/pod/apps","/pod/data","/device","/device/network","/device/services","/device/runtime","/device/logs","/inbox","/notifications"]);function isXpodProductPath(r){const e=r.replace(/\/$/u,"");return desktopPages.has(e)?!0:XPOD_RETURN_PATH_PREFIXES.slice(0,6).some(t=>e===t||e.startsWith(`${t}/`))}function normalizeXpodReturnPath(r){if(r===void 0)return;if(typeof r!="string"||r.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const e=r.trim(),t=decodeForValidation(e),n=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||n.split("/").some(a=>a==="..")||!isXpodProductPath(n))throw new TypeError("returnTo must be a safe path within the application allow-list");return e}function decodeForValidation(r){let e=r;for(let t=0;t<4;t+=1){let n;try{n=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(n===e)return e;e=n}return e}const XPOD_LOGIN_ROUTE_ID="xpod-current-origin";function createXpodLoginRoute(r=typeof window>"u"?"http://localhost":window.location){const e=toLocation(r),t=e.origin;if(!t||t==="null")throw new TypeError("Xpod login requires a same-origin browser URL");return{id:XPOD_LOGIN_ROUTE_ID,label:"Xpod",identityProvider:{url:t,label:e.host||t},storageProvider:{url:t,label:e.host||t},availability:"ready"}}function normalizeXpodReturnTo(r){return normalizeXpodReturnPath(r)}function assertXpodLoginRoute(r,e){const t=normalizeWebIdLoginRoute(r),n=new URL(e).origin,a=new URL(t.identityProvider.url).origin,i=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||a!==n||i!==n||t.identityProvider.url!==t.storageProvider?.url)throw new TypeError("Xpod login route must use the current origin for identity and storage");return{...t,identityProvider:{...t.identityProvider,url:n},storageProvider:t.storageProvider?{...t.storageProvider,url:n}:void 0}}function toLocation(r){if(typeof r=="string"){const e=new URL(r,typeof window>"u"?void 0:window.location.href);return{origin:e.origin,host:e.host,href:e.href}}return r instanceof URL?{origin:r.origin,host:r.host,href:r.href}:{origin:r.origin,host:r.host,href:r.href}}const ORIGIN_PRIORITY={loopback:10,lan:20,"public-direct":30};async function currentHostLocalPodRoutes(r,e,t={}){if(typeof window>"u")return[];const n=await fetchCurrentProvisionRouteStatus(e,t);return provisionLocalPodRoutes(r,n)}function provisionLocalPodRoutes(r,e,t=typeof window>"u"?"":window.location.href){const n=safeUrl(t);if(!n||!r)return[];if(e.managed===!0&&e.storageRoot&&e.oidcIssuer&&safeUrl(e.storageRoot)?.origin===safeUrl(e.oidcIssuer)?.origin)return[];const a=currentOriginRoute(r,e,n);return[...a?[a]:[],...advertisedRoutes(r,e)].sort((i,o)=>i.priority-o.priority||i.id.localeCompare(o.id))}function currentOriginRoute(r,e,t){const n=safeUrl(r);if(!n||!["http:","https:"].includes(n.protocol)||n.username||n.password||!podBelongsToCurrentHost(r,e))return;const a=safeUrl(e.storageRoot??"")??n;if(a.origin===t.origin)return;const i=currentOriginKind(t);return{id:`${i}-current-origin`,kind:i,canonicalUrl:`${a.origin}/`,targetUrl:`${t.origin}/`,priority:ORIGIN_PRIORITY[i],requiresManagedClient:i!=="public-direct",visibility:i==="loopback"?"local-only":"same-account",health:"healthy"}}function podBelongsToCurrentHost(r,e){return typeof window<"u"&&window.xpodDesktop?!0:e.managed!==!0||typeof e.storageRoot!="string"?!1:coveredByStorageRoot(r,e.storageRoot)}function coveredByStorageRoot(r,e){const t=safeUrl(e),n=safeUrl(r);return!t||!n?!1:n.origin===t.origin||n.href.startsWith(ensureTrailingSlash(t.href))}function advertisedRoutes(r,e){const t=safeUrl(r);if(!t)return[];const n=`${(safeUrl(e.storageRoot??"")??t).origin}/`;return(e.routes??[]).flatMap(a=>{const i=safeUrl(a.targetUrl);return!i||!["http:","https:"].includes(i.protocol)?[]:[{id:a.id,kind:a.kind,canonicalUrl:n,targetUrl:`${i.origin}/`,priority:a.priority,requiresManagedClient:a.requiresManagedClient??!0,visibility:a.visibility??"public",health:a.health??"unknown"}]})}function currentOriginKind(r){return isLoopbackHostname(r.hostname)?"loopback":isPrivateNetworkHostname(r.hostname)?"lan":"public-direct"}function isLoopbackHostname(r){return r==="localhost"||r==="::1"||r==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(r)}function isPrivateNetworkHostname(r){const e=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(r);if(!e)return r.endsWith(".local");const t=Number(e[1]),n=Number(e[2]);return t===10||t===192&&n===168?!0:t===172&&n>=16&&n<=31}async function fetchCurrentProvisionRouteStatus(r,e={}){return typeof window>"u"||window.location.origin==="null"?{}:await probeSolidLocalRouteStatus({fetch:r,url:new URL("/provision/status",window.location.origin).href,signal:e.signal,read:async n=>{if(!n.ok||!n.headers.get("content-type")?.includes("application/json")){await n.arrayBuffer().catch(()=>{});return}const a=await n.json().catch(()=>{});return{managed:a?.managed===!0,storageRoot:typeof a?.publicUrl=="string"?a.publicUrl:void 0,routes:normalizeAdvertisedAccessRoutes(a?.routes)}}})??{}}function normalizeAdvertisedAccessRoutes(r){return Array.isArray(r)?r.flatMap(e=>{if(!e||typeof e!="object")return[];const t=e;return typeof t.targetUrl!="string"||typeof t.kind!="string"?[]:typeof t.priority!="number"||!Number.isFinite(t.priority)?[]:[{id:typeof t.id=="string"&&t.id?t.id:`${t.kind}-${t.targetUrl}`,kind:t.kind,targetUrl:t.targetUrl,priority:t.priority,...typeof t.requiresManagedClient=="boolean"?{requiresManagedClient:t.requiresManagedClient}:{},...typeof t.visibility=="string"?{visibility:t.visibility}:{},...typeof t.health=="string"?{health:t.health}:{}}]}):[]}function safeUrl(r){try{return new URL(r)}catch{return}}function ensureTrailingSlash(r){return r.endsWith("/")?r:`${r}/`}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_SOLID_SESSION_ID_STORAGE_KEY="xpod.solid.sessionId",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(r,e,t){return r.status==="initializing"?{status:"loading",issuer:t}:r.status==="anonymous"?{status:"anonymous",issuer:t}:r.status==="expired"?{status:"expired",webId:r.webId,issuer:t}:r.status==="error"?{status:"error",webId:r.webId,error:r.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:r.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:r,fetch:e}){const t=await fetchProfileStorageUrls(e,r);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash$1(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(r={}){initializeBrowserSparql();const e=createXpodSolidRuntimeStoragePolicy(r.storage);let t=[],n,a;const i=createSolidAccessRouteFetch({fetch:globalThis.fetch,routes:()=>t,refreshRoutes:async()=>{await a?.()},allowLocalOnlyRoutes:!0,managedClient:!0}),o=r.sessionFactory?.({fetch:i})??createInruptSession(e.oidcSession,i);let s=readStoredOidcIssuer(e.issuer),d,u=0;const c=createSolidSessionRuntime({session:{get info(){return o.info},events:o.events,fetch:(m,S)=>S===void 0?o.fetch(m):o.fetch(m,S),login:m=>(u+=1,o.login(m)),logout:m=>(u+=1,o.logout(m)),handleIncomingRedirect:async m=>{const S=++u,A=typeof window>"u"?"http://localhost":window.location.origin,h=await resolveXpodLoginContext(A,globalThis.fetch);if(S!==u)throw new Error("Solid session changed during authority discovery");if(d=h.oidcIssuer,!d)throw new Error("暂时无法确认本机登录信息,请稍后重试。");if(n=h.provisionRouteStatus,t=n?provisionLocalPodRoutes(n.storageRoot,n):[],typeof m!="string"&&m?.restorePreviousSession){const T=new URL(m.url??window.location.href);if(!T.searchParams.has("code")||!T.searchParams.has("state"))return o.handleIncomingRedirect({...m,restorePreviousSession:readActiveRestoreIssuer(e.oidcSession)===d})}return o.handleIncomingRedirect(m)}}}),p={...c,dispose:()=>{u+=1,c.dispose()}},_=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:m,fetch:S})=>drizzle({get info(){return o.info},fetch:S},{podUrl:m,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:p,pod:_,storage:e,transportFetch:i,getIssuer:()=>readIssuerFromSessionInfo(o.info)??s??readStoredOidcIssuer(e.issuer),getProvisionRouteStatus:()=>n,getExpectedIssuer:()=>d,setIssuer:m=>{const S=normalizeXpodOidcIssuer(m);s=S,S&&writeStoredOidcIssuer(S,e.issuer)},setLocalPodRoutes:m=>{t=m?[...m]:[],m===void 0&&(n=void 0)},setLocalPodRoutesRefresh:m=>{a=m},resolveLocalUrl:m=>resolveSolidLocalRouteUrl(m,t.map(toLocalRoute))?.href??m}}function toLocalRoute(r){return{canonicalBaseUrl:r.canonicalUrl,localBaseUrl:r.targetUrl}}function createInruptSession(r=getOptionalPersistentStorage(),e=globalThis.fetch){return new Session({fetch:e,...r?{secureStorage:new InMemoryStorage,insecureStorage:toInruptStorage(r,"insecure")}:{}})}function toInruptStorage(r,e){const t=n=>inruptStorageKey(e,n);return{get:async n=>r.getItem(t(n))??void 0,set:async(n,a)=>{r.setItem(t(n),a)},delete:async n=>{r.removeItem(t(n))}}}function inruptStorageKey(r,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${r}:${e}`}function readActiveRestoreIssuer(r){try{const e=getOptionalPersistentStorage()?.getItem("solidClientAuthenticationUser:currentSession");if(!e)return;const t=r?.getItem(inruptStorageKey("insecure",`solidClientAuthenticationUser:${e}`));return t?normalizeXpodOidcIssuer(JSON.parse(t).issuer):void 0}catch{return}}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function withXpodProvisionScope(r,e){const t=new URL(r);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(r,e){const t=new AbortController;let n;const a=new Promise((i,o)=>{n=setTimeout(()=>{t.abort(),o(new Error("暂时无法确认本机登录信息,请稍后重试。"))},5e3)});try{const i=await Promise.race([e("/provision/status",{headers:{Accept:"application/json"},credentials:"include",signal:t.signal}).catch(()=>{}),a]);if(i?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(r)};const o=i?.ok?await Promise.race([i.json().catch(()=>{}),a]):void 0,s=normalizeXpodOidcIssuer(o?.oidcIssuer),d=normalizeXpodOidcIssuer(o?.publicUrl),u=d?{provisionRouteStatus:{managed:o?.managed===!0,storageRoot:d,oidcIssuer:s,routes:normalizeAdvertisedAccessRoutes(o?.routes)}}:{};if(o?.managed===!1)return{oidcIssuer:s??normalizeXpodOidcIssuer(r),...u};const c=typeof o?.provisionCode=="string"&&o.provisionCode.trim()?o.provisionCode.trim():void 0;if(!s||o?.managed===!0&&!c)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:s,provisionCode:c,...u}}finally{clearTimeout(n)}}function safeAuthError(r){if(r.name==="SolidSessionPendingError"){const e=new Error("上次登录尚未结束,请刷新页面后重新登录。");return e.name=r.name,e}return r.message==="Solid session expired"?r:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(r,e=typeof window>"u"?"http://localhost":window.location.origin){if(!r||typeof r!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(r),n=assertXpodLoginRoute(t.route,e),a=normalizeXpodReturnTo(t.returnTo);return{...t,route:n,authorizationSurface:"redirect",discovery:"strict",...a===void 0?{}:{returnTo:a}}}function useXpodSolidRuntimeContext(){const r=reactExports.useContext(XpodSolidRuntimeContext);if(!r)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return r}function readIssuerFromSessionInfo(r){const e=r.issuer??r.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(r){if(!(typeof r!="string"||!r.trim()))try{const e=new URL(r.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(r,e,t){if(r.status!=="authenticated")return!0;const n=normalizeXpodOidcIssuer(e),a=normalizeXpodOidcIssuer(t);return!n||!a||n!==a?!1:isHttpResourceUrl(r.webId)}function isHttpResourceUrl(r){try{const e=new URL(r);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(r=getOptionalPersistentStorage()){try{return normalizeXpodOidcIssuer(r?.getItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY))}catch{return}}function clearStoredXpodOidcIssuer(r){try{r?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalPersistentStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(r,e=getOptionalPersistentStorage()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,r)}catch{}}function createXpodSolidRuntimeStoragePolicy(r={}){const e=getOptionalPersistentStorage();return{oidcSession:r.oidcSession??e,issuer:r.issuer??e,selectedStorage:r.selectedStorage??e}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function hasInvalidWebIdWhitespace(r){return r!==r.trim()||/[\r\n\t]/.test(r)}const XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1",XPOD_ACCOUNT_REMEMBER_CHOICE_KEY="xpod.account-remember-choice.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(r={}){const e=r.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const n=normalizeRememberedXpodLogin(JSON.parse(t),r.origin??currentOrigin());return n||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(r,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const n=normalizeRememberedXpodLogin(r,e.origin??currentOrigin());if(n)try{t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(n));const a=n.issuer??normalizedIssuer(e.origin??currentOrigin()??"");return clearPendingEmailForIssuer(t,a),clearPendingEmailForIssuer(optionalTemporaryStorage(),a),n}catch{return}}function clearRememberedXpodLogin(r=optionalPersistentStorage()){for(const e of[r,optionalTemporaryStorage()])try{e?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),e?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),e?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(r,e){if(!r||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(r.webId),n=validatedWebId(r.storageBinding.webId),a=normalizedUrl(r.storageBinding.storageUrl,!0),i=validatedWebId(e.webId),o=validatedWebId(e.selectedStorage.webId),s=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!n||!a||!i||!o||!s||t!==n||i!==o||t!==i||a!==s?!1:rememberedXpodAccountMatchesActive(r,e)}function rememberedXpodAccountMatchesActive(r,e){return r?matchingOptionalEmail(r.account.email,e.accountEmail):!1}function readXpodAccountRememberChoice(r,e=optionalPersistentStorage()){try{const n=JSON.parse(e?.getItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY)??"{}")[normalizedIssuer(r??currentOrigin()??"")];return typeof n=="boolean"?n:void 0}catch{return}}function optionalTemporaryStorage(){try{return typeof window>"u"?void 0:window.sessionStorage}catch{return}}function clearPendingEmailForIssuer(r,e){const t=r?.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);(!t||t===e)&&(r?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),r?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY))}function rememberPendingXpodAccountEmail(r,e=optionalPersistentStorage(),t,n=!0,a=optionalTemporaryStorage()){const i=normalizedEmail(r);if(!i)return;const o=normalizedIssuer(t??currentOrigin()??"");try{const s=JSON.parse(e?.getItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY)??"{}"),d=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(e?.setItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY,JSON.stringify({...d,[o]:n})),!n){clearPendingEmailForIssuer(e,o);const c=readRememberedXpodLogin({storage:e});(!c?.issuer||c.issuer===o)&&e?.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}const u=n?e:a;return u?(u.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),u.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,o),n&&clearPendingEmailForIssuer(a,o),i):void 0}catch{return}}function readPendingXpodAccountEmail(r=optionalPersistentStorage(),e,t=optionalTemporaryStorage()){const n=readXpodAccountRememberChoice(e,r)===!1?t:r;if(n)try{const a=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}if(i!==normalizedIssuer(e))return}return a||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),a}catch{return}}function normalizedIssuer(r){try{const e=currentOrigin();return e?new URL(r,e).origin:new URL(r).origin}catch{return r.trim()}}function normalizeRememberedXpodLogin(r,e){if(!r||typeof r!="object")return;const t=r;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||t.issuer!==void 0&&!normalizedUrl(t.issuer)||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const n=t.account,a=t.storageBinding,i=normalizedEmail(n.email),o=validatedWebId(t.webId),s=validatedWebId(a.webId),d=normalizedUrl(a.storageUrl,!0);if(n.email!==void 0&&!i||!o||!s||!d||o!==s)return;const u=normalizedAvatarUrl(n.avatarUrl,[o,d,e]);return{...typeof t.issuer=="string"?{issuer:normalizedIssuer(t.issuer)}:{},account:{...i?{email:i}:{},...normalizedText(n.id)?{id:normalizedText(n.id)}:{},...normalizedText(n.username)?{username:normalizedText(n.username)}:{},...normalizedText(n.displayName)?{displayName:normalizedText(n.displayName)}:{},...u?{avatarUrl:u}:{}},webId:o,storageBinding:{webId:o,storageUrl:d},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(r){if(typeof r!="string")return;const e=r.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(r){if(typeof r!="string")return;const e=r.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(r){return typeof r=="string"&&!hasInvalidWebIdWhitespace(r)&&normalizedUrl(r)?r:void 0}function normalizedUrl(r,e=!1){if(!(typeof r!="string"||r.length>2048))try{const t=new URL(r);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(r,e){const t=normalizedUrl(r);if(!t)return;const n=new URL(t).origin;return e.some(a=>{const i=normalizedUrl(a);return i&&new URL(i).origin===n})?t:void 0}function matchingOptionalEmail(r,e){const t=normalizedEmail(r)?.toLowerCase(),n=normalizedEmail(e)?.toLowerCase();return!t||!n||t===n}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}export{setThing as $,aiConfigModelRef as A,AI_MODEL_CLASS_DEFAULT_CAPABILITY as B,CircleAlert as C,AI_MODEL_CLASS as D,EmailInput as E,FormField as F,aiProviderResource as G,initializeBrowserSparql as H,filterAIModelCapabilityUris as I,withAIModelClassDefaultCapabilities as J,toAIModelClassName as K,LoaderCircle as L,getLinkedResourceUrlAll as M,NoUsableAccessRouteError as N,acp as O,internal_cloneResource as P,getSolidDataset as Q,freeze as R,getSourceUrl as S,getResourceInfo as T,getSourceIri as U,getThingAll as V,WebAccountLayout as W,XpodDeploymentIdentity as X,getIriAll as Y,rdf$e as Z,acl as _,credentialResource as a,real as a$,setIri as a0,removeIri as a1,removeAll as a2,createThing as a3,addIri as a4,removeThing as a5,subjectToRdfJsQuads as a6,DataFactory$H as a7,getIri as a8,saveSolidDatasetAt as a9,outlineButtonClass as aA,Field as aB,string$2 as aC,podTable as aD,ColumnBuilder as aE,PodArrayColumn as aF,PodBooleanColumn as aG,PodColumnBase as aH,PodDateTimeColumn as aI,PodIntegerColumn as aJ,PodJsonColumn as aK,PodObjectColumn as aL,PodStringColumn as aM,PodTable as aN,PodUriColumn as aO,SolidSchema as aP,boolean$2 as aQ,date$3 as aR,generateNanoId as aS,hasStringValue$2 as aT,hasTermValue as aU,id as aV,integer$1 as aW,isSolidSchema as aX,json as aY,mergeSchemaColumns as aZ,object$1 as a_,createSolidDataset as aa,foaf as ab,getThing as ac,getUrlAll as ad,buildThing as ae,Avatar as af,AvatarImage as ag,AvatarFallback as ah,Check as ai,Tooltip as aj,TooltipTrigger as ak,TooltipContent as al,TooltipProvider as am,Info as an,LoaderCircle$1 as ao,resolvePodSignInCopy as ap,usePastDelay as aq,SourceMark as ar,ScreenLayout as as,PodAvatar as at,Spinner as au,formatCopy as av,ActionButton as aw,primaryButtonClass as ax,textButtonClass as ay,Disclosure as az,XpodAuthSurface as b,resolveTermIri as b0,solidSchema as b1,text as b2,timestamp as b3,uri as b4,validateColumnOverride as b5,bufferExports as b6,pickSolidProfileDisplayName as b7,VCARD as b8,FOAF as b9,readRememberedXpodLogin as ba,rememberedXpodLoginMatchesActive as bb,rememberXpodLogin as bc,XPOD_LOGIN_ROUTE_ID as bd,hasInvalidWebIdWhitespace as be,normalizeWebIdLoginTransaction as bf,isCurrentXpodSessionSnapshot as bg,clearStoredXpodOidcIssuer as bh,fetchCurrentProvisionRouteStatus as bi,currentHostLocalPodRoutes as bj,snapshotToState as bk,normalizeXpodLoginTransaction as bl,resolveXpodLoginContext as bm,withXpodProvisionScope as bn,safeAuthError as bo,XpodSolidRuntimeContext as bp,approvalResource as bq,inboxNotificationResource as br,taskResource as bs,clearRememberedXpodLogin as bt,createXpodLoginRoute as bu,XpodSignInFrame as bv,namespaces$6 as bw,credentialDescriptor as c,createXpodSolidRuntimeValue as d,assertXpodLoginRoute as e,XPOD_SOLID_SESSION_ID_STORAGE_KEY as f,XPOD_LAST_OIDC_ISSUER_STORAGE_KEY as g,normalizeAdvertisedAccessRoutes as h,filterWebIdsByStorageRoot as i,getXpodSolidRuntimeValue as j,readPendingXpodAccountEmail as k,XpodBlockingAccountCredentialsSurface as l,rememberPendingXpodAccountEmail as m,normalizeXpodReturnTo as n,useXpodSolidRuntimeContext as o,provisionLocalPodRoutes as p,XpodAccountPageSurface as q,readXpodAccountRememberChoice as r,storageUrlBelongsToRoot as s,Checkbox as t,useSize as u,runResource as v,toAIModelCapabilityUri as w,toAIModelCapabilityName as x,toAIModelClassUri as y,aiModelResource as z};
|
|
567
|
+
`)},n.hextoposhex=lt,n.intarystrtohex=function(ce){ce=(ce=(ce=ce.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return ce.split(/,/).map((function(ye,_e,Re){var Ie=parseInt(ye);if(Ie<0||255<Ie)throw"integer not in range 0-255";return("00"+Ie.toString(16)).slice(-2)})).join("")}catch(ye){throw"malformed integer array string: "+ye}},n.strdiffidx=function(ce,ye){var _e=ce.length;ce.length>ye.length&&(_e=ye.length);for(var Re=0;Re<_e;Re++)if(ce.charCodeAt(Re)!=ye.charCodeAt(Re))return Re;return ce.length!=ye.length?_e:-1},n.KJUR=me;var Yt=me.crypto;n.crypto=Yt;var gr=me.asn1;n.asn1=gr;var Zt=me.jws;n.jws=Zt;var kr=me.lang;n.lang=kr}).call(this,a(28).Buffer)},function(t,n,a){(function(i){var o=a(30),s=a(31),d=a(32);function u(){return p.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function c(z,G){if(u()<G)throw new RangeError("Invalid typed array length");return p.TYPED_ARRAY_SUPPORT?(z=new Uint8Array(G)).__proto__=p.prototype:(z===null&&(z=new p(G)),z.length=G),z}function p(z,G,g){if(!(p.TYPED_ARRAY_SUPPORT||this instanceof p))return new p(z,G,g);if(typeof z=="number"){if(typeof G=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,z)}return _(this,z,G,g)}function _(z,G,g,R){if(typeof G=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&G instanceof ArrayBuffer?(function(B,k,W,$){if(k.byteLength,W<0||k.byteLength<W)throw new RangeError("'offset' is out of bounds");if(k.byteLength<W+($||0))throw new RangeError("'length' is out of bounds");return k=W===void 0&&$===void 0?new Uint8Array(k):$===void 0?new Uint8Array(k,W):new Uint8Array(k,W,$),p.TYPED_ARRAY_SUPPORT?(B=k).__proto__=p.prototype:B=A(B,k),B})(z,G,g,R):typeof G=="string"?(function(B,k,W){if(typeof W=="string"&&W!==""||(W="utf8"),!p.isEncoding(W))throw new TypeError('"encoding" must be a valid string encoding');var $=0|T(k,W),j=(B=c(B,$)).write(k,W);return j!==$&&(B=B.slice(0,j)),B})(z,G,g):(function(B,k){if(p.isBuffer(k)){var W=0|h(k.length);return(B=c(B,W)).length===0||k.copy(B,0,0,W),B}if(k){if(typeof ArrayBuffer<"u"&&k.buffer instanceof ArrayBuffer||"length"in k)return typeof k.length!="number"||(function(j){return j!=j})(k.length)?c(B,0):A(B,k);if(k.type==="Buffer"&&d(k.data))return A(B,k.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(z,G)}function m(z){if(typeof z!="number")throw new TypeError('"size" argument must be a number');if(z<0)throw new RangeError('"size" argument must not be negative')}function S(z,G){if(m(G),z=c(z,G<0?0:0|h(G)),!p.TYPED_ARRAY_SUPPORT)for(var g=0;g<G;++g)z[g]=0;return z}function A(z,G){var g=G.length<0?0:0|h(G.length);z=c(z,g);for(var R=0;R<g;R+=1)z[R]=255&G[R];return z}function h(z){if(z>=u())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+u().toString(16)+" bytes");return 0|z}function T(z,G){if(p.isBuffer(z))return z.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(z)||z instanceof ArrayBuffer))return z.byteLength;typeof z!="string"&&(z=""+z);var g=z.length;if(g===0)return 0;for(var R=!1;;)switch(G){case"ascii":case"latin1":case"binary":return g;case"utf8":case"utf-8":case void 0:return P(z).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*g;case"hex":return g>>>1;case"base64":return M(z).length;default:if(R)return P(z).length;G=(""+G).toLowerCase(),R=!0}}function w(z,G,g){var R=!1;if((G===void 0||G<0)&&(G=0),G>this.length||((g===void 0||g>this.length)&&(g=this.length),g<=0)||(g>>>=0)<=(G>>>=0))return"";for(z||(z="utf8");;)switch(z){case"hex":return se(this,G,g);case"utf8":case"utf-8":return E(this,G,g);case"ascii":return K(this,G,g);case"latin1":case"binary":return te(this,G,g);case"base64":return I(this,G,g);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,G,g);default:if(R)throw new TypeError("Unknown encoding: "+z);z=(z+"").toLowerCase(),R=!0}}function b(z,G,g){var R=z[G];z[G]=z[g],z[g]=R}function N(z,G,g,R,q){if(z.length===0)return-1;if(typeof g=="string"?(R=g,g=0):g>2147483647?g=2147483647:g<-2147483648&&(g=-2147483648),g=+g,isNaN(g)&&(g=q?0:z.length-1),g<0&&(g=z.length+g),g>=z.length){if(q)return-1;g=z.length-1}else if(g<0){if(!q)return-1;g=0}if(typeof G=="string"&&(G=p.from(G,R)),p.isBuffer(G))return G.length===0?-1:O(z,G,g,R,q);if(typeof G=="number")return G&=255,p.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?q?Uint8Array.prototype.indexOf.call(z,G,g):Uint8Array.prototype.lastIndexOf.call(z,G,g):O(z,[G],g,R,q);throw new TypeError("val must be string, number or Buffer")}function O(z,G,g,R,q){var B,k=1,W=z.length,$=G.length;if(R!==void 0&&((R=String(R).toLowerCase())==="ucs2"||R==="ucs-2"||R==="utf16le"||R==="utf-16le")){if(z.length<2||G.length<2)return-1;k=2,W/=2,$/=2,g/=2}function j(Ae,he){return k===1?Ae[he]:Ae.readUInt16BE(he*k)}if(q){var H=-1;for(B=g;B<W;B++)if(j(z,B)===j(G,H===-1?0:B-H)){if(H===-1&&(H=B),B-H+1===$)return H*k}else H!==-1&&(B-=B-H),H=-1}else for(g+$>W&&(g=W-$),B=g;B>=0;B--){for(var L=!0,fe=0;fe<$;fe++)if(j(z,B+fe)!==j(G,fe)){L=!1;break}if(L)return B}return-1}function X(z,G,g,R){g=Number(g)||0;var q=z.length-g;R?(R=Number(R))>q&&(R=q):R=q;var B=G.length;if(B%2!=0)throw new TypeError("Invalid hex string");R>B/2&&(R=B/2);for(var k=0;k<R;++k){var W=parseInt(G.substr(2*k,2),16);if(isNaN(W))return k;z[g+k]=W}return k}function ee(z,G,g,R){return Z(P(G,z.length-g),z,g,R)}function V(z,G,g,R){return Z((function(B){for(var k=[],W=0;W<B.length;++W)k.push(255&B.charCodeAt(W));return k})(G),z,g,R)}function U(z,G,g,R){return V(z,G,g,R)}function v(z,G,g,R){return Z(M(G),z,g,R)}function x(z,G,g,R){return Z((function(B,k){for(var W,$,j,H=[],L=0;L<B.length&&!((k-=2)<0);++L)$=(W=B.charCodeAt(L))>>8,j=W%256,H.push(j),H.push($);return H})(G,z.length-g),z,g,R)}function I(z,G,g){return G===0&&g===z.length?o.fromByteArray(z):o.fromByteArray(z.slice(G,g))}function E(z,G,g){g=Math.min(z.length,g);for(var R=[],q=G;q<g;){var B,k,W,$,j=z[q],H=null,L=j>239?4:j>223?3:j>191?2:1;if(q+L<=g)switch(L){case 1:j<128&&(H=j);break;case 2:(192&(B=z[q+1]))==128&&($=(31&j)<<6|63&B)>127&&(H=$);break;case 3:B=z[q+1],k=z[q+2],(192&B)==128&&(192&k)==128&&($=(15&j)<<12|(63&B)<<6|63&k)>2047&&($<55296||$>57343)&&(H=$);break;case 4:B=z[q+1],k=z[q+2],W=z[q+3],(192&B)==128&&(192&k)==128&&(192&W)==128&&($=(15&j)<<18|(63&B)<<12|(63&k)<<6|63&W)>65535&&$<1114112&&(H=$)}H===null?(H=65533,L=1):H>65535&&(H-=65536,R.push(H>>>10&1023|55296),H=56320|1023&H),R.push(H),q+=L}return(function(Ae){var he=Ae.length;if(he<=Q)return String.fromCharCode.apply(String,Ae);for(var Te="",be=0;be<he;)Te+=String.fromCharCode.apply(String,Ae.slice(be,be+=Q));return Te})(R)}n.Buffer=p,n.SlowBuffer=function(G){return+G!=G&&(G=0),p.alloc(+G)},n.INSPECT_MAX_BYTES=50,p.TYPED_ARRAY_SUPPORT=i.TYPED_ARRAY_SUPPORT!==void 0?i.TYPED_ARRAY_SUPPORT:(function(){try{var G=new Uint8Array(1);return G.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},G.foo()===42&&typeof G.subarray=="function"&&G.subarray(1,1).byteLength===0}catch{return!1}})(),n.kMaxLength=u(),p.poolSize=8192,p._augment=function(z){return z.__proto__=p.prototype,z},p.from=function(z,G,g){return _(null,z,G,g)},p.TYPED_ARRAY_SUPPORT&&(p.prototype.__proto__=Uint8Array.prototype,p.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&p[Symbol.species]===p&&Object.defineProperty(p,Symbol.species,{value:null,configurable:!0})),p.alloc=function(z,G,g){return(function(q,B,k,W){return m(B),B<=0?c(q,B):k!==void 0?typeof W=="string"?c(q,B).fill(k,W):c(q,B).fill(k):c(q,B)})(null,z,G,g)},p.allocUnsafe=function(z){return S(null,z)},p.allocUnsafeSlow=function(z){return S(null,z)},p.isBuffer=function(G){return!(G==null||!G._isBuffer)},p.compare=function(G,g){if(!p.isBuffer(G)||!p.isBuffer(g))throw new TypeError("Arguments must be Buffers");if(G===g)return 0;for(var R=G.length,q=g.length,B=0,k=Math.min(R,q);B<k;++B)if(G[B]!==g[B]){R=G[B],q=g[B];break}return R<q?-1:q<R?1:0},p.isEncoding=function(G){switch(String(G).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},p.concat=function(G,g){if(!d(G))throw new TypeError('"list" argument must be an Array of Buffers');if(G.length===0)return p.alloc(0);var R;if(g===void 0)for(g=0,R=0;R<G.length;++R)g+=G[R].length;var q=p.allocUnsafe(g),B=0;for(R=0;R<G.length;++R){var k=G[R];if(!p.isBuffer(k))throw new TypeError('"list" argument must be an Array of Buffers');k.copy(q,B),B+=k.length}return q},p.byteLength=T,p.prototype._isBuffer=!0,p.prototype.swap16=function(){var G=this.length;if(G%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var g=0;g<G;g+=2)b(this,g,g+1);return this},p.prototype.swap32=function(){var G=this.length;if(G%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var g=0;g<G;g+=4)b(this,g,g+3),b(this,g+1,g+2);return this},p.prototype.swap64=function(){var G=this.length;if(G%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var g=0;g<G;g+=8)b(this,g,g+7),b(this,g+1,g+6),b(this,g+2,g+5),b(this,g+3,g+4);return this},p.prototype.toString=function(){var G=0|this.length;return G===0?"":arguments.length===0?E(this,0,G):w.apply(this,arguments)},p.prototype.equals=function(G){if(!p.isBuffer(G))throw new TypeError("Argument must be a Buffer");return this===G||p.compare(this,G)===0},p.prototype.inspect=function(){var G="",g=n.INSPECT_MAX_BYTES;return this.length>0&&(G=this.toString("hex",0,g).match(/.{2}/g).join(" "),this.length>g&&(G+=" ... ")),"<Buffer "+G+">"},p.prototype.compare=function(G,g,R,q,B){if(!p.isBuffer(G))throw new TypeError("Argument must be a Buffer");if(g===void 0&&(g=0),R===void 0&&(R=G?G.length:0),q===void 0&&(q=0),B===void 0&&(B=this.length),g<0||R>G.length||q<0||B>this.length)throw new RangeError("out of range index");if(q>=B&&g>=R)return 0;if(q>=B)return-1;if(g>=R)return 1;if(this===G)return 0;for(var k=(B>>>=0)-(q>>>=0),W=(R>>>=0)-(g>>>=0),$=Math.min(k,W),j=this.slice(q,B),H=G.slice(g,R),L=0;L<$;++L)if(j[L]!==H[L]){k=j[L],W=H[L];break}return k<W?-1:W<k?1:0},p.prototype.includes=function(G,g,R){return this.indexOf(G,g,R)!==-1},p.prototype.indexOf=function(G,g,R){return N(this,G,g,R,!0)},p.prototype.lastIndexOf=function(G,g,R){return N(this,G,g,R,!1)},p.prototype.write=function(G,g,R,q){if(g===void 0)q="utf8",R=this.length,g=0;else if(R===void 0&&typeof g=="string")q=g,R=this.length,g=0;else{if(!isFinite(g))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");g|=0,isFinite(R)?(R|=0,q===void 0&&(q="utf8")):(q=R,R=void 0)}var B=this.length-g;if((R===void 0||R>B)&&(R=B),G.length>0&&(R<0||g<0)||g>this.length)throw new RangeError("Attempt to write outside buffer bounds");q||(q="utf8");for(var k=!1;;)switch(q){case"hex":return X(this,G,g,R);case"utf8":case"utf-8":return ee(this,G,g,R);case"ascii":return V(this,G,g,R);case"latin1":case"binary":return U(this,G,g,R);case"base64":return v(this,G,g,R);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,G,g,R);default:if(k)throw new TypeError("Unknown encoding: "+q);q=(""+q).toLowerCase(),k=!0}},p.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;function K(z,G,g){var R="";g=Math.min(z.length,g);for(var q=G;q<g;++q)R+=String.fromCharCode(127&z[q]);return R}function te(z,G,g){var R="";g=Math.min(z.length,g);for(var q=G;q<g;++q)R+=String.fromCharCode(z[q]);return R}function se(z,G,g){var R=z.length;(!G||G<0)&&(G=0),(!g||g<0||g>R)&&(g=R);for(var q="",B=G;B<g;++B)q+=ue(z[B]);return q}function D(z,G,g){for(var R=z.slice(G,g),q="",B=0;B<R.length;B+=2)q+=String.fromCharCode(R[B]+256*R[B+1]);return q}function ne(z,G,g){if(z%1!=0||z<0)throw new RangeError("offset is not uint");if(z+G>g)throw new RangeError("Trying to access beyond buffer length")}function y(z,G,g,R,q,B){if(!p.isBuffer(z))throw new TypeError('"buffer" argument must be a Buffer instance');if(G>q||G<B)throw new RangeError('"value" argument is out of bounds');if(g+R>z.length)throw new RangeError("Index out of range")}function C(z,G,g,R){G<0&&(G=65535+G+1);for(var q=0,B=Math.min(z.length-g,2);q<B;++q)z[g+q]=(G&255<<8*(R?q:1-q))>>>8*(R?q:1-q)}function re(z,G,g,R){G<0&&(G=4294967295+G+1);for(var q=0,B=Math.min(z.length-g,4);q<B;++q)z[g+q]=G>>>8*(R?q:3-q)&255}function F(z,G,g,R,q,B){if(g+R>z.length)throw new RangeError("Index out of range");if(g<0)throw new RangeError("Index out of range")}function ie(z,G,g,R,q){return q||F(z,0,g,4),s.write(z,G,g,R,23,4),g+4}function oe(z,G,g,R,q){return q||F(z,0,g,8),s.write(z,G,g,R,52,8),g+8}p.prototype.slice=function(G,g){var R,q=this.length;if((G=~~G)<0?(G+=q)<0&&(G=0):G>q&&(G=q),(g=g===void 0?q:~~g)<0?(g+=q)<0&&(g=0):g>q&&(g=q),g<G&&(g=G),p.TYPED_ARRAY_SUPPORT)(R=this.subarray(G,g)).__proto__=p.prototype;else{var B=g-G;R=new p(B,void 0);for(var k=0;k<B;++k)R[k]=this[k+G]}return R},p.prototype.readUIntLE=function(G,g,R){G|=0,g|=0,R||ne(G,g,this.length);for(var q=this[G],B=1,k=0;++k<g&&(B*=256);)q+=this[G+k]*B;return q},p.prototype.readUIntBE=function(G,g,R){G|=0,g|=0,R||ne(G,g,this.length);for(var q=this[G+--g],B=1;g>0&&(B*=256);)q+=this[G+--g]*B;return q},p.prototype.readUInt8=function(G,g){return g||ne(G,1,this.length),this[G]},p.prototype.readUInt16LE=function(G,g){return g||ne(G,2,this.length),this[G]|this[G+1]<<8},p.prototype.readUInt16BE=function(G,g){return g||ne(G,2,this.length),this[G]<<8|this[G+1]},p.prototype.readUInt32LE=function(G,g){return g||ne(G,4,this.length),(this[G]|this[G+1]<<8|this[G+2]<<16)+16777216*this[G+3]},p.prototype.readUInt32BE=function(G,g){return g||ne(G,4,this.length),16777216*this[G]+(this[G+1]<<16|this[G+2]<<8|this[G+3])},p.prototype.readIntLE=function(G,g,R){G|=0,g|=0,R||ne(G,g,this.length);for(var q=this[G],B=1,k=0;++k<g&&(B*=256);)q+=this[G+k]*B;return q>=(B*=128)&&(q-=Math.pow(2,8*g)),q},p.prototype.readIntBE=function(G,g,R){G|=0,g|=0,R||ne(G,g,this.length);for(var q=g,B=1,k=this[G+--q];q>0&&(B*=256);)k+=this[G+--q]*B;return k>=(B*=128)&&(k-=Math.pow(2,8*g)),k},p.prototype.readInt8=function(G,g){return g||ne(G,1,this.length),128&this[G]?-1*(255-this[G]+1):this[G]},p.prototype.readInt16LE=function(G,g){g||ne(G,2,this.length);var R=this[G]|this[G+1]<<8;return 32768&R?4294901760|R:R},p.prototype.readInt16BE=function(G,g){g||ne(G,2,this.length);var R=this[G+1]|this[G]<<8;return 32768&R?4294901760|R:R},p.prototype.readInt32LE=function(G,g){return g||ne(G,4,this.length),this[G]|this[G+1]<<8|this[G+2]<<16|this[G+3]<<24},p.prototype.readInt32BE=function(G,g){return g||ne(G,4,this.length),this[G]<<24|this[G+1]<<16|this[G+2]<<8|this[G+3]},p.prototype.readFloatLE=function(G,g){return g||ne(G,4,this.length),s.read(this,G,!0,23,4)},p.prototype.readFloatBE=function(G,g){return g||ne(G,4,this.length),s.read(this,G,!1,23,4)},p.prototype.readDoubleLE=function(G,g){return g||ne(G,8,this.length),s.read(this,G,!0,52,8)},p.prototype.readDoubleBE=function(G,g){return g||ne(G,8,this.length),s.read(this,G,!1,52,8)},p.prototype.writeUIntLE=function(G,g,R,q){G=+G,g|=0,R|=0,q||y(this,G,g,R,Math.pow(2,8*R)-1,0);var B=1,k=0;for(this[g]=255&G;++k<R&&(B*=256);)this[g+k]=G/B&255;return g+R},p.prototype.writeUIntBE=function(G,g,R,q){G=+G,g|=0,R|=0,q||y(this,G,g,R,Math.pow(2,8*R)-1,0);var B=R-1,k=1;for(this[g+B]=255&G;--B>=0&&(k*=256);)this[g+B]=G/k&255;return g+R},p.prototype.writeUInt8=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,1,255,0),p.TYPED_ARRAY_SUPPORT||(G=Math.floor(G)),this[g]=255&G,g+1},p.prototype.writeUInt16LE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,2,65535,0),p.TYPED_ARRAY_SUPPORT?(this[g]=255&G,this[g+1]=G>>>8):C(this,G,g,!0),g+2},p.prototype.writeUInt16BE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,2,65535,0),p.TYPED_ARRAY_SUPPORT?(this[g]=G>>>8,this[g+1]=255&G):C(this,G,g,!1),g+2},p.prototype.writeUInt32LE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,4,4294967295,0),p.TYPED_ARRAY_SUPPORT?(this[g+3]=G>>>24,this[g+2]=G>>>16,this[g+1]=G>>>8,this[g]=255&G):re(this,G,g,!0),g+4},p.prototype.writeUInt32BE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,4,4294967295,0),p.TYPED_ARRAY_SUPPORT?(this[g]=G>>>24,this[g+1]=G>>>16,this[g+2]=G>>>8,this[g+3]=255&G):re(this,G,g,!1),g+4},p.prototype.writeIntLE=function(G,g,R,q){if(G=+G,g|=0,!q){var B=Math.pow(2,8*R-1);y(this,G,g,R,B-1,-B)}var k=0,W=1,$=0;for(this[g]=255&G;++k<R&&(W*=256);)G<0&&$===0&&this[g+k-1]!==0&&($=1),this[g+k]=(G/W>>0)-$&255;return g+R},p.prototype.writeIntBE=function(G,g,R,q){if(G=+G,g|=0,!q){var B=Math.pow(2,8*R-1);y(this,G,g,R,B-1,-B)}var k=R-1,W=1,$=0;for(this[g+k]=255&G;--k>=0&&(W*=256);)G<0&&$===0&&this[g+k+1]!==0&&($=1),this[g+k]=(G/W>>0)-$&255;return g+R},p.prototype.writeInt8=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,1,127,-128),p.TYPED_ARRAY_SUPPORT||(G=Math.floor(G)),G<0&&(G=255+G+1),this[g]=255&G,g+1},p.prototype.writeInt16LE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,2,32767,-32768),p.TYPED_ARRAY_SUPPORT?(this[g]=255&G,this[g+1]=G>>>8):C(this,G,g,!0),g+2},p.prototype.writeInt16BE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,2,32767,-32768),p.TYPED_ARRAY_SUPPORT?(this[g]=G>>>8,this[g+1]=255&G):C(this,G,g,!1),g+2},p.prototype.writeInt32LE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,4,2147483647,-2147483648),p.TYPED_ARRAY_SUPPORT?(this[g]=255&G,this[g+1]=G>>>8,this[g+2]=G>>>16,this[g+3]=G>>>24):re(this,G,g,!0),g+4},p.prototype.writeInt32BE=function(G,g,R){return G=+G,g|=0,R||y(this,G,g,4,2147483647,-2147483648),G<0&&(G=4294967295+G+1),p.TYPED_ARRAY_SUPPORT?(this[g]=G>>>24,this[g+1]=G>>>16,this[g+2]=G>>>8,this[g+3]=255&G):re(this,G,g,!1),g+4},p.prototype.writeFloatLE=function(G,g,R){return ie(this,G,g,!0,R)},p.prototype.writeFloatBE=function(G,g,R){return ie(this,G,g,!1,R)},p.prototype.writeDoubleLE=function(G,g,R){return oe(this,G,g,!0,R)},p.prototype.writeDoubleBE=function(G,g,R){return oe(this,G,g,!1,R)},p.prototype.copy=function(G,g,R,q){if(R||(R=0),q||q===0||(q=this.length),g>=G.length&&(g=G.length),g||(g=0),q>0&&q<R&&(q=R),q===R||G.length===0||this.length===0)return 0;if(g<0)throw new RangeError("targetStart out of bounds");if(R<0||R>=this.length)throw new RangeError("sourceStart out of bounds");if(q<0)throw new RangeError("sourceEnd out of bounds");q>this.length&&(q=this.length),G.length-g<q-R&&(q=G.length-g+R);var B,k=q-R;if(this===G&&R<g&&g<q)for(B=k-1;B>=0;--B)G[B+g]=this[B+R];else if(k<1e3||!p.TYPED_ARRAY_SUPPORT)for(B=0;B<k;++B)G[B+g]=this[B+R];else Uint8Array.prototype.set.call(G,this.subarray(R,R+k),g);return k},p.prototype.fill=function(G,g,R,q){if(typeof G=="string"){if(typeof g=="string"?(q=g,g=0,R=this.length):typeof R=="string"&&(q=R,R=this.length),G.length===1){var B=G.charCodeAt(0);B<256&&(G=B)}if(q!==void 0&&typeof q!="string")throw new TypeError("encoding must be a string");if(typeof q=="string"&&!p.isEncoding(q))throw new TypeError("Unknown encoding: "+q)}else typeof G=="number"&&(G&=255);if(g<0||this.length<g||this.length<R)throw new RangeError("Out of range index");if(R<=g)return this;var k;if(g>>>=0,R=R===void 0?this.length:R>>>0,G||(G=0),typeof G=="number")for(k=g;k<R;++k)this[k]=G;else{var W=p.isBuffer(G)?G:P(new p(G,q).toString()),$=W.length;for(k=0;k<R-g;++k)this[k+g]=W[k%$]}return this};var le=/[^+\/0-9A-Za-z-_]/g;function ue(z){return z<16?"0"+z.toString(16):z.toString(16)}function P(z,G){var g;G=G||1/0;for(var R=z.length,q=null,B=[],k=0;k<R;++k){if((g=z.charCodeAt(k))>55295&&g<57344){if(!q){if(g>56319){(G-=3)>-1&&B.push(239,191,189);continue}if(k+1===R){(G-=3)>-1&&B.push(239,191,189);continue}q=g;continue}if(g<56320){(G-=3)>-1&&B.push(239,191,189),q=g;continue}g=65536+(q-55296<<10|g-56320)}else q&&(G-=3)>-1&&B.push(239,191,189);if(q=null,g<128){if((G-=1)<0)break;B.push(g)}else if(g<2048){if((G-=2)<0)break;B.push(g>>6|192,63&g|128)}else if(g<65536){if((G-=3)<0)break;B.push(g>>12|224,g>>6&63|128,63&g|128)}else{if(!(g<1114112))throw new Error("Invalid code point");if((G-=4)<0)break;B.push(g>>18|240,g>>12&63|128,g>>6&63|128,63&g|128)}}return B}function M(z){return o.toByteArray((function(g){if((g=(function(q){return q.trim?q.trim():q.replace(/^\s+|\s+$/g,"")})(g).replace(le,"")).length<2)return"";for(;g.length%4!=0;)g+="=";return g})(z))}function Z(z,G,g,R){for(var q=0;q<R&&!(q+g>=G.length||q>=z.length);++q)G[q+g]=z[q];return q}}).call(this,a(29))},function(t,n){var a;a=(function(){return this})();try{a=a||new Function("return this")()}catch{typeof window=="object"&&(a=window)}t.exports=a},function(t,n,a){n.byteLength=function(S){var A=p(S),h=A[0],T=A[1];return 3*(h+T)/4-T},n.toByteArray=function(S){var A,h,T=p(S),w=T[0],b=T[1],N=new s((function(V,U,v){return 3*(U+v)/4-v})(0,w,b)),O=0,X=b>0?w-4:w;for(h=0;h<X;h+=4)A=o[S.charCodeAt(h)]<<18|o[S.charCodeAt(h+1)]<<12|o[S.charCodeAt(h+2)]<<6|o[S.charCodeAt(h+3)],N[O++]=A>>16&255,N[O++]=A>>8&255,N[O++]=255&A;return b===2&&(A=o[S.charCodeAt(h)]<<2|o[S.charCodeAt(h+1)]>>4,N[O++]=255&A),b===1&&(A=o[S.charCodeAt(h)]<<10|o[S.charCodeAt(h+1)]<<4|o[S.charCodeAt(h+2)]>>2,N[O++]=A>>8&255,N[O++]=255&A),N},n.fromByteArray=function(S){for(var A,h=S.length,T=h%3,w=[],b=16383,N=0,O=h-T;N<O;N+=b)w.push(_(S,N,N+b>O?O:N+b));return T===1?(A=S[h-1],w.push(i[A>>2]+i[A<<4&63]+"==")):T===2&&(A=(S[h-2]<<8)+S[h-1],w.push(i[A>>10]+i[A>>4&63]+i[A<<2&63]+"=")),w.join("")};for(var i=[],o=[],s=typeof Uint8Array<"u"?Uint8Array:Array,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,c=d.length;u<c;++u)i[u]=d[u],o[d.charCodeAt(u)]=u;function p(m){var S=m.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var A=m.indexOf("=");return A===-1&&(A=S),[A,A===S?0:4-A%4]}function _(m,S,A){for(var h,T,w=[],b=S;b<A;b+=3)h=(m[b]<<16&16711680)+(m[b+1]<<8&65280)+(255&m[b+2]),w.push(i[(T=h)>>18&63]+i[T>>12&63]+i[T>>6&63]+i[63&T]);return w.join("")}o[45]=62,o[95]=63},function(t,n){n.read=function(a,i,o,s,d){var u,c,p=8*d-s-1,_=(1<<p)-1,m=_>>1,S=-7,A=o?d-1:0,h=o?-1:1,T=a[i+A];for(A+=h,u=T&(1<<-S)-1,T>>=-S,S+=p;S>0;u=256*u+a[i+A],A+=h,S-=8);for(c=u&(1<<-S)-1,u>>=-S,S+=s;S>0;c=256*c+a[i+A],A+=h,S-=8);if(u===0)u=1-m;else{if(u===_)return c?NaN:1/0*(T?-1:1);c+=Math.pow(2,s),u-=m}return(T?-1:1)*c*Math.pow(2,u-s)},n.write=function(a,i,o,s,d,u){var c,p,_,m=8*u-d-1,S=(1<<m)-1,A=S>>1,h=d===23?Math.pow(2,-24)-Math.pow(2,-77):0,T=s?0:u-1,w=s?1:-1,b=i<0||i===0&&1/i<0?1:0;for(i=Math.abs(i),isNaN(i)||i===1/0?(p=isNaN(i)?1:0,c=S):(c=Math.floor(Math.log(i)/Math.LN2),i*(_=Math.pow(2,-c))<1&&(c--,_*=2),(i+=c+A>=1?h/_:h*Math.pow(2,1-A))*_>=2&&(c++,_/=2),c+A>=S?(p=0,c=S):c+A>=1?(p=(i*_-1)*Math.pow(2,d),c+=A):(p=i*Math.pow(2,A-1)*Math.pow(2,d),c=0));d>=8;a[o+T]=255&p,T+=w,p/=256,d-=8);for(c=c<<d|p,m+=d;m>0;a[o+T]=255&c,T+=w,c/=256,m-=8);a[o+T-w]|=128*b}},function(t,n){var a={}.toString;t.exports=Array.isArray||function(i){return a.call(i)=="[object Array]"}},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.default=function(s){var d=s.jws,u=s.KeyUtil,c=s.X509,p=s.crypto,_=s.hextob64u,m=s.b64tohex,S=s.AllowedSigningAlgs;return(function(){function A(){(function(T,w){if(!(T instanceof w))throw new TypeError("Cannot call a class as a function")})(this,A)}return A.parseJwt=function(T){i.Log.debug("JoseUtil.parseJwt");try{var w=d.JWS.parse(T);return{header:w.headerObj,payload:w.payloadObj}}catch(b){i.Log.error(b)}},A.validateJwt=function(T,w,b,N,O,X,ee){i.Log.debug("JoseUtil.validateJwt");try{if(w.kty==="RSA")if(w.e&&w.n)w=u.getKey(w);else{if(!w.x5c||!w.x5c.length)return i.Log.error("JoseUtil.validateJwt: RSA key missing key material",w),Promise.reject(new Error("RSA key missing key material"));var V=m(w.x5c[0]);w=c.getPublicKeyFromCertHex(V)}else{if(w.kty!=="EC")return i.Log.error("JoseUtil.validateJwt: Unsupported key type",w&&w.kty),Promise.reject(new Error(w.kty));if(!(w.crv&&w.x&&w.y))return i.Log.error("JoseUtil.validateJwt: EC key missing key material",w),Promise.reject(new Error("EC key missing key material"));w=u.getKey(w)}return A._validateJwt(T,w,b,N,O,X,ee)}catch(U){return i.Log.error(U&&U.message||U),Promise.reject("JWT validation failed")}},A.validateJwtAttributes=function(T,w,b,N,O,X){N||(N=0),O||(O=parseInt(Date.now()/1e3));var ee=A.parseJwt(T).payload;if(!ee.iss)return i.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(ee.iss!==w)return i.Log.error("JoseUtil._validateJwt: Invalid issuer in token",ee.iss),Promise.reject(new Error("Invalid issuer in token: "+ee.iss));if(!ee.aud)return i.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(ee.aud===b||Array.isArray(ee.aud)&&ee.aud.indexOf(b)>=0))return i.Log.error("JoseUtil._validateJwt: Invalid audience in token",ee.aud),Promise.reject(new Error("Invalid audience in token: "+ee.aud));if(ee.azp&&ee.azp!==b)return i.Log.error("JoseUtil._validateJwt: Invalid azp in token",ee.azp),Promise.reject(new Error("Invalid azp in token: "+ee.azp));if(!X){var V=O+N,U=O-N;if(!ee.iat)return i.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(V<ee.iat)return i.Log.error("JoseUtil._validateJwt: iat is in the future",ee.iat),Promise.reject(new Error("iat is in the future: "+ee.iat));if(ee.nbf&&V<ee.nbf)return i.Log.error("JoseUtil._validateJwt: nbf is in the future",ee.nbf),Promise.reject(new Error("nbf is in the future: "+ee.nbf));if(!ee.exp)return i.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(ee.exp<U)return i.Log.error("JoseUtil._validateJwt: exp is in the past",ee.exp),Promise.reject(new Error("exp is in the past:"+ee.exp))}return Promise.resolve(ee)},A._validateJwt=function(T,w,b,N,O,X,ee){return A.validateJwtAttributes(T,b,N,O,X,ee).then((function(V){try{return d.JWS.verify(T,w,S)?V:(i.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(U){return i.Log.error(U&&U.message||U),Promise.reject(new Error("signature validation failed"))}}))},A.hashString=function(T,w){try{return p.Util.hashString(T,w)}catch(b){i.Log.error(b)}},A.hexToBase64Url=function(T){try{return _(T)}catch(w){i.Log.error(w)}},A})()};var i=a(0);t.exports=n.default},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.SigninResponse=void 0;var i=(function(){function d(u,c){for(var p=0;p<c.length;p++){var _=c[p];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(u,_.key,_)}}return function(u,c,p){return c&&d(u.prototype,c),p&&d(u,p),u}})(),o=a(3);function s(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")}n.SigninResponse=(function(){function d(u){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";s(this,d);var p=o.UrlUtility.parseUrlFragment(u,c);this.error=p.error,this.error_description=p.error_description,this.error_uri=p.error_uri,this.code=p.code,this.state=p.state,this.id_token=p.id_token,this.session_state=p.session_state,this.access_token=p.access_token,this.token_type=p.token_type,this.scope=p.scope,this.profile=void 0,this.expires_in=p.expires_in}return i(d,[{key:"expires_in",get:function(){if(this.expires_at){var c=parseInt(Date.now()/1e3);return this.expires_at-c}},set:function(c){var p=parseInt(c);if(typeof p=="number"&&p>0){var _=parseInt(Date.now()/1e3);this.expires_at=_+p}}},{key:"expired",get:function(){var c=this.expires_in;if(c!==void 0)return c<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),d})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.SignoutRequest=void 0;var i=a(0),o=a(3),s=a(9);n.SignoutRequest=function d(u){var c=u.url,p=u.id_token_hint,_=u.post_logout_redirect_uri,m=u.data,S=u.extraQueryParams,A=u.request_type;if((function(w,b){if(!(w instanceof b))throw new TypeError("Cannot call a class as a function")})(this,d),!c)throw i.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var h in p&&(c=o.UrlUtility.addQueryParam(c,"id_token_hint",p)),_&&(c=o.UrlUtility.addQueryParam(c,"post_logout_redirect_uri",_),m&&(this.state=new s.State({data:m,request_type:A}),c=o.UrlUtility.addQueryParam(c,"state",this.state.id))),S)c=o.UrlUtility.addQueryParam(c,h,S[h]);this.url=c}},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.SignoutResponse=void 0;var i=a(3);n.SignoutResponse=function o(s){(function(c,p){if(!(c instanceof p))throw new TypeError("Cannot call a class as a function")})(this,o);var d=i.UrlUtility.parseUrlFragment(s,"?");this.error=d.error,this.error_description=d.error_description,this.error_uri=d.error_uri,this.state=d.state}},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.InMemoryWebStorage=void 0;var i=(function(){function s(d,u){for(var c=0;c<u.length;c++){var p=u[c];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(d,p.key,p)}}return function(d,u,c){return u&&s(d.prototype,u),c&&s(d,c),d}})(),o=a(0);n.InMemoryWebStorage=(function(){function s(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,s),this._data={}}return s.prototype.getItem=function(u){return o.Log.debug("InMemoryWebStorage.getItem",u),this._data[u]},s.prototype.setItem=function(u,c){o.Log.debug("InMemoryWebStorage.setItem",u),this._data[u]=c},s.prototype.removeItem=function(u){o.Log.debug("InMemoryWebStorage.removeItem",u),delete this._data[u]},s.prototype.key=function(u){return Object.getOwnPropertyNames(this._data)[u]},i(s,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.UserManager=void 0;var i=(function(){function b(N,O){for(var X=0;X<O.length;X++){var ee=O[X];ee.enumerable=ee.enumerable||!1,ee.configurable=!0,"value"in ee&&(ee.writable=!0),Object.defineProperty(N,ee.key,ee)}}return function(N,O,X){return O&&b(N.prototype,O),X&&b(N,X),N}})(),o=a(0),s=a(10),d=a(39),u=a(15),c=a(45),p=a(47),_=a(18),m=a(8),S=a(20),A=a(11),h=a(4);function T(b,N){if(!(b instanceof N))throw new TypeError("Cannot call a class as a function")}function w(b,N){if(!b)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!N||typeof N!="object"&&typeof N!="function"?b:N}n.UserManager=(function(b){function N(){var O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},X=arguments.length>1&&arguments[1]!==void 0?arguments[1]:p.SilentRenewService,ee=arguments.length>2&&arguments[2]!==void 0?arguments[2]:_.SessionMonitor,V=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,U=arguments.length>4&&arguments[4]!==void 0?arguments[4]:A.TokenClient,v=arguments.length>5&&arguments[5]!==void 0?arguments[5]:h.JoseUtil;T(this,N),O instanceof d.UserManagerSettings||(O=new d.UserManagerSettings(O));var x=w(this,b.call(this,O));return x._events=new c.UserManagerEvents(O),x._silentRenewService=new X(x),x.settings.automaticSilentRenew&&(o.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),x.startSilentRenew()),x.settings.monitorSession&&(o.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),x._sessionMonitor=new ee(x)),x._tokenRevocationClient=new V(x._settings),x._tokenClient=new U(x._settings),x._joseUtil=v,x}return(function(X,ee){if(typeof ee!="function"&&ee!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof ee);X.prototype=Object.create(ee&&ee.prototype,{constructor:{value:X,enumerable:!1,writable:!0,configurable:!0}}),ee&&(Object.setPrototypeOf?Object.setPrototypeOf(X,ee):X.__proto__=ee)})(N,b),N.prototype.getUser=function(){var X=this;return this._loadUser().then((function(ee){return ee?(o.Log.info("UserManager.getUser: user loaded"),X._events.load(ee,!1),ee):(o.Log.info("UserManager.getUser: user not found in storage"),null)}))},N.prototype.removeUser=function(){var X=this;return this.storeUser(null).then((function(){o.Log.info("UserManager.removeUser: user removed from storage"),X._events.unload()}))},N.prototype.signinRedirect=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(X=Object.assign({},X)).request_type="si:r";var ee={useReplaceToNavigate:X.useReplaceToNavigate};return this._signinStart(X,this._redirectNavigator,ee).then((function(){o.Log.info("UserManager.signinRedirect: successful")}))},N.prototype.signinRedirectCallback=function(X){return this._signinEnd(X||this._redirectNavigator.url).then((function(ee){return ee.profile&&ee.profile.sub?o.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",ee.profile.sub):o.Log.info("UserManager.signinRedirectCallback: no sub"),ee}))},N.prototype.signinPopup=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(X=Object.assign({},X)).request_type="si:p";var ee=X.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return ee?(X.redirect_uri=ee,X.display="popup",this._signin(X,this._popupNavigator,{startUrl:ee,popupWindowFeatures:X.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:X.popupWindowTarget||this.settings.popupWindowTarget}).then((function(V){return V&&(V.profile&&V.profile.sub?o.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",V.profile.sub):o.Log.info("UserManager.signinPopup: no sub")),V}))):(o.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},N.prototype.signinPopupCallback=function(X){return this._signinCallback(X,this._popupNavigator).then((function(ee){return ee&&(ee.profile&&ee.profile.sub?o.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",ee.profile.sub):o.Log.info("UserManager.signinPopupCallback: no sub")),ee})).catch((function(ee){o.Log.error(ee.message)}))},N.prototype.signinSilent=function(){var X=this,ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return ee=Object.assign({},ee),this._loadUser().then((function(V){return V&&V.refresh_token?(ee.refresh_token=V.refresh_token,X._useRefreshToken(ee)):(ee.request_type="si:s",ee.id_token_hint=ee.id_token_hint||X.settings.includeIdTokenInSilentRenew&&V&&V.id_token,V&&X._settings.validateSubOnSilentRenew&&(o.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",V.profile.sub),ee.current_sub=V.profile.sub),X._signinSilentIframe(ee))}))},N.prototype._useRefreshToken=function(){var X=this,ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(ee).then((function(V){return V?V.access_token?X._loadUser().then((function(U){if(U){var v=Promise.resolve();return V.id_token&&(v=X._validateIdTokenFromTokenRefreshToken(U.profile,V.id_token)),v.then((function(){return o.Log.debug("UserManager._useRefreshToken: refresh token response success"),U.id_token=V.id_token||U.id_token,U.access_token=V.access_token,U.refresh_token=V.refresh_token||U.refresh_token,U.expires_in=V.expires_in,X.storeUser(U).then((function(){return X._events.load(U),U}))}))}return null})):(o.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(o.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},N.prototype._validateIdTokenFromTokenRefreshToken=function(X,ee){var V=this;return this._metadataService.getIssuer().then((function(U){return V.settings.getEpochTime().then((function(v){return V._joseUtil.validateJwtAttributes(ee,U,V._settings.client_id,V._settings.clockSkew,v).then((function(x){return x?x.sub!==X.sub?(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: sub in id_token does not match current sub"),Promise.reject(new Error("sub in id_token does not match current sub"))):x.auth_time&&x.auth_time!==X.auth_time?(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: auth_time in id_token does not match original auth_time"),Promise.reject(new Error("auth_time in id_token does not match original auth_time"))):x.azp&&x.azp!==X.azp?(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp in id_token does not match original azp"),Promise.reject(new Error("azp in id_token does not match original azp"))):!x.azp&&X.azp?(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: azp not in id_token, but present in original id_token"),Promise.reject(new Error("azp not in id_token, but present in original id_token"))):void 0:(o.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},N.prototype._signinSilentIframe=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ee=X.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return ee?(X.redirect_uri=ee,X.prompt=X.prompt||"none",this._signin(X,this._iframeNavigator,{startUrl:ee,silentRequestTimeout:X.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(V){return V&&(V.profile&&V.profile.sub?o.Log.info("UserManager.signinSilent: successful, signed in sub: ",V.profile.sub):o.Log.info("UserManager.signinSilent: no sub")),V}))):(o.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},N.prototype.signinSilentCallback=function(X){return this._signinCallback(X,this._iframeNavigator).then((function(ee){return ee&&(ee.profile&&ee.profile.sub?o.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",ee.profile.sub):o.Log.info("UserManager.signinSilentCallback: no sub")),ee}))},N.prototype.signinCallback=function(X){var ee=this;return this.readSigninResponseState(X).then((function(V){var U=V.state;return V.response,U.request_type==="si:r"?ee.signinRedirectCallback(X):U.request_type==="si:p"?ee.signinPopupCallback(X):U.request_type==="si:s"?ee.signinSilentCallback(X):Promise.reject(new Error("invalid response_type in state"))}))},N.prototype.signoutCallback=function(X,ee){var V=this;return this.readSignoutResponseState(X).then((function(U){var v=U.state,x=U.response;return v?v.request_type==="so:r"?V.signoutRedirectCallback(X):v.request_type==="so:p"?V.signoutPopupCallback(X,ee):Promise.reject(new Error("invalid response_type in state")):x}))},N.prototype.querySessionStatus=function(){var X=this,ee=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(ee=Object.assign({},ee)).request_type="si:s";var V=ee.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return V?(ee.redirect_uri=V,ee.prompt="none",ee.response_type=ee.response_type||this.settings.query_status_response_type,ee.scope=ee.scope||"openid",ee.skipUserInfo=!0,this._signinStart(ee,this._iframeNavigator,{startUrl:V,silentRequestTimeout:ee.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(U){return X.processSigninResponse(U.url).then((function(v){if(o.Log.debug("UserManager.querySessionStatus: got signin response"),v.session_state&&v.profile.sub)return o.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",v.profile.sub),{session_state:v.session_state,sub:v.profile.sub,sid:v.profile.sid};o.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(v){if(v.session_state&&X.settings.monitorAnonymousSession&&(v.message=="login_required"||v.message=="consent_required"||v.message=="interaction_required"||v.message=="account_selection_required"))return o.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:v.session_state};throw v}))}))):(o.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},N.prototype._signin=function(X,ee){var V=this,U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(X,ee,U).then((function(v){return V._signinEnd(v.url,X)}))},N.prototype._signinStart=function(X,ee){var V=this,U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return ee.prepare(U).then((function(v){return o.Log.debug("UserManager._signinStart: got navigator window handle"),V.createSigninRequest(X).then((function(x){return o.Log.debug("UserManager._signinStart: got signin request"),U.url=x.url,U.id=x.state.id,v.navigate(U)})).catch((function(x){throw v.close&&(o.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),v.close()),x}))}))},N.prototype._signinEnd=function(X){var ee=this,V=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(X).then((function(U){o.Log.debug("UserManager._signinEnd: got signin response");var v=new u.User(U);if(V.current_sub){if(V.current_sub!==v.profile.sub)return o.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",v.profile.sub),Promise.reject(new Error("login_required"));o.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return ee.storeUser(v).then((function(){return o.Log.debug("UserManager._signinEnd: user stored"),ee._events.load(v),v}))}))},N.prototype._signinCallback=function(X,ee){o.Log.debug("UserManager._signinCallback");var V=this._settings.response_mode==="query"||!this._settings.response_mode&&m.SigninRequest.isCode(this._settings.response_type)?"?":"#";return ee.callback(X,void 0,V)},N.prototype.signoutRedirect=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(X=Object.assign({},X)).request_type="so:r";var ee=X.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;ee&&(X.post_logout_redirect_uri=ee);var V={useReplaceToNavigate:X.useReplaceToNavigate};return this._signoutStart(X,this._redirectNavigator,V).then((function(){o.Log.info("UserManager.signoutRedirect: successful")}))},N.prototype.signoutRedirectCallback=function(X){return this._signoutEnd(X||this._redirectNavigator.url).then((function(ee){return o.Log.info("UserManager.signoutRedirectCallback: successful"),ee}))},N.prototype.signoutPopup=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(X=Object.assign({},X)).request_type="so:p";var ee=X.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return X.post_logout_redirect_uri=ee,X.display="popup",X.post_logout_redirect_uri&&(X.state=X.state||{}),this._signout(X,this._popupNavigator,{startUrl:ee,popupWindowFeatures:X.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:X.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){o.Log.info("UserManager.signoutPopup: successful")}))},N.prototype.signoutPopupCallback=function(X,ee){return ee===void 0&&typeof X=="boolean"&&(ee=X,X=null),this._popupNavigator.callback(X,ee,"?").then((function(){o.Log.info("UserManager.signoutPopupCallback: successful")}))},N.prototype._signout=function(X,ee){var V=this,U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(X,ee,U).then((function(v){return V._signoutEnd(v.url)}))},N.prototype._signoutStart=function(){var X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ee=this,V=arguments[1],U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return V.prepare(U).then((function(v){return o.Log.debug("UserManager._signoutStart: got navigator window handle"),ee._loadUser().then((function(x){return o.Log.debug("UserManager._signoutStart: loaded current user from storage"),(ee._settings.revokeAccessTokenOnSignout?ee._revokeInternal(x):Promise.resolve()).then((function(){var I=X.id_token_hint||x&&x.id_token;return I&&(o.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),X.id_token_hint=I),ee.removeUser().then((function(){return o.Log.debug("UserManager._signoutStart: user removed, creating signout request"),ee.createSignoutRequest(X).then((function(E){return o.Log.debug("UserManager._signoutStart: got signout request"),U.url=E.url,E.state&&(U.id=E.state.id),v.navigate(U)}))}))}))})).catch((function(x){throw v.close&&(o.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),v.close()),x}))}))},N.prototype._signoutEnd=function(X){return this.processSignoutResponse(X).then((function(ee){return o.Log.debug("UserManager._signoutEnd: got signout response"),ee}))},N.prototype.revokeAccessToken=function(){var X=this;return this._loadUser().then((function(ee){return X._revokeInternal(ee,!0).then((function(V){if(V)return o.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),ee.access_token=null,ee.refresh_token=null,ee.expires_at=null,ee.token_type=null,X.storeUser(ee).then((function(){o.Log.debug("UserManager.revokeAccessToken: user stored"),X._events.load(ee)}))}))})).then((function(){o.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},N.prototype._revokeInternal=function(X,ee){var V=this;if(X){var U=X.access_token,v=X.refresh_token;return this._revokeAccessTokenInternal(U,ee).then((function(x){return V._revokeRefreshTokenInternal(v,ee).then((function(I){return x||I||o.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),x||I}))}))}return Promise.resolve(!1)},N.prototype._revokeAccessTokenInternal=function(X,ee){return!X||X.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(X,ee).then((function(){return!0}))},N.prototype._revokeRefreshTokenInternal=function(X,ee){return X?this._tokenRevocationClient.revoke(X,ee,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},N.prototype.startSilentRenew=function(){this._silentRenewService.start()},N.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},N.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(X){return X?(o.Log.debug("UserManager._loadUser: user storageString loaded"),u.User.fromStorageString(X)):(o.Log.debug("UserManager._loadUser: no user storageString"),null)}))},N.prototype.storeUser=function(X){if(X){o.Log.debug("UserManager.storeUser: storing user");var ee=X.toStorageString();return this._userStore.set(this._userStoreKey,ee)}return o.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},i(N,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),N})(s.OidcClient)},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.UserManagerSettings=void 0;var i=(function(){function A(h,T){for(var w=0;w<T.length;w++){var b=T[w];b.enumerable=b.enumerable||!1,b.configurable=!0,"value"in b&&(b.writable=!0),Object.defineProperty(h,b.key,b)}}return function(h,T,w){return T&&A(h.prototype,T),w&&A(h,w),h}})(),o=(a(0),a(5)),s=a(40),d=a(41),u=a(43),c=a(6),p=a(1),_=a(8);function m(A,h){if(!(A instanceof h))throw new TypeError("Cannot call a class as a function")}function S(A,h){if(!A)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!h||typeof h!="object"&&typeof h!="function"?A:h}n.UserManagerSettings=(function(A){function h(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},w=T.popup_redirect_uri,b=T.popup_post_logout_redirect_uri,N=T.popupWindowFeatures,O=T.popupWindowTarget,X=T.silent_redirect_uri,ee=T.silentRequestTimeout,V=T.automaticSilentRenew,U=V!==void 0&&V,v=T.validateSubOnSilentRenew,x=v!==void 0&&v,I=T.includeIdTokenInSilentRenew,E=I===void 0||I,Q=T.monitorSession,K=Q===void 0||Q,te=T.monitorAnonymousSession,se=te!==void 0&&te,D=T.checkSessionInterval,ne=D===void 0?2e3:D,y=T.stopCheckSessionOnError,C=y===void 0||y,re=T.query_status_response_type,F=T.revokeAccessTokenOnSignout,ie=F!==void 0&&F,oe=T.accessTokenExpiringNotificationTime,le=oe===void 0?60:oe,ue=T.redirectNavigator,P=ue===void 0?new s.RedirectNavigator:ue,M=T.popupNavigator,Z=M===void 0?new d.PopupNavigator:M,z=T.iframeNavigator,G=z===void 0?new u.IFrameNavigator:z,g=T.userStore,R=g===void 0?new c.WebStorageStateStore({store:p.Global.sessionStorage}):g;m(this,h);var q=S(this,A.call(this,arguments[0]));return q._popup_redirect_uri=w,q._popup_post_logout_redirect_uri=b,q._popupWindowFeatures=N,q._popupWindowTarget=O,q._silent_redirect_uri=X,q._silentRequestTimeout=ee,q._automaticSilentRenew=U,q._validateSubOnSilentRenew=x,q._includeIdTokenInSilentRenew=E,q._accessTokenExpiringNotificationTime=le,q._monitorSession=K,q._monitorAnonymousSession=se,q._checkSessionInterval=ne,q._stopCheckSessionOnError=C,re?q._query_status_response_type=re:arguments[0]&&arguments[0].response_type?q._query_status_response_type=_.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":q._query_status_response_type="id_token",q._revokeAccessTokenOnSignout=ie,q._redirectNavigator=P,q._popupNavigator=Z,q._iframeNavigator=G,q._userStore=R,q}return(function(w,b){if(typeof b!="function"&&b!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof b);w.prototype=Object.create(b&&b.prototype,{constructor:{value:w,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(w,b):w.__proto__=b)})(h,A),i(h,[{key:"popup_redirect_uri",get:function(){return this._popup_redirect_uri}},{key:"popup_post_logout_redirect_uri",get:function(){return this._popup_post_logout_redirect_uri}},{key:"popupWindowFeatures",get:function(){return this._popupWindowFeatures}},{key:"popupWindowTarget",get:function(){return this._popupWindowTarget}},{key:"silent_redirect_uri",get:function(){return this._silent_redirect_uri}},{key:"silentRequestTimeout",get:function(){return this._silentRequestTimeout}},{key:"automaticSilentRenew",get:function(){return this._automaticSilentRenew}},{key:"validateSubOnSilentRenew",get:function(){return this._validateSubOnSilentRenew}},{key:"includeIdTokenInSilentRenew",get:function(){return this._includeIdTokenInSilentRenew}},{key:"accessTokenExpiringNotificationTime",get:function(){return this._accessTokenExpiringNotificationTime}},{key:"monitorSession",get:function(){return this._monitorSession}},{key:"monitorAnonymousSession",get:function(){return this._monitorAnonymousSession}},{key:"checkSessionInterval",get:function(){return this._checkSessionInterval}},{key:"stopCheckSessionOnError",get:function(){return this._stopCheckSessionOnError}},{key:"query_status_response_type",get:function(){return this._query_status_response_type}},{key:"revokeAccessTokenOnSignout",get:function(){return this._revokeAccessTokenOnSignout}},{key:"redirectNavigator",get:function(){return this._redirectNavigator}},{key:"popupNavigator",get:function(){return this._popupNavigator}},{key:"iframeNavigator",get:function(){return this._iframeNavigator}},{key:"userStore",get:function(){return this._userStore}}]),h})(o.OidcClientSettings)},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.RedirectNavigator=void 0;var i=(function(){function s(d,u){for(var c=0;c<u.length;c++){var p=u[c];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(d,p.key,p)}}return function(d,u,c){return u&&s(d.prototype,u),c&&s(d,c),d}})(),o=a(0);n.RedirectNavigator=(function(){function s(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,s)}return s.prototype.prepare=function(){return Promise.resolve(this)},s.prototype.navigate=function(u){return u&&u.url?(u.useReplaceToNavigate?window.location.replace(u.url):window.location=u.url,Promise.resolve()):(o.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},i(s,[{key:"url",get:function(){return window.location.href}}]),s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.PopupNavigator=void 0;var i=a(0),o=a(42);n.PopupNavigator=(function(){function s(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,s)}return s.prototype.prepare=function(u){var c=new o.PopupWindow(u);return Promise.resolve(c)},s.prototype.callback=function(u,c,p){i.Log.debug("PopupNavigator.callback");try{return o.PopupWindow.notifyOpener(u,c,p),Promise.resolve()}catch(_){return Promise.reject(_)}},s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.PopupWindow=void 0;var i=(function(){function d(u,c){for(var p=0;p<c.length;p++){var _=c[p];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(u,_.key,_)}}return function(u,c,p){return c&&d(u.prototype,c),p&&d(u,p),u}})(),o=a(0),s=a(3);n.PopupWindow=(function(){function d(u){var c=this;(function(S,A){if(!(S instanceof A))throw new TypeError("Cannot call a class as a function")})(this,d),this._promise=new Promise((function(m,S){c._resolve=m,c._reject=S}));var p=u.popupWindowTarget||"_blank",_=u.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",p,_),this._popup&&(o.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return d.prototype.navigate=function(c){return this._popup?c&&c.url?(o.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=c.id,this._id&&(window["popupCallback_"+c.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=c.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},d.prototype._success=function(c){o.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(c)},d.prototype._error=function(c){o.Log.error("PopupWindow.error: ",c),this._cleanup(),this._reject(new Error(c))},d.prototype.close=function(){this._cleanup(!1)},d.prototype._cleanup=function(c){o.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!c&&this._popup.close(),this._popup=null},d.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},d.prototype._callback=function(c,p){this._cleanup(p),c?(o.Log.debug("PopupWindow.callback success"),this._success({url:c})):(o.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},d.notifyOpener=function(c,p,_){if(window.opener){if(c=c||window.location.href){var m=s.UrlUtility.parseUrlFragment(c,_);if(m.state){var S="popupCallback_"+m.state,A=window.opener[S];A?(o.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),A(c,p)):o.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else o.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else o.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},i(d,[{key:"promise",get:function(){return this._promise}}]),d})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.IFrameNavigator=void 0;var i=a(0),o=a(44);n.IFrameNavigator=(function(){function s(){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,s)}return s.prototype.prepare=function(u){var c=new o.IFrameWindow(u);return Promise.resolve(c)},s.prototype.callback=function(u){i.Log.debug("IFrameNavigator.callback");try{return o.IFrameWindow.notifyParent(u),Promise.resolve()}catch(c){return Promise.reject(c)}},s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.IFrameWindow=void 0;var i=(function(){function s(d,u){for(var c=0;c<u.length;c++){var p=u[c];p.enumerable=p.enumerable||!1,p.configurable=!0,"value"in p&&(p.writable=!0),Object.defineProperty(d,p.key,p)}}return function(d,u,c){return u&&s(d.prototype,u),c&&s(d,c),d}})(),o=a(0);n.IFrameWindow=(function(){function s(d){var u=this;(function(p,_){if(!(p instanceof _))throw new TypeError("Cannot call a class as a function")})(this,s),this._promise=new Promise((function(c,p){u._resolve=c,u._reject=p})),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.width=0,this._frame.height=0,window.document.body.appendChild(this._frame)}return s.prototype.navigate=function(u){if(u&&u.url){var c=u.silentRequestTimeout||1e4;o.Log.debug("IFrameWindow.navigate: Using timeout of:",c),this._timer=window.setTimeout(this._timeout.bind(this),c),this._frame.src=u.url}else this._error("No url provided");return this.promise},s.prototype._success=function(u){this._cleanup(),o.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(u)},s.prototype._error=function(u){this._cleanup(),o.Log.error(u),this._reject(new Error(u))},s.prototype.close=function(){this._cleanup()},s.prototype._cleanup=function(){this._frame&&(o.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},s.prototype._timeout=function(){o.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},s.prototype._message=function(u){if(o.Log.debug("IFrameWindow.message"),this._timer&&u.origin===this._origin&&u.source===this._frame.contentWindow&&typeof u.data=="string"&&(u.data.startsWith("http://")||u.data.startsWith("https://"))){var c=u.data;c?this._success({url:c}):this._error("Invalid response from frame")}},s.notifyParent=function(u){o.Log.debug("IFrameWindow.notifyParent"),(u=u||window.location.href)&&(o.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(u,location.protocol+"//"+location.host))},i(s,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),s})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.UserManagerEvents=void 0;var i=a(0),o=a(16),s=a(17);n.UserManagerEvents=(function(d){function u(c){(function(m,S){if(!(m instanceof S))throw new TypeError("Cannot call a class as a function")})(this,u);var p=(function(m,S){if(!m)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?m:S})(this,d.call(this,c));return p._userLoaded=new s.Event("User loaded"),p._userUnloaded=new s.Event("User unloaded"),p._silentRenewError=new s.Event("Silent renew error"),p._userSignedIn=new s.Event("User signed in"),p._userSignedOut=new s.Event("User signed out"),p._userSessionChanged=new s.Event("User session changed"),p}return(function(p,_){if(typeof _!="function"&&_!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof _);p.prototype=Object.create(_&&_.prototype,{constructor:{value:p,enumerable:!1,writable:!0,configurable:!0}}),_&&(Object.setPrototypeOf?Object.setPrototypeOf(p,_):p.__proto__=_)})(u,d),u.prototype.load=function(p){var _=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];i.Log.debug("UserManagerEvents.load"),d.prototype.load.call(this,p),_&&this._userLoaded.raise(p)},u.prototype.unload=function(){i.Log.debug("UserManagerEvents.unload"),d.prototype.unload.call(this),this._userUnloaded.raise()},u.prototype.addUserLoaded=function(p){this._userLoaded.addHandler(p)},u.prototype.removeUserLoaded=function(p){this._userLoaded.removeHandler(p)},u.prototype.addUserUnloaded=function(p){this._userUnloaded.addHandler(p)},u.prototype.removeUserUnloaded=function(p){this._userUnloaded.removeHandler(p)},u.prototype.addSilentRenewError=function(p){this._silentRenewError.addHandler(p)},u.prototype.removeSilentRenewError=function(p){this._silentRenewError.removeHandler(p)},u.prototype._raiseSilentRenewError=function(p){i.Log.debug("UserManagerEvents._raiseSilentRenewError",p.message),this._silentRenewError.raise(p)},u.prototype.addUserSignedIn=function(p){this._userSignedIn.addHandler(p)},u.prototype.removeUserSignedIn=function(p){this._userSignedIn.removeHandler(p)},u.prototype._raiseUserSignedIn=function(){i.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},u.prototype.addUserSignedOut=function(p){this._userSignedOut.addHandler(p)},u.prototype.removeUserSignedOut=function(p){this._userSignedOut.removeHandler(p)},u.prototype._raiseUserSignedOut=function(){i.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},u.prototype.addUserSessionChanged=function(p){this._userSessionChanged.addHandler(p)},u.prototype.removeUserSessionChanged=function(p){this._userSessionChanged.removeHandler(p)},u.prototype._raiseUserSessionChanged=function(){i.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},u})(o.AccessTokenEvents)},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.Timer=void 0;var i=(function(){function p(_,m){for(var S=0;S<m.length;S++){var A=m[S];A.enumerable=A.enumerable||!1,A.configurable=!0,"value"in A&&(A.writable=!0),Object.defineProperty(_,A.key,A)}}return function(_,m,S){return m&&p(_.prototype,m),S&&p(_,S),_}})(),o=a(0),s=a(1),d=a(17);function u(p,_){if(!(p instanceof _))throw new TypeError("Cannot call a class as a function")}function c(p,_){if(!p)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!_||typeof _!="object"&&typeof _!="function"?p:_}n.Timer=(function(p){function _(m){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:s.Global.timer,A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;u(this,_);var h=c(this,p.call(this,m));return h._timer=S,h._nowFunc=A||function(){return Date.now()/1e3},h}return(function(S,A){if(typeof A!="function"&&A!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof A);S.prototype=Object.create(A&&A.prototype,{constructor:{value:S,enumerable:!1,writable:!0,configurable:!0}}),A&&(Object.setPrototypeOf?Object.setPrototypeOf(S,A):S.__proto__=A)})(_,p),_.prototype.init=function(S){S<=0&&(S=1),S=parseInt(S);var A=this.now+S;if(this.expiration===A&&this._timerHandle)o.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),o.Log.debug("Timer.init timer "+this._name+" for duration:",S),this._expiration=A;var h=5;S<h&&(h=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*h)}},_.prototype.cancel=function(){this._timerHandle&&(o.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},_.prototype._callback=function(){var S=this._expiration-this.now;o.Log.debug("Timer.callback; "+this._name+" timer expires in:",S),this._expiration<=this.now&&(this.cancel(),p.prototype.raise.call(this))},i(_,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),_})(d.Event)},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.SilentRenewService=void 0;var i=a(0);n.SilentRenewService=(function(){function o(s){(function(u,c){if(!(u instanceof c))throw new TypeError("Cannot call a class as a function")})(this,o),this._userManager=s}return o.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(d){})).catch((function(d){i.Log.error("SilentRenewService.start: Error from getUser:",d.message)})))},o.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},o.prototype._tokenExpiring=function(){var d=this;this._userManager.signinSilent().then((function(u){i.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(u){i.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",u.message),d._userManager.events._raiseSilentRenewError(u)}))},o})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.CordovaPopupNavigator=void 0;var i=a(21);n.CordovaPopupNavigator=(function(){function o(){(function(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")})(this,o)}return o.prototype.prepare=function(d){var u=new i.CordovaPopupWindow(d);return Promise.resolve(u)},o})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.CordovaIFrameNavigator=void 0;var i=a(21);n.CordovaIFrameNavigator=(function(){function o(){(function(d,u){if(!(d instanceof u))throw new TypeError("Cannot call a class as a function")})(this,o)}return o.prototype.prepare=function(d){d.popupWindowFeatures="hidden=yes";var u=new i.CordovaPopupWindow(d);return Promise.resolve(u)},o})()},function(t,n,a){Object.defineProperty(n,"__esModule",{value:!0}),n.Version="1.11.6"}])}))})(oidcClient_min$1)),oidcClient_min$1.exports}var oidcClient_minExports=requireOidcClient_min();function processErrorResponse(r,e){throw r.error==="invalid_redirect_uri"?new Error(`Dynamic client registration failed: the provided redirect uri [${e.redirectUrl?.toString()}] is invalid - ${r.error_description??""}`):r.error==="invalid_client_metadata"?new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(e)} is invalid - ${r.error_description??""}`):new Error(`Dynamic client registration failed: ${r.error} - ${r.error_description??""}`)}function hasClientId(r){return typeof r.client_id=="string"}function hasRedirectUri(r){return Array.isArray(r.redirect_uris)&&r.redirect_uris.every(e=>typeof e=="string")}function validateRegistrationResponse(r,e){if(!hasClientId(r))throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(r)}`);if(e.redirectUrl&&hasRedirectUri(r)&&r.redirect_uris[0]!==e.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(r.redirect_uris)} don't match the provided ${JSON.stringify([e.redirectUrl.toString()])}`);return!0}async function registerClient(r,e){if(!e.registrationEndpoint)throw new Error("Dynamic Registration could not be completed because the issuer has no registration endpoint.");if(!Array.isArray(e.idTokenSigningAlgValuesSupported))throw new Error("The OIDC issuer discovery profile is missing the 'id_token_signing_alg_values_supported' value, which is mandatory.");const t=determineSigningAlg(e.idTokenSigningAlgValuesSupported,PREFERRED_SIGNING_ALG),n={client_name:r.clientName,application_type:"web",redirect_uris:[r.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:t,grant_types:["authorization_code","refresh_token"]},a={"Content-Type":"application/json"},i=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:a,body:JSON.stringify(n)});if(i.ok){const o=await i.json();return validateRegistrationResponse(o,r),{clientId:o.client_id,clientSecret:o.client_secret,expiresAt:o.client_secret_expires_at,idTokenSignedResponseAlg:o.id_token_signed_response_alg,clientType:"dynamic"}}throw i.status===400&&processErrorResponse(await i.json(),r),new Error(`Dynamic client registration failed: the server returned ${i.status} ${i.statusText} - ${await i.text()}`)}function hasError(r){return r.error!==void 0&&typeof r.error=="string"}function hasErrorDescription(r){return r.error_description!==void 0&&typeof r.error_description=="string"}function hasErrorUri(r){return r.error_uri!==void 0&&typeof r.error_uri=="string"}function hasAccessToken(r){return r.access_token!==void 0&&typeof r.access_token=="string"}function hasIdToken(r){return r.id_token!==void 0&&typeof r.id_token=="string"}function hasRefreshToken(r){return r.refresh_token!==void 0&&typeof r.refresh_token=="string"}function hasTokenType(r){return r.token_type!==void 0&&typeof r.token_type=="string"}function hasExpiresIn(r){return r.expires_in===void 0||typeof r.expires_in=="number"}function validatePreconditions(r,e){if(e.grantType&&(!r.grantTypesSupported||!r.grantTypesSupported.includes(e.grantType)))throw new Error(`The issuer [${r.issuer}] does not support the [${e.grantType}] grant`);if(!r.tokenEndpoint)throw new Error(`This issuer [${r.issuer}] does not have a token endpoint`)}function validateTokenEndpointResponse(r,e){if(hasError(r))throw new OidcProviderError(`Token endpoint returned error [${r.error}]${hasErrorDescription(r)?`: ${r.error_description}`:""}${hasErrorUri(r)?` (see ${r.error_uri})`:""}`,r.error,hasErrorDescription(r)?r.error_description:void 0);if(!hasAccessToken(r))throw new InvalidResponseError(["access_token"]);if(!hasIdToken(r))throw new InvalidResponseError(["id_token"]);if(!hasTokenType(r))throw new InvalidResponseError(["token_type"]);if(!hasExpiresIn(r))throw new InvalidResponseError(["expires_in"]);if(!e&&r.token_type.toLowerCase()!=="bearer")throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${r.token_type}].`);return r}async function getTokens(r,e,t,n){validatePreconditions(r,t);const a={"content-type":"application/x-www-form-urlencoded"};let i;n&&(i=await generateDpopKeyPair(),a.DPoP=await createDpopHeader(r.tokenEndpoint,"POST",i)),e.clientSecret&&(a.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const o={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},s={method:"POST",headers:a,body:new URLSearchParams(o).toString()},u=await(await fetch(r.tokenEndpoint,s)).json(),c=validateTokenEndpointResponse(u,n),{webId:p,clientId:_}=await getWebidFromTokenPayload(c.id_token,r.jwksUri,r.issuer,e.clientId);return{accessToken:c.access_token,idToken:c.id_token,refreshToken:hasRefreshToken(c)?c.refresh_token:void 0,webId:p,clientId:_,dpopKey:i,expiresIn:c.expires_in}}const isValidUrl=r=>{try{return new URL(r),!0}catch{return!1}};async function refresh(r,e,t,n){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const a={grant_type:"refresh_token",refresh_token:r};let i={};n!==void 0&&(i={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",n)});let o={};t.clientSecret!==void 0?o={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(a.client_id=t.clientId);const s=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(a).toString(),headers:{...i,...o,"Content-Type":"application/x-www-form-urlencoded"}});let d;try{d=await s.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const u=validateTokenEndpointResponse(d,n!==void 0),{webId:c}=await getWebidFromTokenPayload(u.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:u.access_token,idToken:u.id_token,refreshToken:typeof u.refresh_token=="string"?u.refresh_token:void 0,webId:c,dpopKey:n,expiresIn:u.expires_in}}function normalizeCallbackUrl(r){const e=removeOpenIdParams(r);return e.hash="",r.includes(`${e.origin}/`)?e.href:`${e.origin}${e.href.substring(e.origin.length+1)}`}async function clearOidcPersistentStorage(){await new oidcClient_minExports.OidcClient({response_mode:"query"}).clearStaleState(new oidcClient_minExports.WebStorageStateStore({}));const e=window.localStorage,t=[];for(let n=0;n<=e.length;n+=1){const a=e.key(n);a&&(a.match(/^oidc\..+$/)||a.match(/^solidClientAuthenticationUser:.+$/))&&t.push(a)}t.forEach(n=>e.removeItem(n))}class StorageUtilityBrowser extends StorageUtility{constructor(e,t){super(e,t)}}class ClientAuthentication extends ClientAuthentication$1{login=async(e,t)=>{e.prompt!=="none"&&await this.sessionInfoManager.clear(e.sessionId);const n=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(n))throw new Error(`${n} is not a valid redirect URL, it is either a malformed IRI, includes a hash fragment, or reserved query parameters ('code' or 'state').`);await this.loginHandler.handle({...e,redirectUrl:n,clientName:e.clientName??e.clientId,eventEmitter:t})};validateCurrentSession=async e=>{const t=await this.sessionInfoManager.get(e);return t===void 0||t.clientAppId===void 0||t.issuer===void 0?null:t};handleIncomingRedirect=async(e,t)=>{try{const n=await this.redirectHandler.handle(e,t,void 0);return this.fetch=n.fetch.bind(window),this.boundLogout=n.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:n.isLoggedIn,webId:n.webId,sessionId:n.sessionId,expirationDate:n.expirationDate,clientAppId:n.clientAppId}}catch(n){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",n);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(n=>{setTimeout(()=>n(),1)})}}function hasIssuer(r){return typeof r.oidcIssuer=="string"}function hasRedirectUrl(r){return typeof r.redirectUrl=="string"}class OidcLoginHandler{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,n,a){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=n,this.clientRegistrar=a,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=n,this.clientRegistrar=a}async canHandle(e){return hasIssuer(e)&&hasRedirectUrl(e)}async handle(e){if(!hasIssuer(e))throw new ConfigurationError(`OidcLoginHandler requires an OIDC issuer: missing property 'oidcIssuer' in ${JSON.stringify(e)}`);if(!hasRedirectUrl(e))throw new ConfigurationError(`OidcLoginHandler requires a redirect URL: missing property 'redirectUrl' in ${JSON.stringify(e)}`);const t=await this.issuerConfigFetcher.fetchConfig(e.oidcIssuer),n=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),a={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:n,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(a)}}class AuthorizationCodeWithPkceOidcHandler extends AuthorizationCodeWithPkceOidcHandlerBase{async handle(e){const t={authority:e.issuer.toString(),client_id:e.client.clientId,client_secret:e.client.clientSecret,redirect_uri:e.redirectUrl,response_type:"code",scope:e.scopes.join(" "),filterProtocolClaims:!0,loadUserInfo:!1,code_verifier:!0,prompt:e.prompt??"consent"},n=new oidcClient_minExports.OidcClient(t);try{const a=await n.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:a.state._id,codeVerifier:a.state._code_verifier,targetUrl:a.url.toString()})}catch(a){console.error(a)}}}const WELL_KNOWN_OPENID_CONFIG=".well-known/openid-configuration",issuerConfigKeyMap={issuer:{toKey:"issuer",convertToUrl:!0},authorization_endpoint:{toKey:"authorizationEndpoint",convertToUrl:!0},token_endpoint:{toKey:"tokenEndpoint",convertToUrl:!0},userinfo_endpoint:{toKey:"userinfoEndpoint",convertToUrl:!0},jwks_uri:{toKey:"jwksUri",convertToUrl:!0},registration_endpoint:{toKey:"registrationEndpoint",convertToUrl:!0},end_session_endpoint:{toKey:"endSessionEndpoint",convertToUrl:!0},scopes_supported:{toKey:"scopesSupported"},response_types_supported:{toKey:"responseTypesSupported"},response_modes_supported:{toKey:"responseModesSupported"},grant_types_supported:{toKey:"grantTypesSupported"},acr_values_supported:{toKey:"acrValuesSupported"},subject_types_supported:{toKey:"subjectTypesSupported"},id_token_signing_alg_values_supported:{toKey:"idTokenSigningAlgValuesSupported"},id_token_encryption_alg_values_supported:{toKey:"idTokenEncryptionAlgValuesSupported"},id_token_encryption_enc_values_supported:{toKey:"idTokenEncryptionEncValuesSupported"},userinfo_signing_alg_values_supported:{toKey:"userinfoSigningAlgValuesSupported"},userinfo_encryption_alg_values_supported:{toKey:"userinfoEncryptionAlgValuesSupported"},userinfo_encryption_enc_values_supported:{toKey:"userinfoEncryptionEncValuesSupported"},request_object_signing_alg_values_supported:{toKey:"requestObjectSigningAlgValuesSupported"},request_object_encryption_alg_values_supported:{toKey:"requestObjectEncryptionAlgValuesSupported"},request_object_encryption_enc_values_supported:{toKey:"requestObjectEncryptionEncValuesSupported"},token_endpoint_auth_methods_supported:{toKey:"tokenEndpointAuthMethodsSupported"},token_endpoint_auth_signing_alg_values_supported:{toKey:"tokenEndpointAuthSigningAlgValuesSupported"},display_values_supported:{toKey:"displayValuesSupported"},claim_types_supported:{toKey:"claimTypesSupported"},claims_supported:{toKey:"claimsSupported"},service_documentation:{toKey:"serviceDocumentation"},claims_locales_supported:{toKey:"claimsLocalesSupported"},ui_locales_supported:{toKey:"uiLocalesSupported"},claims_parameter_supported:{toKey:"claimsParameterSupported"},request_parameter_supported:{toKey:"requestParameterSupported"},request_uri_parameter_supported:{toKey:"requestUriParameterSupported"},require_request_uri_registration:{toKey:"requireRequestUriRegistration"},op_policy_uri:{toKey:"opPolicyUri",convertToUrl:!0},op_tos_uri:{toKey:"opTosUri",convertToUrl:!0}};function processConfig(r){const e={};return Object.keys(r).forEach(t=>{issuerConfigKeyMap[t]&&(e[issuerConfigKeyMap[t].toKey]=r[t])}),Array.isArray(e.scopesSupported)||(e.scopesSupported=["openid"]),e}class IssuerConfigFetcher{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}static getLocalStorageKey(e){return`issuerConfig:${e}`}async fetchConfig(e){let t;const n=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,a=await fetch(n);try{t=processConfig(await a.json())}catch(i){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${i.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function clear(r,e){await clear$1(r,e),await clearOidcPersistentStorage()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,n,a,i,o,s,d,u]=await Promise.all([this.storageUtility.getForUser(e,"isLoggedIn",{secure:!0}),this.storageUtility.getForUser(e,"webId",{secure:!0}),this.storageUtility.getForUser(e,"clientId",{secure:!1}),this.storageUtility.getForUser(e,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e,"redirectUrl",{secure:!1}),this.storageUtility.getForUser(e,"refreshToken",{secure:!0}),this.storageUtility.getForUser(e,"issuer",{secure:!1}),this.storageUtility.getForUser(e,"tokenType",{secure:!1})]);if(typeof o=="string"&&!isValidRedirectUrl(o)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(u!==void 0&&!isSupportedTokenType(u))throw new Error(`Tokens of type [${u}] are not supported.`);if(!(a===void 0&&t===void 0&&n===void 0&&s===void 0))return{sessionId:e,webId:n,isLoggedIn:t==="true",redirectUrl:o,refreshToken:s,issuer:d,clientAppId:a,clientAppSecret:i,tokenType:u??"DPoP"}}async clear(e){return clear(e,this.storageUtility)}}class FallbackRedirectHandler{async canHandle(e){try{return new URL(e),!0}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e){return getUnauthenticatedSession()}}class AuthCodeRedirectHandler{storageUtility;sessionInfoManager;issuerConfigFetcher;clientRegistrar;tokerRefresher;fetch;constructor(e,t,n,a,i,o){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=n,this.clientRegistrar=a,this.tokerRefresher=i,this.fetch=o,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=n,this.clientRegistrar=a,this.tokerRefresher=i}async canHandle(e){try{const t=new URL(e);return t.searchParams.get("code")!==null&&t.searchParams.get("state")!==null}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(!await this.canHandle(e))throw new Error(`AuthCodeRedirectHandler cannot handle [${e}]: it is missing one of [code, state].`);const n=new URL(e),a=n.searchParams.get("state"),i=await this.storageUtility.getForUser(a,"sessionId",{errorIfNull:!0}),{issuerConfig:o,codeVerifier:s,redirectUrl:d,dpop:u}=await loadOidcContextFromStorage(i,this.storageUtility,this.issuerConfigFetcher),c=n.searchParams.get("iss");if(typeof c=="string"&&c!==o.issuer)throw new Error(`The value of the iss parameter (${c}) does not match the issuer identifier of the authorization server (${o.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(s===void 0)throw new Error(`The code verifier for session ${i} is missing from storage.`);if(d===void 0)throw new Error(`The redirect URL for session ${i} is missing from storage.`);const p=await this.clientRegistrar.getClient({sessionId:i},o),_=Date.now(),m=await getTokens(o,p,{grantType:"authorization_code",code:n.searchParams.get("code"),codeVerifier:s,redirectUrl:d},u);window.localStorage.removeItem(`oidc.${a}`);let S;m.refreshToken!==void 0&&(S={sessionId:i,refreshToken:m.refreshToken,tokenRefresher:this.tokerRefresher});const A=buildAuthenticatedFetch(m.accessToken,{dpopKey:m.dpopKey,refreshOptions:S,eventEmitter:t,expiresIn:m.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,i,m.webId,m.clientId,"true",void 0,!0);const h=await this.sessionInfoManager.get(i);if(!h)throw new Error(`Could not retrieve session: [${i}].`);return Object.assign(h,{fetch:A,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:m.idToken,endSessionEndpoint:o.endSessionEndpoint}),expirationDate:typeof m.expiresIn=="number"?_+m.expiresIn*1e3:void 0})}}class AggregateRedirectHandler extends AggregateHandler{constructor(e){super(e)}}class BrowserStorage{get storage(){return window.localStorage}async get(e){return this.storage.getItem(e)||void 0}async set(e,t){this.storage.setItem(e,t)}async delete(e){this.storage.removeItem(e)}}class Redirector{redirect(e,t){t&&t.handleRedirect?t.handleRedirect(e):t&&t.redirectByReplacingState?window.history.replaceState({},"",e):window.location.href=e}}class ClientRegistrar{storageUtility;constructor(e){this.storageUtility=e,this.storageUtility=e}async getClient(e,t){const[n,a,i,o,s]=await Promise.all([this.storageUtility.getForUser(e.sessionId,"clientId",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientSecret",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"expiresAt",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientName",{secure:!1}),this.storageUtility.getForUser(e.sessionId,"clientType",{secure:!1})]),d=i!==void 0?Number.parseInt(i,10):-1,u=a!==void 0&&d!==0&&Math.floor(Date.now()/1e3)>d;if(n&&isKnownClientType(s)&&!u)return a!==void 0?{clientId:n,clientSecret:a,clientName:o,clientType:"dynamic",expiresAt:d}:{clientId:n,clientName:o,clientType:s};try{const c=await registerClient(e,t),p={clientId:c.clientId,clientType:"dynamic"};return c.clientSecret!==void 0&&(p.clientSecret=c.clientSecret,p.expiresAt=String(c.expiresAt)),c.idTokenSignedResponseAlg&&(p.idTokenSignedResponseAlg=c.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,p,{secure:!1}),c}catch(c){throw new Error("Client registration failed.",{cause:c})}}}class ErrorOidcHandler{async canHandle(e){try{return new URL(e).searchParams.has("error")}catch(t){throw new Error(`[${e}] is not a valid URL, and cannot be used as a redirect URL: ${t}`)}}async handle(e,t){if(t!==void 0){const n=new URL(e),a=n.searchParams.get("error"),i=n.searchParams.get("error_description");t.emit(EVENTS.ERROR,a,i)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,n){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=n,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=n}async refresh(e,t,n,a){const i=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),o=await this.clientRegistrar.getClient({sessionId:e},i.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(i.dpop&&n===void 0)throw new Error(`For session [${e}], the key bound to the DPoP access token must be provided to refresh said access token.`);const s=await refresh(t,i.issuerConfig,o,n);return s.refreshToken!==void 0&&a?.emit(EVENTS.NEW_REFRESH_TOKEN,s.refreshToken),s}}function getClientAuthenticationWithDependencies(r){const e=new InMemoryStorage,t=r.secureStorage||e,n=r.insecureStorage||new BrowserStorage,a=new StorageUtilityBrowser(t,n),i=new IssuerConfigFetcher(a),o=new ClientRegistrar(a),s=new SessionInfoManager(a),d=new TokenRefresher(a,i,o),u=new Redirector,c=new OidcLoginHandler(a,new AuthorizationCodeWithPkceOidcHandler(a,u),i,o),p=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(a,s,i,o,d,r.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(c,p,new IWaterfallLogoutHandler(s,u),s,i)}const KEY_CURRENT_SESSION=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,KEY_CURRENT_URL=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;async function silentlyAuthenticate(r,e,t){const n=await e.validateCurrentSession(r);return n!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:r,prompt:"none",oidcIssuer:n.issuer,redirectUrl:n.redirectUrl,clientId:n.clientAppId,clientSecret:n.clientAppSecret,tokenType:n.tokenType??"DPoP"},t.events),!0):!1}function isLoggedIn(r){return!!r?.isLoggedIn}class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;xpodErrorLogout=Promise.resolve();constructor(e={},t=void 0){this.events=new EventEmitter,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=getClientAuthenticationWithDependencies({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage,fetch:e.fetch}):this.clientAuthentication=getClientAuthenticationWithDependencies({fetch:e.fetch}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??v4$1(),isLoggedIn:!1},this.events.on(EVENTS.LOGIN,()=>window.localStorage.setItem(KEY_CURRENT_SESSION,this.info.sessionId)),this.events.on(EVENTS.SESSION_EXPIRED,()=>this.internalLogout(!1)),this.events.on(EVENTS.ERROR,()=>{this.xpodErrorLogout=this.xpodErrorLogout.then(()=>this.internalLogout(!1),()=>this.internalLogout(!1)),this.xpodErrorLogout.catch(()=>{})})}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(KEY_CURRENT_SESSION),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(EVENTS.LOGOUT)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t=typeof e=="string"?{url:e}:e,n=t.url??window.location.href;this.tokenRequestInProgress=!0;const a=await this.clientAuthentication.handleIncomingRedirect(n,this.events);try{await this.xpodErrorLogout}catch(i){throw this.tokenRequestInProgress=!1,i}if(isLoggedIn(a)){this.setSessionInfo(a);const i=window.localStorage.getItem(KEY_CURRENT_URL);i===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,i))}else if(t.restorePreviousSession===!0){const i=window.localStorage.getItem(KEY_CURRENT_SESSION);if(i!==null&&await silentlyAuthenticate(i,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,a};setSessionInfo(e){this.info.isLoggedIn=e.isLoggedIn,this.info.webId=e.webId,this.info.sessionId=e.sessionId,this.info.clientAppId=e.clientAppId,this.info.expirationDate=e.expirationDate,this.events.on(EVENTS.SESSION_EXTENDED,t=>{this.info.expirationDate=Date.now()+t*1e3})}}async function chooseAccessRoute(r,e={}){const t=usableRoutes(r,e.managedClient??!0,e.allowLocalOnlyRoutes??!1);if(t.length===0)return null;const n=t[0];if(isSelfProvenRoute(n))return n;const a=e.probe??defaultProbe,i=e.probeTimeoutMs??1e3;return(await Promise.all(t.map(async s=>({route:s,ok:isSelfProvenRoute(s)||await probeWithTimeout(s,a,i)})))).find(s=>s.ok)?.route??null}function isSelfProvenRoute(r){return r.health==="healthy"}function usableRoutes(r,e,t){return r.routes.filter(n=>n.health!=="unreachable").filter(n=>e||!n.requiresManagedClient).filter(n=>t||n.visibility!=="local-only").slice().sort((n,a)=>n.priority-a.priority||n.id.localeCompare(a.id))}function createSolidAccessRouteFetch(r){const e=r.managedClient??!0;let t;const n=async d=>{const u=r.routes(),c=d===void 0?u:u.filter(m=>routeKey(m)!==d),p={canonicalUrl:c[0]?.canonicalUrl??"",routes:c},_=await chooseAccessRoute(p,{managedClient:e,...r.allowLocalOnlyRoutes===void 0?{}:{allowLocalOnlyRoutes:r.allowLocalOnlyRoutes},...r.probeTimeoutMs===void 0?{}:{probeTimeoutMs:r.probeTimeoutMs},...r.probe===void 0?{}:{probe:r.probe}});return t=_??void 0,_},a=async()=>t&&r.routes().some(d=>d.id===t?.id&&d.targetUrl===t?.targetUrl)?t:await n()??void 0,i=d=>createSolidLocalRouteFetch({fetch:r.fetch,routes:()=>[{canonicalBaseUrl:d.canonicalUrl,localBaseUrl:d.targetUrl}]}),o=d=>!!resolveSolidLocalRouteUrl(d,r.routes().map(toLocalRoute$1)),s=d=>{const u=requestUrl(d);if(!u||!o(u))return;const c=r.routes(),p=usableRoutes({canonicalUrl:c[0]?.canonicalUrl??"",routes:c},e,r.allowLocalOnlyRoutes??!1)[0];if(!(!p||sameOrigin(p.targetUrl,u)))return u};return async(d,u)=>{const c=requestUrl(d);if(!c||!o(c))return u===void 0?r.fetch.call(globalThis,d):r.fetch.call(globalThis,d,u);const p=await a();if(!p){const _=s(d);if(_)throw new NoUsableAccessRouteError(_.href,r.routes());return u===void 0?r.fetch.call(globalThis,d):r.fetch.call(globalThis,d,u)}try{return await i(p)(d,u)}catch(_){t=void 0;const m=(u?.method??(d instanceof Request?d.method:"GET")).toUpperCase();if(!["GET","HEAD","OPTIONS"].includes(m))throw _;await r.refreshRoutes?.();const S=await n(routeKey(p));if(S&&routeKey(S)!==routeKey(p))return i(S)(d,u);const A=requestUrl(d);throw A&&o(A)?new NoUsableAccessRouteError(A.href,r.routes(),_):_}}}function routeKey(r){return`${r.id}|${r.targetUrl}`}class NoUsableAccessRouteError extends Error{constructor(e,t,n){super(`No usable access route can reach ${e}`),this.url=e,this.routes=t,this.reason=n,this.name="NoUsableAccessRouteError"}}function toLocalRoute$1(r){return{canonicalBaseUrl:r.canonicalUrl,localBaseUrl:r.targetUrl}}function sameOrigin(r,e){try{return new URL(r).origin===e.origin}catch{return!1}}function requestUrl(r){if(r instanceof Request)try{return new URL(r.url)}catch{return}try{return new URL(String(r))}catch{return}}async function probeWithTimeout(r,e,t){const n=new AbortController,a=setTimeout(()=>n.abort(),t);try{return await Promise.resolve(e(r,n.signal))}catch{return!1}finally{clearTimeout(a)}}function answersAccessRoute(r){return r.status<500}async function defaultProbe(r,e){if(!r.targetUrl.startsWith("http://")&&!r.targetUrl.startsWith("https://"))return r.health==="healthy";const t=await fetch(new URL("/.well-known/solid",r.targetUrl),{method:"HEAD",signal:e});return answersAccessRoute(t)}function snapshotFromSessionInfo(r){return r?.isLoggedIn&&r.webId?{status:"authenticated",webId:r.webId}:{status:"anonymous"}}function normalizeError(r){return r instanceof Error?r:new Error(String(r))}function snapshotFromSessionError(r,e){return{status:"error",webId:e.webId,error:normalizeError(r)}}function snapshotFromSessionExpired(r){return{status:"expired",...r.webId===void 0?{}:{webId:r.webId}}}function areSnapshotsEqual(r,e){return!r||r.status!==e.status||r.webId!==e.webId?!1:r.status==="error"&&e.status==="error"?r.error===e.error:!0}function createSolidSessionRuntime(r={}){const e=r.session??new Session,t=new Set;let n={status:"initializing"},a,i,o,s,d=!1,u=!1,c,p=!1,_=0,m=!1,S=0,A=0,h;const T=()=>{_+=1,m=!0},w=U=>{if(p||((U.status!=="authenticated"||n.status!=="authenticated"||n.webId!==U.webId)&&T(),U.status==="authenticated"&&(m=!1),n=U,areSnapshotsEqual(a,n)))return n;a=n;for(const v of t)v(n);return n},b=()=>{if(h){if(h.generation!==A||h.eventWebId&&h.eventWebId!==e.info.webId)return n;h.eventWebId=e.info.webId}return T(),a=void 0,w(snapshotFromSessionInfo(e.info))},N=()=>(A+=1,w({status:"anonymous"})),O=()=>(A+=1,w(snapshotFromSessionExpired(e.info))),X=(U,v)=>{if(h&&h.generation!==A)return;A+=1;const x=snapshotFromSessionError(v??U??"Solid session error",e.info);u&&(c=x),w(x)};e.events.on(EVENTS.LOGIN,b),e.events.on(EVENTS.SESSION_RESTORED,b),e.events.on(EVENTS.LOGOUT,N),e.events.on(EVENTS.SESSION_EXPIRED,O);const ee=e.events;ee.on(EVENTS.ERROR,X);const V=(U,v)=>{const x=new Promise((I,E)=>{s=()=>I(n),o=setTimeout(()=>{if(o=void 0,!p&&v.generation===A&&(A+=1,n.status==="initializing")){const K=new Error("Previous login is still completing. Reload before reconnecting.");K.name="SolidSessionPendingError",w(snapshotFromSessionError(K,e.info))}I(n)},15e3);const Q=()=>{i===x&&(clearTimeout(o),o=void 0,s=void 0,h===v&&(h=void 0),i=void 0,u=!1,c=void 0)};U.then(K=>{Q(),I(K)},K=>{Q(),E(K)})});return x};return{fetch:e.fetch,createAuthenticatedFetch(U){const v=_,x=()=>{if(p||S>0||m||v!==_||n.status!=="authenticated"||n.webId!==U||!e.info.isLoggedIn||e.info.webId!==U){const I=new Error("Authenticated session is no longer current");throw I.name="AbortError",I}};return async(I,E)=>{x();const Q=await(E===void 0?e.fetch(I):e.fetch(I,E));try{x()}catch(K){throw Q.body?.cancel().catch(()=>{}),K}return Q}},getSnapshot(){return n},initialize(U={}){if(i)return i;if(d||p)return Promise.resolve(n);const v={generation:++A,eventWebId:void 0};h=v;const x=E=>!p&&v.generation===A&&(!E?.isLoggedIn||!v.eventWebId||v.eventWebId===E.webId);u=!0,c=void 0,w({status:"initializing"});const I=e.handleIncomingRedirect({restorePreviousSession:U.restorePreviousSession??!0}).then(E=>{if(!x(E??e.info))return n;const Q=snapshotFromSessionInfo(E??e.info);return Q.status==="anonymous"&&c?.status==="error"?c:(d=!0,w(Q))}).catch(E=>x()?w(snapshotFromSessionError(E,e.info)):n);return i=V(I,v),i},handleIncomingRedirect(U){if(i)return i;if(p)return Promise.resolve(n);const v={generation:++A,eventWebId:void 0};h=v;const x=E=>!p&&v.generation===A&&(!E?.isLoggedIn||!v.eventWebId||v.eventWebId===E.webId);u=!0,c=void 0,w({status:"initializing"});const I=e.handleIncomingRedirect(U).then(E=>{if(!x(E??e.info))return n;const Q=snapshotFromSessionInfo(E??e.info);return Q.status==="anonymous"&&c?.status==="error"?c:(d=!0,w(Q))}).catch(E=>x()?w(snapshotFromSessionError(E,e.info)):n);return i=V(I,v),i},async login(U){A+=1,T(),S+=1;try{if(i){const v=new Error("Previous login is still completing. Reload before reconnecting.");throw v.name="SolidSessionPendingError",v}if(p)throw new Error("Solid session runtime is disposed");await e.login(U)}catch(v){throw w(snapshotFromSessionError(v,e.info)),v}finally{S-=1}},async logout(U){A+=1,T(),S+=1;try{await e.logout(U),w({status:"anonymous"})}catch(v){throw w(snapshotFromSessionError(v,e.info)),v}finally{S-=1}},subscribe(U){return t.add(U),()=>{t.delete(U)}},dispose(){clearTimeout(o),A+=1,T(),p=!0,s?.(),s=void 0,t.clear(),e.events.off(EVENTS.LOGIN,b),e.events.off(EVENTS.SESSION_RESTORED,b),e.events.off(EVENTS.LOGOUT,N),e.events.off(EVENTS.SESSION_EXPIRED,O),ee.off(EVENTS.ERROR,X)}}}const ENDPOINT_PROTOCOLS=new Set(["http:","https:"]),RESERVED_AUTHORIZATION_PARAMETERS=new Set(["state","redirect_uri","client_id","response_type","code_challenge","code_challenge_method"]);function normalizeEndpoint(r,e){if(!r||typeof r.url!="string"||r.url.trim()==="")throw new TypeError(`${e}.url must be a non-empty absolute URL`);if(typeof r.label!="string")throw new TypeError(`${e}.label must be a string`);let t;try{t=new URL(r.url.trim())}catch{throw new TypeError(`${e}.url must be a valid absolute URL`)}if(!ENDPOINT_PROTOCOLS.has(t.protocol))throw new TypeError(`${e}.url must use http or https`);if(t.username||t.password)throw new TypeError(`${e}.url must not contain credentials`);if(t.hash)throw new TypeError(`${e}.url must not contain a fragment`);return{url:t.href,label:r.label}}function validateWebId(r){if(typeof r!="string"||r===""||/[\s\u0000-\u001f\u007f-\u009f]/u.test(r))throw new TypeError("webId must be a non-empty identifier without whitespace or control characters");return r}function normalizeStorageBinding(r){if(!r||typeof r.storageUrl!="string"||r.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");validateWebId(r.webId);let e;try{e=new URL(r.storageUrl.trim())}catch{throw new TypeError("selectedStorage.storageUrl must be a valid absolute URL")}if(!ENDPOINT_PROTOCOLS.has(e.protocol))throw new TypeError("selectedStorage.storageUrl must use http or https");if(e.username||e.password)throw new TypeError("selectedStorage.storageUrl must not contain credentials");if(e.hash)throw new TypeError("selectedStorage.storageUrl must not contain a fragment");return{storageUrl:e.href,webId:r.webId,...r.label===void 0?{}:{label:r.label}}}function ensureEnum(r,e,t){if(!e.includes(r))throw new TypeError(`${t} has an unsupported value`);return r}function normalizeWebIdLoginRoute(r){if(!r||typeof r.id!="string"||r.id.trim()==="")throw new TypeError("route.id must be a non-empty opaque identifier");if(typeof r.label!="string")throw new TypeError("route.label must be a string");return{id:r.id.trim(),label:r.label,...r.description===void 0?{}:{description:r.description},...r.badge===void 0?{}:{badge:{label:r.badge.label,tone:ensureEnum(r.badge.tone,["neutral","primary","success","warning","danger"],"route.badge.tone")}},identityProvider:normalizeEndpoint(r.identityProvider,"route.identityProvider"),...r.storageProvider===void 0?{}:{storageProvider:normalizeEndpoint(r.storageProvider,"route.storageProvider")},availability:ensureEnum(r.availability,["ready","starting","unavailable"],"route.availability"),...r.unavailableReason===void 0?{}:{unavailableReason:r.unavailableReason}}}function decodeForValidation$1(r){let e=r;for(let t=0;t<4;t+=1){let n;try{n=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(n===e)return e;e=n}return e}function matchesAllowedPrefix(r,e){return e.some(t=>{if(t==="/")return r.startsWith("/");const n=t.endsWith("/")?t.slice(0,-1):t;return r===n||r.startsWith(`${n}/`)})}function normalizeApplicationReturnTo(r,e){if(r===void 0)return;if(typeof r!="string"||r.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const t=r.trim(),n=decodeForValidation$1(t),a=n.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||n.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(n)||n.startsWith("//")||a.split("/").some(i=>i==="..")||!matchesAllowedPrefix(a,e))throw new TypeError("returnTo must be a safe path within the application allow-list");return t}function normalizeWebIdLoginTransaction(r){if(!r||typeof r.id!="string"||r.id.trim()==="")throw new TypeError("transaction.id must be a non-empty opaque identifier");const e=r.authorizationParameters===void 0?void 0:{...r.authorizationParameters};if(e){for(const n of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(n.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${n}`)}const t=r.prompt===void 0?void 0:ensureEnum(r.prompt,["login","consent","select_account"],"transaction.prompt");return{id:r.id,route:normalizeWebIdLoginRoute(r.route),...r.selectedStorage===void 0?{}:{selectedStorage:normalizeStorageBinding(r.selectedStorage)},authorizationSurface:ensureEnum(r.authorizationSurface,["redirect","popup","embedded","external"],"transaction.authorizationSurface"),...t===void 0?{}:{prompt:t},discovery:ensureEnum(r.discovery,["standard","strict"],"transaction.discovery"),...e===void 0?{}:{authorizationParameters:e},...r.returnTo===void 0?{}:{returnTo:normalizeApplicationReturnTo(r.returnTo,["/"])}}}const KEY_SEPARATOR="\0";function normalizePodUrl(r){if(typeof r!="string"||r.trim()==="")throw new TypeError("podUrl must be a non-empty absolute URL");let e;try{e=new URL(r.trim())}catch{throw new TypeError("podUrl must be a valid absolute URL")}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("podUrl must use http or https");if(e.username||e.password||e.hash)throw new TypeError("podUrl must not contain credentials or a fragment");return e.href}function compositeKey(r,e){return`${r}${KEY_SEPARATOR}${e}`}function nextGeneration(r,e){const t=(r.get(e)??0)+1;return r.set(e,t),t}function createAbortedOpenError(){const r=new Error("Pod open aborted because the runtime identity changed");return r.name="AbortError",r}function createPodRuntime(r){const{adapter:e}=r,t=new Map,n=new Map,a=new Map,i=new Map,o=new Map,s=new Map,d=(p,_)=>{const m=validateWebId(p);if(_!==void 0){const h=normalizePodUrl(_),T=compositeKey(p,h);nextGeneration(s,T),i.get(T)?.controller.abort(),i.delete(T),n.delete(T);const w=t.get(m);w&&compositeKey(w.webId,w.podUrl)===T&&t.delete(m);return}nextGeneration(o,m),a.get(m)?.controller.abort(),a.delete(m);const S=t.get(m);S&&n.delete(compositeKey(S.webId,S.podUrl)),t.delete(m);const A=`${m}${KEY_SEPARATOR}`;for(const h of[...n.keys()])h.startsWith(A)&&n.delete(h);for(const[h,T]of[...i.entries()])h.startsWith(A)&&(nextGeneration(s,h),T.controller.abort(),i.delete(h))},u=p=>{if(p===void 0){t.clear(),n.clear();for(const _ of a.values())_.controller.abort();for(const _ of i.values())_.controller.abort();a.clear(),i.clear();for(const _ of o.keys())nextGeneration(o,_);for(const _ of s.keys())nextGeneration(s,_);return}if(typeof p=="string"){d(p);return}d(p.webId,p.podUrl)};return{open(p){const _=validateWebId(p.webId),m=p.podUrl===void 0?void 0:normalizePodUrl(p.podUrl);if(m!==void 0){const X=compositeKey(p.webId,m),ee=n.get(X);if(ee)return Promise.resolve(ee);const V=i.get(X);if(V)return V.promise;const U=s.get(X)??0;s.set(X,U);const v=new AbortController,x=()=>!v.signal.aborted&&(s.get(X)??0)===U,I=()=>{if(!x())throw createAbortedOpenError()},E=c({webId:p.webId,podUrl:m,fetch:p.fetch,signal:v.signal,isCurrent:x,assertCurrent:I});i.set(X,{generation:U,promise:E,controller:v});const Q=()=>{const K=i.get(X);K?.generation===U&&K.promise===E&&i.delete(X)};return E.then(Q,Q),E}const S=t.get(_);if(S)return Promise.resolve(S);const A=a.get(_);if(A)return A.promise;const h=o.get(_)??0;o.set(_,h);const T=new AbortController,w=()=>!T.signal.aborted&&(o.get(_)??0)===h,b=()=>{if(!w())throw createAbortedOpenError()},N=(async()=>{const X=await e.discoverPod({webId:p.webId,fetch:p.fetch,signal:T.signal,isCurrent:w});return b(),c({webId:p.webId,podUrl:normalizePodUrl(X),fetch:p.fetch,signal:T.signal,isCurrent:w,assertCurrent:b,generation:h,webIdKey:_,discovered:!0})})();a.set(_,{generation:h,promise:N,controller:T});const O=()=>{const X=a.get(_);X?.generation===h&&X.promise===N&&a.delete(_)};return N.then(O,O),N},clear:u,dispose(){u()}};async function c(p){const _=compositeKey(p.webId,p.podUrl),m=n.get(_);if(m)return p.discovered&&p.webIdKey&&p.isCurrent()&&t.set(p.webIdKey,m),m;const S=await e.openDatabase({webId:p.webId,podUrl:p.podUrl,fetch:p.fetch,signal:p.signal,isCurrent:p.isCurrent});p.assertCurrent(),await e.hydrateCollections({webId:p.webId,podUrl:p.podUrl,database:S,signal:p.signal,isCurrent:p.isCurrent}),p.assertCurrent();const A={webId:p.webId,podUrl:p.podUrl,database:S,collections:"ready"};return p.isCurrent()&&(n.set(_,A),p.discovered&&p.webIdKey&&t.set(p.webIdKey,A)),A}}SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,RDF$6.type,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt,UDFS.disabledAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;RDF$6.type,UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$6.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),offeringId:string$2("offeringId").predicate(UDFS.offeringId),service:string$2("service").predicate(UDFS.service).notNull().default("ai"),status:string$2("status").predicate(UDFS.status).notNull().default("active"),apiKey:string$2("apiKey").predicate(UDFS.apiKey),storageMode:string$2("storageMode").predicate(UDFS.storageMode),secretPayload:string$2("secretPayload").predicate(UDFS.secretPayload),encryptedSecret:string$2("encryptedSecret").predicate(UDFS.encryptedSecret),wrappedDataKey:string$2("wrappedDataKey").predicate(UDFS.wrappedDataKey),encryptionAlgorithm:string$2("encryptionAlgorithm").predicate(UDFS.encryptionAlgorithm),keyVersion:string$2("keyVersion").predicate(UDFS.keyVersion),scopes:text("scopes").array().predicate(UDFS.scopes),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),accountLabel:string$2("accountLabel").predicate(UDFS.accountLabel),lastRefreshAt:timestamp("lastRefreshAt").predicate(UDFS.lastRefreshAt),reauthRequired:boolean$2("reauthRequired").predicate(UDFS.reauthRequired).default(!1),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),label:string$2("label").predicate(UDFS.label),isDefault:boolean$2("isDefault").predicate(UDFS.isDefault).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).defaultNow(),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),clientCredentialId:string$2("clientCredentialId").predicate(UDFS.clientCredentialId),appliedTo:string$2("appliedTo").predicate(UDFS.appliedTo),appliedOn:string$2("appliedOn").predicate(UDFS.appliedOn),appliedAt:timestamp("appliedAt").predicate(UDFS.appliedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),lastFailureCode:string$2("lastFailureCode").predicate(UDFS.lastFailureCode),lastFailureAt:timestamp("lastFailureAt").predicate(UDFS.lastFailureAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId),metadata:json("metadata").predicate(UDFS.metadata)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(r,e){return r&&r.length>0?r:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(r){return taskDir(r)??runDir(r)??deliveryDir(r)??issueDir(r)??threadDir(r)??chatDir(r)??aboutDir(r)}function chatDir(r){const e=typeof r?.chat=="string"?r.chat:void 0;if(!e)return null;const n=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return n?.[1]?`chat/${n[1]}`:null}function threadDir(r){const e=typeof r?.thread=="string"?r.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(r){const e=typeof r?.task=="string"?r.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const n=t.match(/^task\/index\.ttl#([^#/]+)$/);if(n?.[1])return`task/${n[1]}`;const a=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return a?.[1]?`task/${a[1]}`:null}function issueDir(r){const e=typeof r?.issue=="string"?r.issue:void 0;if(!e)return null;const n=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return n?.[1]?`issues/${n[1]}`:null}function deliveryDir(r){const e=typeof r?.delivery=="string"?r.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(r){const e=typeof r?.run=="string"?r.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(r){const e=typeof r?.about=="string"?r.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((r,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(r,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((r,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(r,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(r,e){return e===void 0?void 0:eq(exactFilterColumns[r],e)}function messageListFilter(r){if(!r)return;const e=[exactFilter$1("parent",r.parent),exactFilter$1("chat",r.chat),exactFilter$1("thread",r.thread),exactFilter$1("maker",r.maker),exactFilter$1("role",r.role),exactFilter$1("status",r.status),exactFilter$1("toolName",r.toolName),exactFilter$1("toolCallId",r.toolCallId),exactFilter$1("coordinationId",r.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:r})=>messageListFilter(r)});function chatProjectMemoryResourceId(r){return r.endsWith(".ttl")?r:`${encodeURIComponent(r)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(r=>r?chatProjectMemoryResourceId(r):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:r})=>r?.workspace?eq(chatProjectContextResource.workspace,r.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:r})=>r?.workspace?eq(chatProjectMemoryResource.workspace,r.workspace):void 0});function conversationShareResourceId(r){return r.endsWith(".ttl")?r:`${encodeURIComponent(r)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(r=>r?conversationShareResourceId(r):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:r})=>r?.thread?eq(conversationShareResource.thread,r.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),dueAt:timestamp("dueAt").predicate(UDFS.dueAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),notes:text("notes").predicate(DCTerms.description),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((r,e)=>{const t=resourceKey(r,"report"),n=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${n}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(r){r.UNKNOWN="unknown",r.MAIN_TEXT="main_text",r.THINKING="thinking",r.IMAGE="image",r.CODE="code",r.TOOL="tool",r.TOOL_APPROVAL="tool_approval",r.TASK_PROGRESS="task_progress",r.FILE="file",r.ERROR="error",r.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(r){r.PENDING="pending",r.PROCESSING="processing",r.STREAMING="streaming",r.SUCCESS="success",r.ERROR="error",r.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$6.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(r,e,t){const{rdfType:n,sourceModule:a,extractor:i}=e,o=t["@id"]||t.id;if(!o){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const s=i.getTitle(t),d={id:crypto.randomUUID(),targetType:n,target:o,title:s,snapshotContent:i.getContent?.(t),snapshotAuthor:i.getAuthor?.(t),sourceModule:a,searchText:i.getSearchText?.(t)??s,snapshotMeta:i.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(u){console.error("[StarredSync] Failed to create favorite:",u)}}async function deleteFavorite(r,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(r){return{afterUpdate:async(e,t,n)=>{if(!("starred"in n))return;const a=t.starred,i=t["@id"]||t.id;a?await createFavorite(e,r,t):await deleteFavorite(e,i)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:r=>r.title||"未命名对话",getContent:r=>r.lastMessagePreview},threadSnapshotExtractor={getTitle:r=>r.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(r,e,t){return t===void 0?void 0:eq(r[e],t)}function combineFilters(r){const e=r.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(r){if(r)return combineFilters([exactFilter(candidateExactFilterColumns,"source",r.source),exactFilter(candidateExactFilterColumns,"suggestedType",r.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",r.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",r.status),exactFilter(candidateExactFilterColumns,"chat",r.chat),exactFilter(candidateExactFilterColumns,"thread",r.thread),exactFilter(candidateExactFilterColumns,"task",r.task),exactFilter(candidateExactFilterColumns,"run",r.run)])}function captureEventListFilter(r){if(r)return combineFilters([exactFilter(eventExactFilterColumns,"source",r.source),exactFilter(eventExactFilterColumns,"captureCandidate",r.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",r.targetResource),exactFilter(eventExactFilterColumns,"decision",r.decision),exactFilter(eventExactFilterColumns,"approval",r.approval),exactFilter(eventExactFilterColumns,"inputRequest",r.inputRequest),exactFilter(eventExactFilterColumns,"chat",r.chat),exactFilter(eventExactFilterColumns,"thread",r.thread),exactFilter(eventExactFilterColumns,"task",r.task),exactFilter(eventExactFilterColumns,"run",r.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:r})=>captureCandidateListFilter(r)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:r})=>captureEventListFilter(r)});podTable("settings",{id:id("id").default((r,e)=>{const t=typeof e?.key=="string"?e.key:r;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$6.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});const inboxNotificationResource=podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$6.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(r){r.assertEqual=a=>{};function e(a){}r.assertIs=e;function t(a){throw new Error}r.assertNever=t,r.arrayToEnum=a=>{const i={};for(const o of a)i[o]=o;return i},r.getValidEnumValues=a=>{const i=r.objectKeys(a).filter(s=>typeof a[a[s]]!="number"),o={};for(const s of i)o[s]=a[s];return r.objectValues(o)},r.objectValues=a=>r.objectKeys(a).map(function(i){return a[i]}),r.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const i=[];for(const o in a)Object.prototype.hasOwnProperty.call(a,o)&&i.push(o);return i},r.find=(a,i)=>{for(const o of a)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,i=" | "){return a.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(a,i)=>typeof i=="bigint"?i.toString():i})(util||(util={}));var objectUtil;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=r=>{switch(typeof r){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(r)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(r)?ZodParsedType.array:r===null?ZodParsedType.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&r instanceof Map?ZodParsedType.map:typeof Set<"u"&&r instanceof Set?ZodParsedType.set:typeof Date<"u"&&r instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},n={_errors:[]},a=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(a);else if(o.code==="invalid_return_type")a(o.returnTypeError);else if(o.code==="invalid_arguments")a(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let s=n,d=0;for(;d<o.path.length;){const u=o.path[d];d===o.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(t(o))):s[u]=s[u]||{_errors:[]},s=s[u],d++}}};return a(this),n}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const a of this.issues)if(a.path.length>0){const i=a.path[0];t[i]=t[i]||[],t[i].push(e(a))}else n.push(e(a));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=r=>new ZodError(r);const errorMap=(r,e)=>{let t;switch(r.code){case ZodIssueCode.invalid_type:r.received===ZodParsedType.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(r.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(r.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(r.options)}, received '${r.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:util.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case ZodIssueCode.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(r)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=r=>{const{data:e,path:t,errorMaps:n,issueData:a}=r,i=[...t,...a.path||[]],o={...a,path:i};if(a.message!==void 0)return{...a,path:i,message:a.message};let s="";const d=n.filter(u=>!!u).slice().reverse();for(const u of d)s=u(o,{data:e,defaultError:s}).message;return{...a,path:i,message:s}};function addIssueToContext(r,e){const t=getErrorMap(),n=makeIssue({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(a=>!!a)});r.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const a of t){if(a.status==="aborted")return INVALID;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const a of t){const i=await a.key,o=await a.value;n.push({key:i,value:o})}return ParseStatus.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const a of t){const{key:i,value:o}=a;if(i.status==="aborted"||o.status==="aborted")return INVALID;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||a.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=r=>({status:"dirty",value:r}),OK=r=>({status:"valid",value:r}),isAborted=r=>r.status==="aborted",isDirty=r=>r.status==="dirty",isValid=r=>r.status==="valid",isAsync=r=>typeof Promise<"u"&&r instanceof Promise;var errorUtil;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,n,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(r,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(r.common.issues);return this._error=t,this._error}}};function processCreateParams(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:a}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(o,s)=>{const{message:d}=r;return o.code==="invalid_enum_value"?{message:d??s.defaultError}:typeof s.data>"u"?{message:d??n??s.defaultError}:o.code!=="invalid_type"?{message:s.defaultError}:{message:d??t??s.defaultError}},description:a}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},a=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return isValid(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>isValid(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},a=this._parse({data:e,path:n.path,parent:n}),i=await(isAsync(a)?a:Promise.resolve(a));return handleResult(n,i)}refine(e,t){const n=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,i)=>{const o=e(a),s=()=>i.addIssue({code:ZodIssueCode.custom,...n(a)});return typeof Promise<"u"&&o instanceof Promise?o.then(d=>d?!0:(s(),!1)):o?!0:(s(),!1)})}refinement(e,t){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof t=="function"?t(n,a):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(r){return new RegExp(`^${timeRegexSource(r)}$`)}function datetimeRegex(r){let e=`${dateRegexSource}T${timeRegexSource(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(r,e){return!!((e==="v4"||!e)&&ipv4Regex.test(r)||(e==="v6"||!e)&&ipv6Regex.test(r))}function isValidJWT(r,e){if(!jwtRegex.test(r))return!1;try{const[t]=r.split(".");if(!t)return!1;const n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function isValidCidr(r,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(r)||(e==="v6"||!e)&&ipv6CidrRegex.test(r))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:i.parsedType}),INVALID}const n=new ParseStatus;let a;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,s=e.data.length<i.value;(o||s)&&(a=this._getOrReturnCtx(e,a),o?addIssueToContext(a,{code:ZodIssueCode.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&addIssueToContext(a,{code:ZodIssueCode.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")emailRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"email",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"emoji",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")uuidRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"uuid",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")nanoidRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")cuidRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"cuid",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")cuid2Regex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")ulidRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"ulid",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"url",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"regex",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?datetimeRegex(i).test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?dateRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?timeRegex(i).test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?durationRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"duration",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?isValidIP(e.data,i.version)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"ip",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?isValidJWT(e.data,i.alg)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"jwt",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?isValidCidr(e.data,i.version)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"cidr",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?base64Regex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"base64",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?base64urlRegex.test(e.data)||(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{validation:"base64url",code:ZodIssueCode.invalid_string,message:i.message}),n.dirty()):util.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(a=>e.test(a),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(n)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=r=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:r?.coerce??!1,...processCreateParams(r)});function floatSafeRemainder(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=t>n?t:n,i=Number.parseInt(r.toFixed(a).replace(".","")),o=Number.parseInt(e.toFixed(a).replace(".",""));return i%o/10**a}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:i.parsedType}),INVALID}let n;const a=new ParseStatus;for(const i of this._def.checks)i.kind==="int"?util.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:i.message}),a.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="multipleOf"?floatSafeRemainder(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_finite,message:i.message}),a.dirty()):util.assertNever(i);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,n,a){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:errorUtil.toString(a)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=r=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:r?.coerce||!1,...processCreateParams(r)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let n;const a=new ParseStatus;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),addIssueToContext(n,{code:ZodIssueCode.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):util.assertNever(i);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,n,a){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:errorUtil.toString(a)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=r=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:r?.coerce??!1,...processCreateParams(r)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:n.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=r=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:r?.coerce||!1,...processCreateParams(r)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:i.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_date}),INVALID}const n=new ParseStatus;let a;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(a=this._getOrReturnCtx(e,a),addIssueToContext(a,{code:ZodIssueCode.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):util.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=r=>new ZodDate({checks:[],coerce:r?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(r)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:n.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=r=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(r)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:n.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=r=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(r)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:n.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=r=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(r)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=r=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(r)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=r=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(r)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=r=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(r)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:n.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=r=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(r)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),a=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(a.exactLength!==null){const o=t.data.length>a.exactLength.value,s=t.data.length<a.exactLength.value;(o||s)&&(addIssueToContext(t,{code:o?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:s?a.exactLength.value:void 0,maximum:o?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),n.dirty())}if(a.minLength!==null&&t.data.length<a.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,s)=>a.type._parseAsync(new ParseInputLazyPath(t,o,t.path,s)))).then(o=>ParseStatus.mergeArray(n,o));const i=[...t.data].map((o,s)=>a.type._parseSync(new ParseInputLazyPath(t,o,t.path,s)));return ParseStatus.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(r,e)=>new ZodArray({type:r,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(r){if(r instanceof ZodObject){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...r._def,shape:()=>e})}else return r instanceof ZodArray?new ZodArray({...r._def,type:deepPartialify(r.element)}):r instanceof ZodOptional?ZodOptional.create(deepPartialify(r.unwrap())):r instanceof ZodNullable?ZodNullable.create(deepPartialify(r.unwrap())):r instanceof ZodTuple?ZodTuple.create(r.items.map(e=>deepPartialify(e))):r}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const u=this._getOrReturnCtx(e);return addIssueToContext(u,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:u.parsedType}),INVALID}const{status:n,ctx:a}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),s=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const u in a.data)o.includes(u)||s.push(u);const d=[];for(const u of o){const c=i[u],p=a.data[u];d.push({key:{status:"valid",value:u},value:c._parse(new ParseInputLazyPath(a,p,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof ZodNever){const u=this._def.unknownKeys;if(u==="passthrough")for(const c of s)d.push({key:{status:"valid",value:c},value:{status:"valid",value:a.data[c]}});else if(u==="strict")s.length>0&&(addIssueToContext(a,{code:ZodIssueCode.unrecognized_keys,keys:s}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const c of s){const p=a.data[c];d.push({key:{status:"valid",value:c},value:u._parse(new ParseInputLazyPath(a,p,a.path,c)),alwaysSet:c in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const u=[];for(const c of d){const p=await c.key,_=await c.value;u.push({key:p,value:_,alwaysSet:c.alwaysSet})}return u}).then(u=>ParseStatus.mergeObjectSync(n,u)):ParseStatus.mergeObjectSync(n,d)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{const a=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const n of util.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const n of util.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const n of util.objectKeys(this.shape)){const a=this.shape[n];e&&!e[n]?t[n]=a:t[n]=a.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const n of util.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof ZodOptional;)i=i._def.innerType;t[n]=i}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(r,e)=>new ZodObject({shape:()=>r,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(r,e)=>new ZodObject({shape:()=>r,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(r,e)=>new ZodObject({shape:r,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function a(i){for(const s of i)if(s.result.status==="valid")return s.result;for(const s of i)if(s.result.status==="dirty")return t.common.issues.push(...s.ctx.common.issues),s.result;const o=i.map(s=>new ZodError(s.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}if(t.common.async)return Promise.all(n.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(a);{let i;const o=[];for(const d of n){const u={...t,common:{...t.common,issues:[]},parent:null},c=d._parseSync({data:t.data,path:t.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!i&&(i={result:c,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const s=o.map(d=>new ZodError(d));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:s}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(r,e)=>new ZodUnion({options:r,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(r,e){const t=getParsedType(r),n=getParsedType(e);if(r===e)return{valid:!0,data:r};if(t===ZodParsedType.object&&n===ZodParsedType.object){const a=util.objectKeys(e),i=util.objectKeys(r).filter(s=>a.indexOf(s)!==-1),o={...r,...e};for(const s of i){const d=mergeValues(r[s],e[s]);if(!d.valid)return{valid:!1};o[s]=d.data}return{valid:!0,data:o}}else if(t===ZodParsedType.array&&n===ZodParsedType.array){if(r.length!==e.length)return{valid:!1};const a=[];for(let i=0;i<r.length;i++){const o=r[i],s=e[i],d=mergeValues(o,s);if(!d.valid)return{valid:!1};a.push(d.data)}return{valid:!0,data:a}}else return t===ZodParsedType.date&&n===ZodParsedType.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),a=(i,o)=>{if(isAborted(i)||isAborted(o))return INVALID;const s=mergeValues(i.value,o.value);return s.valid?((isDirty(i)||isDirty(o))&&t.dirty(),{status:t.value,value:s.data}):(addIssueToContext(n,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>a(i,o)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}ZodIntersection.create=(r,e,t)=>new ZodIntersection({left:r,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.array)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:n.parsedType}),INVALID;if(n.data.length<this._def.items.length)return addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&n.data.length>this._def.items.length&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((o,s)=>{const d=this._def.items[s]||this._def.rest;return d?d._parse(new ParseInputLazyPath(n,o,n.path,s)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>ParseStatus.mergeArray(t,o)):ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:r,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.object)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:n.parsedType}),INVALID;const a=[],i=this._def.keyType,o=this._def.valueType;for(const s in n.data)a.push({key:i._parse(new ParseInputLazyPath(n,s,n.path,s)),value:o._parse(new ParseInputLazyPath(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?ParseStatus.mergeObjectAsync(t,a):ParseStatus.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(n)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.map)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:n.parsedType}),INVALID;const a=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([s,d],u)=>({key:a._parse(new ParseInputLazyPath(n,s,n.path,[u,"key"])),value:i._parse(new ParseInputLazyPath(n,d,n.path,[u,"value"]))}));if(n.common.async){const s=new Map;return Promise.resolve().then(async()=>{for(const d of o){const u=await d.key,c=await d.value;if(u.status==="aborted"||c.status==="aborted")return INVALID;(u.status==="dirty"||c.status==="dirty")&&t.dirty(),s.set(u.value,c.value)}return{status:t.value,value:s}})}else{const s=new Map;for(const d of o){const u=d.key,c=d.value;if(u.status==="aborted"||c.status==="aborted")return INVALID;(u.status==="dirty"||c.status==="dirty")&&t.dirty(),s.set(u.value,c.value)}return{status:t.value,value:s}}}}ZodMap.create=(r,e,t)=>new ZodMap({valueType:e,keyType:r,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==ZodParsedType.set)return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:n.parsedType}),INVALID;const a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&(addIssueToContext(n,{code:ZodIssueCode.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const i=this._def.valueType;function o(d){const u=new Set;for(const c of d){if(c.status==="aborted")return INVALID;c.status==="dirty"&&t.dirty(),u.add(c.value)}return{status:t.value,value:u}}const s=[...n.data.values()].map((d,u)=>i._parse(new ParseInputLazyPath(n,d,n.path,u)));return n.common.async?Promise.all(s).then(d=>o(d)):o(s)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(r,e)=>new ZodSet({valueType:r,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(r,e)=>new ZodLazy({getter:r,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(r,e)=>new ZodLiteral({value:r,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(r,e){return new ZodEnum({values:r,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{expected:util.joinValues(n),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:n}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ZodParsedType.string&&n.parsedType!==ZodParsedType.number){const a=util.objectValues(t);return addIssueToContext(n,{expected:util.joinValues(a),received:n.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=util.objectValues(t);return addIssueToContext(n,{received:n.data,code:ZodIssueCode.invalid_enum_value,options:a}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(r,e)=>new ZodNativeEnum({values:r,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const n=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(n.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(r,e)=>new ZodPromise({type:r,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:o=>{addIssueToContext(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),a.type==="preprocess"){const o=a.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async s=>{if(t.value==="aborted")return INVALID;const d=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return d.status==="aborted"?INVALID:d.status==="dirty"||t.value==="dirty"?DIRTY(d.value):d});{if(t.value==="aborted")return INVALID;const s=this._def.schema._parseSync({data:o,path:n.path,parent:n});return s.status==="aborted"?INVALID:s.status==="dirty"||t.value==="dirty"?DIRTY(s.value):s}}if(a.type==="refinement"){const o=s=>{const d=a.refinement(s,i);if(n.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?INVALID:(s.status==="dirty"&&t.dirty(),o(s.value),{status:t.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?INVALID:(s.status==="dirty"&&t.dirty(),o(s.value).then(()=>({status:t.value,value:s.value}))))}if(a.type==="transform")if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!isValid(o))return INVALID;const s=a.transform(o.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>isValid(o)?Promise.resolve(a.transform(o.value,i)).then(s=>({status:t.value,value:s})):INVALID);util.assertNever(a)}}ZodEffects.create=(r,e,t)=>new ZodEffects({schema:r,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(r,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:r},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(r,e)=>new ZodOptional({innerType:r,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(r,e)=>new ZodNullable({innerType:r,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(r,e)=>new ZodDefault({innerType:r,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return isAsync(a)?a.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(r,e)=>new ZodCatch({innerType:r,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const n=this._getOrReturnCtx(e);return addIssueToContext(n,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:n.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=r=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(r)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?INVALID:i.status==="dirty"?(t.dirty(),DIRTY(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?INVALID:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),n=a=>(isValid(a)&&(a.value=Object.freeze(a.value)),a);return isAsync(t)?t.then(a=>n(a)):n(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(r,e)=>new ZodReadonly({innerType:r,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$6.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel},modelClassAliases={chat:"chat",language:"chat",embedding:"embedding",embeddings:"embedding",document_understanding:"document_understanding",rerank:"reranking",reranker:"reranking",reranking:"reranking",image:"image_generation",image_generation:"image_generation",transcription:"speech_recognition",speech_recognition:"speech_recognition",text_to_speech:"speech_synthesis",speech_synthesis:"speech_synthesis",video:"video_generation",video_generation:"video_generation"},AI_MODEL_CLASS_DEFAULT_CAPABILITY={[AI_MODEL_CLASS.chat]:AI_MODEL_CAPABILITY.chat,[AI_MODEL_CLASS.embedding]:AI_MODEL_CAPABILITY.embedding,[AI_MODEL_CLASS.document_understanding]:AI_MODEL_CAPABILITY.document_understanding,[AI_MODEL_CLASS.reranking]:AI_MODEL_CAPABILITY.reranking,[AI_MODEL_CLASS.image_generation]:AI_MODEL_CAPABILITY.image_generation,[AI_MODEL_CLASS.speech_recognition]:AI_MODEL_CAPABILITY.speech_recognition,[AI_MODEL_CLASS.speech_synthesis]:AI_MODEL_CAPABILITY.speech_synthesis,[AI_MODEL_CLASS.video_generation]:AI_MODEL_CAPABILITY.video_generation};new Set(AI_MODEL_MODALITIES);const capabilitySet=new Set(AI_MODEL_CAPABILITIES),capabilityUriSet=new Set(Object.values(AI_MODEL_CAPABILITY)),capabilityNameByUri=new Map(Object.entries(AI_MODEL_CAPABILITY).map(([r,e])=>[e,r])),classNameByUri=new Map(Object.entries(AI_MODEL_CLASS).map(([r,e])=>[e,r])),legacyCapabilityAliases={function_calling:"tool_call",function_call:"tool_call",rerank:"reranking",document:"document_understanding","document-parse":"document_understanding"};function toAIModelClassUri(r){if(r==null)return AI_MODEL_CLASS.chat;if(typeof r=="string"&&Object.values(AI_MODEL_CLASS).includes(r))return r;const e=typeof r=="string"?modelClassAliases[r.trim().toLowerCase()]:void 0;return e?AI_MODEL_CLASS[e]:void 0}function isAIModelCapability(r){return typeof r=="string"&&capabilitySet.has(r)}function isAIModelCapabilityUri(r){return typeof r=="string"&&capabilityUriSet.has(r)}function toAIModelCapabilityUri(r){if(isAIModelCapabilityUri(r))return r;if(typeof r!="string")return;const e=legacyCapabilityAliases[r]??r;return isAIModelCapability(e)?AI_MODEL_CAPABILITY[e]:void 0}function toAIModelCapabilityName(r){return typeof r=="string"?capabilityNameByUri.get(r):void 0}function toAIModelClassName(r){const e=Array.isArray(r)?r:[r];for(const t of e){if(typeof t!="string")continue;const n=classNameByUri.get(t);if(n)return n}return"chat"}function filterAIModelCapabilityUris(r){return Array.isArray(r)?[...new Set(r.map(toAIModelCapabilityUri).filter(e=>!!e))]:[]}function withAIModelClassDefaultCapabilities(r){const e=Array.isArray(r.rdfType)?r.rdfType:[r.rdfType],t=filterAIModelCapabilityUris(r.capabilities);for(const n of e){if(typeof n!="string")continue;const a=AI_MODEL_CLASS_DEFAULT_CAPABILITY[n];a&&t.push(a)}return{...r,capabilities:[...new Set(t)]}}podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(r){const e=r;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const n of Object.values(t??{}))typeof n.options?.predicate=="string"&&(n.getPredicate=()=>n.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(r=>[r.id,r]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(r){return r.trim().toLowerCase()}function normalizeAIConfigResourceId(r){if(!r)return"";const e=r.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),n=t.split("/").pop()||t;return n.endsWith(".ttl")?n.slice(0,-4):n}function aiConfigResourceRefToModelId(r,e){return normalizeAIConfigModelId(r,e)}function normalizeAIConfigModelId(r,e){const t=normalizeAIConfigResourceId(r);if(!t.includes("/"))return t;const[n,...a]=t.split("/");return a.length===0||!e?t:normalizeAIConfigProviderId(n)===normalizeAIConfigProviderId(e)?a.join("/"):t}function normalizeAIConfigProviderId(r){const e=normalizeText(normalizeAIConfigResourceId(r));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(r,e){return aiConfigResourceRefToModelId(r,e)}function buildAIConfigModelStorageId(r,e){return aiModelResource.buildId({id:e,isProvidedBy:aiConfigProviderRef(r)})}function aiConfigProviderRef(r){const e=normalizeAIConfigProviderId(r);return e&&`settings/providers/${aiProviderResource.buildId({id:e})}`}function aiConfigModelRef(r,e){if(e===void 0)return normalizeAIConfigResourceId(r);const t=normalizeAIConfigProviderId(r),n=normalizeAIConfigModelStorageId(e,t);return t&&n?`settings/providers/${buildAIConfigModelStorageId(t,n)}`:n}function definePodModelDescriptor(r){return r}const credentialDescriptor={uri:UDFS.Credential,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Credential,resourceKind:"credential",description:"Generic credential material required by runtimes, tools, MCP servers, and providers.",storage:{base:"/settings/credentials.ttl",resourceIdPattern:"#{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative credential row id. Every credential in a provider pool keeps its own id."},provider:{type:"uri",predicate:UDFS.provider,references:{resource:"provider",key:"id"},description:"Provider resource URI this credential connects through, as a URI relation to the provider row."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},offeringId:{type:"string",predicate:UDFS.offeringId,description:"Offering id this credential connects through. Offerings are catalog content, so this stays a plain attribute, not a relation."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},storageMode:{type:"string",predicate:UDFS.storageMode,description:"Credential storage format, for example plaintext-v1 or secret-cell-v1."},secretPayload:{type:"string",predicate:UDFS.secretPayload,secret:!0,description:"Storage-mode-specific credential payload. plaintext-v1 stores a JSON payload here."},encryptedSecret:{type:"string",predicate:UDFS.encryptedSecret,secret:!0,description:"Encrypted credential payload stored in the Pod."},wrappedDataKey:{type:"string",predicate:UDFS.wrappedDataKey,secret:!0,description:"Wrapped data-encryption key for encrypted credential payloads."},encryptionAlgorithm:{type:"string",predicate:UDFS.encryptionAlgorithm,description:"Credential encryption algorithm identifier."},keyVersion:{type:"string",predicate:UDFS.keyVersion,description:"Key-management version used to encrypt the credential."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Credential scopes granted by the provider."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Credential expiry timestamp."},accountLabel:{type:"string",predicate:UDFS.accountLabel,description:"Provider account label associated with the credential."},lastRefreshAt:{type:"timestamp",predicate:UDFS.lastRefreshAt,description:"Last successful credential refresh timestamp."},reauthRequired:{type:"boolean",predicate:UDFS.reauthRequired,description:"Whether this credential requires user reauthentication."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL recorded on the credential."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for requests made with this credential."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},isDefault:{type:"boolean",predicate:UDFS.isDefault,description:"Whether this credential is the default credential for its provider."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp, set by the store."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful use timestamp."},clientCredentialId:{type:"string",predicate:UDFS.clientCredentialId,description:"Client the issued credential belongs to. An external runtime identifier, not an RDF link."},appliedTo:{type:"string",predicate:UDFS.appliedTo,description:"Client application id the credential is in effect for. A runtime identifier, not an RDF link."},appliedOn:{type:"string",predicate:UDFS.appliedOn,description:"Device id that wrote the applied configuration. A runtime identifier, not an RDF link."},appliedAt:{type:"timestamp",predicate:UDFS.appliedAt,description:"Timestamp when the credential was applied."},failCount:{type:"number",predicate:UDFS.failCount,description:"Failed use count recorded for the credential."},rateLimitResetAt:{type:"timestamp",predicate:UDFS.rateLimitResetAt,description:"Timestamp when the provider rate limit is expected to reset."},lastFailureCode:{type:"string",predicate:UDFS.lastFailureCode,description:"Stable credential failure category. No upstream response body or secret."},lastFailureAt:{type:"timestamp",predicate:UDFS.lastFailureAt,description:"Time when the most recent credential failure was observed."},oauthRefreshToken:{type:"string",predicate:UDFS.oauthRefreshToken,secret:!0,description:"OAuth refresh token."},oauthAccessToken:{type:"string",predicate:UDFS.oauthAccessToken,secret:!0,description:"OAuth access token."},oauthExpiresAt:{type:"timestamp",predicate:UDFS.oauthExpiresAt,description:"OAuth access token expiry timestamp."},projectId:{type:"string",predicate:UDFS.projectId,description:"Provider project identifier recorded for the credential."},organizationId:{type:"string",predicate:UDFS.organizationId,description:"Provider organization identifier recorded for the credential."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata bag; shared relations must be explicit fields."}},uniqueBy:["id"],writableFields:["provider","authMode","offeringId","service","status","apiKey","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","baseUrl","proxyUrl","label","isDefault","lastUsedAt","clientCredentialId","appliedTo","appliedOn","appliedAt","failCount","rateLimitResetAt","lastFailureCode","lastFailureAt","oauthRefreshToken","oauthAccessToken","oauthExpiresAt","projectId","organizationId","metadata"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{id:"cloudflare-5f2c9a1e"}},{request:"保存 OpenAI API key",match:{id:"openai-2b7d4e10"}}]},gatewayAccessKeyDescriptor={uri:UDFS.GatewayAccessKey,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.GatewayAccessKey,resourceKind:"gateway-access-key",description:"Control-primary Pod AI Gateway access key. The key owner is a semantic WebID/URI relation, while the secret itself is represented only by a hash.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/access-keys.ttl#key_1."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID or principal URI that owns this Gateway access key."},secretHash:{type:"string",predicate:UDFS.secretHash,required:!0,secret:!0,description:"Hash of the Gateway secret. Raw access key material must not be stored here."},name:{type:"string",predicate:UDFS.name,description:"User-visible label for distinguishing this Gateway access key."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment target: local or cloud."},scopes:{type:"text",predicate:UDFS.scopes,array:!0,description:"Gateway scopes granted to this key."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Key expiry timestamp."},lastUsedAt:{type:"timestamp",predicate:UDFS.lastUsedAt,description:"Last successful Gateway use timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp. Presence means the key is no longer valid."},disabledAt:{type:"timestamp",predicate:UDFS.disabledAt,description:"Temporary disable timestamp. Clear it to enable the key again."}},uniqueBy:["id"],writableFields:["owner","secretHash","name","deployment","scopes","createdAt","expiresAt","lastUsedAt","revokedAt","disabledAt"],mergePolicy:"upsert",examples:[{request:"Create a local Gateway access key for a user",match:{id:"ai/gateway/access-keys.ttl#key_1"}}]},quotaSnapshotDescriptor={uri:UDFS.QuotaSnapshot,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.QuotaSnapshot,resourceKind:"quota-snapshot",description:"Observed Pod AI Gateway quota state for a provider credential. The credential field is a semantic URI relation, and normalized windows are stored as a serialized literal.",storage:exactIdStorage(),fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id, for example ai/gateway/quota.ttl#quota_1."},credential:{type:"uri",predicate:UDFS.credential,references:{resource:"credential",key:"id"},required:!0,description:"Credential resource URI this quota snapshot describes."},owner:{type:"uri",predicate:UDFS.owner,required:!0,description:"WebID that owns the credential and quota snapshot."},deployment:{type:"string",predicate:UDFS.deployment,required:!0,description:"Gateway deployment scope: local or cloud."},provider:{type:"string",predicate:UDFS.provider,required:!0,description:"Normalized provider id for the quota snapshot."},status:{type:"string",predicate:UDFS.status,required:!0,description:"Quota availability status: available, unsupported, or error."},balance:{type:"number",predicate:UDFS.balance,description:"Normalized remaining quota balance when the provider exposes one."},windows:{type:"text",predicate:UDFS.windows,description:"Serialized normalized quota windows literal, for example JSON produced by Gateway normalization."},observedAt:{type:"timestamp",predicate:UDFS.observedAt,description:"Observation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Snapshot freshness expiry timestamp."},source:{type:"string",predicate:UDFS.source,description:"Observation source such as provider, gateway-cache, or manual."}},uniqueBy:["id"],writableFields:["credential","status","balance","windows","observedAt","expiresAt","source"],mergePolicy:"upsert",examples:[{request:"Record a fresh quota snapshot for a provider credential",match:{id:"ai/gateway/quota.ttl#quota_1"}}]},aiProviderDescriptor={uri:UDFS.Provider,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Provider,resourceKind:"provider",description:"AI provider endpoint configured in the Pod: endpoint, proxy, console entry, backend support, and the models it exposes. Its model rows live in the same provider document and are linked from here through hasModel.",storage:{base:"/settings/providers/",resourceIdPattern:"{key}.ttl"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative provider row id, for example openai.ttl."},displayName:{type:"string",predicate:UDFS.displayName,description:"Provider display name stored on the provider row."},baseUrl:{type:"string",predicate:UDFS.baseUrl,description:"Provider API base URL."},proxyUrl:{type:"string",predicate:UDFS.proxyUrl,description:"Proxy URL used for provider requests."},homepage:{type:"string",predicate:UDFS.homepage,description:"Provider homepage URL."},apiKeyUrl:{type:"string",predicate:UDFS.apiKeyUrl,description:"URL where a user creates an API key for this provider."},connectMode:{type:"string",predicate:UDFS.connectMode,description:"Connection mode recorded for the provider authorization method."},hasModel:{type:"uri",predicate:UDFS.hasModel,references:{resource:"ai-model",key:"id"},array:!0,description:"Model rows this provider exposes, as subjects inside the provider document."},defaultModel:{type:"uri",predicate:UDFS.defaultModel,references:{resource:"ai-model",key:"id"},description:"Default model for this provider when a request does not select one."},supportsBackend:{type:"string",predicate:UDFS.supportsBackend,description:"Backends this provider can serve, read as a backend list by the AI config selector."},capabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Provider capability tags."},rotationPolicy:{type:"string",predicate:UDFS.rotationPolicy,description:"Credential rotation policy recorded for the provider."}},uniqueBy:["id"],writableFields:["displayName","baseUrl","proxyUrl","homepage","apiKeyUrl","connectMode","hasModel","defaultModel","supportsBackend","capabilities","rotationPolicy"],mergePolicy:"upsert",examples:[{request:"Describe the provider document a Pod AI connection writes",match:{id:"openai.ttl"}}]},aiModelDescriptor={uri:UDFS.AIModel,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AIModel,resourceKind:"ai-model",description:"AI model exposed by a provider, stored as a subject inside that provider document. The provider relation and model capabilities are URI facts, while pricing and modality facts stay literals.",storage:{base:"/settings/providers/",resourceIdPattern:"{isProvidedBy.doc}#{key}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative model row id: provider document plus model key, for example openai.ttl#gpt-4o."},rdfType:{type:"uri",predicate:RDF$6.type,array:!0,description:"RDF class of the model row. The base table defaults to AIModel, and subclass tables narrow it."},displayName:{type:"string",predicate:UDFS.displayName,description:"Model display name stored on the model row."},isProvidedBy:{type:"uri",predicate:UDFS.isProvidedBy,references:{resource:"provider",key:"id"},description:"Provider document this model row belongs to, as a URI relation to the provider row."},inputModalities:{type:"text",predicate:UDFS.inputModality,array:!0,description:"Input modalities the model accepts."},outputModalities:{type:"text",predicate:UDFS.outputModality,array:!0,description:"Output modalities the model produces."},runtimeCapabilities:{type:"string",predicate:UDFS.capability,array:!0,description:"Adapter/runtime endpoint capabilities, kept separate from semantic model capabilities."},capabilities:{type:"uri",predicate:UDFS.hasCapability,array:!0,description:"Semantic capabilities of the model, as URIs."},pricingInput:{type:"number",predicate:UDFS.pricingInput,description:"Input token price recorded for the model."},pricingOutput:{type:"number",predicate:UDFS.pricingOutput,description:"Output token price recorded for the model."},status:{type:"string",predicate:UDFS.status,description:"Model availability status."},createdAt:{type:"timestamp",predicate:UDFS.createdAt,description:"Creation timestamp, set by the store."},updatedAt:{type:"timestamp",predicate:UDFS.updatedAt,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["displayName","isProvidedBy","inputModalities","outputModalities","runtimeCapabilities","capabilities","pricingInput","pricingOutput","status","updatedAt"],mergePolicy:"upsert",examples:[{request:"Describe a model row inside a provider document",match:{id:"openai.ttl#gpt-4o"}}]},approvalDescriptor={uri:UDFS.ApprovalRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ApprovalRequest,resourceKind:"approval",description:"Durable approval request control item. Solid inbox notifications may point at this resource, but lifecycle and claim state live here.",storage:{base:"/.data/approvals/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Approval request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource that requested approval."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},toolCallId:{type:"string",predicate:UDFS.toolCallId,required:!0,description:"Opaque runtime tool-call identifier; not an RDF resource link."},toolName:{type:"string",predicate:UDFS.toolName,required:!0,description:"Runtime tool name that requires approval."},target:{type:"uri",predicate:ODRL.target,required:!0,description:"Target resource for the requested action. Schema field uses ODRL target in the executable resource."},action:{type:"uri",predicate:ODRL.action,required:!0,description:"Requested action URI. Schema field uses ODRL action in the executable resource."},risk:{type:"string",predicate:UDFS.risk,required:!0,description:"Risk level assigned by the runtime or policy layer."},status:{type:"string",predicate:UDFS.status,description:"Approval lifecycle status such as pending, handling, approved, rejected, resolved, or expired."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/approval handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to decide the request."},decisionBy:{type:"uri",predicate:UDFS.decisionBy,description:"WebID or agent resource that made the decision."},decisionRole:{type:"string",predicate:UDFS.decisionRole,description:"Role of the decision maker, for example human or secretary."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the decision applies."},reason:{type:"text",predicate:UDFS.reason,description:"Decision reason or policy explanation."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},approvalOptions:{type:"text",predicate:UDFS.approvalOptions,description:"Serialized approval options offered by the runtime."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version used to create or resolve this approval."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Decision timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","toolCallId","toolName","target","action","risk","status","leaseOwner","leaseExpiresAt","assignedTo","decisionBy","decisionRole","onBehalfOf","reason","context","approvalOptions","policyVersion","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending approval from Inbox subscription",match:{id:"2026/06/12.ttl#approval_1"}}]},inputRequestDescriptor={uri:UDFS.InputRequest,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.InputRequest,resourceKind:"input-request",description:"Durable input request control item. It asks for missing information or a choice; approval/authority decisions remain ApprovalRequest.",storage:{base:"/.data/input-requests/",resourceIdPattern:"{id}"},fields:{id:{type:"string",predicate:UDFS.term("id"),required:!0,description:"Input request resource id, including date bucket and fragment when materialized."},session:{type:"uri",predicate:UDFS.session,required:!0,description:"Runtime/session resource waiting for input."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(r="/.data/"){return{base:r,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that created the candidate."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last update timestamp."}},uniqueBy:["id"],writableFields:["source","summary","suggestedType","suggestedTarget","confidence","reason","status","sourceHash","chat","thread","task","run","actor","metadata","updatedAt"],mergePolicy:"upsert",examples:[{request:"Create a capture candidate from an observed chat message",match:{id:"candidates/2026/06/16.ttl#candidate_1"}}]},captureEventDescriptor={uri:UDFS.CaptureEvent,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureEvent,resourceKind:"capture-event",description:"Append-only capture decision ledger. It records direct commits, optimistic commits, candidate creation, promotion, rejection, correction, rollback, duplicate detection, and ignored decisions.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource considered by capture."},captureCandidate:{type:"uri",predicate:UDFS.captureCandidate,references:{resource:"capture-candidate",key:"id"},description:"Candidate resource involved in this event, when applicable."},targetResource:{type:"uri",predicate:UDFS.targetResource,description:"Formal resource affected by this capture decision."},decision:{type:"string",predicate:UDFS.captureDecision,required:!0,description:"Decision such as direct_commit, optimistic_commit, candidate_created, promoted, rejected, corrected, rollback, duplicate, or ignored."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Type suggested at decision time."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Target suggested at decision time."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence at decision time."},reason:{type:"text",predicate:UDFS.reason,description:"Explanation for the capture decision."},userCorrection:{type:"text",predicate:UDFS.userCorrection,description:"User correction to type, target, title, summary, or content."},approval:{type:"uri",predicate:UDFS.approval,references:{resource:"approval",key:"id"},description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,references:{resource:"input-request",key:"id"},description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$6.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,references:{resource:"contact",key:"id"},description:"Optional counterpart/contact represented by this channel."},participants:{type:"uri",predicate:WF.participant,array:!0,description:"Participant resource URIs."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},lastActiveAt:{type:"timestamp",predicate:UDFS.lastActiveAt,description:"Last activity timestamp."},lastMessage:{type:"uri",predicate:UDFS.lastMessage,description:"Latest message pointer."},lastMessagePreview:{type:"text",predicate:SCHEMA.text,description:"Latest message preview."}},uniqueBy:["id"],writableFields:["title","description","avatarUrl","author","status","starred","muted","unreadCount","contact","participants","metadata","lastActiveAt","lastMessage","lastMessagePreview"],mergePolicy:"upsert",examples:[{request:"Create a team chat surface",match:{id:"team/index.ttl#this"}}]},threadDescriptor={uri:SIOC.Thread,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:SIOC.Thread,resourceKind:"thread",description:"Concrete timeline/place under one parent command surface. Ownership is thread.parent via sioc:has_parent.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container."},title:{type:"string",predicate:DCTerms.title,description:"Thread title."},status:{type:"string",predicate:UDFS.status,description:"Thread lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},workspace:{type:"uri",predicate:UDFS.workspace,description:"Storage-layer workspace/container URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."}},uniqueBy:["id"],writableFields:["parent","title","status","starred","workspace","metadata"],mergePolicy:"upsert",examples:[{request:"Create a thread under a chat surface",match:{id:"chat/team/index.ttl#thread"}}]},messageDescriptor={uri:MEETING.Message,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.Message,resourceKind:"message",description:"Human/runtime communication item under one parent command surface and optionally a concrete thread timeline.",storage:exactIdStorage(),fields:{id:idField,parent:{type:"uri",predicate:SIOC.has_parent,required:!0,description:"Parent command surface/container URI."},chat:{type:"uri",predicate:WF.message,references:{resource:"chat",key:"id"},description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,references:{resource:"thread",key:"id"},description:"Thread containment relation."},maker:{type:"uri",predicate:FOAF.maker,description:"Author resource IRI."},role:{type:"string",predicate:UDFS.messageType,description:"Message role."},content:{type:"text",predicate:SIOC.content,required:!0,description:"Plain text content."},richContent:{type:"text",predicate:SIOC.richContent,description:"Structured/rich content payload."},status:{type:"string",predicate:UDFS.messageStatus,description:"Message lifecycle status."},toolName:{type:"string",predicate:UDFS.toolName,description:"Tool name for tool messages."},toolCallId:{type:"string",predicate:UDFS.toolCallId,description:"Opaque tool call id; not a resource relation."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter/UI metadata."},replacedBy:{type:"string",predicate:DCTerms.isReplacedBy,description:"Replacement message reference."},deletedAt:{type:"timestamp",predicate:SCHEMA.dateDeleted,description:"Deletion timestamp."},senderName:{type:"string",predicate:UDFS.senderName,description:"Display sender name."},senderAvatarUrl:{type:"uri",predicate:UDFS.senderAvatarUrl,description:"Display sender avatar."},mentions:{type:"uri",predicate:UDFS.mentions,array:!0,description:"Mentioned resource URIs."},replyTo:{type:"uri",predicate:UDFS.replyTo,description:"Original message URI."},routedBy:{type:"uri",predicate:UDFS.routedBy,description:"Routing agent URI."},routeTargetAgent:{type:"uri",predicate:UDFS.routeTargetAgent,description:"Target agent URI."},coordinationId:{type:"string",predicate:UDFS.coordinationId,description:"Opaque multi-agent coordination id."}},uniqueBy:["id"],writableFields:["parent","chat","thread","maker","role","content","richContent","status","toolName","toolCallId","metadata","replacedBy","deletedAt","senderName","senderAvatarUrl","mentions","replyTo","routedBy","routeTargetAgent","coordinationId"],mergePolicy:"append",examples:[{request:"Append a message under a team chat",match:{id:"chat/team/2026/06/14/messages.ttl#msg_1"}}]},chatProjectContextDescriptor={uri:UDFS.ChatProjectContext,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ChatProjectContext,resourceKind:"chat-project-context",description:"Workspace-scoped instructions and explicit memory-use preference shared by related chat threads.",storage:exactIdStorage("/.data/chat-projects/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this context."},instructions:{type:"text",predicate:UDFS.systemMessage,description:"User-maintained project instructions."},memoryEnabled:{type:"boolean",predicate:UDFS.memoryEnabled,description:"Whether explicit project memories may be injected into model context."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","instructions","memoryEnabled","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Save shared instructions for a workspace",match:{id:"workspace-key.ttl"}}]},chatProjectMemoryDescriptor={uri:UDFS.ProjectMemory,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ProjectMemory,resourceKind:"chat-project-memory",description:"One user-approved, workspace-scoped memory entry with optional message provenance.",storage:exactIdStorage("/.data/chat-project-memories/"),fields:{id:idField,workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI that owns this memory."},text:{type:"text",predicate:SCHEMA.text,required:!0,description:"Explicit memory text."},sourceMessage:{type:"uri",predicate:UDFS.sourceMessage,description:"Optional source message URI."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},updatedAt:{type:"timestamp",predicate:DCTerms.modified,description:"Last modification timestamp."}},uniqueBy:["id"],writableFields:["workspace","text","sourceMessage","createdAt","updatedAt"],mergePolicy:"upsert",examples:[{request:"Remember an explicit project fact",match:{id:"memory-id.ttl"}}]},conversationShareDescriptor={uri:UDFS.ConversationShare,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.ConversationShare,resourceKind:"conversation-share",description:"Revocable metadata record for a sanitized, read-only conversation export.",storage:exactIdStorage("/.data/chat-shares/"),fields:{id:idField,thread:{type:"uri",predicate:UDFS.targetThread,required:!0,description:"Shared thread URI."},resourceUrl:{type:"uri",predicate:SCHEMA.url,required:!0,description:"Public read-only HTML resource URL."},includeToolDetails:{type:"boolean",predicate:UDFS.includeToolDetails,description:"Whether sanitized tool details were included."},excludedMessageIds:{type:"string",predicate:UDFS.excludedMessage,array:!0,description:"Messages excluded by the user before sharing."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp."}},uniqueBy:["id"],writableFields:["thread","resourceUrl","includeToolDetails","excludedMessageIds","createdAt","revokedAt"],mergePolicy:"upsert",examples:[{request:"Record a read-only conversation share",match:{id:"share-id.ttl"}}]},ideaDescriptor={uri:UDFS.Idea,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Idea,resourceKind:"idea",description:"File-primary candidate extracted from conversation before it is promoted to committed work. The document owns human-readable content; meta owns status and routing facts.",storage:exactIdStorage("/.data/ideas/"),fields:{id:idField,summary:{type:"string",predicate:DCTerms.abstract,required:!0,description:"Short summary of the idea."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the idea body."},input:{type:"text",predicate:DCTerms.description,description:"Original or synthesized input text."},status:{type:"string",predicate:UDFS.status,description:"Idea lifecycle status."},commitment:{type:"string",predicate:UDFS.commitment,description:"Commitment level such as thought, direction, tentative_decision, or committed."},affectedArea:{type:"string",predicate:UDFS.affectedArea,description:"System or product area the idea may affect."},currentUnderstanding:{type:"text",predicate:UDFS.currentUnderstanding,description:"Current synthesized understanding."},openQuestions:{type:"text",predicate:UDFS.openQuestions,array:!0,description:"Open questions before promotion."},related:{type:"uri",predicate:DCTerms.relation,array:!0,description:"Related control records or resources."},conflicts:{type:"text",predicate:UDFS.conflicts,array:!0,description:"Potential semantic conflicts."},nextStep:{type:"text",predicate:UDFS.nextStep,description:"Suggested next action."},promotedTo:{type:"uri",predicate:UDFS.promotedTo,description:"Committed resource created from the idea."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},sourceMessages:{type:"uri",predicate:DCTerms.source,array:!0,description:"Source messages."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["summary","document","input","status","commitment","affectedArea","currentUnderstanding","openQuestions","related","conflicts","nextStep","promotedTo","chat","thread","sourceMessages","createdBy","metadata"],mergePolicy:"upsert",examples:[{request:"Capture a fragmented product idea for later triage",match:{id:"2026/05/28.ttl#idea_symphony_quality_metrics"}}]},issueDescriptor={uri:UDFS.Issue,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Issue,resourceKind:"issue",description:"File-primary user-facing work item for a requirement, bug, support item, investigation, or feature request. The document owns human-readable content; meta owns status and routing facts.",storage:{base:"/.data/issues/",resourceIdPattern:"{id}"},fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Compact issue label for list/search surfaces; the file owns the full title/body."},document:{type:"uri",predicate:DCTerms.source,description:"Pod file that owns the issue body."},description:{type:"text",predicate:DCTerms.description,description:"Issue description."},status:{type:"string",predicate:UDFS.status,description:"Issue lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Issue priority."},labels:{type:"text",predicate:UDFS.tags,array:!0,description:"Tags or labels."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,references:{resource:"issue",key:"id"},description:"Parent issue."},tasks:{type:"uri",predicate:UDFS.task,array:!0,description:"Executable task slices."},createdBy:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},closedAt:{type:"timestamp",predicate:UDFS.closedAt,description:"Closure timestamp."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."}},uniqueBy:["id"],writableFields:["title","document","description","status","priority","labels","chat","thread","parentIssue","tasks","createdBy","assignedTo","closedAt","deletedAt"],mergePolicy:"upsert",examples:[{request:"Create a Symphony issue for a delegated implementation slice",match:{id:"issue_symphony_runtime_projection.ttl"}}]},taskDescriptor={uri:UDFS.Task,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Task,resourceKind:"task",description:"Durable executable work unit. Scheduling, runner selection, and concrete attempts live outside Task.",storage:exactIdStorage("/.data/task/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,description:"Task title."},instruction:{type:"text",predicate:UDFS.instruction,required:!0,description:"Executable instruction."},prompt:{type:"text",predicate:UDFS.prompt,description:"Runtime prompt projection."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},dueAt:{type:"timestamp",predicate:UDFS.dueAt,description:"Deadline, independent of execution scheduling."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Time the task was completed."},notes:{type:"text",predicate:DCTerms.description,description:"User notes about the task."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","dueAt","completedAt","notes","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},required:!0,description:"Scheduled task."},status:{type:"string",predicate:UDFS.status,description:"Schedule lifecycle status."},scheduleKind:{type:"string",predicate:UDFS.scheduleKind,description:"Schedule kind: once, interval, or cron."},cron:{type:"string",predicate:UDFS.cron,description:"Cron expression."},intervalSeconds:{type:"number",predicate:UDFS.intervalSeconds,description:"Interval in seconds."},timezone:{type:"string",predicate:UDFS.timezone,description:"Timezone."},startsAt:{type:"timestamp",predicate:UDFS.startsAt,description:"Start timestamp."},nextRunAt:{type:"timestamp",predicate:UDFS.nextRunAt,description:"Next run timestamp."},lastRunAt:{type:"timestamp",predicate:UDFS.lastRunAt,description:"Last run timestamp."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["task","status","scheduleKind","cron","intervalSeconds","timezone","startsAt","nextRunAt","lastRunAt","metadata"],mergePolicy:"upsert",examples:[{request:"Create a time trigger for a task",match:{id:"schedules/schedule_1.ttl"}}]},automationRuleDescriptor={uri:UDFS.AutomationRule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.AutomationRule,resourceKind:"automation_rule",description:"Policy, condition, and action wiring that can dispatch tasks or scheduled work.",storage:exactIdStorage(),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Rule title."},description:{type:"text",predicate:DCTerms.description,description:"Rule description."},status:{type:"string",predicate:UDFS.status,description:"Rule lifecycle status."},ruleKind:{type:"string",predicate:UDFS.ruleKind,description:"Rule kind: event, schedule, or manual."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,references:{resource:"schedule",key:"id"},description:"Schedule that triggers this rule."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},condition:{type:"json",predicate:UDFS.condition,description:"Structured condition."},actions:{type:"json",predicate:UDFS.actions,description:"Structured actions."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},lastTriggeredAt:{type:"timestamp",predicate:UDFS.lastTriggeredAt,description:"Last trigger timestamp."},lastRunStatus:{type:"string",predicate:UDFS.lastRunStatus,description:"Last run status."}},uniqueBy:["id"],writableFields:["title","description","status","ruleKind","task","schedule","source","target","condition","actions","metadata","lastTriggeredAt","lastRunStatus"],mergePolicy:"upsert",examples:[{request:"Create an automation rule that dispatches a task",match:{id:"automation/rule_1.ttl"}}]},deliveryDescriptor={uri:UDFS.Delivery,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Delivery,resourceKind:"delivery",description:"Internal handoff envelope between threads, sessions, agents, and runtimes.",storage:exactIdStorage(),fields:{id:idField,kind:{type:"string",predicate:UDFS.deliveryKind,description:"Delivery kind."},status:{type:"string",predicate:UDFS.status,description:"Delivery lifecycle status."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being delivered."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},target:{type:"uri",predicate:AS.target,description:"Target resource."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,references:{resource:"thread",key:"id"},description:"Target thread."},targetSession:{type:"uri",predicate:UDFS.targetSession,description:"Target session."},actor:{type:"uri",predicate:AS.actor,description:"Actor."},object:{type:"uri",predicate:AS.object,description:"Object resource."},objective:{type:"text",predicate:UDFS.objective,description:"Short objective."},payload:{type:"json",predicate:UDFS.payload,description:"Structured payload."},projection:{type:"json",predicate:UDFS.projection,description:"Runtime projection."},projectedRole:{type:"string",predicate:UDFS.projectedRole,description:"Projected runtime role."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},error:{type:"text",predicate:UDFS.error,description:"Failure detail."},dispatchedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Dispatch timestamp."},consumedAt:{type:"timestamp",predicate:UDFS.consumedAt,description:"Consumption timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["kind","status","task","source","target","chat","thread","targetThread","targetSession","actor","object","objective","payload","projection","projectedRole","metadata","error","dispatchedAt","consumedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Create a worker delivery package",match:{id:"task/symphony/2026/05/28/deliveries.ttl#delivery_1"}}]},runDescriptor={uri:UDFS.Run,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Run,resourceKind:"run",description:"One concrete execution attempt by an agent runtime.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Delivery that caused or carries this run."},trigger:{type:"uri",predicate:UDFS.trigger,description:"Resource that triggered the run."},input:{type:"uri",predicate:UDFS.input,description:"Concrete input/context projection resource."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},required:!0,description:"Runtime thread."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Run lifecycle status."},runner:{type:"string",predicate:UDFS.runner,required:!0,description:"Runtime implementation."},prompt:{type:"string",predicate:UDFS.prompt,description:"Prompt or prompt version."},externalRunId:{type:"string",predicate:UDFS.externalRunId,description:"Opaque external runtime id; not a resource relation."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Lease owner."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Lease expiration timestamp."},heartbeatAt:{type:"timestamp",predicate:UDFS.heartbeatAt,description:"Heartbeat timestamp."},cancelRequestedAt:{type:"timestamp",predicate:UDFS.cancelRequestedAt,description:"Cancel request timestamp."},error:{type:"string",predicate:UDFS.error,description:"Failure detail."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},startedAt:{type:"timestamp",predicate:UDFS.startedAt,description:"Start timestamp."},completedAt:{type:"timestamp",predicate:UDFS.completedAt,description:"Completion timestamp."}},uniqueBy:["id"],writableFields:["task","delivery","trigger","input","thread","workspace","status","runner","prompt","externalRunId","leaseOwner","leaseExpiresAt","heartbeatAt","cancelRequestedAt","error","metadata","startedAt","completedAt"],mergePolicy:"upsert",examples:[{request:"Record a runtime execution attempt",match:{id:"task/symphony/2026/05/28/runs.ttl#run_1"}}]},runStepDescriptor={uri:UDFS.RunStep,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.RunStep,resourceKind:"run_step",description:"Append-only execution fact emitted while a run executes.",storage:exactIdStorage(),fields:{id:idField,run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},required:!0,description:"Run this step belongs to."},stepType:{type:"string",predicate:UDFS.stepType,required:!0,description:"RunStep event type."},message:{type:"string",predicate:DCTerms.description,description:"Human-readable step message."},payload:{type:"json",predicate:UDFS.payload,description:"Structured step payload."}},uniqueBy:["id"],writableFields:["run","stepType","message","payload"],mergePolicy:"append",examples:[{request:"Append a runtime tool call step",match:{id:"task/symphony/2026/05/28/runs.ttl#run-step_1"}}]},evidenceDescriptor={uri:UDFS.Evidence,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Evidence,resourceKind:"evidence",description:"Append-only proof or finding for a workflow control object.",storage:exactIdStorage(),fields:{id:idField,evidenceKind:{type:"string",predicate:UDFS.evidenceKind,required:!0,description:"Evidence kind."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object this evidence supports."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},summary:{type:"text",predicate:DCTerms.abstract,description:"Evidence summary."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the evidence."},outcome:{type:"string",predicate:UDFS.outcome,description:"Evidence outcome."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["evidenceKind","about","issue","task","delivery","run","thread","summary","source","actor","outcome","metadata"],mergePolicy:"append",examples:[{request:"Record test evidence for a task",match:{id:"task/symphony/2026/05/28/evidence.ttl#evidence_1"}}]},reportDescriptor={uri:UDFS.Report,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Report,resourceKind:"report",description:"Closure, review, handoff, status, or quality summary for a control object.",storage:exactIdStorage(),fields:{id:idField,reportKind:{type:"string",predicate:UDFS.reportKind,required:!0,description:"Report kind."},status:{type:"string",predicate:UDFS.status,description:"Report lifecycle status."},outcome:{type:"string",predicate:UDFS.outcome,description:"Reported outcome."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Control object being summarized."},issue:{type:"uri",predicate:UDFS.issue,references:{resource:"issue",key:"id"},description:"Related issue."},task:{type:"uri",predicate:UDFS.task,references:{resource:"task",key:"id"},description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,references:{resource:"delivery",key:"id"},description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,references:{resource:"run",key:"id"},description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,references:{resource:"evidence",key:"id"},array:!0,description:"Evidence summarized by this report."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Report summary."},reviewer:{type:"uri",predicate:SCHEMA.reviewedBy,description:"Reviewer."},actor:{type:"uri",predicate:DCTerms.creator,description:"Actor that produced the report."},source:{type:"uri",predicate:DCTerms.source,description:"Source artifact or document."},metricFacts:{type:"json",predicate:UDFS.metricFacts,description:"Structured metric facts."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},publishedAt:{type:"timestamp",predicate:DCTerms.issued,description:"Publication timestamp."}},uniqueBy:["id"],writableFields:["reportKind","status","outcome","about","issue","task","delivery","run","thread","evidence","summary","reviewer","actor","source","metricFacts","metadata","publishedAt"],mergePolicy:"upsert",examples:[{request:"Publish a worker handoff report",match:{id:"task/symphony/2026/05/28/reports.ttl#report_1"}}]},sessionDescriptor={uri:UDFS.term("Session"),version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.term("Session"),resourceKind:"session",description:"Runtime or collaboration session lifecycle projection for a concrete thread.",storage:exactIdStorage("/.data/sessions/"),fields:{id:idField,owner:{type:"uri",predicate:UDFS.actor,required:!0,description:"Session owner."},chat:{type:"uri",predicate:UDFS.conversation,references:{resource:"chat",key:"id"},description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,references:{resource:"thread",key:"id"},description:"Related thread."},status:{type:"string",predicate:UDFS.sessionStatus,description:"Session lifecycle status."},tool:{type:"string",predicate:UDFS.sessionTool,description:"Runtime tool or backend."},tokenUsage:{type:"number",predicate:UDFS.tokenUsage,description:"Token usage."},messages:{type:"uri",predicate:UDFS.message,array:!0,description:"Messages in this session."},policy:{type:"uri",predicate:UDFS.policy,description:"Policy resource."},policyVersion:{type:"string",predicate:UDFS.policyVersion,description:"Policy version."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."},archivedAt:{type:"timestamp",predicate:UDFS.archivedAt,description:"Archive timestamp."}},uniqueBy:["id"],writableFields:["owner","chat","thread","status","tool","tokenUsage","messages","policy","policyVersion","metadata","archivedAt"],mergePolicy:"upsert",examples:[{request:"Record a worker runtime session",match:{id:"2026/05/28/sess_1.ttl"}}]},officialPodModelDescriptors=[credentialDescriptor,gatewayAccessKeyDescriptor,quotaSnapshotDescriptor,aiProviderDescriptor,aiModelDescriptor,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(r=officialPodModelDescriptors){const e=new Map(r.map(t=>[t.uri,t]));return{list(t={}){return r.filter(n=>!(t.source&&n.source!==t.source||t.resourceKind&&n.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(r=createPodModelDescriptorRegistry()){const e=(t={})=>{const n=t.uri??t.schemaUri;if(!n)return r.list();const a=r.describe(n);return a?[a]:[]};return{list:r.list,describe(t){const n=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return r.describe(n)},classes(t={}){return e(t).map(n=>({schemaUri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description}))},search(t){const n=normalizeSearchTerms(t.query);return n.length===0?[]:r.list({source:t.source,resourceKind:t.resourceKind}).map(a=>scoreDescriptorSearch(a,n)).filter(a=>a!==null).sort((a,i)=>i.score-a.score||a.uri.localeCompare(i.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(n=>Object.entries(n.fields).filter(([a])=>!t.field||a===t.field).map(([a,i])=>({schemaUri:n.uri,field:a,predicate:i.predicate,type:i.type,required:!!i.required,secret:!!i.secret,array:!!i.array,description:i.description})))}}}function normalizeSearchTerms(r){return r.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(r,e){const t=new Set;let n=0;const a=(i,o,s)=>{if(!o)return;const d=o.toLowerCase();for(const u of e)d.includes(u)&&(t.add(i),n+=s)};a("uri",r.uri,10),a("class",r.class,10),a("namespace",r.namespace,4),a("resourceKind",r.resourceKind,8),a("description",r.description,4),a("storage",`${r.storage.base}${r.storage.resourceIdPattern}`,3);for(const[i,o]of Object.entries(r.fields))a(`field:${i}`,i,6),a(`predicate:${i}`,o.predicate,6),a(`description:${i}`,o.description,3);for(const i of r.examples){a("example",i.request,3);for(const[o,s]of Object.entries(i.match))a(`example:${o}`,String(s),3)}return n<=0?null:{uri:r.uri,resourceKind:r.resourceKind,class:r.class,namespace:r.namespace,source:r.source,trustLevel:r.trustLevel,description:r.description,score:n,matchedFields:[...t].sort()}}async function filterWebIdsByStorageRoot(r,e,t){const n=normalizeStorageRoot(t);if(!n)return[];const a=Array.from(new Set(e.filter(o=>typeof o=="string"&&o.length>0)));return(await Promise.all(a.map(async o=>{const d=(await fetchProfileStorageUrls(r,o)).find(u=>storageUrlBelongsToRoot(u,n));return d?{webId:o,storageUrl:ensureTrailingSlash$1(d)}:void 0}))).filter(o=>!!o)}function storageUrlBelongsToRoot(r,e){const t=normalizeStorageUrl(r),n=normalizeStorageRoot(e);return!!(t&&n&&t.startsWith(n))}function normalizeStorageRoot(r){if(r)try{return ensureTrailingSlash$1(new URL(r).toString())}catch{return}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(r,e){const t=await r(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const n=t.headers?.get?.("content-type")??"",a=await t.text().catch(()=>"");if(!a)return[];if(n.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(a)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(a))}function extractStorageUrlsFromTurtle(r){return Array.from(r.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(r){const e=new Set,t=new WeakSet,n=(a,i=!1)=>{if(typeof a=="string"){i&&e.add(a);return}if(!(!a||typeof a!="object")&&!t.has(a)){if(t.add(a),Array.isArray(a)){for(const o of a)n(o,i);return}for(const[o,s]of Object.entries(a)){const d=SOLID_STORAGE_KEYS.has(o);if(i&&o==="@id"){n(s,!0);continue}n(s,i||d)}}};return n(r),Array.from(e)}function normalizeStorageUrl(r){try{return ensureTrailingSlash$1(new URL(r).toString())}catch{return}}function uniqueNormalizedStorageUrls(r){const e=new Set;for(const t of r){const n=normalizeStorageUrl(t);n&&e.add(n)}return Array.from(e)}function ensureTrailingSlash$1(r){return r.replace(/\/+$/u,"")+"/"}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections","/tasks","/pod","/device","/inbox","/notifications"],desktopPages=new Set(["/tasks","/pod","/pod/models","/pod/search","/pod/apps","/pod/data","/device","/device/network","/device/services","/device/runtime","/device/logs","/inbox","/notifications"]);function isXpodProductPath(r){const e=r.replace(/\/$/u,"");return desktopPages.has(e)?!0:XPOD_RETURN_PATH_PREFIXES.slice(0,6).some(t=>e===t||e.startsWith(`${t}/`))}function normalizeXpodReturnPath(r){if(r===void 0)return;if(typeof r!="string"||r.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const e=r.trim(),t=decodeForValidation(e),n=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||n.split("/").some(a=>a==="..")||!isXpodProductPath(n))throw new TypeError("returnTo must be a safe path within the application allow-list");return e}function decodeForValidation(r){let e=r;for(let t=0;t<4;t+=1){let n;try{n=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(n===e)return e;e=n}return e}const XPOD_LOGIN_ROUTE_ID="xpod-current-origin";function createXpodLoginRoute(r=typeof window>"u"?"http://localhost":window.location){const e=toLocation(r),t=e.origin;if(!t||t==="null")throw new TypeError("Xpod login requires a same-origin browser URL");return{id:XPOD_LOGIN_ROUTE_ID,label:"Xpod",identityProvider:{url:t,label:e.host||t},storageProvider:{url:t,label:e.host||t},availability:"ready"}}function normalizeXpodReturnTo(r){return normalizeXpodReturnPath(r)}function assertXpodLoginRoute(r,e){const t=normalizeWebIdLoginRoute(r),n=new URL(e).origin,a=new URL(t.identityProvider.url).origin,i=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||a!==n||i!==n||t.identityProvider.url!==t.storageProvider?.url)throw new TypeError("Xpod login route must use the current origin for identity and storage");return{...t,identityProvider:{...t.identityProvider,url:n},storageProvider:t.storageProvider?{...t.storageProvider,url:n}:void 0}}function toLocation(r){if(typeof r=="string"){const e=new URL(r,typeof window>"u"?void 0:window.location.href);return{origin:e.origin,host:e.host,href:e.href}}return r instanceof URL?{origin:r.origin,host:r.host,href:r.href}:{origin:r.origin,host:r.host,href:r.href}}const ORIGIN_PRIORITY={loopback:10,lan:20,"public-direct":30};async function currentHostLocalPodRoutes(r,e,t={}){if(typeof window>"u")return[];const n=await fetchCurrentProvisionRouteStatus(e,t);return provisionLocalPodRoutes(r,n)}function provisionLocalPodRoutes(r,e,t=typeof window>"u"?"":window.location.href){const n=safeUrl(t);if(!n||!r)return[];if(e.managed===!0&&e.storageRoot&&e.oidcIssuer&&safeUrl(e.storageRoot)?.origin===safeUrl(e.oidcIssuer)?.origin)return[];const a=currentOriginRoute(r,e,n);return[...a?[a]:[],...advertisedRoutes(r,e)].sort((i,o)=>i.priority-o.priority||i.id.localeCompare(o.id))}function currentOriginRoute(r,e,t){const n=safeUrl(r);if(!n||!["http:","https:"].includes(n.protocol)||n.username||n.password||!podBelongsToCurrentHost(r,e))return;const a=safeUrl(e.storageRoot??"")??n;if(a.origin===t.origin)return;const i=currentOriginKind(t);return{id:`${i}-current-origin`,kind:i,canonicalUrl:`${a.origin}/`,targetUrl:`${t.origin}/`,priority:ORIGIN_PRIORITY[i],requiresManagedClient:i!=="public-direct",visibility:i==="loopback"?"local-only":"same-account",health:"healthy"}}function podBelongsToCurrentHost(r,e){return typeof window<"u"&&window.xpodDesktop?!0:e.managed!==!0||typeof e.storageRoot!="string"?!1:coveredByStorageRoot(r,e.storageRoot)}function coveredByStorageRoot(r,e){const t=safeUrl(e),n=safeUrl(r);return!t||!n?!1:n.origin===t.origin||n.href.startsWith(ensureTrailingSlash(t.href))}function advertisedRoutes(r,e){const t=safeUrl(r);if(!t)return[];const n=`${(safeUrl(e.storageRoot??"")??t).origin}/`;return(e.routes??[]).flatMap(a=>{const i=safeUrl(a.targetUrl);return!i||!["http:","https:"].includes(i.protocol)?[]:[{id:a.id,kind:a.kind,canonicalUrl:n,targetUrl:`${i.origin}/`,priority:a.priority,requiresManagedClient:a.requiresManagedClient??!0,visibility:a.visibility??"public",health:a.health??"unknown"}]})}function currentOriginKind(r){return isLoopbackHostname(r.hostname)?"loopback":isPrivateNetworkHostname(r.hostname)?"lan":"public-direct"}function isLoopbackHostname(r){return r==="localhost"||r==="::1"||r==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(r)}function isPrivateNetworkHostname(r){const e=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(r);if(!e)return r.endsWith(".local");const t=Number(e[1]),n=Number(e[2]);return t===10||t===192&&n===168?!0:t===172&&n>=16&&n<=31}async function fetchCurrentProvisionRouteStatus(r,e={}){return typeof window>"u"||window.location.origin==="null"?{}:await probeSolidLocalRouteStatus({fetch:r,url:new URL("/provision/status",window.location.origin).href,signal:e.signal,read:async n=>{if(!n.ok||!n.headers.get("content-type")?.includes("application/json")){await n.arrayBuffer().catch(()=>{});return}const a=await n.json().catch(()=>{});return{managed:a?.managed===!0,storageRoot:typeof a?.publicUrl=="string"?a.publicUrl:void 0,routes:normalizeAdvertisedAccessRoutes(a?.routes)}}})??{}}function normalizeAdvertisedAccessRoutes(r){return Array.isArray(r)?r.flatMap(e=>{if(!e||typeof e!="object")return[];const t=e;return typeof t.targetUrl!="string"||typeof t.kind!="string"?[]:typeof t.priority!="number"||!Number.isFinite(t.priority)?[]:[{id:typeof t.id=="string"&&t.id?t.id:`${t.kind}-${t.targetUrl}`,kind:t.kind,targetUrl:t.targetUrl,priority:t.priority,...typeof t.requiresManagedClient=="boolean"?{requiresManagedClient:t.requiresManagedClient}:{},...typeof t.visibility=="string"?{visibility:t.visibility}:{},...typeof t.health=="string"?{health:t.health}:{}}]}):[]}function safeUrl(r){try{return new URL(r)}catch{return}}function ensureTrailingSlash(r){return r.endsWith("/")?r:`${r}/`}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_SOLID_SESSION_ID_STORAGE_KEY="xpod.solid.sessionId",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(r,e,t){return r.status==="initializing"?{status:"loading",issuer:t}:r.status==="anonymous"?{status:"anonymous",issuer:t}:r.status==="expired"?{status:"expired",webId:r.webId,issuer:t}:r.status==="error"?{status:"error",webId:r.webId,error:r.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:r.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:r,fetch:e}){const t=await fetchProfileStorageUrls(e,r);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash$1(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(r={}){initializeBrowserSparql();const e=createXpodSolidRuntimeStoragePolicy(r.storage);let t=[],n,a;const i=createSolidAccessRouteFetch({fetch:globalThis.fetch,routes:()=>t,refreshRoutes:async()=>{await a?.()},allowLocalOnlyRoutes:!0,managedClient:!0}),o=r.sessionFactory?.({fetch:i})??createInruptSession(e.oidcSession,i);let s=readStoredOidcIssuer(e.issuer),d,u=0;const c=createSolidSessionRuntime({session:{get info(){return o.info},events:o.events,fetch:(m,S)=>S===void 0?o.fetch(m):o.fetch(m,S),login:m=>(u+=1,o.login(m)),logout:m=>(u+=1,o.logout(m)),handleIncomingRedirect:async m=>{const S=++u,A=typeof window>"u"?"http://localhost":window.location.origin,h=await resolveXpodLoginContext(A,globalThis.fetch);if(S!==u)throw new Error("Solid session changed during authority discovery");if(d=h.oidcIssuer,!d)throw new Error("暂时无法确认本机登录信息,请稍后重试。");if(n=h.provisionRouteStatus,t=n?provisionLocalPodRoutes(n.storageRoot,n):[],typeof m!="string"&&m?.restorePreviousSession){const T=new URL(m.url??window.location.href);if(!T.searchParams.has("code")||!T.searchParams.has("state"))return o.handleIncomingRedirect({...m,restorePreviousSession:readActiveRestoreIssuer(e.oidcSession)===d})}return o.handleIncomingRedirect(m)}}}),p={...c,dispose:()=>{u+=1,c.dispose()}},_=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:m,fetch:S})=>drizzle({get info(){return o.info},fetch:S},{podUrl:m,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:p,pod:_,storage:e,transportFetch:i,getIssuer:()=>readIssuerFromSessionInfo(o.info)??s??readStoredOidcIssuer(e.issuer),getProvisionRouteStatus:()=>n,getExpectedIssuer:()=>d,setIssuer:m=>{const S=normalizeXpodOidcIssuer(m);s=S,S&&writeStoredOidcIssuer(S,e.issuer)},setLocalPodRoutes:m=>{t=m?[...m]:[],m===void 0&&(n=void 0)},setLocalPodRoutesRefresh:m=>{a=m},resolveLocalUrl:m=>resolveSolidLocalRouteUrl(m,t.map(toLocalRoute))?.href??m}}function toLocalRoute(r){return{canonicalBaseUrl:r.canonicalUrl,localBaseUrl:r.targetUrl}}function createInruptSession(r=getOptionalPersistentStorage(),e=globalThis.fetch){return new Session({fetch:e,...r?{secureStorage:new InMemoryStorage,insecureStorage:toInruptStorage(r,"insecure")}:{}})}function toInruptStorage(r,e){const t=n=>inruptStorageKey(e,n);return{get:async n=>r.getItem(t(n))??void 0,set:async(n,a)=>{r.setItem(t(n),a)},delete:async n=>{r.removeItem(t(n))}}}function inruptStorageKey(r,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${r}:${e}`}function readActiveRestoreIssuer(r){try{const e=getOptionalPersistentStorage()?.getItem(`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`);if(!e)return;const t=r?.getItem(inruptStorageKey("insecure",`solidClientAuthenticationUser:${e}`));return t?normalizeXpodOidcIssuer(JSON.parse(t).issuer):void 0}catch{return}}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function withXpodProvisionScope(r,e){const t=new URL(r);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(r,e){const t=new AbortController;let n;const a=new Promise((i,o)=>{n=setTimeout(()=>{t.abort(),o(new Error("暂时无法确认本机登录信息,请稍后重试。"))},5e3)});try{const i=await Promise.race([e("/provision/status",{headers:{Accept:"application/json"},credentials:"include",signal:t.signal}).catch(()=>{}),a]);if(i?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(r)};const o=i?.ok?await Promise.race([i.json().catch(()=>{}),a]):void 0,s=normalizeXpodOidcIssuer(o?.oidcIssuer),d=normalizeXpodOidcIssuer(o?.publicUrl),u=d?{provisionRouteStatus:{managed:o?.managed===!0,storageRoot:d,oidcIssuer:s,routes:normalizeAdvertisedAccessRoutes(o?.routes)}}:{};if(o?.managed===!1)return{oidcIssuer:s??normalizeXpodOidcIssuer(r),...u};const c=typeof o?.provisionCode=="string"&&o.provisionCode.trim()?o.provisionCode.trim():void 0;if(!s||o?.managed===!0&&!c)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:s,provisionCode:c,...u}}finally{clearTimeout(n)}}function safeAuthError(r){if(r.name==="SolidSessionPendingError"){const e=new Error("上次登录尚未结束,请刷新页面后重新登录。");return e.name=r.name,e}return r.message==="Solid session expired"?r:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(r,e=typeof window>"u"?"http://localhost":window.location.origin){if(!r||typeof r!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(r),n=assertXpodLoginRoute(t.route,e),a=normalizeXpodReturnTo(t.returnTo);return{...t,route:n,authorizationSurface:"redirect",discovery:"strict",...a===void 0?{}:{returnTo:a}}}function useXpodSolidRuntimeContext(){const r=reactExports.useContext(XpodSolidRuntimeContext);if(!r)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return r}function readIssuerFromSessionInfo(r){const e=r.issuer??r.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(r){if(!(typeof r!="string"||!r.trim()))try{const e=new URL(r.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(r,e,t){if(r.status!=="authenticated")return!0;const n=normalizeXpodOidcIssuer(e),a=normalizeXpodOidcIssuer(t);return!n||!a||n!==a?!1:isHttpResourceUrl(r.webId)}function isHttpResourceUrl(r){try{const e=new URL(r);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(r=getOptionalPersistentStorage()){try{return normalizeXpodOidcIssuer(r?.getItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY))}catch{return}}function clearStoredXpodOidcIssuer(r){try{r?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalPersistentStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(r,e=getOptionalPersistentStorage()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,r)}catch{}}function createXpodSolidRuntimeStoragePolicy(r={}){const e=getOptionalPersistentStorage();return{oidcSession:r.oidcSession??e,issuer:r.issuer??e,selectedStorage:r.selectedStorage??e}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function hasInvalidWebIdWhitespace(r){return r!==r.trim()||/[\r\n\t]/.test(r)}const XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1",XPOD_ACCOUNT_REMEMBER_CHOICE_KEY="xpod.account-remember-choice.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(r={}){const e=r.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const n=normalizeRememberedXpodLogin(JSON.parse(t),r.origin??currentOrigin());return n||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(r,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const n=normalizeRememberedXpodLogin(r,e.origin??currentOrigin());if(n)try{t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(n));const a=n.issuer??normalizedIssuer(e.origin??currentOrigin()??"");return clearPendingEmailForIssuer(t,a),clearPendingEmailForIssuer(optionalTemporaryStorage(),a),n}catch{return}}function clearRememberedXpodLogin(r=optionalPersistentStorage()){for(const e of[r,optionalTemporaryStorage()])try{e?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),e?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),e?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(r,e){if(!r||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(r.webId),n=validatedWebId(r.storageBinding.webId),a=normalizedUrl(r.storageBinding.storageUrl,!0),i=validatedWebId(e.webId),o=validatedWebId(e.selectedStorage.webId),s=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!n||!a||!i||!o||!s||t!==n||i!==o||t!==i||a!==s?!1:rememberedXpodAccountMatchesActive(r,e)}function rememberedXpodAccountMatchesActive(r,e){return r?matchingOptionalEmail(r.account.email,e.accountEmail):!1}function readXpodAccountRememberChoice(r,e=optionalPersistentStorage()){try{const n=JSON.parse(e?.getItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY)??"{}")[normalizedIssuer(r??currentOrigin()??"")];return typeof n=="boolean"?n:void 0}catch{return}}function optionalTemporaryStorage(){try{return typeof window>"u"?void 0:window.sessionStorage}catch{return}}function clearPendingEmailForIssuer(r,e){const t=r?.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);(!t||t===e)&&(r?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),r?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY))}function rememberPendingXpodAccountEmail(r,e=optionalPersistentStorage(),t,n=!0,a=optionalTemporaryStorage()){const i=normalizedEmail(r);if(!i)return;const o=normalizedIssuer(t??currentOrigin()??"");try{const s=JSON.parse(e?.getItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY)??"{}"),d=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(e?.setItem(XPOD_ACCOUNT_REMEMBER_CHOICE_KEY,JSON.stringify({...d,[o]:n})),!n){clearPendingEmailForIssuer(e,o);const c=readRememberedXpodLogin({storage:e});(!c?.issuer||c.issuer===o)&&e?.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}const u=n?e:a;return u?(u.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),u.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,o),n&&clearPendingEmailForIssuer(a,o),i):void 0}catch{return}}function readPendingXpodAccountEmail(r=optionalPersistentStorage(),e,t=optionalTemporaryStorage()){const n=readXpodAccountRememberChoice(e,r)===!1?t:r;if(n)try{const a=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}if(i!==normalizedIssuer(e))return}return a||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),a}catch{return}}function normalizedIssuer(r){try{const e=currentOrigin();return e?new URL(r,e).origin:new URL(r).origin}catch{return r.trim()}}function normalizeRememberedXpodLogin(r,e){if(!r||typeof r!="object")return;const t=r;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||t.issuer!==void 0&&!normalizedUrl(t.issuer)||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const n=t.account,a=t.storageBinding,i=normalizedEmail(n.email),o=validatedWebId(t.webId),s=validatedWebId(a.webId),d=normalizedUrl(a.storageUrl,!0);if(n.email!==void 0&&!i||!o||!s||!d||o!==s)return;const u=normalizedAvatarUrl(n.avatarUrl,[o,d,e]);return{...typeof t.issuer=="string"?{issuer:normalizedIssuer(t.issuer)}:{},account:{...i?{email:i}:{},...normalizedText(n.id)?{id:normalizedText(n.id)}:{},...normalizedText(n.username)?{username:normalizedText(n.username)}:{},...normalizedText(n.displayName)?{displayName:normalizedText(n.displayName)}:{},...u?{avatarUrl:u}:{}},webId:o,storageBinding:{webId:o,storageUrl:d},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(r){if(typeof r!="string")return;const e=r.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(r){if(typeof r!="string")return;const e=r.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(r){return typeof r=="string"&&!hasInvalidWebIdWhitespace(r)&&normalizedUrl(r)?r:void 0}function normalizedUrl(r,e=!1){if(!(typeof r!="string"||r.length>2048))try{const t=new URL(r);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(r,e){const t=normalizedUrl(r);if(!t)return;const n=new URL(t).origin;return e.some(a=>{const i=normalizedUrl(a);return i&&new URL(i).origin===n})?t:void 0}function matchingOptionalEmail(r,e){const t=normalizedEmail(r)?.toLowerCase(),n=normalizedEmail(e)?.toLowerCase();return!t||!n||t===n}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}export{setThing as $,aiConfigModelRef as A,AI_MODEL_CLASS_DEFAULT_CAPABILITY as B,CircleAlert as C,AI_MODEL_CLASS as D,EmailInput as E,FormField as F,aiProviderResource as G,initializeBrowserSparql as H,filterAIModelCapabilityUris as I,withAIModelClassDefaultCapabilities as J,toAIModelClassName as K,LoaderCircle as L,getLinkedResourceUrlAll as M,NoUsableAccessRouteError as N,acp as O,internal_cloneResource as P,getSolidDataset as Q,freeze as R,getSourceUrl as S,getResourceInfo as T,getSourceIri as U,getThingAll as V,WebAccountLayout as W,XpodDeploymentIdentity as X,getIriAll as Y,rdf$e as Z,acl as _,credentialResource as a,mergeSchemaColumns as a$,setIri as a0,removeIri as a1,removeAll as a2,createThing as a3,addIri as a4,removeThing as a5,subjectToRdfJsQuads as a6,DataFactory$H as a7,getIri as a8,saveSolidDatasetAt as a9,textButtonClass as aA,Disclosure as aB,outlineButtonClass as aC,Field as aD,string$2 as aE,podTable as aF,ColumnBuilder as aG,PodArrayColumn as aH,PodBooleanColumn as aI,PodColumnBase as aJ,PodDateTimeColumn as aK,PodIntegerColumn as aL,PodJsonColumn as aM,PodObjectColumn as aN,PodStringColumn as aO,PodTable as aP,PodUriColumn as aQ,SolidSchema as aR,boolean$2 as aS,date$3 as aT,generateNanoId as aU,hasStringValue$2 as aV,hasTermValue as aW,id as aX,integer$1 as aY,isSolidSchema as aZ,json as a_,createSolidDataset as aa,foaf as ab,getThing as ac,getUrlAll as ad,buildThing as ae,addUrl as af,quotaSnapshotResource as ag,Avatar as ah,AvatarImage as ai,AvatarFallback as aj,Check as ak,Tooltip as al,TooltipTrigger as am,TooltipContent as an,TooltipProvider as ao,Info as ap,LoaderCircle$1 as aq,resolvePodSignInCopy as ar,usePastDelay as as,SourceMark as at,ScreenLayout as au,PodAvatar as av,Spinner as aw,formatCopy as ax,ActionButton as ay,primaryButtonClass as az,XpodAuthSurface as b,object$1 as b0,real as b1,resolveTermIri as b2,solidSchema as b3,text as b4,timestamp as b5,uri as b6,validateColumnOverride as b7,bufferExports as b8,pickSolidProfileDisplayName as b9,VCARD as ba,FOAF as bb,readRememberedXpodLogin as bc,rememberedXpodLoginMatchesActive as bd,rememberXpodLogin as be,XPOD_LOGIN_ROUTE_ID as bf,hasInvalidWebIdWhitespace as bg,normalizeWebIdLoginTransaction as bh,isCurrentXpodSessionSnapshot as bi,clearStoredXpodOidcIssuer as bj,fetchCurrentProvisionRouteStatus as bk,currentHostLocalPodRoutes as bl,snapshotToState as bm,normalizeXpodLoginTransaction as bn,resolveXpodLoginContext as bo,withXpodProvisionScope as bp,safeAuthError as bq,XpodSolidRuntimeContext as br,approvalResource as bs,inboxNotificationResource as bt,taskResource as bu,clearRememberedXpodLogin as bv,createXpodLoginRoute as bw,XpodSignInFrame as bx,namespaces$6 as by,credentialDescriptor as c,createXpodSolidRuntimeValue as d,assertXpodLoginRoute as e,XPOD_SOLID_SESSION_ID_STORAGE_KEY as f,XPOD_LAST_OIDC_ISSUER_STORAGE_KEY as g,normalizeAdvertisedAccessRoutes as h,filterWebIdsByStorageRoot as i,getXpodSolidRuntimeValue as j,readPendingXpodAccountEmail as k,XpodBlockingAccountCredentialsSurface as l,rememberPendingXpodAccountEmail as m,normalizeXpodReturnTo as n,useXpodSolidRuntimeContext as o,provisionLocalPodRoutes as p,XpodAccountPageSurface as q,readXpodAccountRememberChoice as r,storageUrlBelongsToRoot as s,Checkbox as t,useSize as u,runResource as v,toAIModelCapabilityUri as w,toAIModelCapabilityName as x,toAIModelClassUri as y,aiModelResource as z};
|