@undefineds.co/xpod 0.3.74 → 0.3.75
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/container/common.js +1 -7
- package/dist/runtime/css-process.js +0 -1
- package/package.json +1 -1
- package/static/auth-callback/assets/{AiConfigContext-DNfRNaZQ.js → AiConfigContext-BvBdu_A3.js} +1 -1
- package/static/auth-callback/assets/{AiConfigPage-BBiTOm3o.js → AiConfigPage-BpDw4jco.js} +1 -1
- package/static/auth-callback/assets/{DocumentProcessingPanel-BzpEwqKT.js → DocumentProcessingPanel-BmZ_jzRr.js} +1 -1
- package/static/auth-callback/assets/{IndexLifecyclePanel-CvXMwooQ.js → IndexLifecyclePanel-BfQBjN4z.js} +1 -1
- package/static/auth-callback/assets/{IndexSubjectPanel-CayA221L.js → IndexSubjectPanel-BlsnatPt.js} +1 -1
- package/static/auth-callback/assets/{ModelAssignmentsPanel-Iew2QgtR.js → ModelAssignmentsPanel-KA6Mdndz.js} +1 -1
- package/static/auth-callback/assets/{ModelsPage-CTJKAUA3.js → ModelsPage-C7jymyIY.js} +1 -1
- package/static/auth-callback/assets/{NetworkPage--8ZCjIHB.js → NetworkPage-k2ShktNm.js} +1 -1
- package/static/auth-callback/assets/{PaneListHeader-BT-OGKL7.js → PaneListHeader-mLMe_dvU.js} +1 -1
- package/static/auth-callback/assets/{SearchIndexingPanel-CFjjk1-C.js → SearchIndexingPanel-CqV9um_t.js} +1 -1
- package/static/auth-callback/assets/{StatusSubjectPanel-DAN5Ej9q.js → StatusSubjectPanel-BgMBTbr2.js} +1 -1
- package/static/auth-callback/assets/{StatusWorkspace-CEgmKJcX.js → StatusWorkspace-zbSyhdG2.js} +1 -1
- package/static/auth-callback/assets/{SystemSettingsPage-Bk0TB4RU.js → SystemSettingsPage-CtW79nW6.js} +1 -1
- package/static/auth-callback/assets/{SystemSettingsSubjectPanel-CKl8ukiz.js → SystemSettingsSubjectPanel-ZOPKYUtZ.js} +1 -1
- package/static/auth-callback/assets/{activity-BOtct9Ie.js → activity-BQ-CQE3O.js} +1 -1
- package/static/auth-callback/assets/{auth-callback-ai6OMe6C.js → auth-callback-Htr_CB_g.js} +3 -3
- package/static/auth-callback/assets/{badge-DGSg5wio.js → badge-D5SGTJeO.js} +1 -1
- package/static/auth-callback/assets/{download-4eVPmxQ_.js → download-DK183Ldo.js} +1 -1
- package/static/auth-callback/assets/{external-link-BlD92fAM.js → external-link-LDHy_4bn.js} +1 -1
- package/static/auth-callback/assets/{index-7ppych8q.js → index-2WmlePQ9.js} +1 -1
- package/static/auth-callback/assets/{index-FrugCRsJ.js → index-BWrvgHqK.js} +1 -1
- package/static/auth-callback/assets/{index-browser-dwpJ2mdT.js → index-browser-DUd4E4-x.js} +1 -1
- package/static/auth-callback/assets/{key-round-BFOQbNNp.js → key-round-ibX79Kr-.js} +1 -1
- package/static/auth-callback/assets/{rotate-ccw-BySVgaAP.js → rotate-ccw-B2_VMaiX.js} +1 -1
- package/static/auth-callback/assets/{skeleton-CgcxPTqc.js → skeleton-F4nrpycc.js} +1 -1
- package/static/auth-callback/assets/{waypoints-DM902DhB.js → waypoints-DImIq93f.js} +1 -1
- package/static/auth-callback/assets/{workspace-layout-DlZlN49Q.js → workspace-layout-IVCSYU21.js} +1 -1
- package/static/auth-callback/auth-callback.html +1 -1
- package/static/dashboard/assets/{AiConfigContext-VnWI7bOR.js → AiConfigContext-cjjfYTo9.js} +1 -1
- package/static/dashboard/assets/{AiConfigPage-Dn3oxXcA.js → AiConfigPage-CO0DSD_j.js} +1 -1
- package/static/dashboard/assets/{DocumentProcessingPanel-CAF1uLi3.js → DocumentProcessingPanel-DMGnH8Oj.js} +1 -1
- package/static/dashboard/assets/{IndexLifecyclePanel-D9zVZwu8.js → IndexLifecyclePanel-DSkIOCL5.js} +1 -1
- package/static/dashboard/assets/{IndexSubjectPanel-_JCGwJmO.js → IndexSubjectPanel-qWN_DbAp.js} +1 -1
- package/static/dashboard/assets/{ModelAssignmentsPanel-DtlxQxFa.js → ModelAssignmentsPanel-DCf83uM3.js} +1 -1
- package/static/dashboard/assets/{ModelsPage-CCNTpXM5.js → ModelsPage-CMnvSrl5.js} +1 -1
- package/static/dashboard/assets/{NetworkPage-BAKv9unq.js → NetworkPage-C8Gkwclb.js} +1 -1
- package/static/dashboard/assets/{PaneListHeader-Dr1jq2Ii.js → PaneListHeader-BtU_8cDK.js} +1 -1
- package/static/dashboard/assets/{SearchIndexingPanel-BW0pPrQB.js → SearchIndexingPanel-DEn12pNU.js} +1 -1
- package/static/dashboard/assets/{StatusSubjectPanel-c9iebk4M.js → StatusSubjectPanel-B1_ILg2d.js} +1 -1
- package/static/dashboard/assets/{StatusWorkspace-KZ7zrrmB.js → StatusWorkspace-BG6nMNCo.js} +1 -1
- package/static/dashboard/assets/{SystemSettingsPage-fVSfJMi9.js → SystemSettingsPage-BnWYIXaM.js} +1 -1
- package/static/dashboard/assets/{SystemSettingsSubjectPanel-DUSxcVT8.js → SystemSettingsSubjectPanel-C_mYVPWb.js} +1 -1
- package/static/dashboard/assets/{activity-Dg4XxJA8.js → activity-DYJ7PdRl.js} +1 -1
- package/static/dashboard/assets/{badge-OHMG7sYk.js → badge-BIaZco1P.js} +1 -1
- package/static/dashboard/assets/{dashboard-UuQZ5g0B.js → dashboard-Dl40_MEa.js} +2 -2
- package/static/dashboard/assets/{download-CkbQhuL2.js → download-By16k9VK.js} +1 -1
- package/static/dashboard/assets/{external-link-C15frgwD.js → external-link-B92xOG_d.js} +1 -1
- package/static/dashboard/assets/{index-BiU8tNWd.js → index-BajZpJ48.js} +1 -1
- package/static/dashboard/assets/{index-JUkJUI4K.js → index-wsVPom_x.js} +1 -1
- package/static/dashboard/assets/{key-round-BVREfX5D.js → key-round-Clo5FOwA.js} +1 -1
- package/static/dashboard/assets/{rotate-ccw-cPEquKE_.js → rotate-ccw-smWSfi1L.js} +1 -1
- package/static/dashboard/assets/{skeleton-BPM2LdA5.js → skeleton-BrTaGeJw.js} +1 -1
- package/static/dashboard/assets/{waypoints-Cd3kODMk.js → waypoints-DGPQInE7.js} +1 -1
- package/static/dashboard/assets/{workspace-layout-BP3gLLXb.js → workspace-layout-CPU4XRmb.js} +1 -1
- package/static/dashboard/dashboard.html +1 -1
- package/static/settings/assets/{AiConfigContext-B-D3riwG.js → AiConfigContext-CT29_OyW.js} +1 -1
- package/static/settings/assets/{AiConfigPage-CAYT-CgT.js → AiConfigPage-WIE95S28.js} +1 -1
- package/static/settings/assets/{DocumentProcessingPanel-D__vS86O.js → DocumentProcessingPanel-KG8Sq999.js} +1 -1
- package/static/settings/assets/{IndexLifecyclePanel-CuYEAG62.js → IndexLifecyclePanel-iKvtHDXY.js} +1 -1
- package/static/settings/assets/{IndexSubjectPanel-Do71gQQC.js → IndexSubjectPanel-BQdSCkk4.js} +1 -1
- package/static/settings/assets/{ModelAssignmentsPanel-Cn3kSze7.js → ModelAssignmentsPanel-P8QcVB0F.js} +1 -1
- package/static/settings/assets/{ModelsPage-BKO0ARYt.js → ModelsPage-UZkZGqor.js} +1 -1
- package/static/settings/assets/{NetworkPage-XPYrdyVd.js → NetworkPage-Dcpcvg15.js} +1 -1
- package/static/settings/assets/{PaneListHeader-BAiQcCss.js → PaneListHeader--gHtZws5.js} +1 -1
- package/static/settings/assets/{SearchIndexingPanel-Bx3Fco0x.js → SearchIndexingPanel-DdgJSJYQ.js} +1 -1
- package/static/settings/assets/{StatusSubjectPanel-BzKzXmSL.js → StatusSubjectPanel-UOxp_XVL.js} +1 -1
- package/static/settings/assets/{StatusWorkspace-NjLpo9xp.js → StatusWorkspace-CPNXuD12.js} +1 -1
- package/static/settings/assets/{SystemSettingsPage-CclI_Lpv.js → SystemSettingsPage-B6ySeVPw.js} +1 -1
- package/static/settings/assets/{SystemSettingsSubjectPanel-CMnSE-8N.js → SystemSettingsSubjectPanel-I7zWmpiI.js} +1 -1
- package/static/settings/assets/{activity-DYpNPFzG.js → activity-CFhmzahP.js} +1 -1
- package/static/settings/assets/{badge-C7Vhmg28.js → badge-BBdUc5B-.js} +1 -1
- package/static/settings/assets/{download-DdXcAiwj.js → download-WJE9-yxQ.js} +1 -1
- package/static/settings/assets/{external-link-D7thdQae.js → external-link-RKoYyCp_.js} +1 -1
- package/static/settings/assets/{index-CwBKvDQZ.js → index-Bq2o0Bif.js} +1 -1
- package/static/settings/assets/{index-BnYbrf5s.js → index-DvxneI5O.js} +1 -1
- package/static/settings/assets/{index-browser-DYzi1DO1.js → index-browser-Qmo6EsFT.js} +1 -1
- package/static/settings/assets/{key-round-BXErodZA.js → key-round-r-D9sQUK.js} +1 -1
- package/static/settings/assets/{rotate-ccw-DPyOBmDD.js → rotate-ccw-D3IIhbPH.js} +1 -1
- package/static/settings/assets/{settings-BGpEf8nx.js → settings-D8oDBXWg.js} +3 -3
- package/static/settings/assets/{skeleton-S9l3JIr9.js → skeleton-DrL4RQuw.js} +1 -1
- package/static/settings/assets/{waypoints-C5By7zWc.js → waypoints-C5sRhpJw.js} +1 -1
- package/static/settings/assets/{workspace-layout-Bb6RVAEx.js → workspace-layout-B4ALmWsM.js} +1 -1
- package/static/settings/settings.html +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Bq2o0Bif.js","assets/admin-BU4m6Ko2.js","assets/activity-CFhmzahP.js","assets/external-link-RKoYyCp_.js","assets/index-DvxneI5O.js","assets/download-WJE9-yxQ.js","assets/key-round-r-D9sQUK.js","assets/NetworkPage-Dcpcvg15.js","assets/PaneListHeader--gHtZws5.js","assets/waypoints-C5sRhpJw.js","assets/workspace-layout-B4ALmWsM.js","assets/badge-BBdUc5B-.js","assets/rotate-ccw-D3IIhbPH.js","assets/StatusWorkspace-CPNXuD12.js","assets/StatusSubjectPanel-UOxp_XVL.js","assets/IndexSubjectPanel-BQdSCkk4.js","assets/skeleton-DrL4RQuw.js","assets/ModelsPage-UZkZGqor.js","assets/ai-connections-Bm52UO7Y.js","assets/index-browser-Qmo6EsFT.js","assets/AiConfigPage-WIE95S28.js","assets/AiConfigContext-CT29_OyW.js","assets/ModelAssignmentsPanel-P8QcVB0F.js","assets/DocumentProcessingPanel-KG8Sq999.js","assets/SearchIndexingPanel-DdgJSJYQ.js","assets/IndexLifecyclePanel-iKvtHDXY.js","assets/SystemSettingsPage-B6ySeVPw.js","assets/SystemSettingsSubjectPanel-I7zWmpiI.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
function _mergeNamespaces(n,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in n)){const o=Object.getOwnPropertyDescriptor(i,s);o&&Object.defineProperty(n,s,o.get?o:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function t(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(s){if(s.ep)return;s.ep=!0;const o=t(s);fetch(s.href,o)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function i(){var s=!1;try{s=this instanceof i}catch{}return s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var s=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return n[i]}})}),t}var jsxRuntime={exports:{}},reactJsxRuntime_production={};var hasRequiredReactJsxRuntime_production;function requireReactJsxRuntime_production(){if(hasRequiredReactJsxRuntime_production)return reactJsxRuntime_production;hasRequiredReactJsxRuntime_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,s,o){var l=null;if(o!==void 0&&(l=""+o),s.key!==void 0&&(l=""+s.key),"key"in s){o={};for(var u in s)u!=="key"&&(o[u]=s[u])}else o=s;return s=o.ref,{$$typeof:n,type:i,key:l,ref:s!==void 0?s:null,props:o}}return reactJsxRuntime_production.Fragment=e,reactJsxRuntime_production.jsx=t,reactJsxRuntime_production.jsxs=t,reactJsxRuntime_production}var hasRequiredJsxRuntime;function requireJsxRuntime(){return hasRequiredJsxRuntime||(hasRequiredJsxRuntime=1,jsxRuntime.exports=requireReactJsxRuntime_production()),jsxRuntime.exports}var jsxRuntimeExports=requireJsxRuntime(),react={exports:{}},react_production={};var hasRequiredReact_production;function requireReact_production(){if(hasRequiredReact_production)return react_production;hasRequiredReact_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),y=Symbol.iterator;function v(Z){return Z===null||typeof Z!="object"?null:(Z=y&&Z[y]||Z["@@iterator"],typeof Z=="function"?Z:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,x={};function A(Z,fe,oe){this.props=Z,this.context=fe,this.refs=x,this.updater=oe||S}A.prototype.isReactComponent={},A.prototype.setState=function(Z,fe){if(typeof Z!="object"&&typeof Z!="function"&&Z!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,Z,fe,"setState")},A.prototype.forceUpdate=function(Z){this.updater.enqueueForceUpdate(this,Z,"forceUpdate")};function I(){}I.prototype=A.prototype;function T(Z,fe,oe){this.props=Z,this.context=fe,this.refs=x,this.updater=oe||S}var F=T.prototype=new I;F.constructor=T,E(F,A.prototype),F.isPureReactComponent=!0;var P=Array.isArray;function V(){}var B={H:null,A:null,T:null,S:null},Y=Object.prototype.hasOwnProperty;function _e(Z,fe,oe){var Pe=oe.ref;return{$$typeof:n,type:Z,key:fe,ref:Pe!==void 0?Pe:null,props:oe}}function j(Z,fe){return _e(Z.type,fe,Z.props)}function ee(Z){return typeof Z=="object"&&Z!==null&&Z.$$typeof===n}function me(Z){var fe={"=":"=0",":":"=2"};return"$"+Z.replace(/[=:]/g,function(oe){return fe[oe]})}var te=/\/+/g;function Ce(Z,fe){return typeof Z=="object"&&Z!==null&&Z.key!=null?me(""+Z.key):fe.toString(36)}function Oe(Z){switch(Z.status){case"fulfilled":return Z.value;case"rejected":throw Z.reason;default:switch(typeof Z.status=="string"?Z.then(V,V):(Z.status="pending",Z.then(function(fe){Z.status==="pending"&&(Z.status="fulfilled",Z.value=fe)},function(fe){Z.status==="pending"&&(Z.status="rejected",Z.reason=fe)})),Z.status){case"fulfilled":return Z.value;case"rejected":throw Z.reason}}throw Z}function ye(Z,fe,oe,Pe,je){var Qe=typeof Z;(Qe==="undefined"||Qe==="boolean")&&(Z=null);var We=!1;if(Z===null)We=!0;else switch(Qe){case"bigint":case"string":case"number":We=!0;break;case"object":switch(Z.$$typeof){case n:case e:We=!0;break;case p:return We=Z._init,ye(We(Z._payload),fe,oe,Pe,je)}}if(We)return je=je(Z),We=Pe===""?"."+Ce(Z,0):Pe,P(je)?(oe="",We!=null&&(oe=We.replace(te,"$&/")+"/"),ye(je,fe,oe,"",function(Me){return Me})):je!=null&&(ee(je)&&(je=j(je,oe+(je.key==null||Z&&Z.key===je.key?"":(""+je.key).replace(te,"$&/")+"/")+We)),fe.push(je)),1;We=0;var ge=Pe===""?".":Pe+":";if(P(Z))for(var pe=0;pe<Z.length;pe++)Pe=Z[pe],Qe=ge+Ce(Pe,pe),We+=ye(Pe,fe,oe,Qe,je);else if(pe=v(Z),typeof pe=="function")for(Z=pe.call(Z),pe=0;!(Pe=Z.next()).done;)Pe=Pe.value,Qe=ge+Ce(Pe,pe++),We+=ye(Pe,fe,oe,Qe,je);else if(Qe==="object"){if(typeof Z.then=="function")return ye(Oe(Z),fe,oe,Pe,je);throw fe=String(Z),Error("Objects are not valid as a React child (found: "+(fe==="[object Object]"?"object with keys {"+Object.keys(Z).join(", ")+"}":fe)+"). If you meant to render a collection of children, use an array instead.")}return We}function qe(Z,fe,oe){if(Z==null)return Z;var Pe=[],je=0;return ye(Z,Pe,"","",function(Qe){return fe.call(oe,Qe,je++)}),Pe}function de(Z){if(Z._status===-1){var fe=Z._result;fe=fe(),fe.then(function(oe){(Z._status===0||Z._status===-1)&&(Z._status=1,Z._result=oe)},function(oe){(Z._status===0||Z._status===-1)&&(Z._status=2,Z._result=oe)}),Z._status===-1&&(Z._status=0,Z._result=fe)}if(Z._status===1)return Z._result.default;throw Z._result}var Fe=typeof reportError=="function"?reportError:function(Z){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var fe=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof Z=="object"&&Z!==null&&typeof Z.message=="string"?String(Z.message):String(Z),error:Z});if(!window.dispatchEvent(fe))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",Z);return}console.error(Z)},O={map:qe,forEach:function(Z,fe,oe){qe(Z,function(){fe.apply(this,arguments)},oe)},count:function(Z){var fe=0;return qe(Z,function(){fe++}),fe},toArray:function(Z){return qe(Z,function(fe){return fe})||[]},only:function(Z){if(!ee(Z))throw Error("React.Children.only expected to receive a single React element child.");return Z}};return react_production.Activity=g,react_production.Children=O,react_production.Component=A,react_production.Fragment=t,react_production.Profiler=s,react_production.PureComponent=T,react_production.StrictMode=i,react_production.Suspense=h,react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=B,react_production.__COMPILER_RUNTIME={__proto__:null,c:function(Z){return B.H.useMemoCache(Z)}},react_production.cache=function(Z){return function(){return Z.apply(null,arguments)}},react_production.cacheSignal=function(){return null},react_production.cloneElement=function(Z,fe,oe){if(Z==null)throw Error("The argument must be a React element, but you passed "+Z+".");var Pe=E({},Z.props),je=Z.key;if(fe!=null)for(Qe in fe.key!==void 0&&(je=""+fe.key),fe)!Y.call(fe,Qe)||Qe==="key"||Qe==="__self"||Qe==="__source"||Qe==="ref"&&fe.ref===void 0||(Pe[Qe]=fe[Qe]);var Qe=arguments.length-2;if(Qe===1)Pe.children=oe;else if(1<Qe){for(var We=Array(Qe),ge=0;ge<Qe;ge++)We[ge]=arguments[ge+2];Pe.children=We}return _e(Z.type,je,Pe)},react_production.createContext=function(Z){return Z={$$typeof:l,_currentValue:Z,_currentValue2:Z,_threadCount:0,Provider:null,Consumer:null},Z.Provider=Z,Z.Consumer={$$typeof:o,_context:Z},Z},react_production.createElement=function(Z,fe,oe){var Pe,je={},Qe=null;if(fe!=null)for(Pe in fe.key!==void 0&&(Qe=""+fe.key),fe)Y.call(fe,Pe)&&Pe!=="key"&&Pe!=="__self"&&Pe!=="__source"&&(je[Pe]=fe[Pe]);var We=arguments.length-2;if(We===1)je.children=oe;else if(1<We){for(var ge=Array(We),pe=0;pe<We;pe++)ge[pe]=arguments[pe+2];je.children=ge}if(Z&&Z.defaultProps)for(Pe in We=Z.defaultProps,We)je[Pe]===void 0&&(je[Pe]=We[Pe]);return _e(Z,Qe,je)},react_production.createRef=function(){return{current:null}},react_production.forwardRef=function(Z){return{$$typeof:u,render:Z}},react_production.isValidElement=ee,react_production.lazy=function(Z){return{$$typeof:p,_payload:{_status:-1,_result:Z},_init:de}},react_production.memo=function(Z,fe){return{$$typeof:d,type:Z,compare:fe===void 0?null:fe}},react_production.startTransition=function(Z){var fe=B.T,oe={};B.T=oe;try{var Pe=Z(),je=B.S;je!==null&&je(oe,Pe),typeof Pe=="object"&&Pe!==null&&typeof Pe.then=="function"&&Pe.then(V,Fe)}catch(Qe){Fe(Qe)}finally{fe!==null&&oe.types!==null&&(fe.types=oe.types),B.T=fe}},react_production.unstable_useCacheRefresh=function(){return B.H.useCacheRefresh()},react_production.use=function(Z){return B.H.use(Z)},react_production.useActionState=function(Z,fe,oe){return B.H.useActionState(Z,fe,oe)},react_production.useCallback=function(Z,fe){return B.H.useCallback(Z,fe)},react_production.useContext=function(Z){return B.H.useContext(Z)},react_production.useDebugValue=function(){},react_production.useDeferredValue=function(Z,fe){return B.H.useDeferredValue(Z,fe)},react_production.useEffect=function(Z,fe){return B.H.useEffect(Z,fe)},react_production.useEffectEvent=function(Z){return B.H.useEffectEvent(Z)},react_production.useId=function(){return B.H.useId()},react_production.useImperativeHandle=function(Z,fe,oe){return B.H.useImperativeHandle(Z,fe,oe)},react_production.useInsertionEffect=function(Z,fe){return B.H.useInsertionEffect(Z,fe)},react_production.useLayoutEffect=function(Z,fe){return B.H.useLayoutEffect(Z,fe)},react_production.useMemo=function(Z,fe){return B.H.useMemo(Z,fe)},react_production.useOptimistic=function(Z,fe){return B.H.useOptimistic(Z,fe)},react_production.useReducer=function(Z,fe,oe){return B.H.useReducer(Z,fe,oe)},react_production.useRef=function(Z){return B.H.useRef(Z)},react_production.useState=function(Z){return B.H.useState(Z)},react_production.useSyncExternalStore=function(Z,fe,oe){return B.H.useSyncExternalStore(Z,fe,oe)},react_production.useTransition=function(){return B.H.useTransition()},react_production.version="19.2.8",react_production}var hasRequiredReact;function requireReact(){return hasRequiredReact||(hasRequiredReact=1,react.exports=requireReact_production()),react.exports}var reactExports=requireReact();const React=getDefaultExportFromCjs(reactExports),React4=_mergeNamespaces({__proto__:null,default:React},[reactExports]);var client={exports:{}},reactDomClient_production={},scheduler={exports:{}},scheduler_production={};var hasRequiredScheduler_production;function requireScheduler_production(){return hasRequiredScheduler_production||(hasRequiredScheduler_production=1,(function(n){function e(ye,qe){var de=ye.length;ye.push(qe);e:for(;0<de;){var Fe=de-1>>>1,O=ye[Fe];if(0<s(O,qe))ye[Fe]=qe,ye[de]=O,de=Fe;else break e}}function t(ye){return ye.length===0?null:ye[0]}function i(ye){if(ye.length===0)return null;var qe=ye[0],de=ye.pop();if(de!==qe){ye[0]=de;e:for(var Fe=0,O=ye.length,Z=O>>>1;Fe<Z;){var fe=2*(Fe+1)-1,oe=ye[fe],Pe=fe+1,je=ye[Pe];if(0>s(oe,de))Pe<O&&0>s(je,oe)?(ye[Fe]=je,ye[Pe]=de,Fe=Pe):(ye[Fe]=oe,ye[fe]=de,Fe=fe);else if(Pe<O&&0>s(je,de))ye[Fe]=je,ye[Pe]=de,Fe=Pe;else break e}}return qe}function s(ye,qe){var de=ye.sortIndex-qe.sortIndex;return de!==0?de:ye.id-qe.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;n.unstable_now=function(){return o.now()}}else{var l=Date,u=l.now();n.unstable_now=function(){return l.now()-u}}var h=[],d=[],p=1,g=null,y=3,v=!1,S=!1,E=!1,x=!1,A=typeof setTimeout=="function"?setTimeout:null,I=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function F(ye){for(var qe=t(d);qe!==null;){if(qe.callback===null)i(d);else if(qe.startTime<=ye)i(d),qe.sortIndex=qe.expirationTime,e(h,qe);else break;qe=t(d)}}function P(ye){if(E=!1,F(ye),!S)if(t(h)!==null)S=!0,V||(V=!0,me());else{var qe=t(d);qe!==null&&Oe(P,qe.startTime-ye)}}var V=!1,B=-1,Y=5,_e=-1;function j(){return x?!0:!(n.unstable_now()-_e<Y)}function ee(){if(x=!1,V){var ye=n.unstable_now();_e=ye;var qe=!0;try{e:{S=!1,E&&(E=!1,I(B),B=-1),v=!0;var de=y;try{t:{for(F(ye),g=t(h);g!==null&&!(g.expirationTime>ye&&j());){var Fe=g.callback;if(typeof Fe=="function"){g.callback=null,y=g.priorityLevel;var O=Fe(g.expirationTime<=ye);if(ye=n.unstable_now(),typeof O=="function"){g.callback=O,F(ye),qe=!0;break t}g===t(h)&&i(h),F(ye)}else i(h);g=t(h)}if(g!==null)qe=!0;else{var Z=t(d);Z!==null&&Oe(P,Z.startTime-ye),qe=!1}}break e}finally{g=null,y=de,v=!1}qe=void 0}}finally{qe?me():V=!1}}}var me;if(typeof T=="function")me=function(){T(ee)};else if(typeof MessageChannel<"u"){var te=new MessageChannel,Ce=te.port2;te.port1.onmessage=ee,me=function(){Ce.postMessage(null)}}else me=function(){A(ee,0)};function Oe(ye,qe){B=A(function(){ye(n.unstable_now())},qe)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(ye){ye.callback=null},n.unstable_forceFrameRate=function(ye){0>ye||125<ye?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Y=0<ye?Math.floor(1e3/ye):5},n.unstable_getCurrentPriorityLevel=function(){return y},n.unstable_next=function(ye){switch(y){case 1:case 2:case 3:var qe=3;break;default:qe=y}var de=y;y=qe;try{return ye()}finally{y=de}},n.unstable_requestPaint=function(){x=!0},n.unstable_runWithPriority=function(ye,qe){switch(ye){case 1:case 2:case 3:case 4:case 5:break;default:ye=3}var de=y;y=ye;try{return qe()}finally{y=de}},n.unstable_scheduleCallback=function(ye,qe,de){var Fe=n.unstable_now();switch(typeof de=="object"&&de!==null?(de=de.delay,de=typeof de=="number"&&0<de?Fe+de:Fe):de=Fe,ye){case 1:var O=-1;break;case 2:O=250;break;case 5:O=1073741823;break;case 4:O=1e4;break;default:O=5e3}return O=de+O,ye={id:p++,callback:qe,priorityLevel:ye,startTime:de,expirationTime:O,sortIndex:-1},de>Fe?(ye.sortIndex=de,e(d,ye),t(h)===null&&ye===t(d)&&(E?(I(B),B=-1):E=!0,Oe(P,de-Fe))):(ye.sortIndex=O,e(h,ye),S||v||(S=!0,V||(V=!0,me()))),ye},n.unstable_shouldYield=j,n.unstable_wrapCallback=function(ye){var qe=y;return function(){var de=y;y=qe;try{return ye.apply(this,arguments)}finally{y=de}}}})(scheduler_production)),scheduler_production}var hasRequiredScheduler;function requireScheduler(){return hasRequiredScheduler||(hasRequiredScheduler=1,scheduler.exports=requireScheduler_production()),scheduler.exports}var reactDom={exports:{}},reactDom_production={};var hasRequiredReactDom_production;function requireReactDom_production(){if(hasRequiredReactDom_production)return reactDom_production;hasRequiredReactDom_production=1;var n=requireReact();function e(h){var d="https://react.dev/errors/"+h;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var p=2;p<arguments.length;p++)d+="&args[]="+encodeURIComponent(arguments[p])}return"Minified React error #"+h+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function t(){}var i={d:{f:t,r:function(){throw Error(e(522))},D:t,C:t,L:t,m:t,X:t,S:t,M:t},p:0,findDOMNode:null},s=Symbol.for("react.portal");function o(h,d,p){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:g==null?null:""+g,children:h,containerInfo:d,implementation:p}}var l=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function u(h,d){if(h==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,reactDom_production.createPortal=function(h,d){var p=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return o(h,d,null,p)},reactDom_production.flushSync=function(h){var d=l.T,p=i.p;try{if(l.T=null,i.p=2,h)return h()}finally{l.T=d,i.p=p,i.d.f()}},reactDom_production.preconnect=function(h,d){typeof h=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,i.d.C(h,d))},reactDom_production.prefetchDNS=function(h){typeof h=="string"&&i.d.D(h)},reactDom_production.preinit=function(h,d){if(typeof h=="string"&&d&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin),y=typeof d.integrity=="string"?d.integrity:void 0,v=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;p==="style"?i.d.S(h,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:g,integrity:y,fetchPriority:v}):p==="script"&&i.d.X(h,{crossOrigin:g,integrity:y,fetchPriority:v,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},reactDom_production.preinitModule=function(h,d){if(typeof h=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var p=u(d.as,d.crossOrigin);i.d.M(h,{crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&i.d.M(h)},reactDom_production.preload=function(h,d){if(typeof h=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin);i.d.L(h,p,{crossOrigin:g,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},reactDom_production.preloadModule=function(h,d){if(typeof h=="string")if(d){var p=u(d.as,d.crossOrigin);i.d.m(h,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else i.d.m(h)},reactDom_production.requestFormReset=function(h){i.d.r(h)},reactDom_production.unstable_batchedUpdates=function(h,d){return h(d)},reactDom_production.useFormState=function(h,d,p){return l.H.useFormState(h,d,p)},reactDom_production.useFormStatus=function(){return l.H.useHostTransitionStatus()},reactDom_production.version="19.2.8",reactDom_production}var hasRequiredReactDom;function requireReactDom(){if(hasRequiredReactDom)return reactDom.exports;hasRequiredReactDom=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),reactDom.exports=requireReactDom_production(),reactDom.exports}var hasRequiredReactDomClient_production;function requireReactDomClient_production(){if(hasRequiredReactDomClient_production)return reactDomClient_production;hasRequiredReactDomClient_production=1;var n=requireScheduler(),e=requireReact(),t=requireReactDom();function i(a){var c="https://react.dev/errors/"+a;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var f=2;f<arguments.length;f++)c+="&args[]="+encodeURIComponent(arguments[f])}return"Minified React error #"+a+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(a){return!(!a||a.nodeType!==1&&a.nodeType!==9&&a.nodeType!==11)}function o(a){var c=a,f=a;if(a.alternate)for(;c.return;)c=c.return;else{a=c;do c=a,(c.flags&4098)!==0&&(f=c.return),a=c.return;while(a)}return c.tag===3?f:null}function l(a){if(a.tag===13){var c=a.memoizedState;if(c===null&&(a=a.alternate,a!==null&&(c=a.memoizedState)),c!==null)return c.dehydrated}return null}function u(a){if(a.tag===31){var c=a.memoizedState;if(c===null&&(a=a.alternate,a!==null&&(c=a.memoizedState)),c!==null)return c.dehydrated}return null}function h(a){if(o(a)!==a)throw Error(i(188))}function d(a){var c=a.alternate;if(!c){if(c=o(a),c===null)throw Error(i(188));return c!==a?null:a}for(var f=a,m=c;;){var R=f.return;if(R===null)break;var D=R.alternate;if(D===null){if(m=R.return,m!==null){f=m;continue}break}if(R.child===D.child){for(D=R.child;D;){if(D===f)return h(R),a;if(D===m)return h(R),c;D=D.sibling}throw Error(i(188))}if(f.return!==m.return)f=R,m=D;else{for(var K=!1,ce=R.child;ce;){if(ce===f){K=!0,f=R,m=D;break}if(ce===m){K=!0,m=R,f=D;break}ce=ce.sibling}if(!K){for(ce=D.child;ce;){if(ce===f){K=!0,f=D,m=R;break}if(ce===m){K=!0,m=D,f=R;break}ce=ce.sibling}if(!K)throw Error(i(189))}}if(f.alternate!==m)throw Error(i(190))}if(f.tag!==3)throw Error(i(188));return f.stateNode.current===f?a:c}function p(a){var c=a.tag;if(c===5||c===26||c===27||c===6)return a;for(a=a.child;a!==null;){if(c=p(a),c!==null)return c;a=a.sibling}return null}var g=Object.assign,y=Symbol.for("react.element"),v=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),x=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),I=Symbol.for("react.consumer"),T=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),V=Symbol.for("react.suspense_list"),B=Symbol.for("react.memo"),Y=Symbol.for("react.lazy"),_e=Symbol.for("react.activity"),j=Symbol.for("react.memo_cache_sentinel"),ee=Symbol.iterator;function me(a){return a===null||typeof a!="object"?null:(a=ee&&a[ee]||a["@@iterator"],typeof a=="function"?a:null)}var te=Symbol.for("react.client.reference");function Ce(a){if(a==null)return null;if(typeof a=="function")return a.$$typeof===te?null:a.displayName||a.name||null;if(typeof a=="string")return a;switch(a){case E:return"Fragment";case A:return"Profiler";case x:return"StrictMode";case P:return"Suspense";case V:return"SuspenseList";case _e:return"Activity"}if(typeof a=="object")switch(a.$$typeof){case S:return"Portal";case T:return a.displayName||"Context";case I:return(a._context.displayName||"Context")+".Consumer";case F:var c=a.render;return a=a.displayName,a||(a=c.displayName||c.name||"",a=a!==""?"ForwardRef("+a+")":"ForwardRef"),a;case B:return c=a.displayName||null,c!==null?c:Ce(a.type)||"Memo";case Y:c=a._payload,a=a._init;try{return Ce(a(c))}catch{}}return null}var Oe=Array.isArray,ye=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,qe=t.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,de={pending:!1,data:null,method:null,action:null},Fe=[],O=-1;function Z(a){return{current:a}}function fe(a){0>O||(a.current=Fe[O],Fe[O]=null,O--)}function oe(a,c){O++,Fe[O]=a.current,a.current=c}var Pe=Z(null),je=Z(null),Qe=Z(null),We=Z(null);function ge(a,c){switch(oe(Qe,c),oe(je,a),oe(Pe,null),c.nodeType){case 9:case 11:a=(a=c.documentElement)&&(a=a.namespaceURI)?jf(a):0;break;default:if(a=c.tagName,c=c.namespaceURI)c=jf(c),a=Mf(c,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}fe(Pe),oe(Pe,a)}function pe(){fe(Pe),fe(je),fe(Qe)}function Me(a){a.memoizedState!==null&&oe(We,a);var c=Pe.current,f=Mf(c,a.type);c!==f&&(oe(je,a),oe(Pe,f))}function se(a){je.current===a&&(fe(Pe),fe(je)),We.current===a&&(fe(We),ao._currentValue=de)}var M,N;function L(a){if(M===void 0)try{throw Error()}catch(f){var c=f.stack.trim().match(/\n( *(at )?)/);M=c&&c[1]||"",N=-1<f.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<f.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+M+a+N}var H=!1;function re(a,c){if(!a||H)return"";H=!0;var f=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var m={DetermineComponentFrameRoot:function(){try{if(c){var ft=function(){throw Error()};if(Object.defineProperty(ft.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ft,[])}catch(st){var rt=st}Reflect.construct(a,[],ft)}else{try{ft.call()}catch(st){rt=st}a.call(ft.prototype)}}else{try{throw Error()}catch(st){rt=st}(ft=a())&&typeof ft.catch=="function"&&ft.catch(function(){})}}catch(st){if(st&&rt&&typeof st.stack=="string")return[st.stack,rt.stack]}return[null,null]}};m.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var R=Object.getOwnPropertyDescriptor(m.DetermineComponentFrameRoot,"name");R&&R.configurable&&Object.defineProperty(m.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var D=m.DetermineComponentFrameRoot(),K=D[0],ce=D[1];if(K&&ce){var Le=K.split(`
|
|
@@ -45,7 +45,7 @@ LIMIT 50`,prefixes:{}},d=s.kind==="sparql"?await this.dialect.executeOnResource(
|
|
|
45
45
|
VALUES ?linkPred { ${u} }
|
|
46
46
|
?parent ?linkPred ?child .
|
|
47
47
|
OPTIONAL { ?child ?pred ?obj . }
|
|
48
|
-
}`,prefixes:{}},F=await h.executeQueryWithSource(T,x);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,y=new Map,v=new Map;d.forEach(x=>{const A=this.normalizeInlineIri(x.parent),I=this.normalizeInlineIri(x.linkPred),T=this.normalizeInlineIri(x.child),F=this.normalizeInlineIri(x.pred),P=this.normalizeInlineObjectValue(x.obj);if(!A||!I)return;const V=o.get(I);if(V){const j=y.get(A)??new Map,ee=j.get(V.name)??[];T&&!ee.includes(T)&&ee.push(T),j.set(V.name,ee),y.set(A,j)}if(!T||!F)return;const B=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},Y=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,B);return}const _e=B[Y];_e===void 0?B[Y]=P:Array.isArray(_e)?B[Y]=[..._e,P]:B[Y]=[_e,P],v.set(T,B)});const S=x=>{if(Array.isArray(x))return x.map(I=>this.normalizeInlineIri(I)).filter(I=>!!I);const A=this.normalizeInlineIri(x);return A?[A]:[]},E=(x,A,I)=>{const T=x?y.get(x)?.get(I.name)??[]:[],P=(T.length>0?T:S(A)).map(V=>v.get(V)??{"@id":V,id:this.extractIdFromSubject(V,t)});return I.dataType==="array"?P:P[0]??null};return e.forEach(x=>{const A=this.normalizeInlineIri(x["@id"]??x.subject??x.uri??x.id);s.forEach(I=>{x[I.name]=E(A,x[I.name],I)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const o of this.orderByClauses){const l=this.getOrderByValue(i,o.column),u=this.getOrderByValue(s,o.column),h=this.compareOrderByValues(l,u);if(h!==0)return o.direction==="desc"?-h:h}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const o=this.serializeValueForKey(s);t.has(o)||(t.add(o),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(o=>{const l=this.normalizeInlineIri(o["@id"])??this.normalizeInlineIri(o.subject)??this.normalizeInlineIri(o.uri)??(typeof o.id=="string"?o.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...o});return}if(!t.has(l)){const d={...o};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const y=this.getColumnDefinitionForRowKey(p);(y?.options?.isArray||y?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),h=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(o).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const y=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...y];v.forEach(A=>{const I=h(A);S.some(T=>h(T)===I)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),x=E?.options?.isArray||E?.dataType==="array";!x&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):x?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(o=>t.get(o))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){if(!e)return!1;if(e.dataType==="object"||e.dataType==="json")return!0;if(e.dataType==="array"){const t=e.elementType??e.options?.baseType;return t==="object"||t==="json"}return!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,o=s.left.alias===e.alias?s.left:s.right,l=o===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const x=this.serializeValueForKey(E);u.has(x)||u.set(x,E)}if(u.size===0)return[];const h=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(o.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const x=d(),I=await(conditionTargetsReservedIdentifier(E)?x.applyInternalQueryCondition(E):x.where(E));S.push(...I)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const y=this.buildJoinLookupCondition(p,h);if(y){const S=d(),x=await(conditionTargetsReservedIdentifier(y)?S.applyInternalQueryCondition(y):S.where(y));return this.normalizeJoinRows(e,x)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,o=s.left.alias===e.alias?s.left:s.right,l=o===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),h=o.column==="id"&&u.length>0;if(!h&&i.length===1)return;const d=new Map;for(const y of i){const v=y.left.alias===e.alias?y.left:y.right;d.set(v.column,y)}const p=[],g=new Set;for(const y of t){const v=this.getRowValueForColumn(y,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],x=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,V=this.getRowValueForColumn(y,P);if(V==null){if(h&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(Y=>{const _e=d.get(Y);if(!_e)return!0;const ee=(_e.left.alias===e.alias?_e.left:_e.right)===_e.left?_e.right:_e.left,me=this.getRowValueForColumn(y,ee);return me==null})));A=!0;break}const B=e.table.getColumn(F.column);if(!B){A=!0;break}E.push(eq(B,V)),x.push(`${F.column}:${this.serializeValueForKey(V)}`)}if(A)continue;if(h&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const B=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,Y=this.getRowValueForColumn(y,B);return Y==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const I=x.join("|");g.has(I)||(g.add(I),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),o=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${o}, join.${o})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const o=this.extractSubjectValue(i);if(o){s.subject=o,s["@id"]=o,s.uri=o,s[`${e.alias}.subject`]=o,s[`${e.alias}.@id`]=o,s[`${e.alias}.uri`]=o;const l=this.extractIdFromSubject(o,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const y of i)p.push({...g,...y});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[o]=s,l=o.left.alias===t.alias?o.left:o.right,u=l===o.left?o.right:o.left,h=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const y=this.serializeValueForKey(g);h.has(y)||h.set(y,[]),h.get(y).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),y=this.serializeValueForKey(g),S=(g!=null?h.get(y)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(o=>{const l=o.left.alias===i?o.left:o.right,u=l===o.left?o.right:o.left,h=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return h==null||d===void 0||d===null?!1:this.serializeValueForKey(h)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,o=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(o.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const o=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return o==null;case"IS NOT NULL":return o!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(o=>this.evaluateCondition(e,o)):i.toUpperCase()==="OR"?s.some(o=>this.evaluateCondition(e,o)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const o=parsePodResourceRef(t,e)?.resourceId;if(o)return o}if(t){const o=this.session.getDialect?.(),u=(o?.getUriResolver?.()??new UriResolverImpl(o?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const o=e.slice(s+1);if(o.length>0)return o}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(o=>o.id||o["@id"]).filter(o=>typeof o=="string"&&o.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),o=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(o),o}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(o){console.error("[InsertQueryBuilder] afterInsert hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[o,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,o,l);for(const[o,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,o,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const o=e;return o.length===0?o():o(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),o=inferSPARQLQueryType(s);if(!o)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:o,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},o=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):o;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,o])=>Array.isArray(o));return s.length===0?i:i.map(o=>{const l={...o};for(const[u,h]of s)u in l&&(l[u]=[...h]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const o of e)try{await t.afterUpdate(i,o,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),o=inferSPARQLQueryType(s);if(!o)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:o,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},o=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):o;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(o){console.error("[DeleteQueryBuilder] afterDelete hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(o=>i.unregisterResourceSubject?.(e.table,o));return}s.forEach(o=>i.registerResourceSubject?.(e.table,o))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const o=this.getKnownRowIri(s);o&&i.add(o)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,o,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,o,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-DYzi1DO1.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),o=new Map;s.headers&&s.headers.forEach((h,d)=>{o.set(d.toLowerCase(),h||"")});const u={...s,headers:{get:h=>{const d=h.toLowerCase();return o.get(d)||null},has:h=>{const d=h.toLowerCase();return o.has(d)},forEach:h=>{o.forEach((d,p)=>h(d,p))},entries:()=>o.entries(),keys:()=>o.keys(),values:()=>o.values(),[Symbol.iterator]:()=>o.entries(),includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(o.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1}},status:s.status||200,statusText:s.statusText||"OK",ok:s.ok!==void 0?s.ok:!0,url:s.url||(typeof t=="string"?t:t.toString()),type:s.type||"basic",redirected:s.redirected||!1,body:s.body,bodyUsed:s.bodyUsed||!1,includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(o.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(h){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(h)),""}},json:async()=>{try{return await s.json()}catch(h){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(h)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(h){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(h)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(o=>{const l=o,u={},h=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>h(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())h(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&h(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let o=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(o=d.headers.get("ETag"),this.logging&&o&&console.log(`[UPDATE] Got ETag for ${s}: ${o}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":o??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),h=await u(l);if(h.ok)i.push({success:!0,source:s,status:h.status}),await this.invalidateCache(t,s);else if(h.status===409||h.status===412){this.logging&&console.log(`[UPDATE] ${h.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(h.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const y={...l,"If-Match":g},v=await u(y);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await h.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${h.status} ${h.statusText}`,details:p})}}else{const d=await h.text();i.push({success:!1,source:s,error:`${h.status} ${h.statusText}`,details:d})}}catch(o){i.push({success:!1,source:s,error:this.formatError(o)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
|
|
48
|
+
}`,prefixes:{}},F=await h.executeQueryWithSource(T,x);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,y=new Map,v=new Map;d.forEach(x=>{const A=this.normalizeInlineIri(x.parent),I=this.normalizeInlineIri(x.linkPred),T=this.normalizeInlineIri(x.child),F=this.normalizeInlineIri(x.pred),P=this.normalizeInlineObjectValue(x.obj);if(!A||!I)return;const V=o.get(I);if(V){const j=y.get(A)??new Map,ee=j.get(V.name)??[];T&&!ee.includes(T)&&ee.push(T),j.set(V.name,ee),y.set(A,j)}if(!T||!F)return;const B=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},Y=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,B);return}const _e=B[Y];_e===void 0?B[Y]=P:Array.isArray(_e)?B[Y]=[..._e,P]:B[Y]=[_e,P],v.set(T,B)});const S=x=>{if(Array.isArray(x))return x.map(I=>this.normalizeInlineIri(I)).filter(I=>!!I);const A=this.normalizeInlineIri(x);return A?[A]:[]},E=(x,A,I)=>{const T=x?y.get(x)?.get(I.name)??[]:[],P=(T.length>0?T:S(A)).map(V=>v.get(V)??{"@id":V,id:this.extractIdFromSubject(V,t)});return I.dataType==="array"?P:P[0]??null};return e.forEach(x=>{const A=this.normalizeInlineIri(x["@id"]??x.subject??x.uri??x.id);s.forEach(I=>{x[I.name]=E(A,x[I.name],I)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const o of this.orderByClauses){const l=this.getOrderByValue(i,o.column),u=this.getOrderByValue(s,o.column),h=this.compareOrderByValues(l,u);if(h!==0)return o.direction==="desc"?-h:h}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const o=this.serializeValueForKey(s);t.has(o)||(t.add(o),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(o=>{const l=this.normalizeInlineIri(o["@id"])??this.normalizeInlineIri(o.subject)??this.normalizeInlineIri(o.uri)??(typeof o.id=="string"?o.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...o});return}if(!t.has(l)){const d={...o};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const y=this.getColumnDefinitionForRowKey(p);(y?.options?.isArray||y?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),h=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(o).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const y=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...y];v.forEach(A=>{const I=h(A);S.some(T=>h(T)===I)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),x=E?.options?.isArray||E?.dataType==="array";!x&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):x?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(o=>t.get(o))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){if(!e)return!1;if(e.dataType==="object"||e.dataType==="json")return!0;if(e.dataType==="array"){const t=e.elementType??e.options?.baseType;return t==="object"||t==="json"}return!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,o=s.left.alias===e.alias?s.left:s.right,l=o===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const x=this.serializeValueForKey(E);u.has(x)||u.set(x,E)}if(u.size===0)return[];const h=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(o.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const x=d(),I=await(conditionTargetsReservedIdentifier(E)?x.applyInternalQueryCondition(E):x.where(E));S.push(...I)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const y=this.buildJoinLookupCondition(p,h);if(y){const S=d(),x=await(conditionTargetsReservedIdentifier(y)?S.applyInternalQueryCondition(y):S.where(y));return this.normalizeJoinRows(e,x)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,o=s.left.alias===e.alias?s.left:s.right,l=o===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),h=o.column==="id"&&u.length>0;if(!h&&i.length===1)return;const d=new Map;for(const y of i){const v=y.left.alias===e.alias?y.left:y.right;d.set(v.column,y)}const p=[],g=new Set;for(const y of t){const v=this.getRowValueForColumn(y,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],x=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,V=this.getRowValueForColumn(y,P);if(V==null){if(h&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(Y=>{const _e=d.get(Y);if(!_e)return!0;const ee=(_e.left.alias===e.alias?_e.left:_e.right)===_e.left?_e.right:_e.left,me=this.getRowValueForColumn(y,ee);return me==null})));A=!0;break}const B=e.table.getColumn(F.column);if(!B){A=!0;break}E.push(eq(B,V)),x.push(`${F.column}:${this.serializeValueForKey(V)}`)}if(A)continue;if(h&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const B=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,Y=this.getRowValueForColumn(y,B);return Y==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const I=x.join("|");g.has(I)||(g.add(I),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),o=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${o}, join.${o})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const o=this.extractSubjectValue(i);if(o){s.subject=o,s["@id"]=o,s.uri=o,s[`${e.alias}.subject`]=o,s[`${e.alias}.@id`]=o,s[`${e.alias}.uri`]=o;const l=this.extractIdFromSubject(o,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const y of i)p.push({...g,...y});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[o]=s,l=o.left.alias===t.alias?o.left:o.right,u=l===o.left?o.right:o.left,h=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const y=this.serializeValueForKey(g);h.has(y)||h.set(y,[]),h.get(y).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),y=this.serializeValueForKey(g),S=(g!=null?h.get(y)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(o=>{const l=o.left.alias===i?o.left:o.right,u=l===o.left?o.right:o.left,h=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return h==null||d===void 0||d===null?!1:this.serializeValueForKey(h)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,o=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(o.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const o=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return o==null;case"IS NOT NULL":return o!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(o=>this.evaluateCondition(e,o)):i.toUpperCase()==="OR"?s.some(o=>this.evaluateCondition(e,o)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const o=parsePodResourceRef(t,e)?.resourceId;if(o)return o}if(t){const o=this.session.getDialect?.(),u=(o?.getUriResolver?.()??new UriResolverImpl(o?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const o=e.slice(s+1);if(o.length>0)return o}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(o=>o.id||o["@id"]).filter(o=>typeof o=="string"&&o.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),o=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(o),o}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(o){console.error("[InsertQueryBuilder] afterInsert hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[o,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,o,l);for(const[o,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,o,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const o=e;return o.length===0?o():o(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),o=inferSPARQLQueryType(s);if(!o)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:o,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},o=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):o;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,o])=>Array.isArray(o));return s.length===0?i:i.map(o=>{const l={...o};for(const[u,h]of s)u in l&&(l[u]=[...h]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const o of e)try{await t.afterUpdate(i,o,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),o=inferSPARQLQueryType(s);if(!o)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:o,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},o=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):o;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(o){console.error("[DeleteQueryBuilder] afterDelete hook failed:",o)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(o=>i.unregisterResourceSubject?.(e.table,o));return}s.forEach(o=>i.registerResourceSubject?.(e.table,o))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const o=this.getKnownRowIri(s);o&&i.add(o)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,o,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,o,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-Qmo6EsFT.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),o=new Map;s.headers&&s.headers.forEach((h,d)=>{o.set(d.toLowerCase(),h||"")});const u={...s,headers:{get:h=>{const d=h.toLowerCase();return o.get(d)||null},has:h=>{const d=h.toLowerCase();return o.has(d)},forEach:h=>{o.forEach((d,p)=>h(d,p))},entries:()=>o.entries(),keys:()=>o.keys(),values:()=>o.values(),[Symbol.iterator]:()=>o.entries(),includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(o.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1}},status:s.status||200,statusText:s.statusText||"OK",ok:s.ok!==void 0?s.ok:!0,url:s.url||(typeof t=="string"?t:t.toString()),type:s.type||"basic",redirected:s.redirected||!1,body:s.body,bodyUsed:s.bodyUsed||!1,includes:h=>{if(!h)return!1;for(const[d,p]of Array.from(o.entries()))if(d.toLowerCase().includes(h.toLowerCase())||p.toLowerCase().includes(h.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(h){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(h)),""}},json:async()=>{try{return await s.json()}catch(h){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(h)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(h){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(h)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(o=>{const l=o,u={},h=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>h(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())h(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&h(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let o=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(o=d.headers.get("ETag"),this.logging&&o&&console.log(`[UPDATE] Got ETag for ${s}: ${o}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":o??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),h=await u(l);if(h.ok)i.push({success:!0,source:s,status:h.status}),await this.invalidateCache(t,s);else if(h.status===409||h.status===412){this.logging&&console.log(`[UPDATE] ${h.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(h.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const y={...l,"If-Match":g},v=await u(y);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await h.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${h.status} ${h.statusText}`,details:p})}}else{const d=await h.text();i.push({success:!1,source:s,error:`${h.status} ${h.statusText}`,details:d})}}catch(o){i.push({success:!1,source:s,error:this.formatError(o)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
|
|
49
49
|
SELECT ?subject ?predicate ?object WHERE {
|
|
50
50
|
?subject ?predicate ?object .
|
|
51
51
|
FILTER(STRSTARTS(STR(?subject), "${i}"))
|
|
@@ -303,4 +303,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
303
303
|
`},typeof _=="string"&&(_.indexOf("-----BEGIN")!=-1?this.readCertPEM(_):$.lang.String.isHex(_)&&this.readCertHex(_))}Ge.prototype.sign=function(_,b){var w=(function(k){return $.crypto.Util.hashString(k,b)})(_);return this.signWithMessageHash(w,b)},Ge.prototype.signWithMessageHash=function(_,b){var w=at($.crypto.Util.getPaddedDigestInfoHex(_,b,this.n.bitLength()),16);return gr(this.doPrivate(w).toString(16),this.n.bitLength())},Ge.prototype.signPSS=function(_,b,w){var C=(function(Q){return $.crypto.Util.hashHex(Q,b)})(ir(_));return w===void 0&&(w=-1),this.signWithMessageHashPSS(C,b,w)},Ge.prototype.signWithMessageHashPSS=function(_,b,w){var C,k=hr(_),Q=k.length,ne=this.n.bitLength()-1,xe=Math.ceil(ne/8),be=function(ie){return $.crypto.Util.hashHex(ie,b)};if(w===-1||w===void 0)w=Q;else if(w===-2)w=xe-Q-2;else if(w<-2)throw new Error("invalid salt length");if(xe<Q+w+2)throw new Error("data too long");var ve="";w>0&&(ve=new Array(w),new he().nextBytes(ve),ve=String.fromCharCode.apply(String,ve));var we=hr(be(ir("\0\0\0\0\0\0\0\0"+k+ve))),Te=[];for(C=0;C<xe-w-Q-2;C+=1)Te[C]=0;var Ne=String.fromCharCode.apply(String,Te)+""+ve,$e=li(we,Ne.length,be),Ke=[];for(C=0;C<Ne.length;C+=1)Ke[C]=Ne.charCodeAt(C)^$e.charCodeAt(C);var Ye=65280>>8*xe-ne&255;for(Ke[0]&=~Ye,C=0;C<Q;C++)Ke.push(we.charCodeAt(C));return Ke.push(188),gr(this.doPrivate(new j(Ke)).toString(16),this.n.bitLength())},Ge.prototype.verify=function(_,b){if((b=b.toLowerCase()).match(/^[0-9a-f]+$/)==null)return!1;var w=at(b,16),C=this.n.bitLength();if(w.bitLength()>C)return!1;var k=this.doPublic(w).toString(16);if(k.length+3!=C/4)return!1;var Q=Sr(k.replace(/^1f+00/,""));if(Q.length==0)return!1;var ne=Q[0];return Q[1]==(function(be){return $.crypto.Util.hashString(be,ne)})(_)},Ge.prototype.verifyWithMessageHash=function(_,b){if(b.length!=Math.ceil(this.n.bitLength()/4))return!1;var w=at(b,16);if(w.bitLength()>this.n.bitLength())return 0;var C=Sr(this.doPublic(w).toString(16).replace(/^1f+00/,""));return C.length==0?!1:(C[0],C[1]==_)},Ge.prototype.verifyPSS=function(_,b,w,C){var k=(function(ne){return $.crypto.Util.hashHex(ne,w)})(ir(_));return C===void 0&&(C=-1),this.verifyWithMessageHashPSS(k,b,w,C)},Ge.prototype.verifyWithMessageHashPSS=function(_,b,w,C){if(b.length!=Math.ceil(this.n.bitLength()/4))return!1;var k,Q=new j(b,16),ne=function(Ie){return $.crypto.Util.hashHex(Ie,w)},xe=hr(_),be=xe.length,ve=this.n.bitLength()-1,we=Math.ceil(ve/8);if(C===-1||C===void 0)C=be;else if(C===-2)C=we-be-2;else if(C<-2)throw new Error("invalid salt length");if(we<be+C+2)throw new Error("data too long");var Te=this.doPublic(Q).toByteArray();for(k=0;k<Te.length;k+=1)Te[k]&=255;for(;Te.length<we;)Te.unshift(0);if(Te[we-1]!==188)throw new Error("encoded message does not end in 0xbc");var Ne=(Te=String.fromCharCode.apply(String,Te)).substr(0,we-be-1),$e=Te.substr(Ne.length,be),Ke=65280>>8*we-ve&255;if((Ne.charCodeAt(0)&Ke)!=0)throw new Error("bits beyond keysize not zero");var Ye=li($e,Ne.length,ne),tt=[];for(k=0;k<Ne.length;k+=1)tt[k]=Ne.charCodeAt(k)^Ye.charCodeAt(k);tt[0]&=~Ke;var ie=we-be-C-2;for(k=0;k<ie;k+=1)if(tt[k]!==0)throw new Error("leftmost octets not zero");if(tt[ie]!==1)throw new Error("0x01 marker not found");return $e===hr(ne(ir("\0\0\0\0\0\0\0\0"+xe+String.fromCharCode.apply(String,tt.slice(-C)))))},Ge.SALT_LEN_HLEN=-1,Ge.SALT_LEN_MAX=-2,Ge.SALT_LEN_RECOVER=-2,lr.hex2dn=function(_,b){b===void 0&&(b=0);var w=new lr;return ke.getTLV(_,b),w.getX500Name(_).str},lr.hex2rdn=function(_,b){if(b===void 0&&(b=0),_.substr(b,2)!=="31")throw new Error("malformed RDN");for(var w=new Array,C=ke.getChildIdx(_,b),k=0;k<C.length;k++)w.push(lr.hex2attrTypeValue(_,C[k]));return(w=w.map((function(Q){return Q.replace("+","\\+")}))).join("+")},lr.hex2attrTypeValue=function(_,b){var w=ke,C=w.getV;if(b===void 0&&(b=0),_.substr(b,2)!=="30")throw new Error("malformed attribute type and value");var k=w.getChildIdx(_,b);k.length!==2||_.substr(k[0],2);var Q=C(_,k[0]),ne=$.asn1.ASN1Util.oidHexToInt(Q);return $.asn1.x509.OID.oid2atype(ne)+"="+hr(C(_,k[1]))},lr.getPublicKeyFromCertHex=function(_){var b=new lr;return b.readCertHex(_),b.getPublicKey()},lr.getPublicKeyFromCertPEM=function(_){var b=new lr;return b.readCertPEM(_),b.getPublicKey()},lr.getPublicKeyInfoPropOfCertPEM=function(_){var b,w,C=ke.getVbyList,k={};return k.algparam=null,(b=new lr).readCertPEM(_),w=b.getPublicKeyHex(),k.keyhex=C(w,0,[1],"03").substr(2),k.algoid=C(w,0,[0,0],"06"),k.algoid==="2a8648ce3d0201"&&(k.algparam=C(w,0,[0,1],"06")),k},lr.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],$!==void 0&&$||(i.KJUR=$={}),$.jws!==void 0&&$.jws||($.jws={}),$.jws.JWS=function(){var _=$.jws.JWS.isSafeJSONString;this.parseJWS=function(b,w){if(this.parsedJWS===void 0||!w&&this.parsedJWS.sigvalH===void 0){var C=b.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(C==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var k=C[1],Q=C[2],ne=C[3],xe=k+"."+Q;if(this.parsedJWS={},this.parsedJWS.headB64U=k,this.parsedJWS.payloadB64U=Q,this.parsedJWS.sigvalB64U=ne,this.parsedJWS.si=xe,!w){var be=Ut(ne),ve=at(be,16);this.parsedJWS.sigvalH=be,this.parsedJWS.sigvalBI=ve}var we=Ve(k),Te=Ve(Q);if(this.parsedJWS.headS=we,this.parsedJWS.payloadS=Te,!_(we,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+we}}},$.jws.JWS.sign=function(_,b,w,C,k){var Q,ne,xe,be=$,ve=be.jws.JWS,we=ve.readSafeJSONString,Te=ve.isSafeJSONString,Ne=be.crypto,$e=(Ne.ECDSA,Ne.Mac),Ke=Ne.Signature,Ye=JSON;if(typeof b!="string"&&(b===void 0?"undefined":A(b))!="object")throw"spHeader must be JSON string or object: "+b;if((b===void 0?"undefined":A(b))=="object"&&(ne=b,Q=Ye.stringify(ne)),typeof b=="string"){if(!Te(Q=b))throw"JWS Head is not safe JSON string: "+Q;ne=we(Q)}if(xe=w,(w===void 0?"undefined":A(w))=="object"&&(xe=Ye.stringify(w)),_!=""&&_!=null||ne.alg===void 0||(_=ne.alg),_!=""&&_!=null&&ne.alg===void 0&&(ne.alg=_,Q=Ye.stringify(ne)),_!==ne.alg)throw"alg and sHeader.alg doesn't match: "+_+"!="+ne.alg;var tt=null;if(ve.jwsalg2sigalg[_]===void 0)throw"unsupported alg name: "+_;tt=ve.jwsalg2sigalg[_];var ie=De(Q)+"."+De(xe),Re="";if(tt.substr(0,4)=="Hmac"){if(C===void 0)throw"mac key shall be specified for HS* alg";var Ie=new $e({alg:tt,prov:"cryptojs",pass:C});Ie.updateString(ie),Re=Ie.doFinal()}else if(tt.indexOf("withECDSA")!=-1){(Je=new Ke({alg:tt})).init(C,k),Je.updateString(ie);var Ue=Je.sign();Re=$.crypto.ECDSA.asn1SigToConcatSig(Ue)}else{var Je;tt!="none"&&((Je=new Ke({alg:tt})).init(C,k),Je.updateString(ie),Re=Je.sign())}return ie+"."+er(Re)},$.jws.JWS.verify=function(_,b,w){var C,k=$,Q=k.jws.JWS,ne=Q.readSafeJSONString,xe=k.crypto,be=xe.ECDSA,ve=xe.Mac,we=xe.Signature;A(Ge)!==void 0&&(C=Ge);var Te=_.split(".");if(Te.length!==3)return!1;var Ne=Te[0]+"."+Te[1],$e=Ut(Te[2]),Ke=ne(Ve(Te[0])),Ye=null,tt=null;if(Ke.alg===void 0)throw"algorithm not specified in header";if(tt=(Ye=Ke.alg).substr(0,2),w!=null&&Object.prototype.toString.call(w)==="[object Array]"&&w.length>0&&(":"+w.join(":")+":").indexOf(":"+Ye+":")==-1)throw"algorithm '"+Ye+"' not accepted in the list";if(Ye!="none"&&b===null)throw"key shall be specified to verify.";if(typeof b=="string"&&b.indexOf("-----BEGIN ")!=-1&&(b=Tt.getKey(b)),!(tt!="RS"&&tt!="PS"||b instanceof C))throw"key shall be a RSAKey obj for RS* and PS* algs";if(tt=="ES"&&!(b instanceof be))throw"key shall be a ECDSA obj for ES* algs";var ie=null;if(Q.jwsalg2sigalg[Ke.alg]===void 0)throw"unsupported alg name: "+Ye;if((ie=Q.jwsalg2sigalg[Ye])=="none")throw"not supported";if(ie.substr(0,4)=="Hmac"){if(b===void 0)throw"hexadecimal key shall be specified for HMAC";var Re=new ve({alg:ie,pass:b});return Re.updateString(Ne),$e==Re.doFinal()}if(ie.indexOf("withECDSA")!=-1){var Ie,Ue=null;try{Ue=be.concatSigToASN1Sig($e)}catch{return!1}return(Ie=new we({alg:ie})).init(b),Ie.updateString(Ne),Ie.verify(Ue)}return(Ie=new we({alg:ie})).init(b),Ie.updateString(Ne),Ie.verify($e)},$.jws.JWS.parse=function(_){var b,w,C,k=_.split("."),Q={};if(k.length!=2&&k.length!=3)throw"malformed sJWS: wrong number of '.' splitted elements";return b=k[0],w=k[1],k.length==3&&(C=k[2]),Q.headerObj=$.jws.JWS.readSafeJSONString(Ve(b)),Q.payloadObj=$.jws.JWS.readSafeJSONString(Ve(w)),Q.headerPP=JSON.stringify(Q.headerObj,null," "),Q.payloadObj==null?Q.payloadPP=Ve(w):Q.payloadPP=JSON.stringify(Q.payloadObj,null," "),C!==void 0&&(Q.sigHex=Ut(C)),Q},$.jws.JWS.verifyJWT=function(_,b,w){var C=$.jws,k=C.JWS,Q=k.readSafeJSONString,ne=k.inArray,xe=k.includedArray,be=_.split("."),ve=be[0],we=be[1],Te=(Ut(be[2]),Q(Ve(ve))),Ne=Q(Ve(we));if(Te.alg===void 0)return!1;if(w.alg===void 0)throw"acceptField.alg shall be specified";if(!ne(Te.alg,w.alg)||Ne.iss!==void 0&&A(w.iss)==="object"&&!ne(Ne.iss,w.iss)||Ne.sub!==void 0&&A(w.sub)==="object"&&!ne(Ne.sub,w.sub))return!1;if(Ne.aud!==void 0&&A(w.aud)==="object"){if(typeof Ne.aud=="string"){if(!ne(Ne.aud,w.aud))return!1}else if(A(Ne.aud)=="object"&&!xe(Ne.aud,w.aud))return!1}var $e=C.IntDate.getNow();return w.verifyAt!==void 0&&typeof w.verifyAt=="number"&&($e=w.verifyAt),w.gracePeriod!==void 0&&typeof w.gracePeriod=="number"||(w.gracePeriod=0),!(Ne.exp!==void 0&&typeof Ne.exp=="number"&&Ne.exp+w.gracePeriod<$e)&&!(Ne.nbf!==void 0&&typeof Ne.nbf=="number"&&$e<Ne.nbf-w.gracePeriod)&&!(Ne.iat!==void 0&&typeof Ne.iat=="number"&&$e<Ne.iat-w.gracePeriod)&&(Ne.jti===void 0||w.jti===void 0||Ne.jti===w.jti)&&!!k.verify(_,b,w.alg)},$.jws.JWS.includedArray=function(_,b){var w=$.jws.JWS.inArray;if(_===null||(_===void 0?"undefined":A(_))!=="object"||typeof _.length!="number")return!1;for(var C=0;C<_.length;C++)if(!w(_[C],b))return!1;return!0},$.jws.JWS.inArray=function(_,b){if(b===null||(b===void 0?"undefined":A(b))!=="object"||typeof b.length!="number")return!1;for(var w=0;w<b.length;w++)if(b[w]==_)return!0;return!1},$.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"},$.jws.JWS.isSafeJSONString=function(_,b,w){var C=null;try{return((C=q(_))===void 0?"undefined":A(C))!="object"||C.constructor===Array?0:(b&&(b[w]=C),1)}catch{return 0}},$.jws.JWS.readSafeJSONString=function(_){var b=null;try{return((b=q(_))===void 0?"undefined":A(b))!="object"||b.constructor===Array?null:b}catch{return null}},$.jws.JWS.getEncodedSignatureValueFromJWS=function(_){var b=_.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(b==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return b[1]},$.jws.JWS.getJWKthumbprint=function(_){if(_.kty!=="RSA"&&_.kty!=="EC"&&_.kty!=="oct")throw"unsupported algorithm for JWK Thumprint";var b="{";if(_.kty==="RSA"){if(typeof _.n!="string"||typeof _.e!="string")throw"wrong n and e value for RSA key";b+='"e":"'+_.e+'",',b+='"kty":"'+_.kty+'",',b+='"n":"'+_.n+'"}'}else if(_.kty==="EC"){if(typeof _.crv!="string"||typeof _.x!="string"||typeof _.y!="string")throw"wrong crv, x and y value for EC key";b+='"crv":"'+_.crv+'",',b+='"kty":"'+_.kty+'",',b+='"x":"'+_.x+'",',b+='"y":"'+_.y+'"}'}else if(_.kty==="oct"){if(typeof _.k!="string")throw"wrong k value for oct(symmetric) key";b+='"kty":"'+_.kty+'",',b+='"k":"'+_.k+'"}'}var w=ir(b);return er($.crypto.Util.hashHex(w,"sha256"))},$.jws.IntDate={},$.jws.IntDate.get=function(_){var b=$.jws.IntDate,w=b.getNow,C=b.getZulu;if(_=="now")return w();if(_=="now + 1hour")return w()+3600;if(_=="now + 1day")return w()+86400;if(_=="now + 1month")return w()+2592e3;if(_=="now + 1year")return w()+31536e3;if(_.match(/Z$/))return C(_);if(_.match(/^[0-9]+$/))return parseInt(_);throw"unsupported format: "+_},$.jws.IntDate.getZulu=function(_){return $t(_)},$.jws.IntDate.getNow=function(){return~~(new Date/1e3)},$.jws.IntDate.intDate2UTCString=function(_){return new Date(1e3*_).toUTCString()},$.jws.IntDate.intDate2Zulu=function(_){var b=new Date(1e3*_);return("0000"+b.getUTCFullYear()).slice(-4)+("00"+(b.getUTCMonth()+1)).slice(-2)+("00"+b.getUTCDate()).slice(-2)+("00"+b.getUTCHours()).slice(-2)+("00"+b.getUTCMinutes()).slice(-2)+("00"+b.getUTCSeconds()).slice(-2)+"Z"},i.SecureRandom=he,i.rng_seed_time=re,i.BigInteger=j,i.RSAKey=Ge;var ci=$.crypto.EDSA;i.EDSA=ci;var kr=$.crypto.DSA;i.DSA=kr;var xn=$.crypto.Signature;i.Signature=xn;var Rr=$.crypto.MessageDigest;i.MessageDigest=Rr;var vi=$.crypto.Mac;i.Mac=vi;var wi=$.crypto.Cipher;i.Cipher=wi,i.KEYUTIL=Tt,i.ASN1HEX=ke,i.X509=lr,i.CryptoJS=F,i.b64tohex=Y,i.b64toBA=_e,i.stoBA=mt,i.BAtos=St,i.BAtohex=Rt,i.stohex=kt,i.stob64=function(b){return B(kt(b))},i.stob64u=function(b){return Ft(B(kt(b)))},i.b64utos=function(b){return St(_e(on(b)))},i.b64tob64u=Ft,i.b64utob64=on,i.hex2b64=B,i.hextob64u=er,i.b64utohex=Ut,i.utf8tob64u=De,i.b64utoutf8=Ve,i.utf8tob64=function(b){return B(Wt(zt(b)))},i.b64toutf8=function(b){return decodeURIComponent(ln(Y(b)))},i.utf8tohex=xr,i.hextoutf8=Bt,i.hextorstr=hr,i.rstrtohex=ir,i.hextob64=Wr,i.hextob64nl=z,i.b64nltohex=W,i.hextopem=ze,i.pemtohex=He,i.hextoArrayBuffer=function(b){if(b.length%2!=0)throw"input is not even length";if(b.match(/^[0-9A-Fa-f]+$/)==null)throw"input is not hexadecimal";for(var w=new ArrayBuffer(b.length/2),C=new DataView(w),k=0;k<b.length/2;k++)C.setUint8(k,parseInt(b.substr(2*k,2),16));return w},i.ArrayBuffertohex=function(b){for(var w="",C=new DataView(b),k=0;k<b.byteLength;k++)w+=("00"+C.getUint8(k).toString(16)).slice(-2);return w},i.zulutomsec=lt,i.zulutosec=$t,i.zulutodate=function(b){return new Date(lt(b))},i.datetozulu=function(b,w,C){var k,Q=b.getUTCFullYear();if(w){if(Q<1950||2049<Q)throw"not proper year for UTCTime: "+Q;k=(""+Q).slice(-2)}else k=("000"+Q).slice(-4);if(k+=("0"+(b.getUTCMonth()+1)).slice(-2),k+=("0"+b.getUTCDate()).slice(-2),k+=("0"+b.getUTCHours()).slice(-2),k+=("0"+b.getUTCMinutes()).slice(-2),k+=("0"+b.getUTCSeconds()).slice(-2),C){var ne=b.getUTCMilliseconds();ne!==0&&(k+="."+(ne=(ne=("00"+ne).slice(-3)).replace(/0+$/g,"")))}return k+="Z"},i.uricmptohex=Wt,i.hextouricmp=ln,i.ipv6tohex=Er,i.hextoipv6=ar,i.hextoip=Sn,i.iptohex=function(b){var w="malformed IP address";if(!(b=b.toLowerCase(b)).match(/^[0-9.]+$/)){if(b.match(/^[0-9a-f:]+$/)&&b.indexOf(":")!==-1)return Er(b);throw w}var C=b.split(".");if(C.length!==4)throw w;var k="";try{for(var Q=0;Q<4;Q++)k+=("0"+parseInt(C[Q]).toString(16)).slice(-2);return k}catch{throw w}},i.encodeURIComponentAll=zt,i.newline_toUnix=function(b){return b=b.replace(/\r\n/gm,`
|
|
304
304
|
`)},i.newline_toDos=function(b){return b=(b=b.replace(/\r\n/gm,`
|
|
305
305
|
`)).replace(/\n/gm,`\r
|
|
306
|
-
`)},i.hextoposhex=Pr,i.intarystrtohex=function(b){b=(b=(b=b.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return b.split(/,/).map((function(w,C,k){var Q=parseInt(w);if(Q<0||255<Q)throw"integer not in range 0-255";return("00"+Q.toString(16)).slice(-2)})).join("")}catch(w){throw"malformed integer array string: "+w}},i.strdiffidx=function(b,w){var C=b.length;b.length>w.length&&(C=w.length);for(var k=0;k<C;k++)if(b.charCodeAt(k)!=w.charCodeAt(k))return k;return b.length!=w.length?C:-1},i.KJUR=$;var En=$.crypto;i.crypto=En;var gn=$.asn1;i.asn1=gn;var Rn=$.jws;i.jws=Rn;var ws=$.lang;i.lang=ws}).call(this,s(28).Buffer)},function(t,i,s){(function(o){var l=s(30),u=s(31),h=s(32);function d(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function p(se,M){if(d()<M)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(se=new Uint8Array(M)).__proto__=g.prototype:(se===null&&(se=new g(M)),se.length=M),se}function g(se,M,N){if(!(g.TYPED_ARRAY_SUPPORT||this instanceof g))return new g(se,M,N);if(typeof se=="number"){if(typeof M=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,se)}return y(this,se,M,N)}function y(se,M,N,L){if(typeof M=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&M instanceof ArrayBuffer?(function(re,le,Ee,G){if(le.byteLength,Ee<0||le.byteLength<Ee)throw new RangeError("'offset' is out of bounds");if(le.byteLength<Ee+(G||0))throw new RangeError("'length' is out of bounds");return le=Ee===void 0&&G===void 0?new Uint8Array(le):G===void 0?new Uint8Array(le,Ee):new Uint8Array(le,Ee,G),g.TYPED_ARRAY_SUPPORT?(re=le).__proto__=g.prototype:re=E(re,le),re})(se,M,N,L):typeof M=="string"?(function(re,le,Ee){if(typeof Ee=="string"&&Ee!==""||(Ee="utf8"),!g.isEncoding(Ee))throw new TypeError('"encoding" must be a valid string encoding');var G=0|A(le,Ee),Se=(re=p(re,G)).write(le,Ee);return Se!==G&&(re=re.slice(0,Se)),re})(se,M,N):(function(re,le){if(g.isBuffer(le)){var Ee=0|x(le.length);return(re=p(re,Ee)).length===0||le.copy(re,0,0,Ee),re}if(le){if(typeof ArrayBuffer<"u"&&le.buffer instanceof ArrayBuffer||"length"in le)return typeof le.length!="number"||(function(Se){return Se!=Se})(le.length)?p(re,0):E(re,le);if(le.type==="Buffer"&&h(le.data))return E(re,le.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(se,M)}function v(se){if(typeof se!="number")throw new TypeError('"size" argument must be a number');if(se<0)throw new RangeError('"size" argument must not be negative')}function S(se,M){if(v(M),se=p(se,M<0?0:0|x(M)),!g.TYPED_ARRAY_SUPPORT)for(var N=0;N<M;++N)se[N]=0;return se}function E(se,M){var N=M.length<0?0:0|x(M.length);se=p(se,N);for(var L=0;L<N;L+=1)se[L]=255&M[L];return se}function x(se){if(se>=d())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+d().toString(16)+" bytes");return 0|se}function A(se,M){if(g.isBuffer(se))return se.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(se)||se instanceof ArrayBuffer))return se.byteLength;typeof se!="string"&&(se=""+se);var N=se.length;if(N===0)return 0;for(var L=!1;;)switch(M){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":case void 0:return ge(se).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*N;case"hex":return N>>>1;case"base64":return pe(se).length;default:if(L)return ge(se).length;M=(""+M).toLowerCase(),L=!0}}function I(se,M,N){var L=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0)<=(M>>>=0))return"";for(se||(se="utf8");;)switch(se){case"hex":return qe(this,M,N);case"utf8":case"utf-8":return te(this,M,N);case"ascii":return Oe(this,M,N);case"latin1":case"binary":return ye(this,M,N);case"base64":return me(this,M,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return de(this,M,N);default:if(L)throw new TypeError("Unknown encoding: "+se);se=(se+"").toLowerCase(),L=!0}}function T(se,M,N){var L=se[M];se[M]=se[N],se[N]=L}function F(se,M,N,L,H){if(se.length===0)return-1;if(typeof N=="string"?(L=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,isNaN(N)&&(N=H?0:se.length-1),N<0&&(N=se.length+N),N>=se.length){if(H)return-1;N=se.length-1}else if(N<0){if(!H)return-1;N=0}if(typeof M=="string"&&(M=g.from(M,L)),g.isBuffer(M))return M.length===0?-1:P(se,M,N,L,H);if(typeof M=="number")return M&=255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?H?Uint8Array.prototype.indexOf.call(se,M,N):Uint8Array.prototype.lastIndexOf.call(se,M,N):P(se,[M],N,L,H);throw new TypeError("val must be string, number or Buffer")}function P(se,M,N,L,H){var re,le=1,Ee=se.length,G=M.length;if(L!==void 0&&((L=String(L).toLowerCase())==="ucs2"||L==="ucs-2"||L==="utf16le"||L==="utf-16le")){if(se.length<2||M.length<2)return-1;le=2,Ee/=2,G/=2,N/=2}function Se(ht,Ge){return le===1?ht[Ge]:ht.readUInt16BE(Ge*le)}if(H){var Ae=-1;for(re=N;re<Ee;re++)if(Se(se,re)===Se(M,Ae===-1?0:re-Ae)){if(Ae===-1&&(Ae=re),re-Ae+1===G)return Ae*le}else Ae!==-1&&(re-=re-Ae),Ae=-1}else for(N+G>Ee&&(N=Ee-G),re=N;re>=0;re--){for(var he=!0,at=0;at<G;at++)if(Se(se,re+at)!==Se(M,at)){he=!1;break}if(he)return re}return-1}function V(se,M,N,L){N=Number(N)||0;var H=se.length-N;L?(L=Number(L))>H&&(L=H):L=H;var re=M.length;if(re%2!=0)throw new TypeError("Invalid hex string");L>re/2&&(L=re/2);for(var le=0;le<L;++le){var Ee=parseInt(M.substr(2*le,2),16);if(isNaN(Ee))return le;se[N+le]=Ee}return le}function B(se,M,N,L){return Me(ge(M,se.length-N),se,N,L)}function Y(se,M,N,L){return Me((function(re){for(var le=[],Ee=0;Ee<re.length;++Ee)le.push(255&re.charCodeAt(Ee));return le})(M),se,N,L)}function _e(se,M,N,L){return Y(se,M,N,L)}function j(se,M,N,L){return Me(pe(M),se,N,L)}function ee(se,M,N,L){return Me((function(re,le){for(var Ee,G,Se,Ae=[],he=0;he<re.length&&!((le-=2)<0);++he)G=(Ee=re.charCodeAt(he))>>8,Se=Ee%256,Ae.push(Se),Ae.push(G);return Ae})(M,se.length-N),se,N,L)}function me(se,M,N){return M===0&&N===se.length?l.fromByteArray(se):l.fromByteArray(se.slice(M,N))}function te(se,M,N){N=Math.min(se.length,N);for(var L=[],H=M;H<N;){var re,le,Ee,G,Se=se[H],Ae=null,he=Se>239?4:Se>223?3:Se>191?2:1;if(H+he<=N)switch(he){case 1:Se<128&&(Ae=Se);break;case 2:(192&(re=se[H+1]))==128&&(G=(31&Se)<<6|63&re)>127&&(Ae=G);break;case 3:re=se[H+1],le=se[H+2],(192&re)==128&&(192&le)==128&&(G=(15&Se)<<12|(63&re)<<6|63&le)>2047&&(G<55296||G>57343)&&(Ae=G);break;case 4:re=se[H+1],le=se[H+2],Ee=se[H+3],(192&re)==128&&(192&le)==128&&(192&Ee)==128&&(G=(15&Se)<<18|(63&re)<<12|(63&le)<<6|63&Ee)>65535&&G<1114112&&(Ae=G)}Ae===null?(Ae=65533,he=1):Ae>65535&&(Ae-=65536,L.push(Ae>>>10&1023|55296),Ae=56320|1023&Ae),L.push(Ae),H+=he}return(function(ht){var Ge=ht.length;if(Ge<=Ce)return String.fromCharCode.apply(String,ht);for(var gt="",J=0;J<Ge;)gt+=String.fromCharCode.apply(String,ht.slice(J,J+=Ce));return gt})(L)}i.Buffer=g,i.SlowBuffer=function(M){return+M!=M&&(M=0),g.alloc(+M)},i.INSPECT_MAX_BYTES=50,g.TYPED_ARRAY_SUPPORT=o.TYPED_ARRAY_SUPPORT!==void 0?o.TYPED_ARRAY_SUPPORT:(function(){try{var M=new Uint8Array(1);return M.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},M.foo()===42&&typeof M.subarray=="function"&&M.subarray(1,1).byteLength===0}catch{return!1}})(),i.kMaxLength=d(),g.poolSize=8192,g._augment=function(se){return se.__proto__=g.prototype,se},g.from=function(se,M,N){return y(null,se,M,N)},g.TYPED_ARRAY_SUPPORT&&(g.prototype.__proto__=Uint8Array.prototype,g.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&g[Symbol.species]===g&&Object.defineProperty(g,Symbol.species,{value:null,configurable:!0})),g.alloc=function(se,M,N){return(function(H,re,le,Ee){return v(re),re<=0?p(H,re):le!==void 0?typeof Ee=="string"?p(H,re).fill(le,Ee):p(H,re).fill(le):p(H,re)})(null,se,M,N)},g.allocUnsafe=function(se){return S(null,se)},g.allocUnsafeSlow=function(se){return S(null,se)},g.isBuffer=function(M){return!(M==null||!M._isBuffer)},g.compare=function(M,N){if(!g.isBuffer(M)||!g.isBuffer(N))throw new TypeError("Arguments must be Buffers");if(M===N)return 0;for(var L=M.length,H=N.length,re=0,le=Math.min(L,H);re<le;++re)if(M[re]!==N[re]){L=M[re],H=N[re];break}return L<H?-1:H<L?1:0},g.isEncoding=function(M){switch(String(M).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}},g.concat=function(M,N){if(!h(M))throw new TypeError('"list" argument must be an Array of Buffers');if(M.length===0)return g.alloc(0);var L;if(N===void 0)for(N=0,L=0;L<M.length;++L)N+=M[L].length;var H=g.allocUnsafe(N),re=0;for(L=0;L<M.length;++L){var le=M[L];if(!g.isBuffer(le))throw new TypeError('"list" argument must be an Array of Buffers');le.copy(H,re),re+=le.length}return H},g.byteLength=A,g.prototype._isBuffer=!0,g.prototype.swap16=function(){var M=this.length;if(M%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var N=0;N<M;N+=2)T(this,N,N+1);return this},g.prototype.swap32=function(){var M=this.length;if(M%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var N=0;N<M;N+=4)T(this,N,N+3),T(this,N+1,N+2);return this},g.prototype.swap64=function(){var M=this.length;if(M%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var N=0;N<M;N+=8)T(this,N,N+7),T(this,N+1,N+6),T(this,N+2,N+5),T(this,N+3,N+4);return this},g.prototype.toString=function(){var M=0|this.length;return M===0?"":arguments.length===0?te(this,0,M):I.apply(this,arguments)},g.prototype.equals=function(M){if(!g.isBuffer(M))throw new TypeError("Argument must be a Buffer");return this===M||g.compare(this,M)===0},g.prototype.inspect=function(){var M="",N=i.INSPECT_MAX_BYTES;return this.length>0&&(M=this.toString("hex",0,N).match(/.{2}/g).join(" "),this.length>N&&(M+=" ... ")),"<Buffer "+M+">"},g.prototype.compare=function(M,N,L,H,re){if(!g.isBuffer(M))throw new TypeError("Argument must be a Buffer");if(N===void 0&&(N=0),L===void 0&&(L=M?M.length:0),H===void 0&&(H=0),re===void 0&&(re=this.length),N<0||L>M.length||H<0||re>this.length)throw new RangeError("out of range index");if(H>=re&&N>=L)return 0;if(H>=re)return-1;if(N>=L)return 1;if(this===M)return 0;for(var le=(re>>>=0)-(H>>>=0),Ee=(L>>>=0)-(N>>>=0),G=Math.min(le,Ee),Se=this.slice(H,re),Ae=M.slice(N,L),he=0;he<G;++he)if(Se[he]!==Ae[he]){le=Se[he],Ee=Ae[he];break}return le<Ee?-1:Ee<le?1:0},g.prototype.includes=function(M,N,L){return this.indexOf(M,N,L)!==-1},g.prototype.indexOf=function(M,N,L){return F(this,M,N,L,!0)},g.prototype.lastIndexOf=function(M,N,L){return F(this,M,N,L,!1)},g.prototype.write=function(M,N,L,H){if(N===void 0)H="utf8",L=this.length,N=0;else if(L===void 0&&typeof N=="string")H=N,L=this.length,N=0;else{if(!isFinite(N))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");N|=0,isFinite(L)?(L|=0,H===void 0&&(H="utf8")):(H=L,L=void 0)}var re=this.length-N;if((L===void 0||L>re)&&(L=re),M.length>0&&(L<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");H||(H="utf8");for(var le=!1;;)switch(H){case"hex":return V(this,M,N,L);case"utf8":case"utf-8":return B(this,M,N,L);case"ascii":return Y(this,M,N,L);case"latin1":case"binary":return _e(this,M,N,L);case"base64":return j(this,M,N,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,M,N,L);default:if(le)throw new TypeError("Unknown encoding: "+H);H=(""+H).toLowerCase(),le=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ce=4096;function Oe(se,M,N){var L="";N=Math.min(se.length,N);for(var H=M;H<N;++H)L+=String.fromCharCode(127&se[H]);return L}function ye(se,M,N){var L="";N=Math.min(se.length,N);for(var H=M;H<N;++H)L+=String.fromCharCode(se[H]);return L}function qe(se,M,N){var L=se.length;(!M||M<0)&&(M=0),(!N||N<0||N>L)&&(N=L);for(var H="",re=M;re<N;++re)H+=We(se[re]);return H}function de(se,M,N){for(var L=se.slice(M,N),H="",re=0;re<L.length;re+=2)H+=String.fromCharCode(L[re]+256*L[re+1]);return H}function Fe(se,M,N){if(se%1!=0||se<0)throw new RangeError("offset is not uint");if(se+M>N)throw new RangeError("Trying to access beyond buffer length")}function O(se,M,N,L,H,re){if(!g.isBuffer(se))throw new TypeError('"buffer" argument must be a Buffer instance');if(M>H||M<re)throw new RangeError('"value" argument is out of bounds');if(N+L>se.length)throw new RangeError("Index out of range")}function Z(se,M,N,L){M<0&&(M=65535+M+1);for(var H=0,re=Math.min(se.length-N,2);H<re;++H)se[N+H]=(M&255<<8*(L?H:1-H))>>>8*(L?H:1-H)}function fe(se,M,N,L){M<0&&(M=4294967295+M+1);for(var H=0,re=Math.min(se.length-N,4);H<re;++H)se[N+H]=M>>>8*(L?H:3-H)&255}function oe(se,M,N,L,H,re){if(N+L>se.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function Pe(se,M,N,L,H){return H||oe(se,0,N,4),u.write(se,M,N,L,23,4),N+4}function je(se,M,N,L,H){return H||oe(se,0,N,8),u.write(se,M,N,L,52,8),N+8}g.prototype.slice=function(M,N){var L,H=this.length;if((M=~~M)<0?(M+=H)<0&&(M=0):M>H&&(M=H),(N=N===void 0?H:~~N)<0?(N+=H)<0&&(N=0):N>H&&(N=H),N<M&&(N=M),g.TYPED_ARRAY_SUPPORT)(L=this.subarray(M,N)).__proto__=g.prototype;else{var re=N-M;L=new g(re,void 0);for(var le=0;le<re;++le)L[le]=this[le+M]}return L},g.prototype.readUIntLE=function(M,N,L){M|=0,N|=0,L||Fe(M,N,this.length);for(var H=this[M],re=1,le=0;++le<N&&(re*=256);)H+=this[M+le]*re;return H},g.prototype.readUIntBE=function(M,N,L){M|=0,N|=0,L||Fe(M,N,this.length);for(var H=this[M+--N],re=1;N>0&&(re*=256);)H+=this[M+--N]*re;return H},g.prototype.readUInt8=function(M,N){return N||Fe(M,1,this.length),this[M]},g.prototype.readUInt16LE=function(M,N){return N||Fe(M,2,this.length),this[M]|this[M+1]<<8},g.prototype.readUInt16BE=function(M,N){return N||Fe(M,2,this.length),this[M]<<8|this[M+1]},g.prototype.readUInt32LE=function(M,N){return N||Fe(M,4,this.length),(this[M]|this[M+1]<<8|this[M+2]<<16)+16777216*this[M+3]},g.prototype.readUInt32BE=function(M,N){return N||Fe(M,4,this.length),16777216*this[M]+(this[M+1]<<16|this[M+2]<<8|this[M+3])},g.prototype.readIntLE=function(M,N,L){M|=0,N|=0,L||Fe(M,N,this.length);for(var H=this[M],re=1,le=0;++le<N&&(re*=256);)H+=this[M+le]*re;return H>=(re*=128)&&(H-=Math.pow(2,8*N)),H},g.prototype.readIntBE=function(M,N,L){M|=0,N|=0,L||Fe(M,N,this.length);for(var H=N,re=1,le=this[M+--H];H>0&&(re*=256);)le+=this[M+--H]*re;return le>=(re*=128)&&(le-=Math.pow(2,8*N)),le},g.prototype.readInt8=function(M,N){return N||Fe(M,1,this.length),128&this[M]?-1*(255-this[M]+1):this[M]},g.prototype.readInt16LE=function(M,N){N||Fe(M,2,this.length);var L=this[M]|this[M+1]<<8;return 32768&L?4294901760|L:L},g.prototype.readInt16BE=function(M,N){N||Fe(M,2,this.length);var L=this[M+1]|this[M]<<8;return 32768&L?4294901760|L:L},g.prototype.readInt32LE=function(M,N){return N||Fe(M,4,this.length),this[M]|this[M+1]<<8|this[M+2]<<16|this[M+3]<<24},g.prototype.readInt32BE=function(M,N){return N||Fe(M,4,this.length),this[M]<<24|this[M+1]<<16|this[M+2]<<8|this[M+3]},g.prototype.readFloatLE=function(M,N){return N||Fe(M,4,this.length),u.read(this,M,!0,23,4)},g.prototype.readFloatBE=function(M,N){return N||Fe(M,4,this.length),u.read(this,M,!1,23,4)},g.prototype.readDoubleLE=function(M,N){return N||Fe(M,8,this.length),u.read(this,M,!0,52,8)},g.prototype.readDoubleBE=function(M,N){return N||Fe(M,8,this.length),u.read(this,M,!1,52,8)},g.prototype.writeUIntLE=function(M,N,L,H){M=+M,N|=0,L|=0,H||O(this,M,N,L,Math.pow(2,8*L)-1,0);var re=1,le=0;for(this[N]=255&M;++le<L&&(re*=256);)this[N+le]=M/re&255;return N+L},g.prototype.writeUIntBE=function(M,N,L,H){M=+M,N|=0,L|=0,H||O(this,M,N,L,Math.pow(2,8*L)-1,0);var re=L-1,le=1;for(this[N+re]=255&M;--re>=0&&(le*=256);)this[N+re]=M/le&255;return N+L},g.prototype.writeUInt8=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,1,255,0),g.TYPED_ARRAY_SUPPORT||(M=Math.floor(M)),this[N]=255&M,N+1},g.prototype.writeUInt16LE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=255&M,this[N+1]=M>>>8):Z(this,M,N,!0),N+2},g.prototype.writeUInt16BE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=M>>>8,this[N+1]=255&M):Z(this,M,N,!1),N+2},g.prototype.writeUInt32LE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N+3]=M>>>24,this[N+2]=M>>>16,this[N+1]=M>>>8,this[N]=255&M):fe(this,M,N,!0),N+4},g.prototype.writeUInt32BE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N]=M>>>24,this[N+1]=M>>>16,this[N+2]=M>>>8,this[N+3]=255&M):fe(this,M,N,!1),N+4},g.prototype.writeIntLE=function(M,N,L,H){if(M=+M,N|=0,!H){var re=Math.pow(2,8*L-1);O(this,M,N,L,re-1,-re)}var le=0,Ee=1,G=0;for(this[N]=255&M;++le<L&&(Ee*=256);)M<0&&G===0&&this[N+le-1]!==0&&(G=1),this[N+le]=(M/Ee>>0)-G&255;return N+L},g.prototype.writeIntBE=function(M,N,L,H){if(M=+M,N|=0,!H){var re=Math.pow(2,8*L-1);O(this,M,N,L,re-1,-re)}var le=L-1,Ee=1,G=0;for(this[N+le]=255&M;--le>=0&&(Ee*=256);)M<0&&G===0&&this[N+le+1]!==0&&(G=1),this[N+le]=(M/Ee>>0)-G&255;return N+L},g.prototype.writeInt8=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,1,127,-128),g.TYPED_ARRAY_SUPPORT||(M=Math.floor(M)),M<0&&(M=255+M+1),this[N]=255&M,N+1},g.prototype.writeInt16LE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=255&M,this[N+1]=M>>>8):Z(this,M,N,!0),N+2},g.prototype.writeInt16BE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=M>>>8,this[N+1]=255&M):Z(this,M,N,!1),N+2},g.prototype.writeInt32LE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[N]=255&M,this[N+1]=M>>>8,this[N+2]=M>>>16,this[N+3]=M>>>24):fe(this,M,N,!0),N+4},g.prototype.writeInt32BE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,4,2147483647,-2147483648),M<0&&(M=4294967295+M+1),g.TYPED_ARRAY_SUPPORT?(this[N]=M>>>24,this[N+1]=M>>>16,this[N+2]=M>>>8,this[N+3]=255&M):fe(this,M,N,!1),N+4},g.prototype.writeFloatLE=function(M,N,L){return Pe(this,M,N,!0,L)},g.prototype.writeFloatBE=function(M,N,L){return Pe(this,M,N,!1,L)},g.prototype.writeDoubleLE=function(M,N,L){return je(this,M,N,!0,L)},g.prototype.writeDoubleBE=function(M,N,L){return je(this,M,N,!1,L)},g.prototype.copy=function(M,N,L,H){if(L||(L=0),H||H===0||(H=this.length),N>=M.length&&(N=M.length),N||(N=0),H>0&&H<L&&(H=L),H===L||M.length===0||this.length===0)return 0;if(N<0)throw new RangeError("targetStart out of bounds");if(L<0||L>=this.length)throw new RangeError("sourceStart out of bounds");if(H<0)throw new RangeError("sourceEnd out of bounds");H>this.length&&(H=this.length),M.length-N<H-L&&(H=M.length-N+L);var re,le=H-L;if(this===M&&L<N&&N<H)for(re=le-1;re>=0;--re)M[re+N]=this[re+L];else if(le<1e3||!g.TYPED_ARRAY_SUPPORT)for(re=0;re<le;++re)M[re+N]=this[re+L];else Uint8Array.prototype.set.call(M,this.subarray(L,L+le),N);return le},g.prototype.fill=function(M,N,L,H){if(typeof M=="string"){if(typeof N=="string"?(H=N,N=0,L=this.length):typeof L=="string"&&(H=L,L=this.length),M.length===1){var re=M.charCodeAt(0);re<256&&(M=re)}if(H!==void 0&&typeof H!="string")throw new TypeError("encoding must be a string");if(typeof H=="string"&&!g.isEncoding(H))throw new TypeError("Unknown encoding: "+H)}else typeof M=="number"&&(M&=255);if(N<0||this.length<N||this.length<L)throw new RangeError("Out of range index");if(L<=N)return this;var le;if(N>>>=0,L=L===void 0?this.length:L>>>0,M||(M=0),typeof M=="number")for(le=N;le<L;++le)this[le]=M;else{var Ee=g.isBuffer(M)?M:ge(new g(M,H).toString()),G=Ee.length;for(le=0;le<L-N;++le)this[le+N]=Ee[le%G]}return this};var Qe=/[^+\/0-9A-Za-z-_]/g;function We(se){return se<16?"0"+se.toString(16):se.toString(16)}function ge(se,M){var N;M=M||1/0;for(var L=se.length,H=null,re=[],le=0;le<L;++le){if((N=se.charCodeAt(le))>55295&&N<57344){if(!H){if(N>56319){(M-=3)>-1&&re.push(239,191,189);continue}if(le+1===L){(M-=3)>-1&&re.push(239,191,189);continue}H=N;continue}if(N<56320){(M-=3)>-1&&re.push(239,191,189),H=N;continue}N=65536+(H-55296<<10|N-56320)}else H&&(M-=3)>-1&&re.push(239,191,189);if(H=null,N<128){if((M-=1)<0)break;re.push(N)}else if(N<2048){if((M-=2)<0)break;re.push(N>>6|192,63&N|128)}else if(N<65536){if((M-=3)<0)break;re.push(N>>12|224,N>>6&63|128,63&N|128)}else{if(!(N<1114112))throw new Error("Invalid code point");if((M-=4)<0)break;re.push(N>>18|240,N>>12&63|128,N>>6&63|128,63&N|128)}}return re}function pe(se){return l.toByteArray((function(N){if((N=(function(H){return H.trim?H.trim():H.replace(/^\s+|\s+$/g,"")})(N).replace(Qe,"")).length<2)return"";for(;N.length%4!=0;)N+="=";return N})(se))}function Me(se,M,N,L){for(var H=0;H<L&&!(H+N>=M.length||H>=se.length);++H)M[H+N]=se[H];return H}}).call(this,s(29))},function(t,i){var s;s=(function(){return this})();try{s=s||new Function("return this")()}catch{typeof window=="object"&&(s=window)}t.exports=s},function(t,i,s){i.byteLength=function(S){var E=g(S),x=E[0],A=E[1];return 3*(x+A)/4-A},i.toByteArray=function(S){var E,x,A=g(S),I=A[0],T=A[1],F=new u((function(Y,_e,j){return 3*(_e+j)/4-j})(0,I,T)),P=0,V=T>0?I-4:I;for(x=0;x<V;x+=4)E=l[S.charCodeAt(x)]<<18|l[S.charCodeAt(x+1)]<<12|l[S.charCodeAt(x+2)]<<6|l[S.charCodeAt(x+3)],F[P++]=E>>16&255,F[P++]=E>>8&255,F[P++]=255&E;return T===2&&(E=l[S.charCodeAt(x)]<<2|l[S.charCodeAt(x+1)]>>4,F[P++]=255&E),T===1&&(E=l[S.charCodeAt(x)]<<10|l[S.charCodeAt(x+1)]<<4|l[S.charCodeAt(x+2)]>>2,F[P++]=E>>8&255,F[P++]=255&E),F},i.fromByteArray=function(S){for(var E,x=S.length,A=x%3,I=[],T=16383,F=0,P=x-A;F<P;F+=T)I.push(y(S,F,F+T>P?P:F+T));return A===1?(E=S[x-1],I.push(o[E>>2]+o[E<<4&63]+"==")):A===2&&(E=(S[x-2]<<8)+S[x-1],I.push(o[E>>10]+o[E>>4&63]+o[E<<2&63]+"=")),I.join("")};for(var o=[],l=[],u=typeof Uint8Array<"u"?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;d<p;++d)o[d]=h[d],l[h.charCodeAt(d)]=d;function g(v){var S=v.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var E=v.indexOf("=");return E===-1&&(E=S),[E,E===S?0:4-E%4]}function y(v,S,E){for(var x,A,I=[],T=S;T<E;T+=3)x=(v[T]<<16&16711680)+(v[T+1]<<8&65280)+(255&v[T+2]),I.push(o[(A=x)>>18&63]+o[A>>12&63]+o[A>>6&63]+o[63&A]);return I.join("")}l[45]=62,l[95]=63},function(t,i){i.read=function(s,o,l,u,h){var d,p,g=8*h-u-1,y=(1<<g)-1,v=y>>1,S=-7,E=l?h-1:0,x=l?-1:1,A=s[o+E];for(E+=x,d=A&(1<<-S)-1,A>>=-S,S+=g;S>0;d=256*d+s[o+E],E+=x,S-=8);for(p=d&(1<<-S)-1,d>>=-S,S+=u;S>0;p=256*p+s[o+E],E+=x,S-=8);if(d===0)d=1-v;else{if(d===y)return p?NaN:1/0*(A?-1:1);p+=Math.pow(2,u),d-=v}return(A?-1:1)*p*Math.pow(2,d-u)},i.write=function(s,o,l,u,h,d){var p,g,y,v=8*d-h-1,S=(1<<v)-1,E=S>>1,x=h===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=u?0:d-1,I=u?1:-1,T=o<0||o===0&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(g=isNaN(o)?1:0,p=S):(p=Math.floor(Math.log(o)/Math.LN2),o*(y=Math.pow(2,-p))<1&&(p--,y*=2),(o+=p+E>=1?x/y:x*Math.pow(2,1-E))*y>=2&&(p++,y/=2),p+E>=S?(g=0,p=S):p+E>=1?(g=(o*y-1)*Math.pow(2,h),p+=E):(g=o*Math.pow(2,E-1)*Math.pow(2,h),p=0));h>=8;s[l+A]=255&g,A+=I,g/=256,h-=8);for(p=p<<h|g,v+=h;v>0;s[l+A]=255&p,A+=I,p/=256,v-=8);s[l+A-I]|=128*T}},function(t,i){var s={}.toString;t.exports=Array.isArray||function(o){return s.call(o)=="[object Array]"}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(u){var h=u.jws,d=u.KeyUtil,p=u.X509,g=u.crypto,y=u.hextob64u,v=u.b64tohex,S=u.AllowedSigningAlgs;return(function(){function E(){(function(A,I){if(!(A instanceof I))throw new TypeError("Cannot call a class as a function")})(this,E)}return E.parseJwt=function(A){o.Log.debug("JoseUtil.parseJwt");try{var I=h.JWS.parse(A);return{header:I.headerObj,payload:I.payloadObj}}catch(T){o.Log.error(T)}},E.validateJwt=function(A,I,T,F,P,V,B){o.Log.debug("JoseUtil.validateJwt");try{if(I.kty==="RSA")if(I.e&&I.n)I=d.getKey(I);else{if(!I.x5c||!I.x5c.length)return o.Log.error("JoseUtil.validateJwt: RSA key missing key material",I),Promise.reject(new Error("RSA key missing key material"));var Y=v(I.x5c[0]);I=p.getPublicKeyFromCertHex(Y)}else{if(I.kty!=="EC")return o.Log.error("JoseUtil.validateJwt: Unsupported key type",I&&I.kty),Promise.reject(new Error(I.kty));if(!(I.crv&&I.x&&I.y))return o.Log.error("JoseUtil.validateJwt: EC key missing key material",I),Promise.reject(new Error("EC key missing key material"));I=d.getKey(I)}return E._validateJwt(A,I,T,F,P,V,B)}catch(_e){return o.Log.error(_e&&_e.message||_e),Promise.reject("JWT validation failed")}},E.validateJwtAttributes=function(A,I,T,F,P,V){F||(F=0),P||(P=parseInt(Date.now()/1e3));var B=E.parseJwt(A).payload;if(!B.iss)return o.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(B.iss!==I)return o.Log.error("JoseUtil._validateJwt: Invalid issuer in token",B.iss),Promise.reject(new Error("Invalid issuer in token: "+B.iss));if(!B.aud)return o.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(B.aud===T||Array.isArray(B.aud)&&B.aud.indexOf(T)>=0))return o.Log.error("JoseUtil._validateJwt: Invalid audience in token",B.aud),Promise.reject(new Error("Invalid audience in token: "+B.aud));if(B.azp&&B.azp!==T)return o.Log.error("JoseUtil._validateJwt: Invalid azp in token",B.azp),Promise.reject(new Error("Invalid azp in token: "+B.azp));if(!V){var Y=P+F,_e=P-F;if(!B.iat)return o.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(Y<B.iat)return o.Log.error("JoseUtil._validateJwt: iat is in the future",B.iat),Promise.reject(new Error("iat is in the future: "+B.iat));if(B.nbf&&Y<B.nbf)return o.Log.error("JoseUtil._validateJwt: nbf is in the future",B.nbf),Promise.reject(new Error("nbf is in the future: "+B.nbf));if(!B.exp)return o.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(B.exp<_e)return o.Log.error("JoseUtil._validateJwt: exp is in the past",B.exp),Promise.reject(new Error("exp is in the past:"+B.exp))}return Promise.resolve(B)},E._validateJwt=function(A,I,T,F,P,V,B){return E.validateJwtAttributes(A,T,F,P,V,B).then((function(Y){try{return h.JWS.verify(A,I,S)?Y:(o.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(_e){return o.Log.error(_e&&_e.message||_e),Promise.reject(new Error("signature validation failed"))}}))},E.hashString=function(A,I){try{return g.Util.hashString(A,I)}catch(T){o.Log.error(T)}},E.hexToBase64Url=function(A){try{return y(A)}catch(I){o.Log.error(I)}},E})()};var o=s(0);t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninResponse=void 0;var o=(function(){function h(d,p){for(var g=0;g<p.length;g++){var y=p[g];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(d,y.key,y)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(3);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.SigninResponse=(function(){function h(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";u(this,h);var g=l.UrlUtility.parseUrlFragment(d,p);this.error=g.error,this.error_description=g.error_description,this.error_uri=g.error_uri,this.code=g.code,this.state=g.state,this.id_token=g.id_token,this.session_state=g.session_state,this.access_token=g.access_token,this.token_type=g.token_type,this.scope=g.scope,this.profile=void 0,this.expires_in=g.expires_in}return o(h,[{key:"expires_in",get:function(){if(this.expires_at){var p=parseInt(Date.now()/1e3);return this.expires_at-p}},set:function(p){var g=parseInt(p);if(typeof g=="number"&&g>0){var y=parseInt(Date.now()/1e3);this.expires_at=y+g}}},{key:"expired",get:function(){var p=this.expires_in;if(p!==void 0)return p<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutRequest=void 0;var o=s(0),l=s(3),u=s(9);i.SignoutRequest=function h(d){var p=d.url,g=d.id_token_hint,y=d.post_logout_redirect_uri,v=d.data,S=d.extraQueryParams,E=d.request_type;if((function(I,T){if(!(I instanceof T))throw new TypeError("Cannot call a class as a function")})(this,h),!p)throw o.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var x in g&&(p=l.UrlUtility.addQueryParam(p,"id_token_hint",g)),y&&(p=l.UrlUtility.addQueryParam(p,"post_logout_redirect_uri",y),v&&(this.state=new u.State({data:v,request_type:E}),p=l.UrlUtility.addQueryParam(p,"state",this.state.id))),S)p=l.UrlUtility.addQueryParam(p,x,S[x]);this.url=p}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutResponse=void 0;var o=s(3);i.SignoutResponse=function l(u){(function(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")})(this,l);var h=o.UrlUtility.parseUrlFragment(u,"?");this.error=h.error,this.error_description=h.error_description,this.error_uri=h.error_uri,this.state=h.state}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.InMemoryWebStorage=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.InMemoryWebStorage=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u),this._data={}}return u.prototype.getItem=function(d){return l.Log.debug("InMemoryWebStorage.getItem",d),this._data[d]},u.prototype.setItem=function(d,p){l.Log.debug("InMemoryWebStorage.setItem",d),this._data[d]=p},u.prototype.removeItem=function(d){l.Log.debug("InMemoryWebStorage.removeItem",d),delete this._data[d]},u.prototype.key=function(d){return Object.getOwnPropertyNames(this._data)[d]},o(u,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManager=void 0;var o=(function(){function T(F,P){for(var V=0;V<P.length;V++){var B=P[V];B.enumerable=B.enumerable||!1,B.configurable=!0,"value"in B&&(B.writable=!0),Object.defineProperty(F,B.key,B)}}return function(F,P,V){return P&&T(F.prototype,P),V&&T(F,V),F}})(),l=s(0),u=s(10),h=s(39),d=s(15),p=s(45),g=s(47),y=s(18),v=s(8),S=s(20),E=s(11),x=s(4);function A(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function I(T,F){if(!T)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!F||typeof F!="object"&&typeof F!="function"?T:F}i.UserManager=(function(T){function F(){var P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},V=arguments.length>1&&arguments[1]!==void 0?arguments[1]:g.SilentRenewService,B=arguments.length>2&&arguments[2]!==void 0?arguments[2]:y.SessionMonitor,Y=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,_e=arguments.length>4&&arguments[4]!==void 0?arguments[4]:E.TokenClient,j=arguments.length>5&&arguments[5]!==void 0?arguments[5]:x.JoseUtil;A(this,F),P instanceof h.UserManagerSettings||(P=new h.UserManagerSettings(P));var ee=I(this,T.call(this,P));return ee._events=new p.UserManagerEvents(P),ee._silentRenewService=new V(ee),ee.settings.automaticSilentRenew&&(l.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),ee.startSilentRenew()),ee.settings.monitorSession&&(l.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),ee._sessionMonitor=new B(ee)),ee._tokenRevocationClient=new Y(ee._settings),ee._tokenClient=new _e(ee._settings),ee._joseUtil=j,ee}return(function(V,B){if(typeof B!="function"&&B!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof B);V.prototype=Object.create(B&&B.prototype,{constructor:{value:V,enumerable:!1,writable:!0,configurable:!0}}),B&&(Object.setPrototypeOf?Object.setPrototypeOf(V,B):V.__proto__=B)})(F,T),F.prototype.getUser=function(){var V=this;return this._loadUser().then((function(B){return B?(l.Log.info("UserManager.getUser: user loaded"),V._events.load(B,!1),B):(l.Log.info("UserManager.getUser: user not found in storage"),null)}))},F.prototype.removeUser=function(){var V=this;return this.storeUser(null).then((function(){l.Log.info("UserManager.removeUser: user removed from storage"),V._events.unload()}))},F.prototype.signinRedirect=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(V=Object.assign({},V)).request_type="si:r";var B={useReplaceToNavigate:V.useReplaceToNavigate};return this._signinStart(V,this._redirectNavigator,B).then((function(){l.Log.info("UserManager.signinRedirect: successful")}))},F.prototype.signinRedirectCallback=function(V){return this._signinEnd(V||this._redirectNavigator.url).then((function(B){return B.profile&&B.profile.sub?l.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",B.profile.sub):l.Log.info("UserManager.signinRedirectCallback: no sub"),B}))},F.prototype.signinPopup=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(V=Object.assign({},V)).request_type="si:p";var B=V.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return B?(V.redirect_uri=B,V.display="popup",this._signin(V,this._popupNavigator,{startUrl:B,popupWindowFeatures:V.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:V.popupWindowTarget||this.settings.popupWindowTarget}).then((function(Y){return Y&&(Y.profile&&Y.profile.sub?l.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",Y.profile.sub):l.Log.info("UserManager.signinPopup: no sub")),Y}))):(l.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},F.prototype.signinPopupCallback=function(V){return this._signinCallback(V,this._popupNavigator).then((function(B){return B&&(B.profile&&B.profile.sub?l.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",B.profile.sub):l.Log.info("UserManager.signinPopupCallback: no sub")),B})).catch((function(B){l.Log.error(B.message)}))},F.prototype.signinSilent=function(){var V=this,B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return B=Object.assign({},B),this._loadUser().then((function(Y){return Y&&Y.refresh_token?(B.refresh_token=Y.refresh_token,V._useRefreshToken(B)):(B.request_type="si:s",B.id_token_hint=B.id_token_hint||V.settings.includeIdTokenInSilentRenew&&Y&&Y.id_token,Y&&V._settings.validateSubOnSilentRenew&&(l.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",Y.profile.sub),B.current_sub=Y.profile.sub),V._signinSilentIframe(B))}))},F.prototype._useRefreshToken=function(){var V=this,B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(B).then((function(Y){return Y?Y.access_token?V._loadUser().then((function(_e){if(_e){var j=Promise.resolve();return Y.id_token&&(j=V._validateIdTokenFromTokenRefreshToken(_e.profile,Y.id_token)),j.then((function(){return l.Log.debug("UserManager._useRefreshToken: refresh token response success"),_e.id_token=Y.id_token||_e.id_token,_e.access_token=Y.access_token,_e.refresh_token=Y.refresh_token||_e.refresh_token,_e.expires_in=Y.expires_in,V.storeUser(_e).then((function(){return V._events.load(_e),_e}))}))}return null})):(l.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(l.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},F.prototype._validateIdTokenFromTokenRefreshToken=function(V,B){var Y=this;return this._metadataService.getIssuer().then((function(_e){return Y.settings.getEpochTime().then((function(j){return Y._joseUtil.validateJwtAttributes(B,_e,Y._settings.client_id,Y._settings.clockSkew,j).then((function(ee){return ee?ee.sub!==V.sub?(l.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"))):ee.auth_time&&ee.auth_time!==V.auth_time?(l.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"))):ee.azp&&ee.azp!==V.azp?(l.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"))):!ee.azp&&V.azp?(l.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:(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},F.prototype._signinSilentIframe=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},B=V.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return B?(V.redirect_uri=B,V.prompt=V.prompt||"none",this._signin(V,this._iframeNavigator,{startUrl:B,silentRequestTimeout:V.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(Y){return Y&&(Y.profile&&Y.profile.sub?l.Log.info("UserManager.signinSilent: successful, signed in sub: ",Y.profile.sub):l.Log.info("UserManager.signinSilent: no sub")),Y}))):(l.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype.signinSilentCallback=function(V){return this._signinCallback(V,this._iframeNavigator).then((function(B){return B&&(B.profile&&B.profile.sub?l.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",B.profile.sub):l.Log.info("UserManager.signinSilentCallback: no sub")),B}))},F.prototype.signinCallback=function(V){var B=this;return this.readSigninResponseState(V).then((function(Y){var _e=Y.state;return Y.response,_e.request_type==="si:r"?B.signinRedirectCallback(V):_e.request_type==="si:p"?B.signinPopupCallback(V):_e.request_type==="si:s"?B.signinSilentCallback(V):Promise.reject(new Error("invalid response_type in state"))}))},F.prototype.signoutCallback=function(V,B){var Y=this;return this.readSignoutResponseState(V).then((function(_e){var j=_e.state,ee=_e.response;return j?j.request_type==="so:r"?Y.signoutRedirectCallback(V):j.request_type==="so:p"?Y.signoutPopupCallback(V,B):Promise.reject(new Error("invalid response_type in state")):ee}))},F.prototype.querySessionStatus=function(){var V=this,B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(B=Object.assign({},B)).request_type="si:s";var Y=B.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return Y?(B.redirect_uri=Y,B.prompt="none",B.response_type=B.response_type||this.settings.query_status_response_type,B.scope=B.scope||"openid",B.skipUserInfo=!0,this._signinStart(B,this._iframeNavigator,{startUrl:Y,silentRequestTimeout:B.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(_e){return V.processSigninResponse(_e.url).then((function(j){if(l.Log.debug("UserManager.querySessionStatus: got signin response"),j.session_state&&j.profile.sub)return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",j.profile.sub),{session_state:j.session_state,sub:j.profile.sub,sid:j.profile.sid};l.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(j){if(j.session_state&&V.settings.monitorAnonymousSession&&(j.message=="login_required"||j.message=="consent_required"||j.message=="interaction_required"||j.message=="account_selection_required"))return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:j.session_state};throw j}))}))):(l.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype._signin=function(V,B){var Y=this,_e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(V,B,_e).then((function(j){return Y._signinEnd(j.url,V)}))},F.prototype._signinStart=function(V,B){var Y=this,_e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return B.prepare(_e).then((function(j){return l.Log.debug("UserManager._signinStart: got navigator window handle"),Y.createSigninRequest(V).then((function(ee){return l.Log.debug("UserManager._signinStart: got signin request"),_e.url=ee.url,_e.id=ee.state.id,j.navigate(_e)})).catch((function(ee){throw j.close&&(l.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),j.close()),ee}))}))},F.prototype._signinEnd=function(V){var B=this,Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(V).then((function(_e){l.Log.debug("UserManager._signinEnd: got signin response");var j=new d.User(_e);if(Y.current_sub){if(Y.current_sub!==j.profile.sub)return l.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",j.profile.sub),Promise.reject(new Error("login_required"));l.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return B.storeUser(j).then((function(){return l.Log.debug("UserManager._signinEnd: user stored"),B._events.load(j),j}))}))},F.prototype._signinCallback=function(V,B){l.Log.debug("UserManager._signinCallback");var Y=this._settings.response_mode==="query"||!this._settings.response_mode&&v.SigninRequest.isCode(this._settings.response_type)?"?":"#";return B.callback(V,void 0,Y)},F.prototype.signoutRedirect=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(V=Object.assign({},V)).request_type="so:r";var B=V.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;B&&(V.post_logout_redirect_uri=B);var Y={useReplaceToNavigate:V.useReplaceToNavigate};return this._signoutStart(V,this._redirectNavigator,Y).then((function(){l.Log.info("UserManager.signoutRedirect: successful")}))},F.prototype.signoutRedirectCallback=function(V){return this._signoutEnd(V||this._redirectNavigator.url).then((function(B){return l.Log.info("UserManager.signoutRedirectCallback: successful"),B}))},F.prototype.signoutPopup=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(V=Object.assign({},V)).request_type="so:p";var B=V.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return V.post_logout_redirect_uri=B,V.display="popup",V.post_logout_redirect_uri&&(V.state=V.state||{}),this._signout(V,this._popupNavigator,{startUrl:B,popupWindowFeatures:V.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:V.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){l.Log.info("UserManager.signoutPopup: successful")}))},F.prototype.signoutPopupCallback=function(V,B){return B===void 0&&typeof V=="boolean"&&(B=V,V=null),this._popupNavigator.callback(V,B,"?").then((function(){l.Log.info("UserManager.signoutPopupCallback: successful")}))},F.prototype._signout=function(V,B){var Y=this,_e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(V,B,_e).then((function(j){return Y._signoutEnd(j.url)}))},F.prototype._signoutStart=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},B=this,Y=arguments[1],_e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return Y.prepare(_e).then((function(j){return l.Log.debug("UserManager._signoutStart: got navigator window handle"),B._loadUser().then((function(ee){return l.Log.debug("UserManager._signoutStart: loaded current user from storage"),(B._settings.revokeAccessTokenOnSignout?B._revokeInternal(ee):Promise.resolve()).then((function(){var me=V.id_token_hint||ee&&ee.id_token;return me&&(l.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),V.id_token_hint=me),B.removeUser().then((function(){return l.Log.debug("UserManager._signoutStart: user removed, creating signout request"),B.createSignoutRequest(V).then((function(te){return l.Log.debug("UserManager._signoutStart: got signout request"),_e.url=te.url,te.state&&(_e.id=te.state.id),j.navigate(_e)}))}))}))})).catch((function(ee){throw j.close&&(l.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),j.close()),ee}))}))},F.prototype._signoutEnd=function(V){return this.processSignoutResponse(V).then((function(B){return l.Log.debug("UserManager._signoutEnd: got signout response"),B}))},F.prototype.revokeAccessToken=function(){var V=this;return this._loadUser().then((function(B){return V._revokeInternal(B,!0).then((function(Y){if(Y)return l.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),B.access_token=null,B.refresh_token=null,B.expires_at=null,B.token_type=null,V.storeUser(B).then((function(){l.Log.debug("UserManager.revokeAccessToken: user stored"),V._events.load(B)}))}))})).then((function(){l.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},F.prototype._revokeInternal=function(V,B){var Y=this;if(V){var _e=V.access_token,j=V.refresh_token;return this._revokeAccessTokenInternal(_e,B).then((function(ee){return Y._revokeRefreshTokenInternal(j,B).then((function(me){return ee||me||l.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),ee||me}))}))}return Promise.resolve(!1)},F.prototype._revokeAccessTokenInternal=function(V,B){return!V||V.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(V,B).then((function(){return!0}))},F.prototype._revokeRefreshTokenInternal=function(V,B){return V?this._tokenRevocationClient.revoke(V,B,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},F.prototype.startSilentRenew=function(){this._silentRenewService.start()},F.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},F.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(V){return V?(l.Log.debug("UserManager._loadUser: user storageString loaded"),d.User.fromStorageString(V)):(l.Log.debug("UserManager._loadUser: no user storageString"),null)}))},F.prototype.storeUser=function(V){if(V){l.Log.debug("UserManager.storeUser: storing user");var B=V.toStorageString();return this._userStore.set(this._userStoreKey,B)}return l.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},o(F,[{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}}]),F})(u.OidcClient)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerSettings=void 0;var o=(function(){function E(x,A){for(var I=0;I<A.length;I++){var T=A[I];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(x,T.key,T)}}return function(x,A,I){return A&&E(x.prototype,A),I&&E(x,I),x}})(),l=(s(0),s(5)),u=s(40),h=s(41),d=s(43),p=s(6),g=s(1),y=s(8);function v(E,x){if(!(E instanceof x))throw new TypeError("Cannot call a class as a function")}function S(E,x){if(!E)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!x||typeof x!="object"&&typeof x!="function"?E:x}i.UserManagerSettings=(function(E){function x(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},I=A.popup_redirect_uri,T=A.popup_post_logout_redirect_uri,F=A.popupWindowFeatures,P=A.popupWindowTarget,V=A.silent_redirect_uri,B=A.silentRequestTimeout,Y=A.automaticSilentRenew,_e=Y!==void 0&&Y,j=A.validateSubOnSilentRenew,ee=j!==void 0&&j,me=A.includeIdTokenInSilentRenew,te=me===void 0||me,Ce=A.monitorSession,Oe=Ce===void 0||Ce,ye=A.monitorAnonymousSession,qe=ye!==void 0&&ye,de=A.checkSessionInterval,Fe=de===void 0?2e3:de,O=A.stopCheckSessionOnError,Z=O===void 0||O,fe=A.query_status_response_type,oe=A.revokeAccessTokenOnSignout,Pe=oe!==void 0&&oe,je=A.accessTokenExpiringNotificationTime,Qe=je===void 0?60:je,We=A.redirectNavigator,ge=We===void 0?new u.RedirectNavigator:We,pe=A.popupNavigator,Me=pe===void 0?new h.PopupNavigator:pe,se=A.iframeNavigator,M=se===void 0?new d.IFrameNavigator:se,N=A.userStore,L=N===void 0?new p.WebStorageStateStore({store:g.Global.sessionStorage}):N;v(this,x);var H=S(this,E.call(this,arguments[0]));return H._popup_redirect_uri=I,H._popup_post_logout_redirect_uri=T,H._popupWindowFeatures=F,H._popupWindowTarget=P,H._silent_redirect_uri=V,H._silentRequestTimeout=B,H._automaticSilentRenew=_e,H._validateSubOnSilentRenew=ee,H._includeIdTokenInSilentRenew=te,H._accessTokenExpiringNotificationTime=Qe,H._monitorSession=Oe,H._monitorAnonymousSession=qe,H._checkSessionInterval=Fe,H._stopCheckSessionOnError=Z,fe?H._query_status_response_type=fe:arguments[0]&&arguments[0].response_type?H._query_status_response_type=y.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":H._query_status_response_type="id_token",H._revokeAccessTokenOnSignout=Pe,H._redirectNavigator=ge,H._popupNavigator=Me,H._iframeNavigator=M,H._userStore=L,H}return(function(I,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof T);I.prototype=Object.create(T&&T.prototype,{constructor:{value:I,enumerable:!1,writable:!0,configurable:!0}}),T&&(Object.setPrototypeOf?Object.setPrototypeOf(I,T):I.__proto__=T)})(x,E),o(x,[{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}}]),x})(l.OidcClientSettings)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.RedirectNavigator=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.RedirectNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(){return Promise.resolve(this)},u.prototype.navigate=function(d){return d&&d.url?(d.useReplaceToNavigate?window.location.replace(d.url):window.location=d.url,Promise.resolve()):(l.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},o(u,[{key:"url",get:function(){return window.location.href}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupNavigator=void 0;var o=s(0),l=s(42);i.PopupNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.PopupWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d,p,g){o.Log.debug("PopupNavigator.callback");try{return l.PopupWindow.notifyOpener(d,p,g),Promise.resolve()}catch(y){return Promise.reject(y)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupWindow=void 0;var o=(function(){function h(d,p){for(var g=0;g<p.length;g++){var y=p[g];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(d,y.key,y)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(0),u=s(3);i.PopupWindow=(function(){function h(d){var p=this;(function(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")})(this,h),this._promise=new Promise((function(v,S){p._resolve=v,p._reject=S}));var g=d.popupWindowTarget||"_blank",y=d.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",g,y),this._popup&&(l.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return h.prototype.navigate=function(p){return this._popup?p&&p.url?(l.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=p.id,this._id&&(window["popupCallback_"+p.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=p.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},h.prototype._success=function(p){l.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(p)},h.prototype._error=function(p){l.Log.error("PopupWindow.error: ",p),this._cleanup(),this._reject(new Error(p))},h.prototype.close=function(){this._cleanup(!1)},h.prototype._cleanup=function(p){l.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!p&&this._popup.close(),this._popup=null},h.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},h.prototype._callback=function(p,g){this._cleanup(g),p?(l.Log.debug("PopupWindow.callback success"),this._success({url:p})):(l.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},h.notifyOpener=function(p,g,y){if(window.opener){if(p=p||window.location.href){var v=u.UrlUtility.parseUrlFragment(p,y);if(v.state){var S="popupCallback_"+v.state,E=window.opener[S];E?(l.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),E(p,g)):l.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else l.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else l.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},o(h,[{key:"promise",get:function(){return this._promise}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameNavigator=void 0;var o=s(0),l=s(44);i.IFrameNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.IFrameWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d){o.Log.debug("IFrameNavigator.callback");try{return l.IFrameWindow.notifyParent(d),Promise.resolve()}catch(p){return Promise.reject(p)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameWindow=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.IFrameWindow=(function(){function u(h){var d=this;(function(g,y){if(!(g instanceof y))throw new TypeError("Cannot call a class as a function")})(this,u),this._promise=new Promise((function(p,g){d._resolve=p,d._reject=g})),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 u.prototype.navigate=function(d){if(d&&d.url){var p=d.silentRequestTimeout||1e4;l.Log.debug("IFrameWindow.navigate: Using timeout of:",p),this._timer=window.setTimeout(this._timeout.bind(this),p),this._frame.src=d.url}else this._error("No url provided");return this.promise},u.prototype._success=function(d){this._cleanup(),l.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(d)},u.prototype._error=function(d){this._cleanup(),l.Log.error(d),this._reject(new Error(d))},u.prototype.close=function(){this._cleanup()},u.prototype._cleanup=function(){this._frame&&(l.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)},u.prototype._timeout=function(){l.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},u.prototype._message=function(d){if(l.Log.debug("IFrameWindow.message"),this._timer&&d.origin===this._origin&&d.source===this._frame.contentWindow&&typeof d.data=="string"&&(d.data.startsWith("http://")||d.data.startsWith("https://"))){var p=d.data;p?this._success({url:p}):this._error("Invalid response from frame")}},u.notifyParent=function(d){l.Log.debug("IFrameWindow.notifyParent"),(d=d||window.location.href)&&(l.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(d,location.protocol+"//"+location.host))},o(u,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerEvents=void 0;var o=s(0),l=s(16),u=s(17);i.UserManagerEvents=(function(h){function d(p){(function(v,S){if(!(v instanceof S))throw new TypeError("Cannot call a class as a function")})(this,d);var g=(function(v,S){if(!v)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?v:S})(this,h.call(this,p));return g._userLoaded=new u.Event("User loaded"),g._userUnloaded=new u.Event("User unloaded"),g._silentRenewError=new u.Event("Silent renew error"),g._userSignedIn=new u.Event("User signed in"),g._userSignedOut=new u.Event("User signed out"),g._userSessionChanged=new u.Event("User session changed"),g}return(function(g,y){if(typeof y!="function"&&y!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof y);g.prototype=Object.create(y&&y.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),y&&(Object.setPrototypeOf?Object.setPrototypeOf(g,y):g.__proto__=y)})(d,h),d.prototype.load=function(g){var y=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];o.Log.debug("UserManagerEvents.load"),h.prototype.load.call(this,g),y&&this._userLoaded.raise(g)},d.prototype.unload=function(){o.Log.debug("UserManagerEvents.unload"),h.prototype.unload.call(this),this._userUnloaded.raise()},d.prototype.addUserLoaded=function(g){this._userLoaded.addHandler(g)},d.prototype.removeUserLoaded=function(g){this._userLoaded.removeHandler(g)},d.prototype.addUserUnloaded=function(g){this._userUnloaded.addHandler(g)},d.prototype.removeUserUnloaded=function(g){this._userUnloaded.removeHandler(g)},d.prototype.addSilentRenewError=function(g){this._silentRenewError.addHandler(g)},d.prototype.removeSilentRenewError=function(g){this._silentRenewError.removeHandler(g)},d.prototype._raiseSilentRenewError=function(g){o.Log.debug("UserManagerEvents._raiseSilentRenewError",g.message),this._silentRenewError.raise(g)},d.prototype.addUserSignedIn=function(g){this._userSignedIn.addHandler(g)},d.prototype.removeUserSignedIn=function(g){this._userSignedIn.removeHandler(g)},d.prototype._raiseUserSignedIn=function(){o.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},d.prototype.addUserSignedOut=function(g){this._userSignedOut.addHandler(g)},d.prototype.removeUserSignedOut=function(g){this._userSignedOut.removeHandler(g)},d.prototype._raiseUserSignedOut=function(){o.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},d.prototype.addUserSessionChanged=function(g){this._userSessionChanged.addHandler(g)},d.prototype.removeUserSessionChanged=function(g){this._userSessionChanged.removeHandler(g)},d.prototype._raiseUserSessionChanged=function(){o.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},d})(l.AccessTokenEvents)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Timer=void 0;var o=(function(){function g(y,v){for(var S=0;S<v.length;S++){var E=v[S];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty(y,E.key,E)}}return function(y,v,S){return v&&g(y.prototype,v),S&&g(y,S),y}})(),l=s(0),u=s(1),h=s(17);function d(g,y){if(!(g instanceof y))throw new TypeError("Cannot call a class as a function")}function p(g,y){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!y||typeof y!="object"&&typeof y!="function"?g:y}i.Timer=(function(g){function y(v){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.Global.timer,E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;d(this,y);var x=p(this,g.call(this,v));return x._timer=S,x._nowFunc=E||function(){return Date.now()/1e3},x}return(function(S,E){if(typeof E!="function"&&E!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof E);S.prototype=Object.create(E&&E.prototype,{constructor:{value:S,enumerable:!1,writable:!0,configurable:!0}}),E&&(Object.setPrototypeOf?Object.setPrototypeOf(S,E):S.__proto__=E)})(y,g),y.prototype.init=function(S){S<=0&&(S=1),S=parseInt(S);var E=this.now+S;if(this.expiration===E&&this._timerHandle)l.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),l.Log.debug("Timer.init timer "+this._name+" for duration:",S),this._expiration=E;var x=5;S<x&&(x=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*x)}},y.prototype.cancel=function(){this._timerHandle&&(l.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},y.prototype._callback=function(){var S=this._expiration-this.now;l.Log.debug("Timer.callback; "+this._name+" timer expires in:",S),this._expiration<=this.now&&(this.cancel(),g.prototype.raise.call(this))},o(y,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),y})(h.Event)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SilentRenewService=void 0;var o=s(0);i.SilentRenewService=(function(){function l(u){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,l),this._userManager=u}return l.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(h){})).catch((function(h){o.Log.error("SilentRenewService.start: Error from getUser:",h.message)})))},l.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},l.prototype._tokenExpiring=function(){var h=this;this._userManager.signinSilent().then((function(d){o.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(d){o.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",d.message),h._userManager.events._raiseSilentRenewError(d)}))},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupNavigator=void 0;var o=s(21);i.CordovaPopupNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){var d=new o.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaIFrameNavigator=void 0;var o=s(21);i.CordovaIFrameNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){h.popupWindowFeatures="hidden=yes";var d=new o.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Version="1.11.6"}])}))})(oidcClient_min$1)),oidcClient_min$1.exports}var oidcClient_minExports=requireOidcClient_min();function processErrorResponse(n,e){throw n.error==="invalid_redirect_uri"?new Error(`Dynamic client registration failed: the provided redirect uri [${e.redirectUrl?.toString()}] is invalid - ${n.error_description??""}`):n.error==="invalid_client_metadata"?new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(e)} is invalid - ${n.error_description??""}`):new Error(`Dynamic client registration failed: ${n.error} - ${n.error_description??""}`)}function hasClientId(n){return typeof n.client_id=="string"}function hasRedirectUri(n){return Array.isArray(n.redirect_uris)&&n.redirect_uris.every(e=>typeof e=="string")}function validateRegistrationResponse(n,e){if(!hasClientId(n))throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(n)}`);if(e.redirectUrl&&hasRedirectUri(n)&&n.redirect_uris[0]!==e.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(n.redirect_uris)} don't match the provided ${JSON.stringify([e.redirectUrl.toString()])}`);return!0}async function registerClient(n,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),i={client_name:n.clientName,application_type:"web",redirect_uris:[n.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:t,grant_types:["authorization_code","refresh_token"]},s={"Content-Type":"application/json"},o=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:s,body:JSON.stringify(i)});if(o.ok){const l=await o.json();return validateRegistrationResponse(l,n),{clientId:l.client_id,clientSecret:l.client_secret,expiresAt:l.client_secret_expires_at,idTokenSignedResponseAlg:l.id_token_signed_response_alg,clientType:"dynamic"}}throw o.status===400&&processErrorResponse(await o.json(),n),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function hasError(n){return n.error!==void 0&&typeof n.error=="string"}function hasErrorDescription(n){return n.error_description!==void 0&&typeof n.error_description=="string"}function hasErrorUri(n){return n.error_uri!==void 0&&typeof n.error_uri=="string"}function hasAccessToken(n){return n.access_token!==void 0&&typeof n.access_token=="string"}function hasIdToken(n){return n.id_token!==void 0&&typeof n.id_token=="string"}function hasRefreshToken(n){return n.refresh_token!==void 0&&typeof n.refresh_token=="string"}function hasTokenType(n){return n.token_type!==void 0&&typeof n.token_type=="string"}function hasExpiresIn(n){return n.expires_in===void 0||typeof n.expires_in=="number"}function validatePreconditions(n,e){if(e.grantType&&(!n.grantTypesSupported||!n.grantTypesSupported.includes(e.grantType)))throw new Error(`The issuer [${n.issuer}] does not support the [${e.grantType}] grant`);if(!n.tokenEndpoint)throw new Error(`This issuer [${n.issuer}] does not have a token endpoint`)}function validateTokenEndpointResponse(n,e){if(hasError(n))throw new OidcProviderError(`Token endpoint returned error [${n.error}]${hasErrorDescription(n)?`: ${n.error_description}`:""}${hasErrorUri(n)?` (see ${n.error_uri})`:""}`,n.error,hasErrorDescription(n)?n.error_description:void 0);if(!hasAccessToken(n))throw new InvalidResponseError(["access_token"]);if(!hasIdToken(n))throw new InvalidResponseError(["id_token"]);if(!hasTokenType(n))throw new InvalidResponseError(["token_type"]);if(!hasExpiresIn(n))throw new InvalidResponseError(["expires_in"]);if(!e&&n.token_type.toLowerCase()!=="bearer")throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${n.token_type}].`);return n}async function getTokens(n,e,t,i){validatePreconditions(n,t);const s={"content-type":"application/x-www-form-urlencoded"};let o;i&&(o=await generateDpopKeyPair(),s.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",o)),e.clientSecret&&(s.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const l={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},u={method:"POST",headers:s,body:new URLSearchParams(l).toString()},d=await(await fetch(n.tokenEndpoint,u)).json(),p=validateTokenEndpointResponse(d,i),{webId:g,clientId:y}=await getWebidFromTokenPayload(p.id_token,n.jwksUri,n.issuer,e.clientId);return{accessToken:p.access_token,idToken:p.id_token,refreshToken:hasRefreshToken(p)?p.refresh_token:void 0,webId:g,clientId:y,dpopKey:o,expiresIn:p.expires_in}}const isValidUrl=n=>{try{return new URL(n),!0}catch{return!1}};async function refresh(n,e,t,i){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const s={grant_type:"refresh_token",refresh_token:n};let o={};i!==void 0&&(o={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",i)});let l={};t.clientSecret!==void 0?l={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(s.client_id=t.clientId);const u=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(s).toString(),headers:{...o,...l,"Content-Type":"application/x-www-form-urlencoded"}});let h;try{h=await u.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const d=validateTokenEndpointResponse(h,i!==void 0),{webId:p}=await getWebidFromTokenPayload(d.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:d.access_token,idToken:d.id_token,refreshToken:typeof d.refresh_token=="string"?d.refresh_token:void 0,webId:p,dpopKey:i,expiresIn:d.expires_in}}function normalizeCallbackUrl(n){const e=removeOpenIdParams(n);return e.hash="",n.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 i=0;i<=e.length;i+=1){const s=e.key(i);s&&(s.match(/^oidc\..+$/)||s.match(/^solidClientAuthenticationUser:.+$/))&&t.push(s)}t.forEach(i=>e.removeItem(i))}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 i=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(i))throw new Error(`${i} 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:i,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 i=await this.redirectHandler.handle(e,t,void 0);return this.fetch=i.fetch.bind(window),this.boundLogout=i.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:i.isLoggedIn,webId:i.webId,sessionId:i.sessionId,expirationDate:i.expirationDate,clientAppId:i.clientAppId}}catch(i){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",i);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(i=>{setTimeout(()=>i(),1)})}}function hasIssuer(n){return typeof n.oidcIssuer=="string"}function hasRedirectUrl(n){return typeof n.redirectUrl=="string"}class OidcLoginHandler{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,i,s){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s}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),i=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),s={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:i,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(s)}}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"},i=new oidcClient_minExports.OidcClient(t);try{const s=await i.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:s.state._id,codeVerifier:s.state._code_verifier,targetUrl:s.url.toString()})}catch(s){console.error(s)}}}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(n){const e={};return Object.keys(n).forEach(t=>{issuerConfigKeyMap[t]&&(e[issuerConfigKeyMap[t].toKey]=n[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 i=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,s=await fetch(i);try{t=processConfig(await s.json())}catch(o){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${o.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function clear(n,e){await clear$1(n,e),await clearOidcPersistentStorage()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,i,s,o,l,u,h,d]=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 l=="string"&&!isValidRedirectUrl(l)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(d!==void 0&&!isSupportedTokenType(d))throw new Error(`Tokens of type [${d}] are not supported.`);if(!(s===void 0&&t===void 0&&i===void 0&&u===void 0))return{sessionId:e,webId:i,isLoggedIn:t==="true",redirectUrl:l,refreshToken:u,issuer:h,clientAppId:s,clientAppSecret:o,tokenType:d??"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,i,s,o,l){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=o,this.fetch=l,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=o}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 i=new URL(e),s=i.searchParams.get("state"),o=await this.storageUtility.getForUser(s,"sessionId",{errorIfNull:!0}),{issuerConfig:l,codeVerifier:u,redirectUrl:h,dpop:d}=await loadOidcContextFromStorage(o,this.storageUtility,this.issuerConfigFetcher),p=i.searchParams.get("iss");if(typeof p=="string"&&p!==l.issuer)throw new Error(`The value of the iss parameter (${p}) does not match the issuer identifier of the authorization server (${l.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(u===void 0)throw new Error(`The code verifier for session ${o} is missing from storage.`);if(h===void 0)throw new Error(`The redirect URL for session ${o} is missing from storage.`);const g=await this.clientRegistrar.getClient({sessionId:o},l),y=Date.now(),v=await getTokens(l,g,{grantType:"authorization_code",code:i.searchParams.get("code"),codeVerifier:u,redirectUrl:h},d);window.localStorage.removeItem(`oidc.${s}`);let S;v.refreshToken!==void 0&&(S={sessionId:o,refreshToken:v.refreshToken,tokenRefresher:this.tokerRefresher});const E=buildAuthenticatedFetch(v.accessToken,{dpopKey:v.dpopKey,refreshOptions:S,eventEmitter:t,expiresIn:v.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,o,v.webId,v.clientId,"true",void 0,!0);const x=await this.sessionInfoManager.get(o);if(!x)throw new Error(`Could not retrieve session: [${o}].`);return Object.assign(x,{fetch:E,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:v.idToken,endSessionEndpoint:l.endSessionEndpoint}),expirationDate:typeof v.expiresIn=="number"?y+v.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[i,s,o,l,u]=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})]),h=o!==void 0?Number.parseInt(o,10):-1,d=s!==void 0&&h!==0&&Math.floor(Date.now()/1e3)>h;if(i&&isKnownClientType(u)&&!d)return s!==void 0?{clientId:i,clientSecret:s,clientName:l,clientType:"dynamic",expiresAt:h}:{clientId:i,clientName:l,clientType:u};try{const p=await registerClient(e,t),g={clientId:p.clientId,clientType:"dynamic"};return p.clientSecret!==void 0&&(g.clientSecret=p.clientSecret,g.expiresAt=String(p.expiresAt)),p.idTokenSignedResponseAlg&&(g.idTokenSignedResponseAlg=p.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,g,{secure:!1}),p}catch(p){throw new Error("Client registration failed.",{cause:p})}}}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 i=new URL(e),s=i.searchParams.get("error"),o=i.searchParams.get("error_description");t.emit(EVENTS.ERROR,s,o)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,i){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i}async refresh(e,t,i,s){const o=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),l=await this.clientRegistrar.getClient({sessionId:e},o.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(o.dpop&&i===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 u=await refresh(t,o.issuerConfig,l,i);return u.refreshToken!==void 0&&s?.emit(EVENTS.NEW_REFRESH_TOKEN,u.refreshToken),u}}function getClientAuthenticationWithDependencies(n){const e=new InMemoryStorage,t=n.secureStorage||e,i=n.insecureStorage||new BrowserStorage,s=new StorageUtilityBrowser(t,i),o=new IssuerConfigFetcher(s),l=new ClientRegistrar(s),u=new SessionInfoManager(s),h=new TokenRefresher(s,o,l),d=new Redirector,p=new OidcLoginHandler(s,new AuthorizationCodeWithPkceOidcHandler(s,d),o,l),g=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(s,u,o,l,h,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(p,g,new IWaterfallLogoutHandler(u,d),u,o)}const KEY_CURRENT_SESSION=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,KEY_CURRENT_URL=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;async function silentlyAuthenticate(n,e,t){const i=await e.validateCurrentSession(n);return i!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:n,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:i.tokenType??"DPoP"},t.events),!0):!1}function isLoggedIn(n){return!!n?.isLoggedIn}class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;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(),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.internalLogout(!1))}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,i=t.url??window.location.href;this.tokenRequestInProgress=!0;const s=await this.clientAuthentication.handleIncomingRedirect(i,this.events);if(isLoggedIn(s)){this.setSessionInfo(s);const o=window.localStorage.getItem(KEY_CURRENT_URL);o===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,o))}else if(t.restorePreviousSession===!0){const o=window.localStorage.getItem(KEY_CURRENT_SESSION);if(o!==null&&await silentlyAuthenticate(o,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,s};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})}}function snapshotFromSessionInfo(n){return n?.isLoggedIn&&n.webId?{status:"authenticated",webId:n.webId}:{status:"anonymous"}}function normalizeError(n){return n instanceof Error?n:new Error(String(n))}function snapshotFromSessionError(n,e){return{status:"error",webId:e.webId,error:normalizeError(n)}}function snapshotFromSessionExpired(n){return{status:"expired",...n.webId===void 0?{}:{webId:n.webId}}}function areSnapshotsEqual(n,e){return!n||n.status!==e.status||n.webId!==e.webId?!1:n.status==="error"&&e.status==="error"?n.error===e.error:!0}function createSolidSessionRuntime(n={}){const e=n.session??new Session,t=new Set;let i={status:"initializing"},s,o,l=!1,u=!1,h,d=!1;const p=x=>{if(i=x,d||areSnapshotsEqual(s,i))return i;s=i;for(const A of t)A(i);return i},g=()=>p(snapshotFromSessionInfo(e.info)),y=()=>p({status:"anonymous"}),v=()=>p(snapshotFromSessionExpired(e.info)),S=(x,A)=>{const I=snapshotFromSessionError(A??x??"Solid session error",e.info);u&&(h=I),p(I)};e.events.on(EVENTS.LOGIN,g),e.events.on(EVENTS.SESSION_RESTORED,g),e.events.on(EVENTS.LOGOUT,y),e.events.on(EVENTS.SESSION_EXPIRED,v);const E=e.events;return E.on(EVENTS.ERROR,S),{fetch:e.fetch,getSnapshot(){return i},initialize(x={}){if(o)return o;if(l)return Promise.resolve(i);u=!0,h=void 0,p({status:"initializing"});const A=e.handleIncomingRedirect({restorePreviousSession:x.restorePreviousSession??!0}).then(I=>{const T=snapshotFromSessionInfo(I??e.info);return T.status==="anonymous"&&h?.status==="error"?h:(l=!0,p(T))}).catch(I=>p(snapshotFromSessionError(I,e.info))).finally(()=>{o===A&&(o=void 0,u=!1,h=void 0)});return o=A,o},handleIncomingRedirect(x){if(o)return o;u=!0,h=void 0,p({status:"initializing"});const A=e.handleIncomingRedirect(x).then(I=>{const T=snapshotFromSessionInfo(I??e.info);return T.status==="anonymous"&&h?.status==="error"?h:(l=!0,p(T))}).catch(I=>p(snapshotFromSessionError(I,e.info))).finally(()=>{o===A&&(o=void 0,u=!1,h=void 0)});return o=A,A},login(x){return e.login(x)},async logout(x){await e.logout(x),p({status:"anonymous"})},subscribe(x){return t.add(x),()=>{t.delete(x)}},dispose(){d=!0,t.clear(),e.events.off(EVENTS.LOGIN,g),e.events.off(EVENTS.SESSION_RESTORED,g),e.events.off(EVENTS.LOGOUT,y),e.events.off(EVENTS.SESSION_EXPIRED,v),E.off(EVENTS.ERROR,S)}}}const KEY_SEPARATOR="\0";function normalizeIdentityPart(n){const e=n.trim();try{return new URL(e).href}catch{return e}}function normalizePodUrl(n){if(typeof n!="string"||n.trim()==="")throw new TypeError("podUrl must be a non-empty absolute URL");let e;try{e=new URL(n.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(n,e){return`${normalizeIdentityPart(n)}${KEY_SEPARATOR}${normalizeIdentityPart(e)}`}function nextGeneration(n,e){const t=(n.get(e)??0)+1;return n.set(e,t),t}function createAbortedOpenError(){const n=new Error("Pod open aborted because the runtime identity changed");return n.name="AbortError",n}function createPodRuntime(n){const{adapter:e}=n,t=new Map,i=new Map,s=new Map,o=new Map,l=new Map,u=new Map,h=(g,y)=>{const v=normalizeIdentityPart(g);if(y!==void 0){const x=normalizePodUrl(y),A=compositeKey(g,x);nextGeneration(u,A),o.get(A)?.controller.abort(),o.delete(A),i.delete(A);const I=t.get(v);I&&compositeKey(I.webId,I.podUrl)===A&&t.delete(v);return}nextGeneration(l,v),s.get(v)?.controller.abort(),s.delete(v);const S=t.get(v);S&&i.delete(compositeKey(S.webId,S.podUrl)),t.delete(v);const E=`${v}${KEY_SEPARATOR}`;for(const x of[...i.keys()])x.startsWith(E)&&i.delete(x);for(const[x,A]of[...o.entries()])x.startsWith(E)&&(nextGeneration(u,x),A.controller.abort(),o.delete(x))},d=g=>{if(!g){t.clear(),i.clear();for(const y of s.values())y.controller.abort();for(const y of o.values())y.controller.abort();s.clear(),o.clear();for(const y of l.keys())nextGeneration(l,y);for(const y of u.keys())nextGeneration(u,y);return}if(typeof g=="string"){h(g);return}h(g.webId,g.podUrl)};return{open(g){const y=normalizeIdentityPart(g.webId),v=g.podUrl===void 0?void 0:normalizePodUrl(g.podUrl);if(v!==void 0){const V=compositeKey(g.webId,v),B=i.get(V);if(B)return Promise.resolve(B);const Y=o.get(V);if(Y)return Y.promise;const _e=u.get(V)??0;u.set(V,_e);const j=new AbortController,ee=()=>!j.signal.aborted&&(u.get(V)??0)===_e,me=()=>{if(!ee())throw createAbortedOpenError()},te=p({webId:g.webId,podUrl:v,fetch:g.fetch,signal:j.signal,isCurrent:ee,assertCurrent:me});o.set(V,{generation:_e,promise:te,controller:j});const Ce=()=>{const Oe=o.get(V);Oe?.generation===_e&&Oe.promise===te&&o.delete(V)};return te.then(Ce,Ce),te}const S=t.get(y);if(S)return Promise.resolve(S);const E=s.get(y);if(E)return E.promise;const x=l.get(y)??0;l.set(y,x);const A=new AbortController,I=()=>!A.signal.aborted&&(l.get(y)??0)===x,T=()=>{if(!I())throw createAbortedOpenError()},F=(async()=>{const V=await e.discoverPod({webId:g.webId,fetch:g.fetch,signal:A.signal,isCurrent:I});return T(),p({webId:g.webId,podUrl:normalizePodUrl(V),fetch:g.fetch,signal:A.signal,isCurrent:I,assertCurrent:T,generation:x,webIdKey:y,discovered:!0})})();s.set(y,{generation:x,promise:F,controller:A});const P=()=>{const V=s.get(y);V?.generation===x&&V.promise===F&&s.delete(y)};return F.then(P,P),F},clear:d,dispose(){d()}};async function p(g){const y=compositeKey(g.webId,g.podUrl),v=i.get(y);if(v)return g.discovered&&g.webIdKey&&g.isCurrent()&&t.set(g.webIdKey,v),v;const S=await e.openDatabase({webId:g.webId,podUrl:g.podUrl,fetch:g.fetch,signal:g.signal,isCurrent:g.isCurrent});g.assertCurrent(),await e.hydrateCollections({webId:g.webId,podUrl:g.podUrl,database:S,signal:g.signal,isCurrent:g.isCurrent}),g.assertCurrent();const E={webId:g.webId,podUrl:g.podUrl,database:S,collections:"ready"};return g.isCurrent()&&(i.set(y,E),g.discovered&&g.webIdKey&&t.set(g.webIdKey,E)),E}}const SolidRuntimeContext=reactExports.createContext(null);function SolidRuntimeProvider({value:n,children:e}){return reactExports.createElement(SolidRuntimeContext.Provider,{value:n},e)}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(n,e){if(!n||typeof n.url!="string"||n.url.trim()==="")throw new TypeError(`${e}.url must be a non-empty absolute URL`);if(typeof n.label!="string")throw new TypeError(`${e}.label must be a string`);let t;try{t=new URL(n.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:n.label}}function normalizeStorageBinding(n){if(!n||typeof n.storageUrl!="string"||n.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");if(typeof n.webId!="string"||n.webId.trim()==="")throw new TypeError("selectedStorage.webId must be a non-empty identifier URL");let e;try{e=new URL(n.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:n.webId,...n.label===void 0?{}:{label:n.label}}}function ensureEnum(n,e,t){if(!e.includes(n))throw new TypeError(`${t} has an unsupported value`);return n}function normalizeWebIdLoginRoute(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("route.id must be a non-empty opaque identifier");if(typeof n.label!="string")throw new TypeError("route.label must be a string");return{id:n.id.trim(),label:n.label,...n.description===void 0?{}:{description:n.description},...n.badge===void 0?{}:{badge:{label:n.badge.label,tone:ensureEnum(n.badge.tone,["neutral","primary","success","warning","danger"],"route.badge.tone")}},identityProvider:normalizeEndpoint(n.identityProvider,"route.identityProvider"),...n.storageProvider===void 0?{}:{storageProvider:normalizeEndpoint(n.storageProvider,"route.storageProvider")},availability:ensureEnum(n.availability,["ready","starting","unavailable"],"route.availability"),...n.unavailableReason===void 0?{}:{unavailableReason:n.unavailableReason}}}function decodeForValidation$1(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}function matchesAllowedPrefix(n,e){return e.some(t=>{if(t==="/")return n.startsWith("/");const i=t.endsWith("/")?t.slice(0,-1):t;return n===i||n.startsWith(`${i}/`)})}function normalizeApplicationReturnTo(n,e){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const t=n.trim(),i=decodeForValidation$1(t),s=i.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||i.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(i)||i.startsWith("//")||s.split("/").some(o=>o==="..")||!matchesAllowedPrefix(s,e))throw new TypeError("returnTo must be a safe path within the application allow-list");return t}function normalizeWebIdLoginTransaction(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("transaction.id must be a non-empty opaque identifier");const e=n.authorizationParameters===void 0?void 0:{...n.authorizationParameters};if(e){for(const i of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(i.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${i}`)}const t=n.prompt===void 0?void 0:ensureEnum(n.prompt,["login","consent","select_account"],"transaction.prompt");return{id:n.id,route:normalizeWebIdLoginRoute(n.route),...n.selectedStorage===void 0?{}:{selectedStorage:normalizeStorageBinding(n.selectedStorage)},authorizationSurface:ensureEnum(n.authorizationSurface,["redirect","popup","embedded","external"],"transaction.authorizationSurface"),...t===void 0?{}:{prompt:t},discovery:ensureEnum(n.discovery,["standard","strict"],"transaction.discovery"),...e===void 0?{}:{authorizationParameters:e},...n.returnTo===void 0?{}:{returnTo:normalizeApplicationReturnTo(n.returnTo,["/"])}}}const SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER="x-xpod-canonical-url",SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER="x-xpod-canonical-origin",SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER="x-xpod-canonical-host",SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER="x-xpod-local-route-url";async function discoverSolidLocalRoute(n){let e;try{e=await n.fetch.call(globalThis,n.statusUrl??"/provision/status",{credentials:"include",headers:{accept:"application/json"}})}catch{return}if(!e?.ok)return;const t=await e.json().catch(()=>{});if(typeof t?.publicUrl=="string")try{return normalizeRoute({canonicalBaseUrl:t.publicUrl,localBaseUrl:n.localBaseUrl})}catch{return}}function resolveSolidLocalRouteUrl(n,e){let t;try{t=n instanceof URL?new URL(n.href):new URL(n)}catch{return}const i=e.map(normalizeRoute).filter(s=>isInsideBase(t,s.canonicalBaseUrl)).sort((s,o)=>o.canonicalBaseUrl.length-s.canonicalBaseUrl.length)[0];return i?replaceBase(t,i):void 0}function createSolidLocalRouteFetch(n){return async(e,t)=>{const i=requestUrl(e);if(!i)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const s=n.routes(),o=resolveSolidLocalRouteUrl(i,s);if(!o)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const l=routedHeaders(e,t,i,o);let u;if(e instanceof Request){const d=new Request(new Request(o,e),{headers:l});u=t===void 0?await n.fetch.call(globalThis,d):await n.fetch.call(globalThis,d,{...t,headers:l})}else u=await n.fetch.call(globalThis,o,{...t,headers:l});const h=resolveSolidLocalRouteUrl(u.url,s.map(d=>({canonicalBaseUrl:d.localBaseUrl,localBaseUrl:d.canonicalBaseUrl})));return h?withResponseUrl(u,h.href):u}}function withResponseUrl(n,e){const t=n.clone.bind(n);return Object.defineProperties(n,{url:{value:e,configurable:!0},clone:{value:()=>withResponseUrl(t(),e),configurable:!0}}),n}function requestUrl(n){if(n instanceof Request)return new URL(n.url);try{return new URL(String(n))}catch{return}}function normalizeRoute(n){return{canonicalBaseUrl:normalizeBaseUrl(n.canonicalBaseUrl),localBaseUrl:normalizeBaseUrl(n.localBaseUrl)}}function normalizeBaseUrl(n){const e=new URL(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("Solid local routes must use http or https");return e.search="",e.hash="",e.href.endsWith("/")?e.href:`${e.href}/`}function isInsideBase(n,e){const t=new URL(e);return n.origin===t.origin&&n.pathname.startsWith(t.pathname)}function replaceBase(n,e){const t=new URL(e.canonicalBaseUrl),i=new URL(e.localBaseUrl),s=n.pathname.slice(t.pathname.length),o=new URL(s,i);return o.search=n.search,o.hash=n.hash,o}function routedHeaders(n,e,t,i){const s=n instanceof Request?n:void 0,o=new Headers(s?.headers??void 0);return new Headers(e?.headers??void 0).forEach((l,u)=>o.set(u,l)),o.set(SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER,t.toString()),o.set(SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER,t.origin),o.set(SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER,t.host),o.set(SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER,i.toString()),o}SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),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),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(n,e){return n&&n.length>0?n:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(n){return taskDir(n)??runDir(n)??deliveryDir(n)??issueDir(n)??threadDir(n)??chatDir(n)??aboutDir(n)}function chatDir(n){const e=typeof n?.chat=="string"?n.chat:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return i?.[1]?`chat/${i[1]}`:null}function threadDir(n){const e=typeof n?.thread=="string"?n.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(n){const e=typeof n?.task=="string"?n.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const i=t.match(/^task\/index\.ttl#([^#/]+)$/);if(i?.[1])return`task/${i[1]}`;const s=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return s?.[1]?`task/${s[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`issues/${i[1]}`:null}function deliveryDir(n){const e=typeof n?.delivery=="string"?n.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(n){const e=typeof n?.run=="string"?n.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(n){const e=typeof n?.about=="string"?n.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(n,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(n,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(n,e){return e===void 0?void 0:eq(exactFilterColumns[n],e)}function messageListFilter(n){if(!n)return;const e=[exactFilter$1("parent",n.parent),exactFilter$1("chat",n.chat),exactFilter$1("thread",n.thread),exactFilter$1("maker",n.maker),exactFilter$1("role",n.role),exactFilter$1("status",n.status),exactFilter$1("toolName",n.toolName),exactFilter$1("toolCallId",n.toolCallId),exactFilter$1("coordinationId",n.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>messageListFilter(n)});function chatProjectMemoryResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(n=>n?chatProjectMemoryResourceId(n):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:n})=>n?.workspace?eq(chatProjectContextResource.workspace,n.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>n?.workspace?eq(chatProjectMemoryResource.workspace,n.workspace):void 0});function conversationShareResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(n=>n?conversationShareResourceId(n):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>n?.thread?eq(conversationShareResource.thread,n.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((n,e)=>{const t=resourceKey(n,"report"),i=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${i}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(n){n.UNKNOWN="unknown",n.MAIN_TEXT="main_text",n.THINKING="thinking",n.IMAGE="image",n.CODE="code",n.TOOL="tool",n.TOOL_APPROVAL="tool_approval",n.TASK_PROGRESS="task_progress",n.FILE="file",n.ERROR="error",n.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(n){n.PENDING="pending",n.PROCESSING="processing",n.STREAMING="streaming",n.SUCCESS="success",n.ERROR="error",n.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$1.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(n,e,t){const{rdfType:i,sourceModule:s,extractor:o}=e,l=t["@id"]||t.id;if(!l){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const u=o.getTitle(t),h={id:crypto.randomUUID(),targetType:i,target:l,title:u,snapshotContent:o.getContent?.(t),snapshotAuthor:o.getAuthor?.(t),sourceModule:s,searchText:o.getSearchText?.(t)??u,snapshotMeta:o.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(d){console.error("[StarredSync] Failed to create favorite:",d)}}async function deleteFavorite(n,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(n){return{afterUpdate:async(e,t,i)=>{if(!("starred"in i))return;const s=t.starred,o=t["@id"]||t.id;s?await createFavorite(e,n,t):await deleteFavorite(e,o)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:n=>n.title||"未命名对话",getContent:n=>n.lastMessagePreview},threadSnapshotExtractor={getTitle:n=>n.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(n,e,t){return t===void 0?void 0:eq(n[e],t)}function combineFilters(n){const e=n.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(n){if(n)return combineFilters([exactFilter(candidateExactFilterColumns,"source",n.source),exactFilter(candidateExactFilterColumns,"suggestedType",n.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",n.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",n.status),exactFilter(candidateExactFilterColumns,"chat",n.chat),exactFilter(candidateExactFilterColumns,"thread",n.thread),exactFilter(candidateExactFilterColumns,"task",n.task),exactFilter(candidateExactFilterColumns,"run",n.run)])}function captureEventListFilter(n){if(n)return combineFilters([exactFilter(eventExactFilterColumns,"source",n.source),exactFilter(eventExactFilterColumns,"captureCandidate",n.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",n.targetResource),exactFilter(eventExactFilterColumns,"decision",n.decision),exactFilter(eventExactFilterColumns,"approval",n.approval),exactFilter(eventExactFilterColumns,"inputRequest",n.inputRequest),exactFilter(eventExactFilterColumns,"chat",n.chat),exactFilter(eventExactFilterColumns,"thread",n.thread),exactFilter(eventExactFilterColumns,"task",n.task),exactFilter(eventExactFilterColumns,"run",n.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureCandidateListFilter(n)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureEventListFilter(n)});podTable("settings",{id:id("id").default((n,e)=>{const t=typeof e?.key=="string"?e.key:n;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const o={};for(const l of s)o[l]=l;return o},n.getValidEnumValues=s=>{const o=n.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of o)l[u]=s[u];return n.objectValues(l)},n.objectValues=s=>n.objectKeys(s).map(function(o){return s[o]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&o.push(l);return o},n.find=(s,o)=>{for(const l of s)if(o(l))return l},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function i(s,o=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(o)}n.joinValues=i,n.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(util||(util={}));var objectUtil;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=n=>{switch(typeof n){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(n)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(n)?ZodParsedType.array:n===null?ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(o){return o.message},i={_errors:[]},s=o=>{for(const l of o.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let u=i,h=0;for(;h<l.path.length;){const d=l.path[h];h===l.path.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(l))):u[d]=u[d]||{_errors:[]},u=u[d],h++}}};return s(this),i}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];t[o]=t[o]||[],t[o].push(e(s))}else i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=n=>new ZodError(n);const errorMap=(n,e)=>{let t;switch(n.code){case ZodIssueCode.invalid_type:n.received===ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(n.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(n.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(n.options)}, received '${n.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(n)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,o=[...t,...s.path||[]],l={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let u="";const h=i.filter(d=>!!d).slice().reverse();for(const d of h)u=d(l,{data:e,defaultError:u}).message;return{...s,path:o,message:u}};function addIssueToContext(n,e){const t=getErrorMap(),i=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(s=>!!s)});n.common.issues.push(i)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const o=await s.key,l=await s.value;i.push({key:o,value:l})}return ParseStatus.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:o,value:l}=s;if(o.status==="aborted"||l.status==="aborted")return INVALID;o.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(i[o.value]=l.value)}return{status:e.value,value:i}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=n=>({status:"dirty",value:n}),OK=n=>({status:"valid",value:n}),isAborted=n=>n.status==="aborted",isDirty=n=>n.status==="dirty",isValid=n=>n.status==="valid",isAsync=n=>typeof Promise<"u"&&n instanceof Promise;var errorUtil;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(n,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(n.common.issues);return this._error=t,this._error}}};function processCreateParams(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{const{message:h}=n;return l.code==="invalid_enum_value"?{message:h??u.defaultError}:typeof u.data>"u"?{message:h??i??u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:h??t??u.defaultError}},description:s}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parseSync({data:e,path:i.path,parent:i});return handleResult(i,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return isValid(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>isValid(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parse({data:e,path:i.path,parent:i}),o=await(isAsync(s)?s:Promise.resolve(s));return handleResult(i,o)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const l=e(s),u=()=>o.addIssue({code:ZodIssueCode.custom,...i(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(h=>h?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(n){return new RegExp(`^${timeRegexSource(n)}$`)}function datetimeRegex(n){let e=`${dateRegexSource}T${timeRegexSource(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(n,e){return!!((e==="v4"||!e)&&ipv4Regex.test(n)||(e==="v6"||!e)&&ipv6Regex.test(n))}function isValidJWT(n,e){if(!jwtRegex.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function isValidCidr(n,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(n)||(e==="v6"||!e)&&ipv6CidrRegex.test(n))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:o.parsedType}),INVALID}const i=new ParseStatus;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),i.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),i.dirty());else if(o.kind==="length"){const l=e.data.length>o.value,u=e.data.length<o.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):u&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),i.dirty())}else if(o.kind==="email")emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="uuid")uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="nanoid")nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="cuid")cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="cuid2")cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="ulid")ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),i.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),i.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),i.dirty()):o.kind==="datetime"?datetimeRegex(o).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),i.dirty()):o.kind==="date"?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),i.dirty()):o.kind==="time"?timeRegex(o).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),i.dirty()):o.kind==="duration"?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="ip"?isValidIP(e.data,o.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="jwt"?isValidJWT(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="cidr"?isValidCidr(e.data,o.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="base64"?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="base64url"?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(i)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=n=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:n?.coerce??!1,...processCreateParams(n)});function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,o=Number.parseInt(n.toFixed(s).replace(".","")),l=Number.parseInt(e.toFixed(s).replace(".",""));return o%l/10**s}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:o.parsedType}),INVALID}let i;const s=new ParseStatus;for(const o of this._def.checks)o.kind==="int"?util.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?floatSafeRemainder(e.data,o.value)!==0&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_finite,message:o.message}),s.dirty()):util.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=n=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let i;const s=new ParseStatus;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):util.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=n=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:n?.coerce??!1,...processCreateParams(n)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:i.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=n=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:o.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_date}),INVALID}const i=new ParseStatus;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),i.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),i.dirty()):util.assertNever(o);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=n=>new ZodDate({checks:[],coerce:n?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(n)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:i.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=n=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(n)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:i.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=n=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(n)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:i.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=n=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(n)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=n=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(n)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=n=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(n)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=n=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(n)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:i.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=n=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(n)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(s.exactLength!==null){const l=t.data.length>s.exactLength.value,u=t.data.length<s.exactLength.value;(l||u)&&(addIssueToContext(t,{code:l?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,u)=>s.type._parseAsync(new ParseInputLazyPath(t,l,t.path,u)))).then(l=>ParseStatus.mergeArray(i,l));const o=[...t.data].map((l,u)=>s.type._parseSync(new ParseInputLazyPath(t,l,t.path,u)));return ParseStatus.mergeArray(i,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(n,e)=>new ZodArray({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(n){if(n instanceof ZodObject){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=ZodOptional.create(deepPartialify(i))}return new ZodObject({...n._def,shape:()=>e})}else return n instanceof ZodArray?new ZodArray({...n._def,type:deepPartialify(n.element)}):n instanceof ZodOptional?ZodOptional.create(deepPartialify(n.unwrap())):n instanceof ZodNullable?ZodNullable.create(deepPartialify(n.unwrap())):n instanceof ZodTuple?ZodTuple.create(n.items.map(e=>deepPartialify(e))):n}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:i,ctx:s}=this._processInputParams(e),{shape:o,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in s.data)l.includes(d)||u.push(d);const h=[];for(const d of l){const p=o[d],g=s.data[d];h.push({key:{status:"valid",value:d},value:p._parse(new ParseInputLazyPath(s,g,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ZodNever){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of u)h.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")u.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:u}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of u){const g=s.data[p];h.push({key:{status:"valid",value:p},value:d._parse(new ParseInputLazyPath(s,g,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of h){const g=await p.key,y=await p.value;d.push({key:g,value:y,alwaysSet:p.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(i,d)):ParseStatus.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const s=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const i of util.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const i of util.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const i of util.objectKeys(this.shape)){const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const i of util.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let o=this.shape[i];for(;o instanceof ZodOptional;)o=o._def.innerType;t[i]=o}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(n,e)=>new ZodObject({shape:n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(o){for(const u of o)if(u.result.status==="valid")return u.result;for(const u of o)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;const l=o.map(u=>new ZodError(u.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:l}),INVALID}if(t.common.async)return Promise.all(i.map(async o=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(s);{let o;const l=[];for(const h of i){const d={...t,common:{...t.common,issues:[]},parent:null},p=h._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!o&&(o={result:p,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const u=l.map(h=>new ZodError(h));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:u}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(n,e)=>new ZodUnion({options:n,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(n,e){const t=getParsedType(n),i=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&i===ZodParsedType.object){const s=util.objectKeys(e),o=util.objectKeys(n).filter(u=>s.indexOf(u)!==-1),l={...n,...e};for(const u of o){const h=mergeValues(n[u],e[u]);if(!h.valid)return{valid:!1};l[u]=h.data}return{valid:!0,data:l}}else if(t===ZodParsedType.array&&i===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<n.length;o++){const l=n[o],u=e[o],h=mergeValues(l,u);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return t===ZodParsedType.date&&i===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(o,l)=>{if(isAborted(o)||isAborted(l))return INVALID;const u=mergeValues(o.value,l.value);return u.valid?((isDirty(o)||isDirty(l))&&t.dirty(),{status:t.value,value:u.data}):(addIssueToContext(i,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([o,l])=>s(o,l)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ZodIntersection.create=(n,e,t)=>new ZodIntersection({left:n,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.array)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:i.parsedType}),INVALID;if(i.data.length<this._def.items.length)return addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&i.data.length>this._def.items.length&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...i.data].map((l,u)=>{const h=this._def.items[u]||this._def.rest;return h?h._parse(new ParseInputLazyPath(i,l,i.path,u)):null}).filter(l=>!!l);return i.common.async?Promise.all(o).then(l=>ParseStatus.mergeArray(t,l)):ParseStatus.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:n,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.object)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:i.parsedType}),INVALID;const s=[],o=this._def.keyType,l=this._def.valueType;for(const u in i.data)s.push({key:o._parse(new ParseInputLazyPath(i,u,i.path,u)),value:l._parse(new ParseInputLazyPath(i,i.data[u],i.path,u)),alwaysSet:u in i.data});return i.common.async?ParseStatus.mergeObjectAsync(t,s):ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(i)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.map)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:i.parsedType}),INVALID;const s=this._def.keyType,o=this._def.valueType,l=[...i.data.entries()].map(([u,h],d)=>({key:s._parse(new ParseInputLazyPath(i,u,i.path,[d,"key"])),value:o._parse(new ParseInputLazyPath(i,h,i.path,[d,"value"]))}));if(i.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const h of l){const d=await h.key,p=await h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}})}else{const u=new Map;for(const h of l){const d=h.key,p=h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}}}}ZodMap.create=(n,e,t)=>new ZodMap({valueType:e,keyType:n,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.set)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:i.parsedType}),INVALID;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function l(h){const d=new Set;for(const p of h){if(p.status==="aborted")return INVALID;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const u=[...i.data.values()].map((h,d)=>o._parse(new ParseInputLazyPath(i,h,i.path,d)));return i.common.async?Promise.all(u).then(h=>l(h)):l(u)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(n,e)=>new ZodSet({valueType:n,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(n,e)=>new ZodLazy({getter:n,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(n,e)=>new ZodLiteral({value:n,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(n,e){return new ZodEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{expected:util.joinValues(i),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==ZodParsedType.string&&i.parsedType!==ZodParsedType.number){const s=util.objectValues(t);return addIssueToContext(i,{expected:util.joinValues(s),received:i.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=util.objectValues(t);return addIssueToContext(i,{received:i.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(n,e)=>new ZodNativeEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const i=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(n,e)=>new ZodPromise({type:n,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:l=>{addIssueToContext(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const l=s.transform(i.data,o);if(i.common.async)return Promise.resolve(l).then(async u=>{if(t.value==="aborted")return INVALID;const h=await this._def.schema._parseAsync({data:u,path:i.path,parent:i});return h.status==="aborted"?INVALID:h.status==="dirty"||t.value==="dirty"?DIRTY(h.value):h});{if(t.value==="aborted")return INVALID;const u=this._def.schema._parseSync({data:l,path:i.path,parent:i});return u.status==="aborted"?INVALID:u.status==="dirty"||t.value==="dirty"?DIRTY(u.value):u}}if(s.type==="refinement"){const l=u=>{const h=s.refinement(u,o);if(i.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(i.common.async===!1){const u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value).then(()=>({status:t.value,value:u.value}))))}if(s.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!isValid(l))return INVALID;const u=s.transform(l.value,o);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>isValid(l)?Promise.resolve(s.transform(l.value,o)).then(u=>({status:t.value,value:u})):INVALID);util.assertNever(s)}}ZodEffects.create=(n,e,t)=>new ZodEffects({schema:n,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(n,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:n},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(n,e)=>new ZodOptional({innerType:n,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(n,e)=>new ZodNullable({innerType:n,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===ZodParsedType.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(n,e)=>new ZodDefault({innerType:n,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return isAsync(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(n,e)=>new ZodCatch({innerType:n,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:i.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=n=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(n)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?INVALID:o.status==="dirty"?(t.dirty(),DIRTY(o.value)):this._def.out._parseAsync({data:o.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),i=s=>(isValid(s)&&(s.value=Object.freeze(s.value)),s);return isAsync(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(n,e)=>new ZodReadonly({innerType:n,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel};new Set(AI_MODEL_MODALITIES);new Set(AI_MODEL_CAPABILITIES);new Set(Object.values(AI_MODEL_CAPABILITY));new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(n){const e=n;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const i of Object.values(t??{}))typeof i.options?.predicate=="string"&&(i.getPredicate=()=>i.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(n=>[n.id,n]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(n){return n.trim().toLowerCase()}function normalizeAIConfigResourceId(n){if(!n)return"";const e=n.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),i=t.split("/").pop()||t;return i.endsWith(".ttl")?i.slice(0,-4):i}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[i,...s]=t.split("/");return s.length===0||!e?t:normalizeAIConfigProviderId(i)===normalizeAIConfigProviderId(e)?s.join("/"):t}function normalizeAIConfigProviderId(n){const e=normalizeText(normalizeAIConfigResourceId(n));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(n,e){return aiConfigResourceRefToModelId(n,e)}function aiConfigModelRef(n,e){if(e===void 0)return normalizeAIConfigResourceId(n);const t=normalizeAIConfigProviderId(n),i=normalizeAIConfigModelStorageId(e,t);return t&&i?`/settings/providers/${t}.ttl#${i}`:i}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:"Local credential id."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},providerId:{type:"string",predicate:UDFS.provider,required:!0,description:"Provider identifier such as openai or cloudflare."},secretType:{type:"string",predicate:UDFS.secretType,required:!0,description:"Provider-specific secret kind such as api-key or tunnel-token."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},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."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."}},uniqueBy:["service","providerId","secretType"],writableFields:["label","apiKey","authMode","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","status"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{service:"infra",providerId:"cloudflare",secretType:"tunnel-token"}},{request:"保存 OpenAI API key",match:{service:"ai",providerId:"openai",secretType:"api-key"}}]},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,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"}}]},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,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,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,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(n="/.data/"){return{base:n,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},run:{type:"uri",predicate:UDFS.run,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,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,description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$1.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,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,description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,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,description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,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,description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,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,description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,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,description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,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,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,description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,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,description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,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,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,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,description:"Related issue."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,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,description:"Related issue."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,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,description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,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,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(n=officialPodModelDescriptors){const e=new Map(n.map(t=>[t.uri,t]));return{list(t={}){return n.filter(i=>!(t.source&&i.source!==t.source||t.resourceKind&&i.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(n=createPodModelDescriptorRegistry()){const e=(t={})=>{const i=t.uri??t.schemaUri;if(!i)return n.list();const s=n.describe(i);return s?[s]:[]};return{list:n.list,describe(t){const i=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return n.describe(i)},classes(t={}){return e(t).map(i=>({schemaUri:i.uri,resourceKind:i.resourceKind,class:i.class,namespace:i.namespace,source:i.source,trustLevel:i.trustLevel,description:i.description}))},search(t){const i=normalizeSearchTerms(t.query);return i.length===0?[]:n.list({source:t.source,resourceKind:t.resourceKind}).map(s=>scoreDescriptorSearch(s,i)).filter(s=>s!==null).sort((s,o)=>o.score-s.score||s.uri.localeCompare(o.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(i=>Object.entries(i.fields).filter(([s])=>!t.field||s===t.field).map(([s,o])=>({schemaUri:i.uri,field:s,predicate:o.predicate,type:o.type,required:!!o.required,secret:!!o.secret,array:!!o.array,description:o.description})))}}}function normalizeSearchTerms(n){return n.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(n,e){const t=new Set;let i=0;const s=(o,l,u)=>{if(!l)return;const h=l.toLowerCase();for(const d of e)h.includes(d)&&(t.add(o),i+=u)};s("uri",n.uri,10),s("class",n.class,10),s("namespace",n.namespace,4),s("resourceKind",n.resourceKind,8),s("description",n.description,4),s("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[o,l]of Object.entries(n.fields))s(`field:${o}`,o,6),s(`predicate:${o}`,l.predicate,6),s(`description:${o}`,l.description,3);for(const o of n.examples){s("example",o.request,3);for(const[l,u]of Object.entries(o.match))s(`example:${l}`,String(u),3)}return i<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:i,matchedFields:[...t].sort()}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(n,e){const t=await n(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const i=t.headers?.get?.("content-type")??"",s=await t.text().catch(()=>"");if(!s)return[];if(i.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(s)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(s))}function extractStorageUrlsFromTurtle(n){return Array.from(n.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(n){const e=new Set,t=new WeakSet,i=(s,o=!1)=>{if(typeof s=="string"){o&&e.add(s);return}if(!(!s||typeof s!="object")&&!t.has(s)){if(t.add(s),Array.isArray(s)){for(const l of s)i(l,o);return}for(const[l,u]of Object.entries(s)){const h=SOLID_STORAGE_KEYS.has(l);if(o&&l==="@id"){i(u,!0);continue}i(u,o||h)}}};return i(n),Array.from(e)}function normalizeStorageUrl(n){try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}function uniqueNormalizedStorageUrls(n){const e=new Set;for(const t of n){const i=normalizeStorageUrl(t);i&&e.add(i)}return Array.from(e)}function ensureTrailingSlash(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections"];function normalizeXpodReturnPath(n){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const e=n.trim(),t=decodeForValidation(e),i=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||i.split("/").some(s=>s==="..")||!XPOD_RETURN_PATH_PREFIXES.some(s=>i===s||i.startsWith(`${s}/`)))throw new TypeError("returnTo must be a safe path within the application allow-list");return e}function decodeForValidation(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}const XPOD_LOGIN_ROUTE_ID="xpod-current-origin";function createXpodLoginRoute(n=typeof window>"u"?"http://localhost":window.location){const e=toLocation(n),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(n){return normalizeXpodReturnPath(n)}function assertXpodLoginRoute(n,e){const t=normalizeWebIdLoginRoute(n),i=new URL(e).origin,s=new URL(t.identityProvider.url).origin,o=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||s!==i||o!==i||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:i},storageProvider:t.storageProvider?{...t.storageProvider,url:i}:void 0}}function toLocation(n){if(typeof n=="string"){const e=new URL(n,typeof window>"u"?void 0:window.location.href);return{origin:e.origin,host:e.host,href:e.href}}return n instanceof URL?{origin:n.origin,host:n.host,href:n.href}:{origin:n.origin,host:n.host,href:n.href}}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_SOLID_SESSION_ID_STORAGE_KEY="xpod.solid.sessionId",INRUPT_CURRENT_SESSION_STORAGE_KEY="solidClientAuthn:currentSession",INRUPT_SESSION_STORAGE_KEY_PREFIX="solidClientAuthenticationUser:",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",INRUPT_DYNAMIC_CLIENT_FIELDS=["clientId","clientSecret","clientName","clientType","expiresAt","idTokenSignedResponseAlg"],INRUPT_STORAGE_NAMESPACES=["secure","insecure"],XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(n,e,t){return n.status==="initializing"?{status:"loading",issuer:t}:n.status==="anonymous"?{status:"anonymous",issuer:t}:n.status==="expired"?{status:"expired",webId:n.webId,issuer:t}:n.status==="error"?{status:"error",webId:n.webId,error:n.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:n.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:n,fetch:e}){const t=await fetchProfileStorageUrls(e,n);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[];const i=createSolidLocalRouteFetch({fetch:globalThis.fetch,routes:()=>t}),s=n.sessionFactory?.({fetch:i})??createInruptSession(e.sessionId,e.oidcSession,i);let o=readStoredOidcIssuer(e.issuer);const l=createSolidSessionRuntime({session:s}),u=l.handleIncomingRedirect,h=g=>{const y=readIssuerFromSessionInfo(s.info)??o??readStoredOidcIssuer(e.issuer),v=o??expectedSameOriginIssuer(y);return g.status==="authenticated"&&isCurrentXpodSessionSnapshot(g,y,v)&&rememberInruptCurrentSession(e),g},d={...l,initialize:async g=>h(await l.initialize(g)),...u?{handleIncomingRedirect:async g=>h(await u(g))}:{}},p=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:g,fetch:y})=>drizzle({get info(){return s.info},fetch:y},{podUrl:g,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:d,pod:p,storage:e,getIssuer:()=>readIssuerFromSessionInfo(s.info)??o??readStoredOidcIssuer(e.issuer),getExpectedIssuer:()=>o??expectedSameOriginIssuer(readIssuerFromSessionInfo(s.info)),setIssuer:g=>{const y=normalizeXpodOidcIssuer(g);o=y,y&&writeStoredOidcIssuer(y,e.issuer)},setLocalPodRoute:g=>{t=g?[g,...["/api/","/v1/"].map(y=>({canonicalBaseUrl:new URL(y,g.canonicalBaseUrl).href,localBaseUrl:new URL(y,g.localBaseUrl).href}))]:[]}}}function createInruptSession(n=getOptionalPersistentStorage$1(),e=getOptionalPersistentStorage$1(),t=globalThis.fetch){let i;try{i=n?.getItem(XPOD_SOLID_SESSION_ID_STORAGE_KEY)??void 0,i||(i=globalThis.crypto?.randomUUID?.()??`xpod-${Date.now().toString(36)}`,n?.setItem(XPOD_SOLID_SESSION_ID_STORAGE_KEY,i))}catch{}const s=n??getOptionalPersistentStorage$1();for(const o of new Set([e,s].filter(Boolean)))migrateLegacyInruptSessionRecords(o);return e?new Session({secureStorage:toInruptStorage(e,"secure"),insecureStorage:toInruptStorage(s??e,"insecure"),fetch:t},i):new Session({fetch:t},i)}function toInruptStorage(n,e){const t=i=>e?inruptStorageKey(e,i):i;return{get:async i=>n.getItem(t(i))??void 0,set:async(i,s)=>{n.setItem(t(i),s)},delete:async i=>{n.removeItem(t(i))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}function migrateLegacyInruptSessionRecords(n){if(n)try{const e=storageKeys(n).filter(t=>t.startsWith(INRUPT_SESSION_STORAGE_KEY_PREFIX));for(const t of e){const i=n.getItem(t);if(i!==null){for(const s of INRUPT_STORAGE_NAMESPACES){const o=inruptStorageKey(s,t);n.getItem(o)===null&&n.setItem(o,i)}n.removeItem(t)}}}catch{}}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function clearCachedInruptDynamicClientRegistration(n){const e=n.oidcSession;if(!e)return;const t=storageKeys(e).filter(isInruptSessionStorageRecordKey);for(const i of t){const s=e.getItem(i);if(s)try{const o=JSON.parse(s);for(const l of INRUPT_DYNAMIC_CLIENT_FIELDS)delete o[l];e.setItem(i,JSON.stringify(o))}catch{e.removeItem(i)}}}function rememberInruptCurrentSession(n){try{const e=n.sessionId?.getItem(XPOD_SOLID_SESSION_ID_STORAGE_KEY);if(!e)return;getOptionalPersistentStorage$1()?.setItem(INRUPT_CURRENT_SESSION_STORAGE_KEY,e)}catch{}}function withXpodProvisionScope(n,e){const t=new URL(n);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(n,e){try{const t=await e("/provision/status",{headers:{Accept:"application/json"},credentials:"include"});if(t.ok){const i=await t.json(),s=normalizeXpodOidcIssuer(i.oidcIssuer);if(s)return{oidcIssuer:s,provisionCode:typeof i.provisionCode=="string"&&i.provisionCode.trim()?i.provisionCode.trim():void 0}}}catch{}return{oidcIssuer:normalizeXpodOidcIssuer(n)}}function isInruptSessionStorageRecordKey(n){return n.startsWith(INRUPT_SESSION_STORAGE_KEY_PREFIX)?!0:INRUPT_STORAGE_NAMESPACES.some(e=>n.startsWith(`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${e}:${INRUPT_SESSION_STORAGE_KEY_PREFIX}`))}function storageKeys(n){return Array.from({length:n.length},(e,t)=>n.key(t)).filter(e=>!!e)}function safeAuthError(n){return n.message==="Solid session expired"?n:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(n,e=typeof window>"u"?"http://localhost":window.location.origin){if(!n||typeof n!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(n),i=assertXpodLoginRoute(t.route,e),s=normalizeXpodReturnTo(t.returnTo);return{...t,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function useXpodSolidRuntimeContext(){const n=reactExports.useContext(XpodSolidRuntimeContext);if(!n)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return n}function readIssuerFromSessionInfo(n){const e=n.issuer??n.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(n){if(!(typeof n!="string"||!n.trim()))try{const e=new URL(n.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(n,e,t){if(n.status!=="authenticated")return!0;const i=normalizeXpodOidcIssuer(e),s=normalizeXpodOidcIssuer(t);return!i||!s||i!==s?!1:isHttpResourceUrl(n.webId)}function expectedSameOriginIssuer(n,e=typeof window>"u"?"http://localhost":window.location.origin){const t=normalizeXpodOidcIssuer(n);return t&&hasOrigin(t,e)?t:void 0}function hasOrigin(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function isHttpResourceUrl(n){try{const e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(n=getOptionalPersistentStorage$1()){try{return normalizeXpodOidcIssuer(n?.getItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY))}catch{return}}function clearStoredXpodOidcIssuer(n){try{n?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalPersistentStorage$1()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage$1()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(n,e=getOptionalPersistentStorage$1()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,n)}catch{}}function createXpodSolidRuntimeStoragePolicy(n={}){const e=getOptionalPersistentStorage$1();return{sessionId:n.sessionId??e,oidcSession:n.oidcSession??e,issuer:n.issuer??e,selectedStorage:n.selectedStorage??e}}function getOptionalPersistentStorage$1(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage$1(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}const useXpodSolidRuntime=useXpodSolidRuntimeContext,XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=normalizedUrl(n.webId),i=normalizedUrl(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),o=normalizedUrl(e.webId),l=normalizedUrl(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!o||!l||!u||t!==i||o!==l||t!==o||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,o=normalizedEmail(i.email),l=normalizedUrl(t.webId),u=normalizedUrl(s.webId),h=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!o||!l||!u||!h||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,h,e]);return{account:{...o?{email:o}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:h},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const o=normalizedUrl(s);return o&&new URL(o).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,o=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??o?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||o&&!rememberedXpodLoginMatchesActive(o,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??o?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??o?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,o,e.currentPod,t,s]),null}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function storeAccountSessionToken(n){n&&writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"}){return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:t.href}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const h=new URL(t,window.location.origin),d=new URL(n.trim(),h);if(d.origin===h.origin&&h.pathname.startsWith("/.account/")&&d.pathname.startsWith("/.account/")&&["http:","https:"].includes(d.protocol)&&!d.username&&!d.password)return d.href}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const h=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(h)return h.href}const o={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,o.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...o,fetch:async()=>l.clone()}):void 0;return u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin),u?resolveSolidLocalRouteUrl(s,[u])?.href:void 0}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[o,l]=reactExports.useState(!0),[u,h]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,y]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),x=g.status==="authenticated",A=o||g.status==="submitting",I=reactExports.useRef(x);reactExports.useEffect(()=>{let j=!0;return resolveXpodAccountIndex().then(ee=>{j&&t(ee)}),()=>{j=!1}},[]),reactExports.useEffect(()=>{I.current=x},[x]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,E.current+=1}),[]);const T=reactExports.useCallback(j=>S.current&&j===E.current,[]),F=reactExports.useCallback(async()=>{const j=new AbortController,ee=setTimeout(()=>j.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{if(!e)return!1;const me=await fetch(new URL("oidc/consent/",e),{headers:storedAccountTokenHeaders(),credentials:"include",signal:j.signal});return me.ok?!!(await me.json()).client:!1}catch{return!1}finally{clearTimeout(ee)}},[e]),P=reactExports.useCallback(async({exposeTransientError:j,generation:ee,confirmUnauthenticated:me})=>{if(!e)return"stale";try{const te=await fetch(e,{headers:storedAccountTokenHeaders(),credentials:"include"});if(!T(ee))return"stale";if(te.ok){const Ce=await te.json().catch(()=>({}));if(!T(ee))return"stale";const Oe=Ce.controls||{},ye=++v.current;p(!1),s(Oe),h(null);const qe=accountStateForControls(Oe);return I.current=qe.status==="authenticated",y(qe),Oe.account?.logout&&isAccountSpaPath()&&F().then(de=>{T(ee)&&ye===v.current&&p(de)}),"ok"}else{if(te.status===401||te.status===403)return me?(v.current+=1,clearAccountSessionToken(),I.current=!1,p(!1),s({}),y({status:"anonymous",mode:"login"}),h(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(te.status))return h(null),y(Oe=>Oe.status==="authenticated"?Oe:transientAccountState(j)),"transient-error";const Ce=`Failed to load account controls (Status: ${te.status})`;return h(Ce),y({status:"error",mode:"login",message:Ce}),"terminal-error"}}catch{return T(ee)?(v.current+=1,p(!1),h(null),y(te=>te.status==="authenticated"?te:transientAccountState(j)),"transient-error"):"stale"}},[F,e,T]),V=reactExports.useCallback(async()=>{const j=++E.current;for(let ee=0;ee<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;ee+=1){const me=ee===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,te=await P({exposeTransientError:me,generation:j});if(te==="unauthenticated")return!T(j)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!T(j))?"stale":P({exposeTransientError:!0,generation:j,confirmUnauthenticated:!0});if(te!=="transient-error")return te;if(!T(j)||!me&&(y(Ce=>Ce.status==="authenticated"?Ce:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[ee]),!T(j)))return"stale"}return"transient-error"},[P,T]);reactExports.useEffect(()=>{if(!e)return;let j=!0;return(async()=>(await V(),j&&S.current&&l(!1)))(),()=>{j=!1}},[V,e]);const B=reactExports.useCallback(async()=>{await V()},[V]),Y=reactExports.useCallback(async()=>{const j=i?.account?.logout,ee=await resolveHostedAccountControlUrl(j,fetch,e);let me=!!(j&&!ee);if(ee)try{const te=await fetch(ee,{method:"POST",headers:storedAccountTokenHeaders(),credentials:"include"});me=!te.ok&&te.status!==401&&te.status!==403}catch{me=!0}if(me){y({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}I.current=!1,clearAccountSessionToken(),p(!1),s({}),h(null),y({status:"anonymous",mode:"login"})},[i?.account?.logout,e]),_e=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:o,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:x,isAnonymous:()=>!I.current,authenticating:A,hasOidcPending:d,refetchControls:B,retry:B,logout:Y,accountState:g,identity:_e},children:n})}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX;if(!isLoopbackHostname$1(window.location.hostname))return new URL(LOCAL_ACCOUNT_INDEX,window.location.origin).href;try{const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(!e.ok)return new URL(LOCAL_ACCOUNT_INDEX,window.location.origin).href;const t=await e.json();if(t.managed===!0&&typeof t.oidcIssuer=="string"){const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return new URL(LOCAL_ACCOUNT_INDEX,i).href}}catch{}return new URL(LOCAL_ACCOUNT_INDEX,window.location.origin).href}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>{globalThis.xpodDesktop?.setWindowMode?.("workspace")},[]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const o=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:o,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}const XPOD_DEFAULT_RETURN_PATH="/dashboard/overview",canonicalRoutes={status:"/status/overview",network:"/network",aiConnections:"/ai-connections",aiConfig:"/ai-config/model-assignments",settings:"/settings/pod"},legacyProductRedirects={"/dashboard":canonicalRoutes.status,[XPOD_DEFAULT_RETURN_PATH]:canonicalRoutes.status,"/dashboard/network":canonicalRoutes.network,"/dashboard/models":canonicalRoutes.aiConnections,"/dashboard/pod":canonicalRoutes.settings,"/dashboard/services":canonicalRoutes.status,"/dashboard/settings":canonicalRoutes.settings,"/settings/models":canonicalRoutes.aiConnections,"/settings/ai-connections":canonicalRoutes.aiConnections,"/settings/ai-config":canonicalRoutes.aiConfig,"/settings/pod":canonicalRoutes.settings,"/settings/network":canonicalRoutes.network,"/settings/services":canonicalRoutes.status,"/settings/system":canonicalRoutes.settings};function canonicalProductPathname(n){return legacyProductRedirects[n]??n}const XPOD_LOGIN_TRANSACTION_VERSION=1,XPOD_LOGIN_TRANSACTION_PREFIX="xpod.auth.transaction.v1",XPOD_LOGIN_TRANSACTION_TTL_MS=600*1e3,XPOD_SELECTED_STORAGE_BINDING_VERSION=1,XPOD_SELECTED_STORAGE_BINDING_KEY="xpod.auth.selected-storage.v1";class XpodLoginTransactionError extends Error{code;constructor(e,t){super(t),this.name="XpodLoginTransactionError",this.code=e}}function readXpodSelectedStorage(n={}){return n.storage?readXpodSelectedStorageFrom(n.storage,n):readXpodSelectedStorageFrom(getOptionalPersistentStorage(),n)??readXpodSelectedStorageFrom(getOptionalSessionStorage(),n)}function readXpodSelectedStorageFrom(n,e){if(!n)return;const t=n.getItem(XPOD_SELECTED_STORAGE_BINDING_KEY);if(!t)return;const i=()=>n.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);let s;try{s=JSON.parse(t)}catch{i();return}if(!isStoredSelectedStorageBinding(s)){i();return}const o=e.now??(()=>Date.now());if(s.expiresAt<=o()){i();return}let l;try{l=normalizeSelectedStorageBinding(s.binding,s.storageRoot??new URL(e.origin??getWindowOrigin()).origin,s.storageRoot===void 0)}catch{i();return}if(e.webId!==void 0&&l.webId!==e.webId){i();return}return l}function clearXpodSelectedStorage(n={}){n.storage?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);try{getOptionalPersistentStorage()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY),getOptionalSessionStorage()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY)}catch{}}function createOpaqueTransactionId(){const n=globalThis.crypto;if(typeof n?.randomUUID=="function")return n.randomUUID();if(typeof n?.getRandomValues=="function"){const e=new Uint8Array(24);return n.getRandomValues(e),`xpod-${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}throw new XpodLoginTransactionError("storage_unavailable","Secure transaction id generation is unavailable")}function createXpodLoginTransactionStore(n={}){const e=n.storage??getSessionStorage(),t=new URL(n.origin??getWindowOrigin()).origin,i=n.now??(()=>Date.now()),s=n.ttlMs??XPOD_LOGIN_TRANSACTION_TTL_MS,o=n.prefix??XPOD_LOGIN_TRANSACTION_PREFIX,l=`${o}.active`,u=y=>`${o}.record.${y}`,h=y=>`${o}.consumed.${y}`,d=y=>{e.getItem(l)===y&&e.removeItem(l),e.removeItem(u(y))},p=(y,v=!0)=>{if(!isSafeTransactionId(y))throw new XpodLoginTransactionError("malformed","Transaction id is malformed");if(e.getItem(h(y))==="1")throw new XpodLoginTransactionError("consumed","Transaction has already been consumed");if(v&&e.getItem(l)!==y)throw new XpodLoginTransactionError("unknown","Transaction is not the active Xpod login transaction");const S=e.getItem(u(y));if(!S)throw v&&e.getItem(l)===y&&e.removeItem(l),new XpodLoginTransactionError("unknown","Xpod login transaction was not found");let E;try{E=JSON.parse(S)}catch{throw d(y),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}if(!isStoredTransaction(E)||E.transaction.id!==y)throw d(y),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed");if(E.expiresAt<=i())throw d(y),new XpodLoginTransactionError("expired","Xpod login transaction has expired");try{const x=normalizePublicTransaction({...E.transaction,authorizationSurface:"redirect",discovery:"strict"},t);return E.transaction={id:x.id,route:x.route,...x.returnTo===void 0?{}:{returnTo:x.returnTo},...x.selectedStorage===void 0?{}:{selectedStorage:x.selectedStorage}},E}catch(x){throw d(y),x instanceof XpodLoginTransactionError?x:new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}};return{begin:y=>{const v=e.getItem(l);if(v){try{p(v)}catch(T){if(!(T instanceof XpodLoginTransactionError&&(T.code==="expired"||T.code==="malformed"||T.code==="unknown")))throw T}if(e.getItem(l)===v)throw new XpodLoginTransactionError("already_active","An Xpod login transaction is already pending in this tab")}const S=isSafeTransactionId(y.id)?y.id:createOpaqueTransactionId(),E=normalizePublicTransaction({...y,id:S},t),x=i(),A=x+s,I={version:XPOD_LOGIN_TRANSACTION_VERSION,createdAt:x,expiresAt:A,transaction:{id:E.id,route:E.route,...E.returnTo===void 0?{}:{returnTo:E.returnTo},...E.selectedStorage===void 0?{}:{selectedStorage:E.selectedStorage}}};return e.setItem(u(E.id),JSON.stringify(I)),e.setItem(l,E.id),E},readSinglePending(){const y=e.getItem(l);if(y)return materialize(p(y).transaction)},updateSelectedStorage(y,v){const S=p(y),E=materialize(S.transaction),x=normalizeBinding(v,t,E.route.storageProvider?.url),A={...S,transaction:{...S.transaction,selectedStorage:x}};e.setItem(u(y),JSON.stringify(A))},consume(y){const v=p(y),S=materialize(v.transaction);return e.removeItem(l),e.removeItem(u(y)),e.setItem(h(y),"1"),S},cancel(y){p(y),e.removeItem(l),e.removeItem(u(y)),e.setItem(h(y),"1")}}}function normalizePublicTransaction(n,e){let t;try{t=normalizeWebIdLoginTransaction(n)}catch(o){throw new XpodLoginTransactionError("malformed",o instanceof Error?o.message:"Transaction is malformed")}let i;try{i=assertXpodLoginRoute(t.route,e)}catch(o){throw new XpodLoginTransactionError("cross_origin",o instanceof Error?o.message:"Transaction route is not local")}let s;try{s=normalizeXpodReturnTo(t.returnTo)}catch(o){throw new XpodLoginTransactionError("mismatch",o instanceof Error?o.message:"Transaction return path is unsafe")}if(t.selectedStorage!==void 0)try{const o=normalizeBinding(t.selectedStorage,e,i.storageProvider?.url);return{id:t.id,route:i,selectedStorage:o,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}catch(o){throw o instanceof XpodLoginTransactionError?o:new XpodLoginTransactionError("mismatch","Selected storage binding is invalid")}return{id:t.id,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function normalizeBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string")throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(i.origin!==e||s.origin!==e||t&&i.origin!==new URL(t).origin)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");if(i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("malformed","Selected storage binding contains unsafe URL data");return{storageUrl:i.href,webId:s.href,...n.label===void 0?{}:{label:n.label}}}function materialize(n){return{id:n.id,route:n.route,authorizationSurface:"redirect",discovery:"strict",...n.returnTo===void 0?{}:{returnTo:n.returnTo},...n.selectedStorage===void 0?{}:{selectedStorage:n.selectedStorage}}}function normalizeSelectedStorageBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string")throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(!urlBelongsToRoot(i,e)||t&&s.origin!==new URL(e).origin||i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");return{storageUrl:i.href,webId:s.href}}function normalizeStorageRoot(n){const e=new URL(n);return e.hash="",e.search="",e.pathname.endsWith("/")||(e.pathname+="/"),e.href}function urlBelongsToRoot(n,e){const t=new URL(normalizeStorageRoot(e));if(n.origin!==t.origin)return!1;const i=t.pathname;return n.pathname===i.slice(0,-1)||n.pathname.startsWith(i)}function isSafeTransactionId(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{16,128}$/.test(n)}function isStoredTransaction(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_LOGIN_TRANSACTION_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.transaction&&typeof e.transaction=="object")}function isStoredSelectedStorageBinding(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_SELECTED_STORAGE_BINDING_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.binding&&typeof e.binding=="object")}function getSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable")}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getWindowOrigin(){return typeof window<"u"&&window.location.origin!=="null"?window.location.origin:"http://localhost"}async function currentHostLocalPodRoute(n,e){if(typeof window>"u")return;const t=desktopLocalPodRoute(n);if(t)return t;if(storageUrlUsesCurrentOrigin(n))return;const i=await fetchCurrentProvisionRouteStatus(e);return currentProvisionLocalPodRoute(n,i)}function currentProvisionLocalPodRoute(n,e){if(!(typeof window>"u")&&!(e.managed!==!0||typeof e.storageRoot!="string")&&managedPublicRouteCoversStorage(n,e.storageRoot))return podScopedLocalRoute(n)}function desktopLocalPodRoute(n){if(!(typeof window>"u"||!window.xpodDesktop))return podScopedLocalRoute(n)}async function fetchCurrentProvisionRouteStatus(n){let e;try{e=await n(new URL("/provision/status",window.location.origin).href,{credentials:"include",headers:{accept:"application/json"}})}catch{return{}}if(!e.ok||!e.headers.get("content-type")?.includes("application/json"))return await e.arrayBuffer().catch(()=>{}),{};const t=await e.json().catch(()=>{});return{managed:t?.managed===!0,storageRoot:typeof t?.publicUrl=="string"?t.publicUrl:void 0}}function podScopedLocalRoute(n){try{const e=new URL(n),t=new URL(e.pathname,window.location.origin);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:(e.search="",e.hash="",t.search="",t.hash="",{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:t.href.endsWith("/")?t.href:`${t.href}/`})}catch{return}}function managedPublicRouteCoversStorage(n,e){try{const t=new URL(e),i=new URL(t.pathname,window.location.origin);return resolveSolidLocalRouteUrl(n,[{canonicalBaseUrl:t.href,localBaseUrl:i.href}])!==void 0}catch{return!1}}function storageUrlUsesCurrentOrigin(n){try{return new URL(n).origin===window.location.origin}catch{return!1}}function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[o,l]=reactExports.useState(s.snapshot),[u,h]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,y]=reactExports.useState(),[v,S]=reactExports.useState(),[E,x]=reactExports.useState(0),[A,I]=reactExports.useState(),T=reactExports.useRef(o),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),V=reactExports.useCallback(async(me,te)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):te===void 0?t.session.fetch(me):t.session.fetch(me,te),[t.session]),B=reactExports.useCallback(()=>{if(P.current)return P.current;const me=(async()=>{try{await t.session.logout();const te=t.session.getSnapshot();(te.status!=="authenticated"||isCurrentXpodSessionSnapshot(te,t.getIssuer(),t.getExpectedIssuer?.()??window.location.origin))&&(F.current=!1)}catch{}finally{const te={status:"anonymous"};t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),t.setIssuer(void 0),T.current=te,l(te),h(void 0),p(void 0),y(void 0),S(void 0),I(void 0)}})().finally(()=>{P.current===me&&(P.current=void 0)});return P.current=me,me},[t,i.issuer,i.selectedStorage]),Y=reactExports.useMemo(()=>({...t.session,fetch:V,getSnapshot:()=>T.current}),[V,t.session]);reactExports.useEffect(()=>{const me=Ce=>{const Oe=t.getIssuer();if(!isCurrentXpodSessionSnapshot(Ce,Oe,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,B();return}Ce.status==="authenticated"&&(F.current=!1);const ye=T.current;T.current=Ce,l(Ce),h(Oe),Ce.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),Ce.status!=="expired"&&y(void 0),S(void 0),I(void 0),t.pod.clear()):(ye.status!=="authenticated"||Ce.webId!==ye.webId)&&(p(void 0),y(void 0),S(void 0),I(void 0),t.pod.clear(ye.status==="authenticated"?{webId:ye.webId}:void 0))},te=t.session.subscribe(me);return me(t.session.getSnapshot()),te},[B,t,i]),reactExports.useEffect(()=>{F.current&&B()},[B]),reactExports.useEffect(()=>{if(o.status!=="authenticated")return;let me=!1;const te=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:o.webId}),Ce={webId:o.webId,...te?{podUrl:te.storageUrl}:{},fetch:V};return(async()=>{try{const Oe=await t.pod.open(Ce),ye=await currentHostLocalPodRoute(Oe.podUrl,fetch);if(me)return;if(t.setLocalPodRoute?.(ye),!me){if(te&&(Oe.webId!==te.webId||!sameUrl$2(Oe.podUrl,te.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),y(void 0),S({webId:o.webId,error:new Error("Selected Pod binding mismatch")});return}p(Oe),y(te??{webId:Oe.webId,storageUrl:Oe.podUrl}),S(void 0)}}catch(Oe){me||S({webId:o.webId,error:Oe instanceof Error?Oe:new Error(String(Oe))})}})(),()=>{me=!0}},[V,E,t,i.selectedStorage,o]);const _e=reactExports.useCallback(()=>{S(void 0),x(me=>me+1)},[]),j=o.status==="authenticated"?o.webId:void 0;reactExports.useEffect(()=>{if(!j)return;let me=!1;return discoverAiClientConfigurationCapability(V).then(te=>{!me&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===j&&I(te)}),()=>{me=!0}},[j,V,t]);const ee=reactExports.useMemo(()=>{const me=u??t.getIssuer(),te=o.status==="authenticated"&&v?.webId===o.webId?v:void 0,Ce=snapshotToState(o,d,me);return{session:Y,pod:t.pod,fetch:V,state:Ce.status==="error"?{...Ce,error:safeAuthError(Ce.error)}:Ce,webId:Ce.webId,podUrl:Ce.podUrl,issuer:Ce.issuer,currentPod:d,selectedStorage:g,...te?{podError:te}:{},retryPodOpen:_e,aiClientConfiguration:A,login:async Oe=>{const ye=normalizeXpodLoginTransaction(Oe),qe=await resolveXpodLoginContext(ye.route.identityProvider.url,fetch),de=qe.oidcIssuer;if(!de)throw new TypeError("Xpod login route has no valid issuer");const Fe=new URL("/auth/callback",window.location.origin);t.setIssuer(de),h(de),clearCachedInruptDynamicClientRegistration(i);try{await t.session.login({oidcIssuer:de,redirectUrl:Fe.toString(),handleRedirect:qe.provisionCode?O=>{window.location.assign(withXpodProvisionScope(O,qe.provisionCode))}:void 0})}catch(O){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",O,O instanceof Error?O.cause:void 0),O}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),y(void 0),I(void 0)}}},[A,d,V,Y,u,v,_e,t,i,g,o]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:Y,pod:t.pod,currentPod:d},children:jsxRuntimeExports.jsx(XpodSolidRuntimeContext.Provider,{value:ee,children:n})})}const ANONYMOUS_SNAPSHOT={status:"anonymous"},REJECTED_SESSION_FETCH_ERROR=new Error("Xpod session is unavailable");function currentProviderSession(n){const e=n.session.getSnapshot(),t=n.getIssuer();return isCurrentXpodSessionSnapshot(e,t,n.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:t,rejected:!1}:{snapshot:ANONYMOUS_SNAPSHOT,issuer:void 0,rejected:!0}}function sameUrl$2(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}async function discoverAiClientConfigurationCapability(n){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),t=await n(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!t.ok||!t.headers.get("content-type")?.includes("application/json"))return await t.arrayBuffer().catch(()=>{}),manualAiClientConfigurationCapability();const i=await t.json();if(isRecord(i)&&i.available===!0&&i.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof i.manualInstructions=="string"?i.manualInstructions:manualAiClientConfigurationCapability().manualInstructions}}catch{}return manualAiClientConfigurationCapability()}function manualAiClientConfigurationCapability(){return{available:!1,manualInstructions:"manual client setup is available"}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),o=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const h=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",h),()=>u.removeEventListener("change",h)):(u.addListener?.(h),()=>u.removeListener?.(h))},[]),reactExports.useEffect(()=>{applyXpodTheme(o)},[o]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:o,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,o]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const mergeClasses=(...n)=>n.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim();const toKebabCase=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const toCamelCase=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,i)=>i?i.toUpperCase():t.toLowerCase());const toPascalCase=n=>{const e=toCamelCase(n);return e.charAt(0).toUpperCase()+e.slice(1)};var defaultAttributes={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const hasA11yProp=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const Icon=reactExports.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:s="",children:o,iconNode:l,...u},h)=>reactExports.createElement("svg",{ref:h,...defaultAttributes,width:e,height:e,stroke:n,strokeWidth:i?Number(t)*24/Number(e):t,className:mergeClasses("lucide",s),...!o&&!hasA11yProp(u)&&{"aria-hidden":"true"},...u},[...l.map(([d,p])=>reactExports.createElement(d,p)),...Array.isArray(o)?o:[o]]));const createLucideIcon=(n,e)=>{const t=reactExports.forwardRef(({className:i,...s},o)=>reactExports.createElement(Icon,{ref:o,iconNode:e,className:mergeClasses(`lucide-${toKebabCase(toPascalCase(n))}`,`lucide-${n}`,i),...s}));return t.displayName=toPascalCase(n),t};const __iconNode$d=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]],BrainCircuit=createLucideIcon("brain-circuit",__iconNode$d);const __iconNode$c=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ChevronRight=createLucideIcon("chevron-right",__iconNode$c);const __iconNode$b=[["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("circle-alert",__iconNode$b);const __iconNode$a=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],CircleCheckBig=createLucideIcon("circle-check-big",__iconNode$a);const __iconNode$9=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],CircleCheck=createLucideIcon("circle-check",__iconNode$9);const __iconNode$8=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Copy=createLucideIcon("copy",__iconNode$8);const __iconNode$7=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Database=createLucideIcon("database",__iconNode$7);const __iconNode$6=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Gauge=createLucideIcon("gauge",__iconNode$6);const __iconNode$5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Globe=createLucideIcon("globe",__iconNode$5);const __iconNode$4=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon("loader-circle",__iconNode$4);const __iconNode$3=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],LogOut=createLucideIcon("log-out",__iconNode$3);const __iconNode$2=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],RefreshCw=createLucideIcon("refresh-cw",__iconNode$2);const __iconNode$1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Settings=createLucideIcon("settings",__iconNode$1);const __iconNode=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Sparkles=createLucideIcon("sparkles",__iconNode),globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const h=Math.max(72,t-n.top+12);return{left:8,bottom:h,width:u,maxHeight:Math.max(240,t-h-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",[i,s]=reactExports.useState(accountCardRequestedByUrl(t)),[o,l]=reactExports.useState(),[u,h]=reactExports.useState(),[d,p]=reactExports.useState(),g=reactExports.useRef(null),y=reactExports.useRef(null),v=reactExports.useRef(void 0),S=reactExports.useId(),E=n.identity,x=readPendingXpodAccountEmail(),A=readRememberedXpodLogin()?.account,I=accountCardIdentityFallback(E,x,A),T=useXpodProfileCardIdentity({accountIdentity:t?I:void 0,runtime:t?e:void 0}),F=T.displayName,P=initialsFor(T.displayName),V=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),B=e?.selectedStorage?.storageUrl??e?.podUrl,Y=e?.selectedStorage,_e=e?.currentPod,j=reactExports.useMemo(()=>B?podNameFromUrl(B):void 0,[B]),ee=e?.state.status==="authenticated"&&!!(V&&B&&Y&&_e)&&Y?.webId===V&&sameUrl$1(Y?.storageUrl??"",B??"")&&_e?.webId===V&&sameUrl$1(_e?.podUrl??"",B??""),me=t,te=i&&me,Ce=reactExports.useCallback(de=>{s(de),de||(p(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!te)return;const de=()=>{const Fe=y.current;Fe&&p(accountCardPosition(Fe.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return de(),window.addEventListener("resize",de),window.addEventListener("scroll",de,!0),window.visualViewport?.addEventListener("resize",de),()=>{window.removeEventListener("resize",de),window.removeEventListener("scroll",de,!0),window.visualViewport?.removeEventListener("resize",de)}},[te]),reactExports.useEffect(()=>{if(!me){clearAccountCardRequest();return}if(!te)return;const de=O=>{const Z=O.target;Z instanceof Node&&(g.current?.contains(Z)||y.current?.contains(Z)||Ce(!1))},Fe=O=>{O.key==="Escape"&&(Ce(!1),y.current?.focus())};return document.addEventListener("pointerdown",de),document.addEventListener("keydown",Fe),()=>{document.removeEventListener("pointerdown",de),document.removeEventListener("keydown",Fe)}},[me,te,Ce]),reactExports.useEffect(()=>{!te||!d||g.current?.focus({preventScroll:!0})},[te,d]),reactExports.useEffect(()=>()=>{v.current!==void 0&&window.clearTimeout(v.current)},[]);const Oe=async()=>{l("logout");try{await n.logout(),(n.isAnonymous?.()??!0)&&Ce(!1)}finally{l(void 0)}},ye=async()=>{l("switch");try{if(await n.logout(),!(n.isAnonymous?.()??!0))return;clearRememberedXpodLogin(),Ce(!1),window.location.assign(new URL("/status/overview",window.location.origin))}finally{l(void 0)}},qe=async()=>{const de=T.webId??accountHandle(T.username,I?.id,V);try{await navigator.clipboard.writeText(de),h("Copied")}catch{h("Copy failed")}v.current!==void 0&&window.clearTimeout(v.current),v.current=window.setTimeout(()=>h(void 0),1800)};return me?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:y,type:"button","aria-label":t?`Open account menu for ${F}`:"Open account menu","aria-expanded":te,"aria-controls":te?S:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":ee?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Ce(!te),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[T.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:T.avatarUrl,alt:F}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:P})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:t?F:"Not signed in"})]}),te&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:g,id:S,role:"region",tabIndex:-1,"aria-label":t?F:"Xpod account","data-avatar-card":"true","data-selected-pod-url":B,style:d,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${d?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[T.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:T.avatarUrl,alt:F}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:P})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:F}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:accountHandle(T.username,I?.id,V)}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"Copy Xpod ID",onClick:()=>{qe()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),u?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:u}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${ee?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:ee?"Pod connected":"Account connected"})]})]})]}),T.note||T.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[T.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:T.note}):null,T.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:T.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(j)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(B)]})]}),ee?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-emerald-500","aria-label":"Pod ready"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsxs("div",{className:"p-2",children:[jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{ye()},disabled:o!==void 0,children:[o==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{Oe()},disabled:o!==void 0,children:[o==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const o=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(o,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-CwBKvDQZ.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-CwBKvDQZ.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-CwBKvDQZ.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-XPYrdyVd.js"),__vite__mapDeps([7,8,9,2,10,3,11,12,5]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-NjLpo9xp.js"),__vite__mapDeps([13,2,9,8,10]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-BzKzXmSL.js"),__vite__mapDeps([14,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-Do71gQQC.js"),__vite__mapDeps([15,1,16])));function lazyRoute$1(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}const statusContentRoutes=[{path:"overview",element:lazyRoute$1(jsxRuntimeExports.jsx(StatusPage,{}))},{path:"services/gateway",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"gateway",title:"Gateway"}))},{path:"services/solid-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"css",title:"Solid Server"}))},{path:"services/api-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"api",title:"API Server"}))},{path:"logs",element:lazyRoute$1(jsxRuntimeExports.jsx(LogsPage,{}))},{path:"index",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"overview"}))},{path:"index/rdf",element:lazyRoute$1(jsxRuntimeExports.jsx(RdfPage,{}))},{path:"index/fts",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"fts"}))},{path:"index/vector",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"vector"}))},{path:"index/retrieval-points",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"retrieval-points"}))},{path:"index/cache",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"cache"}))},{path:"index/slow-queries",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"slow-queries"}))},{path:"index/benchmark",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"benchmark"}))}];function statusWorkspaceRoute(n){return{element:lazyRoute$1(jsxRuntimeExports.jsx(StatusWorkspace,{})),children:n}}const dashboardRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),o=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),y=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(y)}catch{return}};let u=!1;const h=p=>{try{return o.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const y=o.readSinglePending();y&&o.cancel(y.id)}catch{}return o.begin(p)}},d=async(p,g)=>{const y=l(p),v={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...y===void 0?{}:{returnTo:y},...g===void 0?{}:{selectedStorage:g}},S=h(v);u=!0;try{await n.runtime.login(S)}catch(E){try{o.cancel(S.id)}catch{}throw E}finally{u=!1}return S};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=o.readSinglePending();p&&o.cancel(p.id)},readPending:()=>o.readSinglePending(),callbackUrl(p){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}const xpodIconUrl="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2064%2064'%20fill='none'%3e%3cpath%20d='M32%207%2051%2016.5v13.8c0%2012.4-7.4%2021.2-19%2027.7-11.6-6.5-19-15.3-19-27.7V16.5L32%207Z'%20stroke='%238A72BE'%20stroke-width='5'%20stroke-linecap='round'%20stroke-linejoin='round'%20/%3e%3c/svg%3e";function XpodLoginBrand({compact:n=!1,showSubtitle:e=!n,subtitle:t="使用 WebID 登录"}){const i=n&&e;return jsxRuntimeExports.jsxs("div",{"data-testid":"xpod-login-brand","data-presentation":n?"compact":"standard",className:i?"flex flex-col items-center justify-center gap-1 text-center":n?"flex items-center justify-center gap-2 text-center":"flex flex-col items-center gap-3 text-center",children:[jsxRuntimeExports.jsx("img",{src:xpodIconUrl,alt:"",className:n?i?"h-16 w-16":"h-7 w-7":"h-11 w-11"}),jsxRuntimeExports.jsxs("div",{className:i?"space-y-1 text-center":n?"text-left":"space-y-1",children:[jsxRuntimeExports.jsx("h1",{className:n?"text-base font-semibold leading-none text-foreground":"text-lg font-semibold text-foreground",children:"Xpod"}),e?jsxRuntimeExports.jsx("p",{className:"text-xs text-primary/80",children:t}):null]})]})}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),s=runtimeState(t.state),o=storageSelectionState(t,s),[l,u]=reactExports.useState(),[h,d]=reactExports.useState(!1),p=reactExports.useRef(0),g=reactExports.useRef(!1),y=reactExports.useRef(!1),v=_e=>{console.error("[WebIdAuthBoundary] authentication action failed",_e),u(actionFailureMessage)},S=_e=>{const j=++p.current;u(void 0),d(!0),_e().catch(ee=>{j===p.current&&v(ee)}).finally(()=>{j===p.current&&d(!1)})},E=()=>S(()=>i.startLogin()),x=()=>{s.status==="authenticated"?t.retryPodOpen?.():S(()=>i.retryLogin())},A=()=>{i.cancelLogin(),p.current+=1,d(!1),u(void 0)},I=()=>S(async()=>{await t.logout(),await i.startLogin()});if(reactExports.useEffect(()=>{t.state.status!=="loading"||g.current||(g.current=!0,t.session.initialize({restorePreviousSession:!0}).catch(v))},[t.session,t.state.status]),reactExports.useEffect(()=>{!e||y.current||s.status!=="anonymous"||(y.current=!0,E())},[e,s.status]),s.status==="authenticated"&&o?.status==="ready")return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const T="remembered"in s?s.remembered:void 0,F=s.status==="restoring",P=h||e&&s.status==="anonymous"&&!l,V=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let B,Y;return l?B=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:l,primaryLabel:"重试",onPrimary:x,secondaryLabel:"取消当前登录",onSecondary:A}):F?(Y=T?void 0:V,B=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:T?.displayName,avatarUrl:T?.avatarUrl,label:rememberedCopy.restoringLabel})):P?B=jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:A}):s.status==="authenticated"?B=o?.status==="conflict"||o?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:o.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:o.message,primaryLabel:"重试",onPrimary:x}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):T?B=jsxRuntimeExports.jsx(LoginAccountView,{name:T.displayName,avatarUrl:T.avatarUrl,bindingLabel:"Xpod",expired:s.status==="expired",expiredTitle:rememberedCopy.expiredTitle,enterLabel:s.status==="expired"?rememberedCopy.reauthenticateLabel(T.displayName):rememberedCopy.continueLabel(T.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:E,onReauthenticate:x,onSwitchAccount:I}):s.status==="error"||s.status==="expired"?B=jsxRuntimeExports.jsx(LoginFailureView,{title:s.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:s.status==="error"?s.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:x}):B=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:V,onStart:E}),jsxRuntimeExports.jsx(AuthSurface,{mode:"page",title:"登录 Xpod",presentation:"compact",host:"document",lead:Y,children:B})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin"}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-BKO0ARYt.js"),__vite__mapDeps([17,18,10,4,11,19]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-CAYT-CgT.js"),__vite__mapDeps([20,8,21,18,10]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-Cn3kSze7.js").then(n=>n.M),__vite__mapDeps([22,21,18])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-D__vS86O.js"),__vite__mapDeps([23,22,21,18])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-Bx3Fco0x.js"),__vite__mapDeps([24,22,21,18])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-CuYEAG62.js"),__vite__mapDeps([25,22,21,18])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-CclI_Lpv.js"),__vite__mapDeps([26,6,1,8,10]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-CMnSE-8N.js"),__vite__mapDeps([27,1,18,12,16,3])).then(n=>({default:n.PodSettingsSubjectPanel})));function lazyRoute(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}function systemSettingsPage(n){return{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(SystemSettingsPage,{})),children:n}]}}const aiConnectionsSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{index:!0,element:lazyRoute(jsxRuntimeExports.jsx(ModelsPage,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:".",replace:!0})}]}],aiConfigSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(AiConfigPage,{})),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})},{path:"model-assignments",element:lazyRoute(jsxRuntimeExports.jsx(ModelAssignmentsPanel,{}))},{path:"document-processing",element:lazyRoute(jsxRuntimeExports.jsx(DocumentProcessingPanel,{}))},{path:"search-indexing",element:lazyRoute(jsxRuntimeExports.jsx(SearchIndexingPanel,{}))},{path:"index-lifecycle",element:lazyRoute(jsxRuntimeExports.jsx(IndexLifecyclePanel,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})}]}]}],systemSettingsSurfaceRoutes=[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})},{element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"pod",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"pod"}))},{path:"identity-access",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"identity-access"}))}])]},systemSettingsPage([{path:"storage",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"storage"}))},{path:"runtime",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"runtime"}))},{path:"cloud",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"cloud"}))},{path:"advanced",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"advanced"}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})}])];function AccountCredentialsFrame({frame:n,children:e}){return n==="bare"?jsxRuntimeExports.jsx("div",{"data-account-credentials-frame":"bare",className:"w-full text-card-foreground",children:e}):jsxRuntimeExports.jsx(Card,{"data-account-credentials-frame":"card",className:"w-full border-border bg-card text-card-foreground",children:e})}function setCredentialValue(n,e,t,i,s){i({...n,[e]:t}),s?.(e,t)}function FieldError({id:n,message:e}){return e?jsxRuntimeExports.jsxs("p",{id:n,role:"alert","aria-live":"polite",className:"flex items-center gap-1.5 text-sm text-destructive",children:[jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-4 w-4 shrink-0"}),e]}):null}function FloatingCredentialField({id:n,label:e,error:t,children:i}){return jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{"data-floating-field":"true",className:"relative",children:[i,jsxRuntimeExports.jsx(Label,{htmlFor:n,className:"pointer-events-none absolute left-3 top-0 z-[1] -translate-y-1/2 bg-card px-1 text-xs leading-none text-muted-foreground transition-[color,font-size,top,transform] duration-150 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:text-sm peer-focus:top-0 peer-focus:-translate-y-1/2 peer-focus:text-xs peer-focus:text-ring peer-disabled:opacity-50 peer-aria-[invalid=true]:text-destructive",children:e})]}),jsxRuntimeExports.jsx(FieldError,{id:`${n}-error`,message:t})]})}function StackedCredentialField({id:n,label:e,error:t,children:i}){return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:n,children:e}),i,jsxRuntimeExports.jsx(FieldError,{id:`${n}-error`,message:t})]})}function CredentialField({id:n,label:e,error:t,floating:i,children:s}){const o=i?FloatingCredentialField:StackedCredentialField;return jsxRuntimeExports.jsx(o,{id:n,label:e,error:t,children:s})}function AccountCredentialsView({mode:n,values:e,onChange:t,onSubmit:i,onFieldChange:s,onModeChange:o,pending:l=!1,errors:u,usernameAvailability:h="idle",usernameSuggestions:d=[],copy:p,frame:g="card",showHeader:y=!0,presentation:v="standard"}){const[S,E]=reactExports.useState(!1),x=reactExports.useId(),A=reactExports.useId(),I=reactExports.useId(),T=reactExports.useId(),F=reactExports.useId(),P=n==="register",V=typeof h=="string"?h:h.status,B=P&&e.password.length>0&&e.confirmation!==void 0&&e.password!==e.confirmation,Y=B&&(S||e.confirmation!==void 0)?p.mismatchError:void 0,_e=P?p.registerAction:p.loginAction,j=v==="compact",ee=j?"peer h-11 rounded-xl px-3 pb-2 pt-4":void 0,me=Ce=>{if(Ce?.preventDefault(),!l){if(P&&B){E(!0);return}E(!1),i(e)}},te=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[y?jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{children:P?p.registerTitle:p.loginTitle}),jsxRuntimeExports.jsx(CardDescription,{children:p.productName})]}):null,jsxRuntimeExports.jsx(CardContent,{className:cn(g==="bare"?"p-0":y?void 0:"pt-6"),children:jsxRuntimeExports.jsxs("form",{onSubmit:me,className:j?"space-y-3":"space-y-4",children:[P?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(CredentialField,{floating:j,id:x,label:p.usernameLabel,error:u?.username,children:jsxRuntimeExports.jsx(Input,{id:x,name:"username",autoComplete:"username",placeholder:j?" ":p.usernamePlaceholder,title:p.usernamePlaceholder,value:e.username??"",disabled:l,"aria-invalid":u?.username?!0:void 0,"aria-describedby":u?.username?`${x}-error`:void 0,className:ee,onChange:Ce=>setCredentialValue(e,"username",Ce.currentTarget.value,t,s)})}),V==="checking"?jsxRuntimeExports.jsxs("p",{role:"status","aria-live":"polite",className:"text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"mr-1 inline h-3.5 w-3.5 animate-spin"}),p.usernameChecking]}):null,V==="available"?jsxRuntimeExports.jsxs("p",{"aria-live":"polite",className:"flex items-center gap-1 text-sm text-primary",children:[jsxRuntimeExports.jsx(CircleCheckBig,{"aria-hidden":"true",className:"h-4 w-4"}),p.usernameAvailable]}):null,V==="unavailable"&&!u?.username?jsxRuntimeExports.jsx("p",{"aria-live":"polite",className:"text-sm text-destructive",children:typeof h=="object"&&h.message?h.message:p.usernameUnavailable}):null,!j&&d.length>0?jsxRuntimeExports.jsxs("div",{className:"space-y-2","aria-label":p.suggestionsLabel,children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:p.suggestionsLabel}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(Ce=>jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",size:"sm",disabled:l,onClick:()=>setCredentialValue(e,"username",Ce,t,s),children:Ce},Ce))})]}):null]}):null,jsxRuntimeExports.jsx(CredentialField,{floating:j,id:A,label:p.emailLabel,error:u?.email,children:jsxRuntimeExports.jsx(Input,{id:A,name:"email",type:"email",autoComplete:"email",placeholder:j?" ":p.emailPlaceholder,title:p.emailPlaceholder,value:e.email??"",disabled:l,"aria-invalid":u?.email?!0:void 0,"aria-describedby":u?.email?`${A}-error`:void 0,className:ee,onChange:Ce=>setCredentialValue(e,"email",Ce.currentTarget.value,t,s)})}),jsxRuntimeExports.jsx(CredentialField,{floating:j,id:I,label:p.passwordLabel,error:u?.password,children:jsxRuntimeExports.jsx(Input,{id:I,name:"password",type:"password",autoComplete:P?"new-password":"current-password",placeholder:j?" ":p.passwordPlaceholder,title:p.passwordPlaceholder,value:e.password,disabled:l,"aria-invalid":u?.password?!0:void 0,"aria-describedby":u?.password?`${I}-error`:void 0,className:ee,onChange:Ce=>setCredentialValue(e,"password",Ce.currentTarget.value,t,s)})}),P?jsxRuntimeExports.jsx(CredentialField,{floating:j,id:T,label:p.confirmationLabel,error:Y??u?.confirmation,children:jsxRuntimeExports.jsx(Input,{id:T,name:"confirmation",type:"password",autoComplete:"new-password",placeholder:j?" ":p.confirmationPlaceholder,title:p.confirmationPlaceholder,value:e.confirmation??"",disabled:l,"aria-invalid":Y||u?.confirmation?!0:void 0,"aria-describedby":Y||u?.confirmation?`${T}-error`:void 0,className:ee,onChange:Ce=>{E(!1),setCredentialValue(e,"confirmation",Ce.currentTarget.value,t,s)}})}):null,jsxRuntimeExports.jsx(FieldError,{id:F,message:u?.form}),jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs(Button,{type:"submit",className:cn("w-full",j&&"h-10 rounded-xl"),disabled:l,children:[l?jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"mr-2 h-4 w-4 animate-spin"}):null,_e]}),o?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:cn("w-full",j&&"h-9 rounded-lg text-xs"),disabled:l,onClick:()=>o(P?"login":"register"),children:P?p.switchToLogin:p.switchToRegister}):null]})]})})]});return jsxRuntimeExports.jsx(AccountCredentialsFrame,{frame:g,children:te})}function AccountCredentialsSurface({surface:n,surfaceTitle:e,presentation:t,host:i,lead:s,footer:o,onClose:l,closeLabel:u,closeOnEscape:h,surfaceClassName:d,contentClassName:p,...g}){return jsxRuntimeExports.jsx(AuthSurface,{mode:n,title:e,presentation:t,host:i,lead:s,onClose:l,closeLabel:u,closeOnEscape:h,className:d,children:jsxRuntimeExports.jsxs("div",{className:p??(t==="compact"?"flex h-full min-h-0 flex-1 flex-col justify-center px-5 pb-5 pt-4":"p-4"),children:[jsxRuntimeExports.jsx(AccountCredentialsView,{...g,frame:"bare",showHeader:!1,presentation:t}),o?jsxRuntimeExports.jsx("div",{className:t==="compact"?"mt-3 space-y-2":"mt-4 space-y-2",children:o}):null]})})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodRegistrationCopy={emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(n.loginUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const o=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(o||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}function getXpodAuthSurfaceHost(){return"document"}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,presentation:e="standard",host:t,lead:i,onAuthenticated:s,onClose:o,surfaceClassName:l,contentClassName:u,initialEmail:h}){const{controls:d,idpIndex:p,isAnonymous:g,refetchControls:y}=useAuth(),[v,S]=reactExports.useState({email:h!==void 0?h:readPendingXpodAccountEmail(void 0,p)??"",password:""}),[E,x]=reactExports.useState(),[A,I]=reactExports.useState(!1),T=reactExports.useRef(!1),F=async V=>{if(!T.current){T.current=!0,I(!0),x(void 0);try{const B=await resolveHostedAccountControlUrl(d?.password?.login,fetch,p)??"/.account/login/password/",Y=await loginAccountPassword({email:V.email?.trim()??"",password:V.password,loginUrl:B,remember:!0,fetchImpl:async(_e,j)=>{const ee=await fetch(_e,j);if(!ee.ok)throw new PasswordLoginStatusError(ee.status);return ee}});if(storeAccountSessionToken(Y.accountToken),rememberPendingXpodAccountEmail(V.email?.trim()??"",void 0,p),await y(),g?.()){clearAccountSessionToken(),x("登录失败,请重试。");return}await s?.()}catch(B){x(B instanceof PasswordLoginStatusError?safeXpodLoginMessage(B.status):safeXpodLoginMessage(500))}finally{T.current=!1,I(!1)}}},P=V=>{S(V),E&&x(void 0)};return jsxRuntimeExports.jsx(AccountCredentialsSurface,{surface:n,surfaceTitle:"登录 Xpod",presentation:e,host:t??(n==="modal"?getXpodAuthSurfaceHost():"document"),lead:i??(e==="compact"?jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}):void 0),copy:xpodAccountCredentialsCopy,surfaceClassName:l,contentClassName:u??(e==="compact"?"flex h-full min-h-0 flex-1 flex-col justify-center px-5 pb-5 pt-4":void 0),onClose:n==="modal"?o:void 0,closeLabel:n==="modal"&&o?"关闭登录":void 0,mode:"login",values:v,onChange:P,onSubmit:F,pending:A,errors:E?{form:E}:void 0})}function AccountAuthBoundary({children:n,accountState:e,retry:t}){const i=useAuth(),s=e??i.accountState,o=t??i.retry;return s.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):s.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):s.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):s.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:s.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{o()},children:"重试"})]})}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"modal",presentation:"compact",host:"document",lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0,subtitle:"使用 Xpod 账号登录 Dashboard"})})}function LoginSurface({children:n}){return jsxRuntimeExports.jsx(AuthSurface,{mode:"modal",title:"登录 Xpod",presentation:"compact",host:"document",lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0}),children:n})}const xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountAuthBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountAuthBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"/status/overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"/status/overview",replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),reactExports.useEffect(()=>{globalThis.xpodDesktop?.setWindowMode?.("workspace")},[]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodShellRoutes,{}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??"/status/overview")}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}initializeXpodTheme();clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodShellApp,{})})}));export{removeIri as $,getDefaultExportFromCjs as A,Button as B,Card as C,Database as D,createSlottable as E,getLinkedResourceUrlAll as F,Gauge as G,acp as H,internal_cloneResource as I,getSolidDataset as J,freeze as K,Link as L,getSourceUrl as M,NavLink as N,Outlet as O,Primitive as P,getResourceInfo as Q,RefreshCw as R,Sparkles as S,getSourceIri as T,getThingAll as U,getIriAll as V,rdf$3 as W,X,acl as Y,setThing as Z,setIri as _,CardHeader as a,removeAll as a0,createThing as a1,addIri as a2,removeThing as a3,subjectToRdfJsQuads as a4,DataFactory$1 as a5,getIri as a6,saveSolidDatasetAt as a7,createSolidDataset as a8,foaf as a9,getThing as aa,getUrlAll as ab,buildThing as ac,Avatar as ad,AvatarImage as ae,AvatarFallback as af,LoginFailureView as ag,LoginConnectingView as ah,Input as ai,Label as aj,Toaster as ak,credentialResource as al,aiProviderResource as am,aiModelResource as an,configureSparqlEngine as ao,createXpodLoginController as ap,requireBuffer as aq,requireLink as ar,getAugmentedNamespace as as,requireBrowser$2 as at,requireSparql as au,requireEvents as av,requireBrowser$3 as aw,requireString_decoder as ax,bufferExports as ay,commonjsGlobal as az,CardTitle as b,createLucideIcon as c,CardDescription as d,CardContent as e,cn as f,cva as g,aiConfigModelRef as h,interactiveFocusClass as i,jsxRuntimeExports as j,useLocation as k,handleListNavigationKeyDown as l,getListNavItemClass as m,Copy as n,useLayoutEffect2 as o,React4 as p,useComposedRefs as q,reactExports as r,useCallbackRef as s,toast as t,useXpodSolidRuntime as u,dispatchDiscreteCustomEvent as v,reactDomExports as w,createContextScope as x,clsx as y,createSlot as z};
|
|
306
|
+
`)},i.hextoposhex=Pr,i.intarystrtohex=function(b){b=(b=(b=b.replace(/^\s*\[\s*/,"")).replace(/\s*\]\s*$/,"")).replace(/\s*/g,"");try{return b.split(/,/).map((function(w,C,k){var Q=parseInt(w);if(Q<0||255<Q)throw"integer not in range 0-255";return("00"+Q.toString(16)).slice(-2)})).join("")}catch(w){throw"malformed integer array string: "+w}},i.strdiffidx=function(b,w){var C=b.length;b.length>w.length&&(C=w.length);for(var k=0;k<C;k++)if(b.charCodeAt(k)!=w.charCodeAt(k))return k;return b.length!=w.length?C:-1},i.KJUR=$;var En=$.crypto;i.crypto=En;var gn=$.asn1;i.asn1=gn;var Rn=$.jws;i.jws=Rn;var ws=$.lang;i.lang=ws}).call(this,s(28).Buffer)},function(t,i,s){(function(o){var l=s(30),u=s(31),h=s(32);function d(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function p(se,M){if(d()<M)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(se=new Uint8Array(M)).__proto__=g.prototype:(se===null&&(se=new g(M)),se.length=M),se}function g(se,M,N){if(!(g.TYPED_ARRAY_SUPPORT||this instanceof g))return new g(se,M,N);if(typeof se=="number"){if(typeof M=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,se)}return y(this,se,M,N)}function y(se,M,N,L){if(typeof M=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&M instanceof ArrayBuffer?(function(re,le,Ee,G){if(le.byteLength,Ee<0||le.byteLength<Ee)throw new RangeError("'offset' is out of bounds");if(le.byteLength<Ee+(G||0))throw new RangeError("'length' is out of bounds");return le=Ee===void 0&&G===void 0?new Uint8Array(le):G===void 0?new Uint8Array(le,Ee):new Uint8Array(le,Ee,G),g.TYPED_ARRAY_SUPPORT?(re=le).__proto__=g.prototype:re=E(re,le),re})(se,M,N,L):typeof M=="string"?(function(re,le,Ee){if(typeof Ee=="string"&&Ee!==""||(Ee="utf8"),!g.isEncoding(Ee))throw new TypeError('"encoding" must be a valid string encoding');var G=0|A(le,Ee),Se=(re=p(re,G)).write(le,Ee);return Se!==G&&(re=re.slice(0,Se)),re})(se,M,N):(function(re,le){if(g.isBuffer(le)){var Ee=0|x(le.length);return(re=p(re,Ee)).length===0||le.copy(re,0,0,Ee),re}if(le){if(typeof ArrayBuffer<"u"&&le.buffer instanceof ArrayBuffer||"length"in le)return typeof le.length!="number"||(function(Se){return Se!=Se})(le.length)?p(re,0):E(re,le);if(le.type==="Buffer"&&h(le.data))return E(re,le.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(se,M)}function v(se){if(typeof se!="number")throw new TypeError('"size" argument must be a number');if(se<0)throw new RangeError('"size" argument must not be negative')}function S(se,M){if(v(M),se=p(se,M<0?0:0|x(M)),!g.TYPED_ARRAY_SUPPORT)for(var N=0;N<M;++N)se[N]=0;return se}function E(se,M){var N=M.length<0?0:0|x(M.length);se=p(se,N);for(var L=0;L<N;L+=1)se[L]=255&M[L];return se}function x(se){if(se>=d())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+d().toString(16)+" bytes");return 0|se}function A(se,M){if(g.isBuffer(se))return se.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(se)||se instanceof ArrayBuffer))return se.byteLength;typeof se!="string"&&(se=""+se);var N=se.length;if(N===0)return 0;for(var L=!1;;)switch(M){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":case void 0:return ge(se).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*N;case"hex":return N>>>1;case"base64":return pe(se).length;default:if(L)return ge(se).length;M=(""+M).toLowerCase(),L=!0}}function I(se,M,N){var L=!1;if((M===void 0||M<0)&&(M=0),M>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0)<=(M>>>=0))return"";for(se||(se="utf8");;)switch(se){case"hex":return qe(this,M,N);case"utf8":case"utf-8":return te(this,M,N);case"ascii":return Oe(this,M,N);case"latin1":case"binary":return ye(this,M,N);case"base64":return me(this,M,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return de(this,M,N);default:if(L)throw new TypeError("Unknown encoding: "+se);se=(se+"").toLowerCase(),L=!0}}function T(se,M,N){var L=se[M];se[M]=se[N],se[N]=L}function F(se,M,N,L,H){if(se.length===0)return-1;if(typeof N=="string"?(L=N,N=0):N>2147483647?N=2147483647:N<-2147483648&&(N=-2147483648),N=+N,isNaN(N)&&(N=H?0:se.length-1),N<0&&(N=se.length+N),N>=se.length){if(H)return-1;N=se.length-1}else if(N<0){if(!H)return-1;N=0}if(typeof M=="string"&&(M=g.from(M,L)),g.isBuffer(M))return M.length===0?-1:P(se,M,N,L,H);if(typeof M=="number")return M&=255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?H?Uint8Array.prototype.indexOf.call(se,M,N):Uint8Array.prototype.lastIndexOf.call(se,M,N):P(se,[M],N,L,H);throw new TypeError("val must be string, number or Buffer")}function P(se,M,N,L,H){var re,le=1,Ee=se.length,G=M.length;if(L!==void 0&&((L=String(L).toLowerCase())==="ucs2"||L==="ucs-2"||L==="utf16le"||L==="utf-16le")){if(se.length<2||M.length<2)return-1;le=2,Ee/=2,G/=2,N/=2}function Se(ht,Ge){return le===1?ht[Ge]:ht.readUInt16BE(Ge*le)}if(H){var Ae=-1;for(re=N;re<Ee;re++)if(Se(se,re)===Se(M,Ae===-1?0:re-Ae)){if(Ae===-1&&(Ae=re),re-Ae+1===G)return Ae*le}else Ae!==-1&&(re-=re-Ae),Ae=-1}else for(N+G>Ee&&(N=Ee-G),re=N;re>=0;re--){for(var he=!0,at=0;at<G;at++)if(Se(se,re+at)!==Se(M,at)){he=!1;break}if(he)return re}return-1}function V(se,M,N,L){N=Number(N)||0;var H=se.length-N;L?(L=Number(L))>H&&(L=H):L=H;var re=M.length;if(re%2!=0)throw new TypeError("Invalid hex string");L>re/2&&(L=re/2);for(var le=0;le<L;++le){var Ee=parseInt(M.substr(2*le,2),16);if(isNaN(Ee))return le;se[N+le]=Ee}return le}function B(se,M,N,L){return Me(ge(M,se.length-N),se,N,L)}function Y(se,M,N,L){return Me((function(re){for(var le=[],Ee=0;Ee<re.length;++Ee)le.push(255&re.charCodeAt(Ee));return le})(M),se,N,L)}function _e(se,M,N,L){return Y(se,M,N,L)}function j(se,M,N,L){return Me(pe(M),se,N,L)}function ee(se,M,N,L){return Me((function(re,le){for(var Ee,G,Se,Ae=[],he=0;he<re.length&&!((le-=2)<0);++he)G=(Ee=re.charCodeAt(he))>>8,Se=Ee%256,Ae.push(Se),Ae.push(G);return Ae})(M,se.length-N),se,N,L)}function me(se,M,N){return M===0&&N===se.length?l.fromByteArray(se):l.fromByteArray(se.slice(M,N))}function te(se,M,N){N=Math.min(se.length,N);for(var L=[],H=M;H<N;){var re,le,Ee,G,Se=se[H],Ae=null,he=Se>239?4:Se>223?3:Se>191?2:1;if(H+he<=N)switch(he){case 1:Se<128&&(Ae=Se);break;case 2:(192&(re=se[H+1]))==128&&(G=(31&Se)<<6|63&re)>127&&(Ae=G);break;case 3:re=se[H+1],le=se[H+2],(192&re)==128&&(192&le)==128&&(G=(15&Se)<<12|(63&re)<<6|63&le)>2047&&(G<55296||G>57343)&&(Ae=G);break;case 4:re=se[H+1],le=se[H+2],Ee=se[H+3],(192&re)==128&&(192&le)==128&&(192&Ee)==128&&(G=(15&Se)<<18|(63&re)<<12|(63&le)<<6|63&Ee)>65535&&G<1114112&&(Ae=G)}Ae===null?(Ae=65533,he=1):Ae>65535&&(Ae-=65536,L.push(Ae>>>10&1023|55296),Ae=56320|1023&Ae),L.push(Ae),H+=he}return(function(ht){var Ge=ht.length;if(Ge<=Ce)return String.fromCharCode.apply(String,ht);for(var gt="",J=0;J<Ge;)gt+=String.fromCharCode.apply(String,ht.slice(J,J+=Ce));return gt})(L)}i.Buffer=g,i.SlowBuffer=function(M){return+M!=M&&(M=0),g.alloc(+M)},i.INSPECT_MAX_BYTES=50,g.TYPED_ARRAY_SUPPORT=o.TYPED_ARRAY_SUPPORT!==void 0?o.TYPED_ARRAY_SUPPORT:(function(){try{var M=new Uint8Array(1);return M.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},M.foo()===42&&typeof M.subarray=="function"&&M.subarray(1,1).byteLength===0}catch{return!1}})(),i.kMaxLength=d(),g.poolSize=8192,g._augment=function(se){return se.__proto__=g.prototype,se},g.from=function(se,M,N){return y(null,se,M,N)},g.TYPED_ARRAY_SUPPORT&&(g.prototype.__proto__=Uint8Array.prototype,g.__proto__=Uint8Array,typeof Symbol<"u"&&Symbol.species&&g[Symbol.species]===g&&Object.defineProperty(g,Symbol.species,{value:null,configurable:!0})),g.alloc=function(se,M,N){return(function(H,re,le,Ee){return v(re),re<=0?p(H,re):le!==void 0?typeof Ee=="string"?p(H,re).fill(le,Ee):p(H,re).fill(le):p(H,re)})(null,se,M,N)},g.allocUnsafe=function(se){return S(null,se)},g.allocUnsafeSlow=function(se){return S(null,se)},g.isBuffer=function(M){return!(M==null||!M._isBuffer)},g.compare=function(M,N){if(!g.isBuffer(M)||!g.isBuffer(N))throw new TypeError("Arguments must be Buffers");if(M===N)return 0;for(var L=M.length,H=N.length,re=0,le=Math.min(L,H);re<le;++re)if(M[re]!==N[re]){L=M[re],H=N[re];break}return L<H?-1:H<L?1:0},g.isEncoding=function(M){switch(String(M).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}},g.concat=function(M,N){if(!h(M))throw new TypeError('"list" argument must be an Array of Buffers');if(M.length===0)return g.alloc(0);var L;if(N===void 0)for(N=0,L=0;L<M.length;++L)N+=M[L].length;var H=g.allocUnsafe(N),re=0;for(L=0;L<M.length;++L){var le=M[L];if(!g.isBuffer(le))throw new TypeError('"list" argument must be an Array of Buffers');le.copy(H,re),re+=le.length}return H},g.byteLength=A,g.prototype._isBuffer=!0,g.prototype.swap16=function(){var M=this.length;if(M%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var N=0;N<M;N+=2)T(this,N,N+1);return this},g.prototype.swap32=function(){var M=this.length;if(M%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var N=0;N<M;N+=4)T(this,N,N+3),T(this,N+1,N+2);return this},g.prototype.swap64=function(){var M=this.length;if(M%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var N=0;N<M;N+=8)T(this,N,N+7),T(this,N+1,N+6),T(this,N+2,N+5),T(this,N+3,N+4);return this},g.prototype.toString=function(){var M=0|this.length;return M===0?"":arguments.length===0?te(this,0,M):I.apply(this,arguments)},g.prototype.equals=function(M){if(!g.isBuffer(M))throw new TypeError("Argument must be a Buffer");return this===M||g.compare(this,M)===0},g.prototype.inspect=function(){var M="",N=i.INSPECT_MAX_BYTES;return this.length>0&&(M=this.toString("hex",0,N).match(/.{2}/g).join(" "),this.length>N&&(M+=" ... ")),"<Buffer "+M+">"},g.prototype.compare=function(M,N,L,H,re){if(!g.isBuffer(M))throw new TypeError("Argument must be a Buffer");if(N===void 0&&(N=0),L===void 0&&(L=M?M.length:0),H===void 0&&(H=0),re===void 0&&(re=this.length),N<0||L>M.length||H<0||re>this.length)throw new RangeError("out of range index");if(H>=re&&N>=L)return 0;if(H>=re)return-1;if(N>=L)return 1;if(this===M)return 0;for(var le=(re>>>=0)-(H>>>=0),Ee=(L>>>=0)-(N>>>=0),G=Math.min(le,Ee),Se=this.slice(H,re),Ae=M.slice(N,L),he=0;he<G;++he)if(Se[he]!==Ae[he]){le=Se[he],Ee=Ae[he];break}return le<Ee?-1:Ee<le?1:0},g.prototype.includes=function(M,N,L){return this.indexOf(M,N,L)!==-1},g.prototype.indexOf=function(M,N,L){return F(this,M,N,L,!0)},g.prototype.lastIndexOf=function(M,N,L){return F(this,M,N,L,!1)},g.prototype.write=function(M,N,L,H){if(N===void 0)H="utf8",L=this.length,N=0;else if(L===void 0&&typeof N=="string")H=N,L=this.length,N=0;else{if(!isFinite(N))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");N|=0,isFinite(L)?(L|=0,H===void 0&&(H="utf8")):(H=L,L=void 0)}var re=this.length-N;if((L===void 0||L>re)&&(L=re),M.length>0&&(L<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");H||(H="utf8");for(var le=!1;;)switch(H){case"hex":return V(this,M,N,L);case"utf8":case"utf-8":return B(this,M,N,L);case"ascii":return Y(this,M,N,L);case"latin1":case"binary":return _e(this,M,N,L);case"base64":return j(this,M,N,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,M,N,L);default:if(le)throw new TypeError("Unknown encoding: "+H);H=(""+H).toLowerCase(),le=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ce=4096;function Oe(se,M,N){var L="";N=Math.min(se.length,N);for(var H=M;H<N;++H)L+=String.fromCharCode(127&se[H]);return L}function ye(se,M,N){var L="";N=Math.min(se.length,N);for(var H=M;H<N;++H)L+=String.fromCharCode(se[H]);return L}function qe(se,M,N){var L=se.length;(!M||M<0)&&(M=0),(!N||N<0||N>L)&&(N=L);for(var H="",re=M;re<N;++re)H+=We(se[re]);return H}function de(se,M,N){for(var L=se.slice(M,N),H="",re=0;re<L.length;re+=2)H+=String.fromCharCode(L[re]+256*L[re+1]);return H}function Fe(se,M,N){if(se%1!=0||se<0)throw new RangeError("offset is not uint");if(se+M>N)throw new RangeError("Trying to access beyond buffer length")}function O(se,M,N,L,H,re){if(!g.isBuffer(se))throw new TypeError('"buffer" argument must be a Buffer instance');if(M>H||M<re)throw new RangeError('"value" argument is out of bounds');if(N+L>se.length)throw new RangeError("Index out of range")}function Z(se,M,N,L){M<0&&(M=65535+M+1);for(var H=0,re=Math.min(se.length-N,2);H<re;++H)se[N+H]=(M&255<<8*(L?H:1-H))>>>8*(L?H:1-H)}function fe(se,M,N,L){M<0&&(M=4294967295+M+1);for(var H=0,re=Math.min(se.length-N,4);H<re;++H)se[N+H]=M>>>8*(L?H:3-H)&255}function oe(se,M,N,L,H,re){if(N+L>se.length)throw new RangeError("Index out of range");if(N<0)throw new RangeError("Index out of range")}function Pe(se,M,N,L,H){return H||oe(se,0,N,4),u.write(se,M,N,L,23,4),N+4}function je(se,M,N,L,H){return H||oe(se,0,N,8),u.write(se,M,N,L,52,8),N+8}g.prototype.slice=function(M,N){var L,H=this.length;if((M=~~M)<0?(M+=H)<0&&(M=0):M>H&&(M=H),(N=N===void 0?H:~~N)<0?(N+=H)<0&&(N=0):N>H&&(N=H),N<M&&(N=M),g.TYPED_ARRAY_SUPPORT)(L=this.subarray(M,N)).__proto__=g.prototype;else{var re=N-M;L=new g(re,void 0);for(var le=0;le<re;++le)L[le]=this[le+M]}return L},g.prototype.readUIntLE=function(M,N,L){M|=0,N|=0,L||Fe(M,N,this.length);for(var H=this[M],re=1,le=0;++le<N&&(re*=256);)H+=this[M+le]*re;return H},g.prototype.readUIntBE=function(M,N,L){M|=0,N|=0,L||Fe(M,N,this.length);for(var H=this[M+--N],re=1;N>0&&(re*=256);)H+=this[M+--N]*re;return H},g.prototype.readUInt8=function(M,N){return N||Fe(M,1,this.length),this[M]},g.prototype.readUInt16LE=function(M,N){return N||Fe(M,2,this.length),this[M]|this[M+1]<<8},g.prototype.readUInt16BE=function(M,N){return N||Fe(M,2,this.length),this[M]<<8|this[M+1]},g.prototype.readUInt32LE=function(M,N){return N||Fe(M,4,this.length),(this[M]|this[M+1]<<8|this[M+2]<<16)+16777216*this[M+3]},g.prototype.readUInt32BE=function(M,N){return N||Fe(M,4,this.length),16777216*this[M]+(this[M+1]<<16|this[M+2]<<8|this[M+3])},g.prototype.readIntLE=function(M,N,L){M|=0,N|=0,L||Fe(M,N,this.length);for(var H=this[M],re=1,le=0;++le<N&&(re*=256);)H+=this[M+le]*re;return H>=(re*=128)&&(H-=Math.pow(2,8*N)),H},g.prototype.readIntBE=function(M,N,L){M|=0,N|=0,L||Fe(M,N,this.length);for(var H=N,re=1,le=this[M+--H];H>0&&(re*=256);)le+=this[M+--H]*re;return le>=(re*=128)&&(le-=Math.pow(2,8*N)),le},g.prototype.readInt8=function(M,N){return N||Fe(M,1,this.length),128&this[M]?-1*(255-this[M]+1):this[M]},g.prototype.readInt16LE=function(M,N){N||Fe(M,2,this.length);var L=this[M]|this[M+1]<<8;return 32768&L?4294901760|L:L},g.prototype.readInt16BE=function(M,N){N||Fe(M,2,this.length);var L=this[M+1]|this[M]<<8;return 32768&L?4294901760|L:L},g.prototype.readInt32LE=function(M,N){return N||Fe(M,4,this.length),this[M]|this[M+1]<<8|this[M+2]<<16|this[M+3]<<24},g.prototype.readInt32BE=function(M,N){return N||Fe(M,4,this.length),this[M]<<24|this[M+1]<<16|this[M+2]<<8|this[M+3]},g.prototype.readFloatLE=function(M,N){return N||Fe(M,4,this.length),u.read(this,M,!0,23,4)},g.prototype.readFloatBE=function(M,N){return N||Fe(M,4,this.length),u.read(this,M,!1,23,4)},g.prototype.readDoubleLE=function(M,N){return N||Fe(M,8,this.length),u.read(this,M,!0,52,8)},g.prototype.readDoubleBE=function(M,N){return N||Fe(M,8,this.length),u.read(this,M,!1,52,8)},g.prototype.writeUIntLE=function(M,N,L,H){M=+M,N|=0,L|=0,H||O(this,M,N,L,Math.pow(2,8*L)-1,0);var re=1,le=0;for(this[N]=255&M;++le<L&&(re*=256);)this[N+le]=M/re&255;return N+L},g.prototype.writeUIntBE=function(M,N,L,H){M=+M,N|=0,L|=0,H||O(this,M,N,L,Math.pow(2,8*L)-1,0);var re=L-1,le=1;for(this[N+re]=255&M;--re>=0&&(le*=256);)this[N+re]=M/le&255;return N+L},g.prototype.writeUInt8=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,1,255,0),g.TYPED_ARRAY_SUPPORT||(M=Math.floor(M)),this[N]=255&M,N+1},g.prototype.writeUInt16LE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=255&M,this[N+1]=M>>>8):Z(this,M,N,!0),N+2},g.prototype.writeUInt16BE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=M>>>8,this[N+1]=255&M):Z(this,M,N,!1),N+2},g.prototype.writeUInt32LE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N+3]=M>>>24,this[N+2]=M>>>16,this[N+1]=M>>>8,this[N]=255&M):fe(this,M,N,!0),N+4},g.prototype.writeUInt32BE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N]=M>>>24,this[N+1]=M>>>16,this[N+2]=M>>>8,this[N+3]=255&M):fe(this,M,N,!1),N+4},g.prototype.writeIntLE=function(M,N,L,H){if(M=+M,N|=0,!H){var re=Math.pow(2,8*L-1);O(this,M,N,L,re-1,-re)}var le=0,Ee=1,G=0;for(this[N]=255&M;++le<L&&(Ee*=256);)M<0&&G===0&&this[N+le-1]!==0&&(G=1),this[N+le]=(M/Ee>>0)-G&255;return N+L},g.prototype.writeIntBE=function(M,N,L,H){if(M=+M,N|=0,!H){var re=Math.pow(2,8*L-1);O(this,M,N,L,re-1,-re)}var le=L-1,Ee=1,G=0;for(this[N+le]=255&M;--le>=0&&(Ee*=256);)M<0&&G===0&&this[N+le+1]!==0&&(G=1),this[N+le]=(M/Ee>>0)-G&255;return N+L},g.prototype.writeInt8=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,1,127,-128),g.TYPED_ARRAY_SUPPORT||(M=Math.floor(M)),M<0&&(M=255+M+1),this[N]=255&M,N+1},g.prototype.writeInt16LE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=255&M,this[N+1]=M>>>8):Z(this,M,N,!0),N+2},g.prototype.writeInt16BE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=M>>>8,this[N+1]=255&M):Z(this,M,N,!1),N+2},g.prototype.writeInt32LE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[N]=255&M,this[N+1]=M>>>8,this[N+2]=M>>>16,this[N+3]=M>>>24):fe(this,M,N,!0),N+4},g.prototype.writeInt32BE=function(M,N,L){return M=+M,N|=0,L||O(this,M,N,4,2147483647,-2147483648),M<0&&(M=4294967295+M+1),g.TYPED_ARRAY_SUPPORT?(this[N]=M>>>24,this[N+1]=M>>>16,this[N+2]=M>>>8,this[N+3]=255&M):fe(this,M,N,!1),N+4},g.prototype.writeFloatLE=function(M,N,L){return Pe(this,M,N,!0,L)},g.prototype.writeFloatBE=function(M,N,L){return Pe(this,M,N,!1,L)},g.prototype.writeDoubleLE=function(M,N,L){return je(this,M,N,!0,L)},g.prototype.writeDoubleBE=function(M,N,L){return je(this,M,N,!1,L)},g.prototype.copy=function(M,N,L,H){if(L||(L=0),H||H===0||(H=this.length),N>=M.length&&(N=M.length),N||(N=0),H>0&&H<L&&(H=L),H===L||M.length===0||this.length===0)return 0;if(N<0)throw new RangeError("targetStart out of bounds");if(L<0||L>=this.length)throw new RangeError("sourceStart out of bounds");if(H<0)throw new RangeError("sourceEnd out of bounds");H>this.length&&(H=this.length),M.length-N<H-L&&(H=M.length-N+L);var re,le=H-L;if(this===M&&L<N&&N<H)for(re=le-1;re>=0;--re)M[re+N]=this[re+L];else if(le<1e3||!g.TYPED_ARRAY_SUPPORT)for(re=0;re<le;++re)M[re+N]=this[re+L];else Uint8Array.prototype.set.call(M,this.subarray(L,L+le),N);return le},g.prototype.fill=function(M,N,L,H){if(typeof M=="string"){if(typeof N=="string"?(H=N,N=0,L=this.length):typeof L=="string"&&(H=L,L=this.length),M.length===1){var re=M.charCodeAt(0);re<256&&(M=re)}if(H!==void 0&&typeof H!="string")throw new TypeError("encoding must be a string");if(typeof H=="string"&&!g.isEncoding(H))throw new TypeError("Unknown encoding: "+H)}else typeof M=="number"&&(M&=255);if(N<0||this.length<N||this.length<L)throw new RangeError("Out of range index");if(L<=N)return this;var le;if(N>>>=0,L=L===void 0?this.length:L>>>0,M||(M=0),typeof M=="number")for(le=N;le<L;++le)this[le]=M;else{var Ee=g.isBuffer(M)?M:ge(new g(M,H).toString()),G=Ee.length;for(le=0;le<L-N;++le)this[le+N]=Ee[le%G]}return this};var Qe=/[^+\/0-9A-Za-z-_]/g;function We(se){return se<16?"0"+se.toString(16):se.toString(16)}function ge(se,M){var N;M=M||1/0;for(var L=se.length,H=null,re=[],le=0;le<L;++le){if((N=se.charCodeAt(le))>55295&&N<57344){if(!H){if(N>56319){(M-=3)>-1&&re.push(239,191,189);continue}if(le+1===L){(M-=3)>-1&&re.push(239,191,189);continue}H=N;continue}if(N<56320){(M-=3)>-1&&re.push(239,191,189),H=N;continue}N=65536+(H-55296<<10|N-56320)}else H&&(M-=3)>-1&&re.push(239,191,189);if(H=null,N<128){if((M-=1)<0)break;re.push(N)}else if(N<2048){if((M-=2)<0)break;re.push(N>>6|192,63&N|128)}else if(N<65536){if((M-=3)<0)break;re.push(N>>12|224,N>>6&63|128,63&N|128)}else{if(!(N<1114112))throw new Error("Invalid code point");if((M-=4)<0)break;re.push(N>>18|240,N>>12&63|128,N>>6&63|128,63&N|128)}}return re}function pe(se){return l.toByteArray((function(N){if((N=(function(H){return H.trim?H.trim():H.replace(/^\s+|\s+$/g,"")})(N).replace(Qe,"")).length<2)return"";for(;N.length%4!=0;)N+="=";return N})(se))}function Me(se,M,N,L){for(var H=0;H<L&&!(H+N>=M.length||H>=se.length);++H)M[H+N]=se[H];return H}}).call(this,s(29))},function(t,i){var s;s=(function(){return this})();try{s=s||new Function("return this")()}catch{typeof window=="object"&&(s=window)}t.exports=s},function(t,i,s){i.byteLength=function(S){var E=g(S),x=E[0],A=E[1];return 3*(x+A)/4-A},i.toByteArray=function(S){var E,x,A=g(S),I=A[0],T=A[1],F=new u((function(Y,_e,j){return 3*(_e+j)/4-j})(0,I,T)),P=0,V=T>0?I-4:I;for(x=0;x<V;x+=4)E=l[S.charCodeAt(x)]<<18|l[S.charCodeAt(x+1)]<<12|l[S.charCodeAt(x+2)]<<6|l[S.charCodeAt(x+3)],F[P++]=E>>16&255,F[P++]=E>>8&255,F[P++]=255&E;return T===2&&(E=l[S.charCodeAt(x)]<<2|l[S.charCodeAt(x+1)]>>4,F[P++]=255&E),T===1&&(E=l[S.charCodeAt(x)]<<10|l[S.charCodeAt(x+1)]<<4|l[S.charCodeAt(x+2)]>>2,F[P++]=E>>8&255,F[P++]=255&E),F},i.fromByteArray=function(S){for(var E,x=S.length,A=x%3,I=[],T=16383,F=0,P=x-A;F<P;F+=T)I.push(y(S,F,F+T>P?P:F+T));return A===1?(E=S[x-1],I.push(o[E>>2]+o[E<<4&63]+"==")):A===2&&(E=(S[x-2]<<8)+S[x-1],I.push(o[E>>10]+o[E>>4&63]+o[E<<2&63]+"=")),I.join("")};for(var o=[],l=[],u=typeof Uint8Array<"u"?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=h.length;d<p;++d)o[d]=h[d],l[h.charCodeAt(d)]=d;function g(v){var S=v.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var E=v.indexOf("=");return E===-1&&(E=S),[E,E===S?0:4-E%4]}function y(v,S,E){for(var x,A,I=[],T=S;T<E;T+=3)x=(v[T]<<16&16711680)+(v[T+1]<<8&65280)+(255&v[T+2]),I.push(o[(A=x)>>18&63]+o[A>>12&63]+o[A>>6&63]+o[63&A]);return I.join("")}l[45]=62,l[95]=63},function(t,i){i.read=function(s,o,l,u,h){var d,p,g=8*h-u-1,y=(1<<g)-1,v=y>>1,S=-7,E=l?h-1:0,x=l?-1:1,A=s[o+E];for(E+=x,d=A&(1<<-S)-1,A>>=-S,S+=g;S>0;d=256*d+s[o+E],E+=x,S-=8);for(p=d&(1<<-S)-1,d>>=-S,S+=u;S>0;p=256*p+s[o+E],E+=x,S-=8);if(d===0)d=1-v;else{if(d===y)return p?NaN:1/0*(A?-1:1);p+=Math.pow(2,u),d-=v}return(A?-1:1)*p*Math.pow(2,d-u)},i.write=function(s,o,l,u,h,d){var p,g,y,v=8*d-h-1,S=(1<<v)-1,E=S>>1,x=h===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=u?0:d-1,I=u?1:-1,T=o<0||o===0&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(g=isNaN(o)?1:0,p=S):(p=Math.floor(Math.log(o)/Math.LN2),o*(y=Math.pow(2,-p))<1&&(p--,y*=2),(o+=p+E>=1?x/y:x*Math.pow(2,1-E))*y>=2&&(p++,y/=2),p+E>=S?(g=0,p=S):p+E>=1?(g=(o*y-1)*Math.pow(2,h),p+=E):(g=o*Math.pow(2,E-1)*Math.pow(2,h),p=0));h>=8;s[l+A]=255&g,A+=I,g/=256,h-=8);for(p=p<<h|g,v+=h;v>0;s[l+A]=255&p,A+=I,p/=256,v-=8);s[l+A-I]|=128*T}},function(t,i){var s={}.toString;t.exports=Array.isArray||function(o){return s.call(o)=="[object Array]"}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(u){var h=u.jws,d=u.KeyUtil,p=u.X509,g=u.crypto,y=u.hextob64u,v=u.b64tohex,S=u.AllowedSigningAlgs;return(function(){function E(){(function(A,I){if(!(A instanceof I))throw new TypeError("Cannot call a class as a function")})(this,E)}return E.parseJwt=function(A){o.Log.debug("JoseUtil.parseJwt");try{var I=h.JWS.parse(A);return{header:I.headerObj,payload:I.payloadObj}}catch(T){o.Log.error(T)}},E.validateJwt=function(A,I,T,F,P,V,B){o.Log.debug("JoseUtil.validateJwt");try{if(I.kty==="RSA")if(I.e&&I.n)I=d.getKey(I);else{if(!I.x5c||!I.x5c.length)return o.Log.error("JoseUtil.validateJwt: RSA key missing key material",I),Promise.reject(new Error("RSA key missing key material"));var Y=v(I.x5c[0]);I=p.getPublicKeyFromCertHex(Y)}else{if(I.kty!=="EC")return o.Log.error("JoseUtil.validateJwt: Unsupported key type",I&&I.kty),Promise.reject(new Error(I.kty));if(!(I.crv&&I.x&&I.y))return o.Log.error("JoseUtil.validateJwt: EC key missing key material",I),Promise.reject(new Error("EC key missing key material"));I=d.getKey(I)}return E._validateJwt(A,I,T,F,P,V,B)}catch(_e){return o.Log.error(_e&&_e.message||_e),Promise.reject("JWT validation failed")}},E.validateJwtAttributes=function(A,I,T,F,P,V){F||(F=0),P||(P=parseInt(Date.now()/1e3));var B=E.parseJwt(A).payload;if(!B.iss)return o.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(B.iss!==I)return o.Log.error("JoseUtil._validateJwt: Invalid issuer in token",B.iss),Promise.reject(new Error("Invalid issuer in token: "+B.iss));if(!B.aud)return o.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(B.aud===T||Array.isArray(B.aud)&&B.aud.indexOf(T)>=0))return o.Log.error("JoseUtil._validateJwt: Invalid audience in token",B.aud),Promise.reject(new Error("Invalid audience in token: "+B.aud));if(B.azp&&B.azp!==T)return o.Log.error("JoseUtil._validateJwt: Invalid azp in token",B.azp),Promise.reject(new Error("Invalid azp in token: "+B.azp));if(!V){var Y=P+F,_e=P-F;if(!B.iat)return o.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(Y<B.iat)return o.Log.error("JoseUtil._validateJwt: iat is in the future",B.iat),Promise.reject(new Error("iat is in the future: "+B.iat));if(B.nbf&&Y<B.nbf)return o.Log.error("JoseUtil._validateJwt: nbf is in the future",B.nbf),Promise.reject(new Error("nbf is in the future: "+B.nbf));if(!B.exp)return o.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(B.exp<_e)return o.Log.error("JoseUtil._validateJwt: exp is in the past",B.exp),Promise.reject(new Error("exp is in the past:"+B.exp))}return Promise.resolve(B)},E._validateJwt=function(A,I,T,F,P,V,B){return E.validateJwtAttributes(A,T,F,P,V,B).then((function(Y){try{return h.JWS.verify(A,I,S)?Y:(o.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(_e){return o.Log.error(_e&&_e.message||_e),Promise.reject(new Error("signature validation failed"))}}))},E.hashString=function(A,I){try{return g.Util.hashString(A,I)}catch(T){o.Log.error(T)}},E.hexToBase64Url=function(A){try{return y(A)}catch(I){o.Log.error(I)}},E})()};var o=s(0);t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninResponse=void 0;var o=(function(){function h(d,p){for(var g=0;g<p.length;g++){var y=p[g];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(d,y.key,y)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(3);function u(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")}i.SigninResponse=(function(){function h(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";u(this,h);var g=l.UrlUtility.parseUrlFragment(d,p);this.error=g.error,this.error_description=g.error_description,this.error_uri=g.error_uri,this.code=g.code,this.state=g.state,this.id_token=g.id_token,this.session_state=g.session_state,this.access_token=g.access_token,this.token_type=g.token_type,this.scope=g.scope,this.profile=void 0,this.expires_in=g.expires_in}return o(h,[{key:"expires_in",get:function(){if(this.expires_at){var p=parseInt(Date.now()/1e3);return this.expires_at-p}},set:function(p){var g=parseInt(p);if(typeof g=="number"&&g>0){var y=parseInt(Date.now()/1e3);this.expires_at=y+g}}},{key:"expired",get:function(){var p=this.expires_in;if(p!==void 0)return p<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf("openid")>=0||!!this.id_token}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutRequest=void 0;var o=s(0),l=s(3),u=s(9);i.SignoutRequest=function h(d){var p=d.url,g=d.id_token_hint,y=d.post_logout_redirect_uri,v=d.data,S=d.extraQueryParams,E=d.request_type;if((function(I,T){if(!(I instanceof T))throw new TypeError("Cannot call a class as a function")})(this,h),!p)throw o.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var x in g&&(p=l.UrlUtility.addQueryParam(p,"id_token_hint",g)),y&&(p=l.UrlUtility.addQueryParam(p,"post_logout_redirect_uri",y),v&&(this.state=new u.State({data:v,request_type:E}),p=l.UrlUtility.addQueryParam(p,"state",this.state.id))),S)p=l.UrlUtility.addQueryParam(p,x,S[x]);this.url=p}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutResponse=void 0;var o=s(3);i.SignoutResponse=function l(u){(function(p,g){if(!(p instanceof g))throw new TypeError("Cannot call a class as a function")})(this,l);var h=o.UrlUtility.parseUrlFragment(u,"?");this.error=h.error,this.error_description=h.error_description,this.error_uri=h.error_uri,this.state=h.state}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.InMemoryWebStorage=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.InMemoryWebStorage=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u),this._data={}}return u.prototype.getItem=function(d){return l.Log.debug("InMemoryWebStorage.getItem",d),this._data[d]},u.prototype.setItem=function(d,p){l.Log.debug("InMemoryWebStorage.setItem",d),this._data[d]=p},u.prototype.removeItem=function(d){l.Log.debug("InMemoryWebStorage.removeItem",d),delete this._data[d]},u.prototype.key=function(d){return Object.getOwnPropertyNames(this._data)[d]},o(u,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManager=void 0;var o=(function(){function T(F,P){for(var V=0;V<P.length;V++){var B=P[V];B.enumerable=B.enumerable||!1,B.configurable=!0,"value"in B&&(B.writable=!0),Object.defineProperty(F,B.key,B)}}return function(F,P,V){return P&&T(F.prototype,P),V&&T(F,V),F}})(),l=s(0),u=s(10),h=s(39),d=s(15),p=s(45),g=s(47),y=s(18),v=s(8),S=s(20),E=s(11),x=s(4);function A(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function I(T,F){if(!T)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!F||typeof F!="object"&&typeof F!="function"?T:F}i.UserManager=(function(T){function F(){var P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},V=arguments.length>1&&arguments[1]!==void 0?arguments[1]:g.SilentRenewService,B=arguments.length>2&&arguments[2]!==void 0?arguments[2]:y.SessionMonitor,Y=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,_e=arguments.length>4&&arguments[4]!==void 0?arguments[4]:E.TokenClient,j=arguments.length>5&&arguments[5]!==void 0?arguments[5]:x.JoseUtil;A(this,F),P instanceof h.UserManagerSettings||(P=new h.UserManagerSettings(P));var ee=I(this,T.call(this,P));return ee._events=new p.UserManagerEvents(P),ee._silentRenewService=new V(ee),ee.settings.automaticSilentRenew&&(l.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),ee.startSilentRenew()),ee.settings.monitorSession&&(l.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),ee._sessionMonitor=new B(ee)),ee._tokenRevocationClient=new Y(ee._settings),ee._tokenClient=new _e(ee._settings),ee._joseUtil=j,ee}return(function(V,B){if(typeof B!="function"&&B!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof B);V.prototype=Object.create(B&&B.prototype,{constructor:{value:V,enumerable:!1,writable:!0,configurable:!0}}),B&&(Object.setPrototypeOf?Object.setPrototypeOf(V,B):V.__proto__=B)})(F,T),F.prototype.getUser=function(){var V=this;return this._loadUser().then((function(B){return B?(l.Log.info("UserManager.getUser: user loaded"),V._events.load(B,!1),B):(l.Log.info("UserManager.getUser: user not found in storage"),null)}))},F.prototype.removeUser=function(){var V=this;return this.storeUser(null).then((function(){l.Log.info("UserManager.removeUser: user removed from storage"),V._events.unload()}))},F.prototype.signinRedirect=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(V=Object.assign({},V)).request_type="si:r";var B={useReplaceToNavigate:V.useReplaceToNavigate};return this._signinStart(V,this._redirectNavigator,B).then((function(){l.Log.info("UserManager.signinRedirect: successful")}))},F.prototype.signinRedirectCallback=function(V){return this._signinEnd(V||this._redirectNavigator.url).then((function(B){return B.profile&&B.profile.sub?l.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",B.profile.sub):l.Log.info("UserManager.signinRedirectCallback: no sub"),B}))},F.prototype.signinPopup=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(V=Object.assign({},V)).request_type="si:p";var B=V.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return B?(V.redirect_uri=B,V.display="popup",this._signin(V,this._popupNavigator,{startUrl:B,popupWindowFeatures:V.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:V.popupWindowTarget||this.settings.popupWindowTarget}).then((function(Y){return Y&&(Y.profile&&Y.profile.sub?l.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",Y.profile.sub):l.Log.info("UserManager.signinPopup: no sub")),Y}))):(l.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},F.prototype.signinPopupCallback=function(V){return this._signinCallback(V,this._popupNavigator).then((function(B){return B&&(B.profile&&B.profile.sub?l.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",B.profile.sub):l.Log.info("UserManager.signinPopupCallback: no sub")),B})).catch((function(B){l.Log.error(B.message)}))},F.prototype.signinSilent=function(){var V=this,B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return B=Object.assign({},B),this._loadUser().then((function(Y){return Y&&Y.refresh_token?(B.refresh_token=Y.refresh_token,V._useRefreshToken(B)):(B.request_type="si:s",B.id_token_hint=B.id_token_hint||V.settings.includeIdTokenInSilentRenew&&Y&&Y.id_token,Y&&V._settings.validateSubOnSilentRenew&&(l.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",Y.profile.sub),B.current_sub=Y.profile.sub),V._signinSilentIframe(B))}))},F.prototype._useRefreshToken=function(){var V=this,B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(B).then((function(Y){return Y?Y.access_token?V._loadUser().then((function(_e){if(_e){var j=Promise.resolve();return Y.id_token&&(j=V._validateIdTokenFromTokenRefreshToken(_e.profile,Y.id_token)),j.then((function(){return l.Log.debug("UserManager._useRefreshToken: refresh token response success"),_e.id_token=Y.id_token||_e.id_token,_e.access_token=Y.access_token,_e.refresh_token=Y.refresh_token||_e.refresh_token,_e.expires_in=Y.expires_in,V.storeUser(_e).then((function(){return V._events.load(_e),_e}))}))}return null})):(l.Log.error("UserManager._useRefreshToken: No access token returned from token endpoint"),Promise.reject("No access token returned from token endpoint")):(l.Log.error("UserManager._useRefreshToken: No response returned from token endpoint"),Promise.reject("No response returned from token endpoint"))}))},F.prototype._validateIdTokenFromTokenRefreshToken=function(V,B){var Y=this;return this._metadataService.getIssuer().then((function(_e){return Y.settings.getEpochTime().then((function(j){return Y._joseUtil.validateJwtAttributes(B,_e,Y._settings.client_id,Y._settings.clockSkew,j).then((function(ee){return ee?ee.sub!==V.sub?(l.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"))):ee.auth_time&&ee.auth_time!==V.auth_time?(l.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"))):ee.azp&&ee.azp!==V.azp?(l.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"))):!ee.azp&&V.azp?(l.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:(l.Log.error("UserManager._validateIdTokenFromTokenRefreshToken: Failed to validate id_token"),Promise.reject(new Error("Failed to validate id_token")))}))}))}))},F.prototype._signinSilentIframe=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},B=V.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return B?(V.redirect_uri=B,V.prompt=V.prompt||"none",this._signin(V,this._iframeNavigator,{startUrl:B,silentRequestTimeout:V.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(Y){return Y&&(Y.profile&&Y.profile.sub?l.Log.info("UserManager.signinSilent: successful, signed in sub: ",Y.profile.sub):l.Log.info("UserManager.signinSilent: no sub")),Y}))):(l.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype.signinSilentCallback=function(V){return this._signinCallback(V,this._iframeNavigator).then((function(B){return B&&(B.profile&&B.profile.sub?l.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",B.profile.sub):l.Log.info("UserManager.signinSilentCallback: no sub")),B}))},F.prototype.signinCallback=function(V){var B=this;return this.readSigninResponseState(V).then((function(Y){var _e=Y.state;return Y.response,_e.request_type==="si:r"?B.signinRedirectCallback(V):_e.request_type==="si:p"?B.signinPopupCallback(V):_e.request_type==="si:s"?B.signinSilentCallback(V):Promise.reject(new Error("invalid response_type in state"))}))},F.prototype.signoutCallback=function(V,B){var Y=this;return this.readSignoutResponseState(V).then((function(_e){var j=_e.state,ee=_e.response;return j?j.request_type==="so:r"?Y.signoutRedirectCallback(V):j.request_type==="so:p"?Y.signoutPopupCallback(V,B):Promise.reject(new Error("invalid response_type in state")):ee}))},F.prototype.querySessionStatus=function(){var V=this,B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(B=Object.assign({},B)).request_type="si:s";var Y=B.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return Y?(B.redirect_uri=Y,B.prompt="none",B.response_type=B.response_type||this.settings.query_status_response_type,B.scope=B.scope||"openid",B.skipUserInfo=!0,this._signinStart(B,this._iframeNavigator,{startUrl:Y,silentRequestTimeout:B.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(_e){return V.processSigninResponse(_e.url).then((function(j){if(l.Log.debug("UserManager.querySessionStatus: got signin response"),j.session_state&&j.profile.sub)return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",j.profile.sub),{session_state:j.session_state,sub:j.profile.sub,sid:j.profile.sid};l.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(j){if(j.session_state&&V.settings.monitorAnonymousSession&&(j.message=="login_required"||j.message=="consent_required"||j.message=="interaction_required"||j.message=="account_selection_required"))return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:j.session_state};throw j}))}))):(l.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype._signin=function(V,B){var Y=this,_e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(V,B,_e).then((function(j){return Y._signinEnd(j.url,V)}))},F.prototype._signinStart=function(V,B){var Y=this,_e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return B.prepare(_e).then((function(j){return l.Log.debug("UserManager._signinStart: got navigator window handle"),Y.createSigninRequest(V).then((function(ee){return l.Log.debug("UserManager._signinStart: got signin request"),_e.url=ee.url,_e.id=ee.state.id,j.navigate(_e)})).catch((function(ee){throw j.close&&(l.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),j.close()),ee}))}))},F.prototype._signinEnd=function(V){var B=this,Y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(V).then((function(_e){l.Log.debug("UserManager._signinEnd: got signin response");var j=new d.User(_e);if(Y.current_sub){if(Y.current_sub!==j.profile.sub)return l.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",j.profile.sub),Promise.reject(new Error("login_required"));l.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return B.storeUser(j).then((function(){return l.Log.debug("UserManager._signinEnd: user stored"),B._events.load(j),j}))}))},F.prototype._signinCallback=function(V,B){l.Log.debug("UserManager._signinCallback");var Y=this._settings.response_mode==="query"||!this._settings.response_mode&&v.SigninRequest.isCode(this._settings.response_type)?"?":"#";return B.callback(V,void 0,Y)},F.prototype.signoutRedirect=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(V=Object.assign({},V)).request_type="so:r";var B=V.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;B&&(V.post_logout_redirect_uri=B);var Y={useReplaceToNavigate:V.useReplaceToNavigate};return this._signoutStart(V,this._redirectNavigator,Y).then((function(){l.Log.info("UserManager.signoutRedirect: successful")}))},F.prototype.signoutRedirectCallback=function(V){return this._signoutEnd(V||this._redirectNavigator.url).then((function(B){return l.Log.info("UserManager.signoutRedirectCallback: successful"),B}))},F.prototype.signoutPopup=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(V=Object.assign({},V)).request_type="so:p";var B=V.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return V.post_logout_redirect_uri=B,V.display="popup",V.post_logout_redirect_uri&&(V.state=V.state||{}),this._signout(V,this._popupNavigator,{startUrl:B,popupWindowFeatures:V.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:V.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){l.Log.info("UserManager.signoutPopup: successful")}))},F.prototype.signoutPopupCallback=function(V,B){return B===void 0&&typeof V=="boolean"&&(B=V,V=null),this._popupNavigator.callback(V,B,"?").then((function(){l.Log.info("UserManager.signoutPopupCallback: successful")}))},F.prototype._signout=function(V,B){var Y=this,_e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(V,B,_e).then((function(j){return Y._signoutEnd(j.url)}))},F.prototype._signoutStart=function(){var V=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},B=this,Y=arguments[1],_e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return Y.prepare(_e).then((function(j){return l.Log.debug("UserManager._signoutStart: got navigator window handle"),B._loadUser().then((function(ee){return l.Log.debug("UserManager._signoutStart: loaded current user from storage"),(B._settings.revokeAccessTokenOnSignout?B._revokeInternal(ee):Promise.resolve()).then((function(){var me=V.id_token_hint||ee&&ee.id_token;return me&&(l.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),V.id_token_hint=me),B.removeUser().then((function(){return l.Log.debug("UserManager._signoutStart: user removed, creating signout request"),B.createSignoutRequest(V).then((function(te){return l.Log.debug("UserManager._signoutStart: got signout request"),_e.url=te.url,te.state&&(_e.id=te.state.id),j.navigate(_e)}))}))}))})).catch((function(ee){throw j.close&&(l.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),j.close()),ee}))}))},F.prototype._signoutEnd=function(V){return this.processSignoutResponse(V).then((function(B){return l.Log.debug("UserManager._signoutEnd: got signout response"),B}))},F.prototype.revokeAccessToken=function(){var V=this;return this._loadUser().then((function(B){return V._revokeInternal(B,!0).then((function(Y){if(Y)return l.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),B.access_token=null,B.refresh_token=null,B.expires_at=null,B.token_type=null,V.storeUser(B).then((function(){l.Log.debug("UserManager.revokeAccessToken: user stored"),V._events.load(B)}))}))})).then((function(){l.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},F.prototype._revokeInternal=function(V,B){var Y=this;if(V){var _e=V.access_token,j=V.refresh_token;return this._revokeAccessTokenInternal(_e,B).then((function(ee){return Y._revokeRefreshTokenInternal(j,B).then((function(me){return ee||me||l.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),ee||me}))}))}return Promise.resolve(!1)},F.prototype._revokeAccessTokenInternal=function(V,B){return!V||V.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(V,B).then((function(){return!0}))},F.prototype._revokeRefreshTokenInternal=function(V,B){return V?this._tokenRevocationClient.revoke(V,B,"refresh_token").then((function(){return!0})):Promise.resolve(!1)},F.prototype.startSilentRenew=function(){this._silentRenewService.start()},F.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},F.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then((function(V){return V?(l.Log.debug("UserManager._loadUser: user storageString loaded"),d.User.fromStorageString(V)):(l.Log.debug("UserManager._loadUser: no user storageString"),null)}))},F.prototype.storeUser=function(V){if(V){l.Log.debug("UserManager.storeUser: storing user");var B=V.toStorageString();return this._userStore.set(this._userStoreKey,B)}return l.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},o(F,[{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}}]),F})(u.OidcClient)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerSettings=void 0;var o=(function(){function E(x,A){for(var I=0;I<A.length;I++){var T=A[I];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(x,T.key,T)}}return function(x,A,I){return A&&E(x.prototype,A),I&&E(x,I),x}})(),l=(s(0),s(5)),u=s(40),h=s(41),d=s(43),p=s(6),g=s(1),y=s(8);function v(E,x){if(!(E instanceof x))throw new TypeError("Cannot call a class as a function")}function S(E,x){if(!E)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!x||typeof x!="object"&&typeof x!="function"?E:x}i.UserManagerSettings=(function(E){function x(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},I=A.popup_redirect_uri,T=A.popup_post_logout_redirect_uri,F=A.popupWindowFeatures,P=A.popupWindowTarget,V=A.silent_redirect_uri,B=A.silentRequestTimeout,Y=A.automaticSilentRenew,_e=Y!==void 0&&Y,j=A.validateSubOnSilentRenew,ee=j!==void 0&&j,me=A.includeIdTokenInSilentRenew,te=me===void 0||me,Ce=A.monitorSession,Oe=Ce===void 0||Ce,ye=A.monitorAnonymousSession,qe=ye!==void 0&&ye,de=A.checkSessionInterval,Fe=de===void 0?2e3:de,O=A.stopCheckSessionOnError,Z=O===void 0||O,fe=A.query_status_response_type,oe=A.revokeAccessTokenOnSignout,Pe=oe!==void 0&&oe,je=A.accessTokenExpiringNotificationTime,Qe=je===void 0?60:je,We=A.redirectNavigator,ge=We===void 0?new u.RedirectNavigator:We,pe=A.popupNavigator,Me=pe===void 0?new h.PopupNavigator:pe,se=A.iframeNavigator,M=se===void 0?new d.IFrameNavigator:se,N=A.userStore,L=N===void 0?new p.WebStorageStateStore({store:g.Global.sessionStorage}):N;v(this,x);var H=S(this,E.call(this,arguments[0]));return H._popup_redirect_uri=I,H._popup_post_logout_redirect_uri=T,H._popupWindowFeatures=F,H._popupWindowTarget=P,H._silent_redirect_uri=V,H._silentRequestTimeout=B,H._automaticSilentRenew=_e,H._validateSubOnSilentRenew=ee,H._includeIdTokenInSilentRenew=te,H._accessTokenExpiringNotificationTime=Qe,H._monitorSession=Oe,H._monitorAnonymousSession=qe,H._checkSessionInterval=Fe,H._stopCheckSessionOnError=Z,fe?H._query_status_response_type=fe:arguments[0]&&arguments[0].response_type?H._query_status_response_type=y.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":H._query_status_response_type="id_token",H._revokeAccessTokenOnSignout=Pe,H._redirectNavigator=ge,H._popupNavigator=Me,H._iframeNavigator=M,H._userStore=L,H}return(function(I,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof T);I.prototype=Object.create(T&&T.prototype,{constructor:{value:I,enumerable:!1,writable:!0,configurable:!0}}),T&&(Object.setPrototypeOf?Object.setPrototypeOf(I,T):I.__proto__=T)})(x,E),o(x,[{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}}]),x})(l.OidcClientSettings)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.RedirectNavigator=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.RedirectNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(){return Promise.resolve(this)},u.prototype.navigate=function(d){return d&&d.url?(d.useReplaceToNavigate?window.location.replace(d.url):window.location=d.url,Promise.resolve()):(l.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},o(u,[{key:"url",get:function(){return window.location.href}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupNavigator=void 0;var o=s(0),l=s(42);i.PopupNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.PopupWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d,p,g){o.Log.debug("PopupNavigator.callback");try{return l.PopupWindow.notifyOpener(d,p,g),Promise.resolve()}catch(y){return Promise.reject(y)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupWindow=void 0;var o=(function(){function h(d,p){for(var g=0;g<p.length;g++){var y=p[g];y.enumerable=y.enumerable||!1,y.configurable=!0,"value"in y&&(y.writable=!0),Object.defineProperty(d,y.key,y)}}return function(d,p,g){return p&&h(d.prototype,p),g&&h(d,g),d}})(),l=s(0),u=s(3);i.PopupWindow=(function(){function h(d){var p=this;(function(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")})(this,h),this._promise=new Promise((function(v,S){p._resolve=v,p._reject=S}));var g=d.popupWindowTarget||"_blank",y=d.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",g,y),this._popup&&(l.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return h.prototype.navigate=function(p){return this._popup?p&&p.url?(l.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=p.id,this._id&&(window["popupCallback_"+p.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=p.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},h.prototype._success=function(p){l.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(p)},h.prototype._error=function(p){l.Log.error("PopupWindow.error: ",p),this._cleanup(),this._reject(new Error(p))},h.prototype.close=function(){this._cleanup(!1)},h.prototype._cleanup=function(p){l.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!p&&this._popup.close(),this._popup=null},h.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},h.prototype._callback=function(p,g){this._cleanup(g),p?(l.Log.debug("PopupWindow.callback success"),this._success({url:p})):(l.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},h.notifyOpener=function(p,g,y){if(window.opener){if(p=p||window.location.href){var v=u.UrlUtility.parseUrlFragment(p,y);if(v.state){var S="popupCallback_"+v.state,E=window.opener[S];E?(l.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),E(p,g)):l.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else l.Log.warn("PopupWindow.notifyOpener: no state found in response url")}}else l.Log.warn("PopupWindow.notifyOpener: no window.opener. Can't complete notification.")},o(h,[{key:"promise",get:function(){return this._promise}}]),h})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameNavigator=void 0;var o=s(0),l=s(44);i.IFrameNavigator=(function(){function u(){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,u)}return u.prototype.prepare=function(d){var p=new l.IFrameWindow(d);return Promise.resolve(p)},u.prototype.callback=function(d){o.Log.debug("IFrameNavigator.callback");try{return l.IFrameWindow.notifyParent(d),Promise.resolve()}catch(p){return Promise.reject(p)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameWindow=void 0;var o=(function(){function u(h,d){for(var p=0;p<d.length;p++){var g=d[p];g.enumerable=g.enumerable||!1,g.configurable=!0,"value"in g&&(g.writable=!0),Object.defineProperty(h,g.key,g)}}return function(h,d,p){return d&&u(h.prototype,d),p&&u(h,p),h}})(),l=s(0);i.IFrameWindow=(function(){function u(h){var d=this;(function(g,y){if(!(g instanceof y))throw new TypeError("Cannot call a class as a function")})(this,u),this._promise=new Promise((function(p,g){d._resolve=p,d._reject=g})),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 u.prototype.navigate=function(d){if(d&&d.url){var p=d.silentRequestTimeout||1e4;l.Log.debug("IFrameWindow.navigate: Using timeout of:",p),this._timer=window.setTimeout(this._timeout.bind(this),p),this._frame.src=d.url}else this._error("No url provided");return this.promise},u.prototype._success=function(d){this._cleanup(),l.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(d)},u.prototype._error=function(d){this._cleanup(),l.Log.error(d),this._reject(new Error(d))},u.prototype.close=function(){this._cleanup()},u.prototype._cleanup=function(){this._frame&&(l.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)},u.prototype._timeout=function(){l.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},u.prototype._message=function(d){if(l.Log.debug("IFrameWindow.message"),this._timer&&d.origin===this._origin&&d.source===this._frame.contentWindow&&typeof d.data=="string"&&(d.data.startsWith("http://")||d.data.startsWith("https://"))){var p=d.data;p?this._success({url:p}):this._error("Invalid response from frame")}},u.notifyParent=function(d){l.Log.debug("IFrameWindow.notifyParent"),(d=d||window.location.href)&&(l.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(d,location.protocol+"//"+location.host))},o(u,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.UserManagerEvents=void 0;var o=s(0),l=s(16),u=s(17);i.UserManagerEvents=(function(h){function d(p){(function(v,S){if(!(v instanceof S))throw new TypeError("Cannot call a class as a function")})(this,d);var g=(function(v,S){if(!v)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!S||typeof S!="object"&&typeof S!="function"?v:S})(this,h.call(this,p));return g._userLoaded=new u.Event("User loaded"),g._userUnloaded=new u.Event("User unloaded"),g._silentRenewError=new u.Event("Silent renew error"),g._userSignedIn=new u.Event("User signed in"),g._userSignedOut=new u.Event("User signed out"),g._userSessionChanged=new u.Event("User session changed"),g}return(function(g,y){if(typeof y!="function"&&y!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof y);g.prototype=Object.create(y&&y.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),y&&(Object.setPrototypeOf?Object.setPrototypeOf(g,y):g.__proto__=y)})(d,h),d.prototype.load=function(g){var y=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];o.Log.debug("UserManagerEvents.load"),h.prototype.load.call(this,g),y&&this._userLoaded.raise(g)},d.prototype.unload=function(){o.Log.debug("UserManagerEvents.unload"),h.prototype.unload.call(this),this._userUnloaded.raise()},d.prototype.addUserLoaded=function(g){this._userLoaded.addHandler(g)},d.prototype.removeUserLoaded=function(g){this._userLoaded.removeHandler(g)},d.prototype.addUserUnloaded=function(g){this._userUnloaded.addHandler(g)},d.prototype.removeUserUnloaded=function(g){this._userUnloaded.removeHandler(g)},d.prototype.addSilentRenewError=function(g){this._silentRenewError.addHandler(g)},d.prototype.removeSilentRenewError=function(g){this._silentRenewError.removeHandler(g)},d.prototype._raiseSilentRenewError=function(g){o.Log.debug("UserManagerEvents._raiseSilentRenewError",g.message),this._silentRenewError.raise(g)},d.prototype.addUserSignedIn=function(g){this._userSignedIn.addHandler(g)},d.prototype.removeUserSignedIn=function(g){this._userSignedIn.removeHandler(g)},d.prototype._raiseUserSignedIn=function(){o.Log.debug("UserManagerEvents._raiseUserSignedIn"),this._userSignedIn.raise()},d.prototype.addUserSignedOut=function(g){this._userSignedOut.addHandler(g)},d.prototype.removeUserSignedOut=function(g){this._userSignedOut.removeHandler(g)},d.prototype._raiseUserSignedOut=function(){o.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise()},d.prototype.addUserSessionChanged=function(g){this._userSessionChanged.addHandler(g)},d.prototype.removeUserSessionChanged=function(g){this._userSessionChanged.removeHandler(g)},d.prototype._raiseUserSessionChanged=function(){o.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise()},d})(l.AccessTokenEvents)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Timer=void 0;var o=(function(){function g(y,v){for(var S=0;S<v.length;S++){var E=v[S];E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty(y,E.key,E)}}return function(y,v,S){return v&&g(y.prototype,v),S&&g(y,S),y}})(),l=s(0),u=s(1),h=s(17);function d(g,y){if(!(g instanceof y))throw new TypeError("Cannot call a class as a function")}function p(g,y){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!y||typeof y!="object"&&typeof y!="function"?g:y}i.Timer=(function(g){function y(v){var S=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u.Global.timer,E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;d(this,y);var x=p(this,g.call(this,v));return x._timer=S,x._nowFunc=E||function(){return Date.now()/1e3},x}return(function(S,E){if(typeof E!="function"&&E!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof E);S.prototype=Object.create(E&&E.prototype,{constructor:{value:S,enumerable:!1,writable:!0,configurable:!0}}),E&&(Object.setPrototypeOf?Object.setPrototypeOf(S,E):S.__proto__=E)})(y,g),y.prototype.init=function(S){S<=0&&(S=1),S=parseInt(S);var E=this.now+S;if(this.expiration===E&&this._timerHandle)l.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);else{this.cancel(),l.Log.debug("Timer.init timer "+this._name+" for duration:",S),this._expiration=E;var x=5;S<x&&(x=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*x)}},y.prototype.cancel=function(){this._timerHandle&&(l.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},y.prototype._callback=function(){var S=this._expiration-this.now;l.Log.debug("Timer.callback; "+this._name+" timer expires in:",S),this._expiration<=this.now&&(this.cancel(),g.prototype.raise.call(this))},o(y,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),y})(h.Event)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SilentRenewService=void 0;var o=s(0);i.SilentRenewService=(function(){function l(u){(function(d,p){if(!(d instanceof p))throw new TypeError("Cannot call a class as a function")})(this,l),this._userManager=u}return l.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then((function(h){})).catch((function(h){o.Log.error("SilentRenewService.start: Error from getUser:",h.message)})))},l.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},l.prototype._tokenExpiring=function(){var h=this;this._userManager.signinSilent().then((function(d){o.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(d){o.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",d.message),h._userManager.events._raiseSilentRenewError(d)}))},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupNavigator=void 0;var o=s(21);i.CordovaPopupNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){var d=new o.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaIFrameNavigator=void 0;var o=s(21);i.CordovaIFrameNavigator=(function(){function l(){(function(h,d){if(!(h instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(h){h.popupWindowFeatures="hidden=yes";var d=new o.CordovaPopupWindow(h);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.Version="1.11.6"}])}))})(oidcClient_min$1)),oidcClient_min$1.exports}var oidcClient_minExports=requireOidcClient_min();function processErrorResponse(n,e){throw n.error==="invalid_redirect_uri"?new Error(`Dynamic client registration failed: the provided redirect uri [${e.redirectUrl?.toString()}] is invalid - ${n.error_description??""}`):n.error==="invalid_client_metadata"?new Error(`Dynamic client registration failed: the provided client metadata ${JSON.stringify(e)} is invalid - ${n.error_description??""}`):new Error(`Dynamic client registration failed: ${n.error} - ${n.error_description??""}`)}function hasClientId(n){return typeof n.client_id=="string"}function hasRedirectUri(n){return Array.isArray(n.redirect_uris)&&n.redirect_uris.every(e=>typeof e=="string")}function validateRegistrationResponse(n,e){if(!hasClientId(n))throw new Error(`Dynamic client registration failed: no client_id has been found on ${JSON.stringify(n)}`);if(e.redirectUrl&&hasRedirectUri(n)&&n.redirect_uris[0]!==e.redirectUrl.toString())throw new Error(`Dynamic client registration failed: the returned redirect URIs ${JSON.stringify(n.redirect_uris)} don't match the provided ${JSON.stringify([e.redirectUrl.toString()])}`);return!0}async function registerClient(n,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),i={client_name:n.clientName,application_type:"web",redirect_uris:[n.redirectUrl?.toString()],subject_type:"public",token_endpoint_auth_method:"client_secret_basic",id_token_signed_response_alg:t,grant_types:["authorization_code","refresh_token"]},s={"Content-Type":"application/json"},o=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:s,body:JSON.stringify(i)});if(o.ok){const l=await o.json();return validateRegistrationResponse(l,n),{clientId:l.client_id,clientSecret:l.client_secret,expiresAt:l.client_secret_expires_at,idTokenSignedResponseAlg:l.id_token_signed_response_alg,clientType:"dynamic"}}throw o.status===400&&processErrorResponse(await o.json(),n),new Error(`Dynamic client registration failed: the server returned ${o.status} ${o.statusText} - ${await o.text()}`)}function hasError(n){return n.error!==void 0&&typeof n.error=="string"}function hasErrorDescription(n){return n.error_description!==void 0&&typeof n.error_description=="string"}function hasErrorUri(n){return n.error_uri!==void 0&&typeof n.error_uri=="string"}function hasAccessToken(n){return n.access_token!==void 0&&typeof n.access_token=="string"}function hasIdToken(n){return n.id_token!==void 0&&typeof n.id_token=="string"}function hasRefreshToken(n){return n.refresh_token!==void 0&&typeof n.refresh_token=="string"}function hasTokenType(n){return n.token_type!==void 0&&typeof n.token_type=="string"}function hasExpiresIn(n){return n.expires_in===void 0||typeof n.expires_in=="number"}function validatePreconditions(n,e){if(e.grantType&&(!n.grantTypesSupported||!n.grantTypesSupported.includes(e.grantType)))throw new Error(`The issuer [${n.issuer}] does not support the [${e.grantType}] grant`);if(!n.tokenEndpoint)throw new Error(`This issuer [${n.issuer}] does not have a token endpoint`)}function validateTokenEndpointResponse(n,e){if(hasError(n))throw new OidcProviderError(`Token endpoint returned error [${n.error}]${hasErrorDescription(n)?`: ${n.error_description}`:""}${hasErrorUri(n)?` (see ${n.error_uri})`:""}`,n.error,hasErrorDescription(n)?n.error_description:void 0);if(!hasAccessToken(n))throw new InvalidResponseError(["access_token"]);if(!hasIdToken(n))throw new InvalidResponseError(["id_token"]);if(!hasTokenType(n))throw new InvalidResponseError(["token_type"]);if(!hasExpiresIn(n))throw new InvalidResponseError(["expires_in"]);if(!e&&n.token_type.toLowerCase()!=="bearer")throw new Error(`Invalid token endpoint response: requested a [Bearer] token, but got a 'token_type' value of [${n.token_type}].`);return n}async function getTokens(n,e,t,i){validatePreconditions(n,t);const s={"content-type":"application/x-www-form-urlencoded"};let o;i&&(o=await generateDpopKeyPair(),s.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",o)),e.clientSecret&&(s.Authorization=`Basic ${btoa(`${e.clientId}:${e.clientSecret}`)}`);const l={grant_type:t.grantType,redirect_uri:t.redirectUrl,code:t.code,code_verifier:t.codeVerifier,client_id:e.clientId},u={method:"POST",headers:s,body:new URLSearchParams(l).toString()},d=await(await fetch(n.tokenEndpoint,u)).json(),p=validateTokenEndpointResponse(d,i),{webId:g,clientId:y}=await getWebidFromTokenPayload(p.id_token,n.jwksUri,n.issuer,e.clientId);return{accessToken:p.access_token,idToken:p.id_token,refreshToken:hasRefreshToken(p)?p.refresh_token:void 0,webId:g,clientId:y,dpopKey:o,expiresIn:p.expires_in}}const isValidUrl=n=>{try{return new URL(n),!0}catch{return!1}};async function refresh(n,e,t,i){if(t.clientId===void 0)throw new Error("No client ID available when trying to refresh the access token.");const s={grant_type:"refresh_token",refresh_token:n};let o={};i!==void 0&&(o={DPoP:await createDpopHeader(e.tokenEndpoint,"POST",i)});let l={};t.clientSecret!==void 0?l={Authorization:`Basic ${btoa(`${t.clientId}:${t.clientSecret}`)}`}:isValidUrl(t.clientId)&&(s.client_id=t.clientId);const u=await fetch(e.tokenEndpoint,{method:"POST",body:new URLSearchParams(s).toString(),headers:{...o,...l,"Content-Type":"application/x-www-form-urlencoded"}});let h;try{h=await u.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const d=validateTokenEndpointResponse(h,i!==void 0),{webId:p}=await getWebidFromTokenPayload(d.id_token,e.jwksUri,e.issuer,t.clientId);return{accessToken:d.access_token,idToken:d.id_token,refreshToken:typeof d.refresh_token=="string"?d.refresh_token:void 0,webId:p,dpopKey:i,expiresIn:d.expires_in}}function normalizeCallbackUrl(n){const e=removeOpenIdParams(n);return e.hash="",n.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 i=0;i<=e.length;i+=1){const s=e.key(i);s&&(s.match(/^oidc\..+$/)||s.match(/^solidClientAuthenticationUser:.+$/))&&t.push(s)}t.forEach(i=>e.removeItem(i))}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 i=e.redirectUrl??normalizeCallbackUrl(window.location.href);if(!isValidRedirectUrl(i))throw new Error(`${i} 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:i,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 i=await this.redirectHandler.handle(e,t,void 0);return this.fetch=i.fetch.bind(window),this.boundLogout=i.getLogoutUrl,await this.cleanUrlAfterRedirect(e),{isLoggedIn:i.isLoggedIn,webId:i.webId,sessionId:i.sessionId,expirationDate:i.expirationDate,clientAppId:i.clientAppId}}catch(i){await this.cleanUrlAfterRedirect(e),t.emit(EVENTS.ERROR,"redirect",i);return}};async cleanUrlAfterRedirect(e){const t=removeOpenIdParams(e).href;for(window.history.replaceState(null,"",t);window.location.href!==t;)await new Promise(i=>{setTimeout(()=>i(),1)})}}function hasIssuer(n){return typeof n.oidcIssuer=="string"}function hasRedirectUrl(n){return typeof n.redirectUrl=="string"}class OidcLoginHandler{storageUtility;oidcHandler;issuerConfigFetcher;clientRegistrar;constructor(e,t,i,s){this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.storageUtility=e,this.oidcHandler=t,this.issuerConfigFetcher=i,this.clientRegistrar=s}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),i=await handleRegistration(e,t,this.storageUtility,this.clientRegistrar),s={issuer:t.issuer,dpop:e.tokenType.toLowerCase()==="dpop",...e,issuerConfiguration:t,client:i,scopes:normalizeScopes(e.customScopes)};return this.oidcHandler.handle(s)}}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"},i=new oidcClient_minExports.OidcClient(t);try{const s=await i.createSigninRequest();return await this.setupRedirectHandler({oidcLoginOptions:e,state:s.state._id,codeVerifier:s.state._code_verifier,targetUrl:s.url.toString()})}catch(s){console.error(s)}}}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(n){const e={};return Object.keys(n).forEach(t=>{issuerConfigKeyMap[t]&&(e[issuerConfigKeyMap[t].toKey]=n[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 i=new URL(WELL_KNOWN_OPENID_CONFIG,e.endsWith("/")?e:`${e}/`).href,s=await fetch(i);try{t=processConfig(await s.json())}catch(o){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${o.message}`)}return await this.storageUtility.set(IssuerConfigFetcher.getLocalStorageKey(e),JSON.stringify(t)),t}}async function clear(n,e){await clear$1(n,e),await clearOidcPersistentStorage()}class SessionInfoManager extends SessionInfoManagerBase{async get(e){const[t,i,s,o,l,u,h,d]=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 l=="string"&&!isValidRedirectUrl(l)){await Promise.all([this.storageUtility.deleteAllUserData(e,{secure:!1}),this.storageUtility.deleteAllUserData(e,{secure:!0})]);return}if(d!==void 0&&!isSupportedTokenType(d))throw new Error(`Tokens of type [${d}] are not supported.`);if(!(s===void 0&&t===void 0&&i===void 0&&u===void 0))return{sessionId:e,webId:i,isLoggedIn:t==="true",redirectUrl:l,refreshToken:u,issuer:h,clientAppId:s,clientAppSecret:o,tokenType:d??"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,i,s,o,l){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=o,this.fetch=l,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=o}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 i=new URL(e),s=i.searchParams.get("state"),o=await this.storageUtility.getForUser(s,"sessionId",{errorIfNull:!0}),{issuerConfig:l,codeVerifier:u,redirectUrl:h,dpop:d}=await loadOidcContextFromStorage(o,this.storageUtility,this.issuerConfigFetcher),p=i.searchParams.get("iss");if(typeof p=="string"&&p!==l.issuer)throw new Error(`The value of the iss parameter (${p}) does not match the issuer identifier of the authorization server (${l.issuer}). See [rfc9207](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.3-3.1.1)`);if(u===void 0)throw new Error(`The code verifier for session ${o} is missing from storage.`);if(h===void 0)throw new Error(`The redirect URL for session ${o} is missing from storage.`);const g=await this.clientRegistrar.getClient({sessionId:o},l),y=Date.now(),v=await getTokens(l,g,{grantType:"authorization_code",code:i.searchParams.get("code"),codeVerifier:u,redirectUrl:h},d);window.localStorage.removeItem(`oidc.${s}`);let S;v.refreshToken!==void 0&&(S={sessionId:o,refreshToken:v.refreshToken,tokenRefresher:this.tokerRefresher});const E=buildAuthenticatedFetch(v.accessToken,{dpopKey:v.dpopKey,refreshOptions:S,eventEmitter:t,expiresIn:v.expiresIn,fetch:this.fetch});await saveSessionInfoToStorage(this.storageUtility,o,v.webId,v.clientId,"true",void 0,!0);const x=await this.sessionInfoManager.get(o);if(!x)throw new Error(`Could not retrieve session: [${o}].`);return Object.assign(x,{fetch:E,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:v.idToken,endSessionEndpoint:l.endSessionEndpoint}),expirationDate:typeof v.expiresIn=="number"?y+v.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[i,s,o,l,u]=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})]),h=o!==void 0?Number.parseInt(o,10):-1,d=s!==void 0&&h!==0&&Math.floor(Date.now()/1e3)>h;if(i&&isKnownClientType(u)&&!d)return s!==void 0?{clientId:i,clientSecret:s,clientName:l,clientType:"dynamic",expiresAt:h}:{clientId:i,clientName:l,clientType:u};try{const p=await registerClient(e,t),g={clientId:p.clientId,clientType:"dynamic"};return p.clientSecret!==void 0&&(g.clientSecret=p.clientSecret,g.expiresAt=String(p.expiresAt)),p.idTokenSignedResponseAlg&&(g.idTokenSignedResponseAlg=p.idTokenSignedResponseAlg),await this.storageUtility.setForUser(e.sessionId,g,{secure:!1}),p}catch(p){throw new Error("Client registration failed.",{cause:p})}}}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 i=new URL(e),s=i.searchParams.get("error"),o=i.searchParams.get("error_description");t.emit(EVENTS.ERROR,s,o)}return getUnauthenticatedSession()}}class TokenRefresher{storageUtility;issuerConfigFetcher;clientRegistrar;constructor(e,t,i){this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i,this.storageUtility=e,this.issuerConfigFetcher=t,this.clientRegistrar=i}async refresh(e,t,i,s){const o=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),l=await this.clientRegistrar.getClient({sessionId:e},o.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(o.dpop&&i===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 u=await refresh(t,o.issuerConfig,l,i);return u.refreshToken!==void 0&&s?.emit(EVENTS.NEW_REFRESH_TOKEN,u.refreshToken),u}}function getClientAuthenticationWithDependencies(n){const e=new InMemoryStorage,t=n.secureStorage||e,i=n.insecureStorage||new BrowserStorage,s=new StorageUtilityBrowser(t,i),o=new IssuerConfigFetcher(s),l=new ClientRegistrar(s),u=new SessionInfoManager(s),h=new TokenRefresher(s,o,l),d=new Redirector,p=new OidcLoginHandler(s,new AuthorizationCodeWithPkceOidcHandler(s,d),o,l),g=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(s,u,o,l,h,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(p,g,new IWaterfallLogoutHandler(u,d),u,o)}const KEY_CURRENT_SESSION=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentSession`,KEY_CURRENT_URL=`${SOLID_CLIENT_AUTHN_KEY_PREFIX}currentUrl`;async function silentlyAuthenticate(n,e,t){const i=await e.validateCurrentSession(n);return i!==null?(window.localStorage.setItem(KEY_CURRENT_URL,window.location.href),await e.login({sessionId:n,prompt:"none",oidcIssuer:i.issuer,redirectUrl:i.redirectUrl,clientId:i.clientAppId,clientSecret:i.clientAppSecret,tokenType:i.tokenType??"DPoP"},t.events),!0):!1}function isLoggedIn(n){return!!n?.isLoggedIn}class Session{info;events;clientAuthentication;tokenRequestInProgress=!1;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(),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.internalLogout(!1))}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,i=t.url??window.location.href;this.tokenRequestInProgress=!0;const s=await this.clientAuthentication.handleIncomingRedirect(i,this.events);if(isLoggedIn(s)){this.setSessionInfo(s);const o=window.localStorage.getItem(KEY_CURRENT_URL);o===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,o))}else if(t.restorePreviousSession===!0){const o=window.localStorage.getItem(KEY_CURRENT_SESSION);if(o!==null&&await silentlyAuthenticate(o,this.clientAuthentication,this))return new Promise(()=>{})}return this.tokenRequestInProgress=!1,s};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})}}function snapshotFromSessionInfo(n){return n?.isLoggedIn&&n.webId?{status:"authenticated",webId:n.webId}:{status:"anonymous"}}function normalizeError(n){return n instanceof Error?n:new Error(String(n))}function snapshotFromSessionError(n,e){return{status:"error",webId:e.webId,error:normalizeError(n)}}function snapshotFromSessionExpired(n){return{status:"expired",...n.webId===void 0?{}:{webId:n.webId}}}function areSnapshotsEqual(n,e){return!n||n.status!==e.status||n.webId!==e.webId?!1:n.status==="error"&&e.status==="error"?n.error===e.error:!0}function createSolidSessionRuntime(n={}){const e=n.session??new Session,t=new Set;let i={status:"initializing"},s,o,l=!1,u=!1,h,d=!1;const p=x=>{if(i=x,d||areSnapshotsEqual(s,i))return i;s=i;for(const A of t)A(i);return i},g=()=>p(snapshotFromSessionInfo(e.info)),y=()=>p({status:"anonymous"}),v=()=>p(snapshotFromSessionExpired(e.info)),S=(x,A)=>{const I=snapshotFromSessionError(A??x??"Solid session error",e.info);u&&(h=I),p(I)};e.events.on(EVENTS.LOGIN,g),e.events.on(EVENTS.SESSION_RESTORED,g),e.events.on(EVENTS.LOGOUT,y),e.events.on(EVENTS.SESSION_EXPIRED,v);const E=e.events;return E.on(EVENTS.ERROR,S),{fetch:e.fetch,getSnapshot(){return i},initialize(x={}){if(o)return o;if(l)return Promise.resolve(i);u=!0,h=void 0,p({status:"initializing"});const A=e.handleIncomingRedirect({restorePreviousSession:x.restorePreviousSession??!0}).then(I=>{const T=snapshotFromSessionInfo(I??e.info);return T.status==="anonymous"&&h?.status==="error"?h:(l=!0,p(T))}).catch(I=>p(snapshotFromSessionError(I,e.info))).finally(()=>{o===A&&(o=void 0,u=!1,h=void 0)});return o=A,o},handleIncomingRedirect(x){if(o)return o;u=!0,h=void 0,p({status:"initializing"});const A=e.handleIncomingRedirect(x).then(I=>{const T=snapshotFromSessionInfo(I??e.info);return T.status==="anonymous"&&h?.status==="error"?h:(l=!0,p(T))}).catch(I=>p(snapshotFromSessionError(I,e.info))).finally(()=>{o===A&&(o=void 0,u=!1,h=void 0)});return o=A,A},login(x){return e.login(x)},async logout(x){await e.logout(x),p({status:"anonymous"})},subscribe(x){return t.add(x),()=>{t.delete(x)}},dispose(){d=!0,t.clear(),e.events.off(EVENTS.LOGIN,g),e.events.off(EVENTS.SESSION_RESTORED,g),e.events.off(EVENTS.LOGOUT,y),e.events.off(EVENTS.SESSION_EXPIRED,v),E.off(EVENTS.ERROR,S)}}}const KEY_SEPARATOR="\0";function normalizeIdentityPart(n){const e=n.trim();try{return new URL(e).href}catch{return e}}function normalizePodUrl(n){if(typeof n!="string"||n.trim()==="")throw new TypeError("podUrl must be a non-empty absolute URL");let e;try{e=new URL(n.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(n,e){return`${normalizeIdentityPart(n)}${KEY_SEPARATOR}${normalizeIdentityPart(e)}`}function nextGeneration(n,e){const t=(n.get(e)??0)+1;return n.set(e,t),t}function createAbortedOpenError(){const n=new Error("Pod open aborted because the runtime identity changed");return n.name="AbortError",n}function createPodRuntime(n){const{adapter:e}=n,t=new Map,i=new Map,s=new Map,o=new Map,l=new Map,u=new Map,h=(g,y)=>{const v=normalizeIdentityPart(g);if(y!==void 0){const x=normalizePodUrl(y),A=compositeKey(g,x);nextGeneration(u,A),o.get(A)?.controller.abort(),o.delete(A),i.delete(A);const I=t.get(v);I&&compositeKey(I.webId,I.podUrl)===A&&t.delete(v);return}nextGeneration(l,v),s.get(v)?.controller.abort(),s.delete(v);const S=t.get(v);S&&i.delete(compositeKey(S.webId,S.podUrl)),t.delete(v);const E=`${v}${KEY_SEPARATOR}`;for(const x of[...i.keys()])x.startsWith(E)&&i.delete(x);for(const[x,A]of[...o.entries()])x.startsWith(E)&&(nextGeneration(u,x),A.controller.abort(),o.delete(x))},d=g=>{if(!g){t.clear(),i.clear();for(const y of s.values())y.controller.abort();for(const y of o.values())y.controller.abort();s.clear(),o.clear();for(const y of l.keys())nextGeneration(l,y);for(const y of u.keys())nextGeneration(u,y);return}if(typeof g=="string"){h(g);return}h(g.webId,g.podUrl)};return{open(g){const y=normalizeIdentityPart(g.webId),v=g.podUrl===void 0?void 0:normalizePodUrl(g.podUrl);if(v!==void 0){const V=compositeKey(g.webId,v),B=i.get(V);if(B)return Promise.resolve(B);const Y=o.get(V);if(Y)return Y.promise;const _e=u.get(V)??0;u.set(V,_e);const j=new AbortController,ee=()=>!j.signal.aborted&&(u.get(V)??0)===_e,me=()=>{if(!ee())throw createAbortedOpenError()},te=p({webId:g.webId,podUrl:v,fetch:g.fetch,signal:j.signal,isCurrent:ee,assertCurrent:me});o.set(V,{generation:_e,promise:te,controller:j});const Ce=()=>{const Oe=o.get(V);Oe?.generation===_e&&Oe.promise===te&&o.delete(V)};return te.then(Ce,Ce),te}const S=t.get(y);if(S)return Promise.resolve(S);const E=s.get(y);if(E)return E.promise;const x=l.get(y)??0;l.set(y,x);const A=new AbortController,I=()=>!A.signal.aborted&&(l.get(y)??0)===x,T=()=>{if(!I())throw createAbortedOpenError()},F=(async()=>{const V=await e.discoverPod({webId:g.webId,fetch:g.fetch,signal:A.signal,isCurrent:I});return T(),p({webId:g.webId,podUrl:normalizePodUrl(V),fetch:g.fetch,signal:A.signal,isCurrent:I,assertCurrent:T,generation:x,webIdKey:y,discovered:!0})})();s.set(y,{generation:x,promise:F,controller:A});const P=()=>{const V=s.get(y);V?.generation===x&&V.promise===F&&s.delete(y)};return F.then(P,P),F},clear:d,dispose(){d()}};async function p(g){const y=compositeKey(g.webId,g.podUrl),v=i.get(y);if(v)return g.discovered&&g.webIdKey&&g.isCurrent()&&t.set(g.webIdKey,v),v;const S=await e.openDatabase({webId:g.webId,podUrl:g.podUrl,fetch:g.fetch,signal:g.signal,isCurrent:g.isCurrent});g.assertCurrent(),await e.hydrateCollections({webId:g.webId,podUrl:g.podUrl,database:S,signal:g.signal,isCurrent:g.isCurrent}),g.assertCurrent();const E={webId:g.webId,podUrl:g.podUrl,database:S,collections:"ready"};return g.isCurrent()&&(i.set(y,E),g.discovered&&g.webIdKey&&t.set(g.webIdKey,E)),E}}const SolidRuntimeContext=reactExports.createContext(null);function SolidRuntimeProvider({value:n,children:e}){return reactExports.createElement(SolidRuntimeContext.Provider,{value:n},e)}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(n,e){if(!n||typeof n.url!="string"||n.url.trim()==="")throw new TypeError(`${e}.url must be a non-empty absolute URL`);if(typeof n.label!="string")throw new TypeError(`${e}.label must be a string`);let t;try{t=new URL(n.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:n.label}}function normalizeStorageBinding(n){if(!n||typeof n.storageUrl!="string"||n.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");if(typeof n.webId!="string"||n.webId.trim()==="")throw new TypeError("selectedStorage.webId must be a non-empty identifier URL");let e;try{e=new URL(n.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:n.webId,...n.label===void 0?{}:{label:n.label}}}function ensureEnum(n,e,t){if(!e.includes(n))throw new TypeError(`${t} has an unsupported value`);return n}function normalizeWebIdLoginRoute(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("route.id must be a non-empty opaque identifier");if(typeof n.label!="string")throw new TypeError("route.label must be a string");return{id:n.id.trim(),label:n.label,...n.description===void 0?{}:{description:n.description},...n.badge===void 0?{}:{badge:{label:n.badge.label,tone:ensureEnum(n.badge.tone,["neutral","primary","success","warning","danger"],"route.badge.tone")}},identityProvider:normalizeEndpoint(n.identityProvider,"route.identityProvider"),...n.storageProvider===void 0?{}:{storageProvider:normalizeEndpoint(n.storageProvider,"route.storageProvider")},availability:ensureEnum(n.availability,["ready","starting","unavailable"],"route.availability"),...n.unavailableReason===void 0?{}:{unavailableReason:n.unavailableReason}}}function decodeForValidation$1(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}function matchesAllowedPrefix(n,e){return e.some(t=>{if(t==="/")return n.startsWith("/");const i=t.endsWith("/")?t.slice(0,-1):t;return n===i||n.startsWith(`${i}/`)})}function normalizeApplicationReturnTo(n,e){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const t=n.trim(),i=decodeForValidation$1(t),s=i.split(/[?#]/,1)[0];if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||i.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(i)||i.startsWith("//")||s.split("/").some(o=>o==="..")||!matchesAllowedPrefix(s,e))throw new TypeError("returnTo must be a safe path within the application allow-list");return t}function normalizeWebIdLoginTransaction(n){if(!n||typeof n.id!="string"||n.id.trim()==="")throw new TypeError("transaction.id must be a non-empty opaque identifier");const e=n.authorizationParameters===void 0?void 0:{...n.authorizationParameters};if(e){for(const i of Object.keys(e))if(RESERVED_AUTHORIZATION_PARAMETERS.has(i.toLowerCase()))throw new TypeError(`authorizationParameters cannot override ${i}`)}const t=n.prompt===void 0?void 0:ensureEnum(n.prompt,["login","consent","select_account"],"transaction.prompt");return{id:n.id,route:normalizeWebIdLoginRoute(n.route),...n.selectedStorage===void 0?{}:{selectedStorage:normalizeStorageBinding(n.selectedStorage)},authorizationSurface:ensureEnum(n.authorizationSurface,["redirect","popup","embedded","external"],"transaction.authorizationSurface"),...t===void 0?{}:{prompt:t},discovery:ensureEnum(n.discovery,["standard","strict"],"transaction.discovery"),...e===void 0?{}:{authorizationParameters:e},...n.returnTo===void 0?{}:{returnTo:normalizeApplicationReturnTo(n.returnTo,["/"])}}}const SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER="x-xpod-canonical-url",SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER="x-xpod-canonical-origin",SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER="x-xpod-canonical-host",SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER="x-xpod-local-route-url";async function discoverSolidLocalRoute(n){let e;try{e=await n.fetch.call(globalThis,n.statusUrl??"/provision/status",{credentials:"include",headers:{accept:"application/json"}})}catch{return}if(!e?.ok)return;const t=await e.json().catch(()=>{});if(typeof t?.publicUrl=="string")try{return normalizeRoute({canonicalBaseUrl:t.publicUrl,localBaseUrl:n.localBaseUrl})}catch{return}}function resolveSolidLocalRouteUrl(n,e){let t;try{t=n instanceof URL?new URL(n.href):new URL(n)}catch{return}const i=e.map(normalizeRoute).filter(s=>isInsideBase(t,s.canonicalBaseUrl)).sort((s,o)=>o.canonicalBaseUrl.length-s.canonicalBaseUrl.length)[0];return i?replaceBase(t,i):void 0}function createSolidLocalRouteFetch(n){return async(e,t)=>{const i=requestUrl(e);if(!i)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const s=n.routes(),o=resolveSolidLocalRouteUrl(i,s);if(!o)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const l=routedHeaders(e,t,i,o);let u;if(e instanceof Request){const d=new Request(new Request(o,e),{headers:l});u=t===void 0?await n.fetch.call(globalThis,d):await n.fetch.call(globalThis,d,{...t,headers:l})}else u=await n.fetch.call(globalThis,o,{...t,headers:l});const h=resolveSolidLocalRouteUrl(u.url,s.map(d=>({canonicalBaseUrl:d.localBaseUrl,localBaseUrl:d.canonicalBaseUrl})));return h?withResponseUrl(u,h.href):u}}function withResponseUrl(n,e){const t=n.clone.bind(n);return Object.defineProperties(n,{url:{value:e,configurable:!0},clone:{value:()=>withResponseUrl(t(),e),configurable:!0}}),n}function requestUrl(n){if(n instanceof Request)return new URL(n.url);try{return new URL(String(n))}catch{return}}function normalizeRoute(n){return{canonicalBaseUrl:normalizeBaseUrl(n.canonicalBaseUrl),localBaseUrl:normalizeBaseUrl(n.localBaseUrl)}}function normalizeBaseUrl(n){const e=new URL(n);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new TypeError("Solid local routes must use http or https");return e.search="",e.hash="",e.href.endsWith("/")?e.href:`${e.href}/`}function isInsideBase(n,e){const t=new URL(e);return n.origin===t.origin&&n.pathname.startsWith(t.pathname)}function replaceBase(n,e){const t=new URL(e.canonicalBaseUrl),i=new URL(e.localBaseUrl),s=n.pathname.slice(t.pathname.length),o=new URL(s,i);return o.search=n.search,o.hash=n.hash,o}function routedHeaders(n,e,t,i){const s=n instanceof Request?n:void 0,o=new Headers(s?.headers??void 0);return new Headers(e?.headers??void 0).forEach((l,u)=>o.set(u,l)),o.set(SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER,t.toString()),o.set(SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER,t.origin),o.set(SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER,t.host),o.set(SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER,i.toString()),o}SCHEMA.image,UDFS.hasContact,WF.participant,UDFS.metadata,UDFS.favorite,UDFS.muted,UDFS.unreadCount,UDFS.lastActiveAt,UDFS.lastMessage,SCHEMA.text;SIOC.has_parent,SIOC.has_member,WF.message,UDFS.messageType,SIOC.content,SIOC.richContent,UDFS.messageStatus,SCHEMA.dateDeleted,UDFS.senderName,UDFS.senderAvatarUrl,UDFS.mentions,UDFS.replyTo,UDFS.routedBy,UDFS.routeTargetAgent,UDFS.coordinationId;SCHEMA.about,UDFS.contactType,AS.audience,UDFS.externalPlatform,UDFS.externalId,UDFS.alias,UDFS.favorite,UDFS.sortKey,UDFS.deletedAt,UDFS.lastSyncedAt;SIOC.has_parent,UDFS.favorite,UDFS.metadata,UDFS.workspace,SIOC.Thread;UDFS.actor,UDFS.conversation,UDFS.inThread,UDFS.sessionStatus,UDFS.sessionTool,UDFS.tokenUsage,UDFS.message,UDFS.policy,UDFS.policyVersion,UDFS.metadata,UDFS.archivedAt;UDFS.instruction,UDFS.prompt,UDFS.issue,UDFS.message,UDFS.workspace,UDFS.status,UDFS.priority,UDFS.assignedTo,UDFS.source,UDFS.metadata;UDFS.task,UDFS.status,UDFS.scheduleKind,UDFS.cron,UDFS.intervalSeconds,UDFS.timezone,UDFS.startsAt,UDFS.nextRunAt,UDFS.lastRunAt,UDFS.metadata;UDFS.status,UDFS.ruleKind,UDFS.task,UDFS.schedule,UDFS.source,UDFS.target,UDFS.condition,UDFS.actions,UDFS.metadata,UDFS.lastTriggeredAt,UDFS.lastRunStatus;UDFS.deliveryKind,UDFS.status,UDFS.task,UDFS.source,AS.target,UDFS.conversation,UDFS.inThread,UDFS.targetThread,UDFS.targetSession,AS.actor,AS.object,UDFS.objective,UDFS.payload,UDFS.projection,UDFS.projectedRole,UDFS.metadata,UDFS.error,UDFS.startedAt,UDFS.consumedAt,UDFS.completedAt;UDFS.task,UDFS.delivery,UDFS.trigger,UDFS.input,UDFS.inThread,UDFS.workspace,UDFS.status,UDFS.runner,UDFS.prompt,UDFS.externalRunId,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.heartbeatAt,UDFS.cancelRequestedAt,UDFS.error,UDFS.metadata,UDFS.startedAt,UDFS.completedAt;UDFS.evidenceKind,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.outcome,UDFS.metadata;UDFS.reportKind,UDFS.status,UDFS.outcome,SCHEMA.about,UDFS.issue,UDFS.task,UDFS.delivery,UDFS.run,UDFS.inThread,UDFS.evidence,SCHEMA.reviewedBy,UDFS.metricFacts,UDFS.metadata;UDFS.run,UDFS.stepType,UDFS.payload;UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.status,UDFS.sourceHash,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,UDFS.metadata;UDFS.captureCandidate,UDFS.targetResource,UDFS.captureDecision,UDFS.suggestedType,UDFS.suggestedTarget,UDFS.confidence,UDFS.reason,UDFS.userCorrection,UDFS.approval,UDFS.inputRequest,UDFS.conversation,UDFS.inThread,UDFS.task,UDFS.run,SCHEMA.about,UDFS.metadata;UDFS.session,UDFS.toolCallId,UDFS.toolName,ODRL.target,ODRL.action,UDFS.risk,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.reason,UDFS.context,UDFS.approvalOptions,UDFS.policyVersion,UDFS.expiresAt,UDFS.resolvedAt;UDFS.session,UDFS.conversation,UDFS.inThread,UDFS.run,UDFS.task,UDFS.requester,UDFS.requestKind,UDFS.prompt,UDFS.context,UDFS.inputOptions,UDFS.status,UDFS.leaseOwner,UDFS.leaseExpiresAt,UDFS.assignedTo,UDFS.response,UDFS.answeredBy,UDFS.onBehalfOf,UDFS.reason,UDFS.metadata,UDFS.expiresAt,UDFS.resolvedAt;UDFS.action,UDFS.actor,UDFS.actorRole,UDFS.onBehalfOf,UDFS.session,UDFS.entry,UDFS.toolCallId,UDFS.toolName,UDFS.approval,UDFS.policy,UDFS.policyVersion;ODRL.target,ODRL.action,UDFS.pageKind,UDFS.status,UDFS.tags,UDFS.sourceKind,UDFS.sourceHash,UDFS.compiledAt,UDFS.compiledFrom,UDFS.effect,UDFS.riskCeiling,UDFS.policy,UDFS.context,UDFS.decisionBy,UDFS.decisionRole,UDFS.onBehalfOf,UDFS.revokedAt;UDFS.summary,UDFS.body,UDFS.source,UDFS.related;AS.actor,AS.object;UDFS.Note,SIOC.about,UDFS.noteKind,UDFS.sourceKey,UDFS.fingerprint,UDFS.readerEngine,UDFS.readerVersion,UDFS.generatedWithModel,UDFS.sourceHash,UDFS.readerOptionsHash,UDFS.representationHash,UDFS.representationMediaType,UDFS.coverageUnit,UDFS.coveredRange,UDFS.readUnits,UDFS.totalUnits,UDFS.status;const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),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),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(n,e){return n&&n.length>0?n:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(n){return taskDir(n)??runDir(n)??deliveryDir(n)??issueDir(n)??threadDir(n)??chatDir(n)??aboutDir(n)}function chatDir(n){const e=typeof n?.chat=="string"?n.chat:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return i?.[1]?`chat/${i[1]}`:null}function threadDir(n){const e=typeof n?.thread=="string"?n.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(n){const e=typeof n?.task=="string"?n.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const i=t.match(/^task\/index\.ttl#([^#/]+)$/);if(i?.[1])return`task/${i[1]}`;const s=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return s?.[1]?`task/${s[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`issues/${i[1]}`:null}function deliveryDir(n){const e=typeof n?.delivery=="string"?n.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(n){const e=typeof n?.run=="string"?n.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(n){const e=typeof n?.about=="string"?n.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(n,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(n,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(n,e){return e===void 0?void 0:eq(exactFilterColumns[n],e)}function messageListFilter(n){if(!n)return;const e=[exactFilter$1("parent",n.parent),exactFilter$1("chat",n.chat),exactFilter$1("thread",n.thread),exactFilter$1("maker",n.maker),exactFilter$1("role",n.role),exactFilter$1("status",n.status),exactFilter$1("toolName",n.toolName),exactFilter$1("toolCallId",n.toolCallId),exactFilter$1("coordinationId",n.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>messageListFilter(n)});function chatProjectMemoryResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(n=>n?chatProjectMemoryResourceId(n):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:n})=>n?.workspace?eq(chatProjectContextResource.workspace,n.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>n?.workspace?eq(chatProjectMemoryResource.workspace,n.workspace):void 0});function conversationShareResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(n=>n?conversationShareResourceId(n):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>n?.thread?eq(conversationShareResource.thread,n.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((n,e)=>{const t=resourceKey(n,"report"),i=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${i}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(n){n.UNKNOWN="unknown",n.MAIN_TEXT="main_text",n.THINKING="thinking",n.IMAGE="image",n.CODE="code",n.TOOL="tool",n.TOOL_APPROVAL="tool_approval",n.TASK_PROGRESS="task_progress",n.FILE="file",n.ERROR="error",n.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(n){n.PENDING="pending",n.PROCESSING="processing",n.STREAMING="streaming",n.SUCCESS="success",n.ERROR="error",n.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$1.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(n,e,t){const{rdfType:i,sourceModule:s,extractor:o}=e,l=t["@id"]||t.id;if(!l){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const u=o.getTitle(t),h={id:crypto.randomUUID(),targetType:i,target:l,title:u,snapshotContent:o.getContent?.(t),snapshotAuthor:o.getAuthor?.(t),sourceModule:s,searchText:o.getSearchText?.(t)??u,snapshotMeta:o.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(d){console.error("[StarredSync] Failed to create favorite:",d)}}async function deleteFavorite(n,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(n){return{afterUpdate:async(e,t,i)=>{if(!("starred"in i))return;const s=t.starred,o=t["@id"]||t.id;s?await createFavorite(e,n,t):await deleteFavorite(e,o)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:n=>n.title||"未命名对话",getContent:n=>n.lastMessagePreview},threadSnapshotExtractor={getTitle:n=>n.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(n,e,t){return t===void 0?void 0:eq(n[e],t)}function combineFilters(n){const e=n.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(n){if(n)return combineFilters([exactFilter(candidateExactFilterColumns,"source",n.source),exactFilter(candidateExactFilterColumns,"suggestedType",n.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",n.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",n.status),exactFilter(candidateExactFilterColumns,"chat",n.chat),exactFilter(candidateExactFilterColumns,"thread",n.thread),exactFilter(candidateExactFilterColumns,"task",n.task),exactFilter(candidateExactFilterColumns,"run",n.run)])}function captureEventListFilter(n){if(n)return combineFilters([exactFilter(eventExactFilterColumns,"source",n.source),exactFilter(eventExactFilterColumns,"captureCandidate",n.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",n.targetResource),exactFilter(eventExactFilterColumns,"decision",n.decision),exactFilter(eventExactFilterColumns,"approval",n.approval),exactFilter(eventExactFilterColumns,"inputRequest",n.inputRequest),exactFilter(eventExactFilterColumns,"chat",n.chat),exactFilter(eventExactFilterColumns,"thread",n.thread),exactFilter(eventExactFilterColumns,"task",n.task),exactFilter(eventExactFilterColumns,"run",n.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureCandidateListFilter(n)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureEventListFilter(n)});podTable("settings",{id:id("id").default((n,e)=>{const t=typeof e?.key=="string"?e.key:n;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const o={};for(const l of s)o[l]=l;return o},n.getValidEnumValues=s=>{const o=n.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of o)l[u]=s[u];return n.objectValues(l)},n.objectValues=s=>n.objectKeys(s).map(function(o){return s[o]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const o=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&o.push(l);return o},n.find=(s,o)=>{for(const l of s)if(o(l))return l},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function i(s,o=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(o)}n.joinValues=i,n.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(util||(util={}));var objectUtil;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=n=>{switch(typeof n){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(n)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(n)?ZodParsedType.array:n===null?ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(o){return o.message},i={_errors:[]},s=o=>{for(const l of o.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let u=i,h=0;for(;h<l.path.length;){const d=l.path[h];h===l.path.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(l))):u[d]=u[d]||{_errors:[]},u=u[d],h++}}};return s(this),i}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)if(s.path.length>0){const o=s.path[0];t[o]=t[o]||[],t[o].push(e(s))}else i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=n=>new ZodError(n);const errorMap=(n,e)=>{let t;switch(n.code){case ZodIssueCode.invalid_type:n.received===ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(n.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(n.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(n.options)}, received '${n.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(n)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,o=[...t,...s.path||[]],l={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let u="";const h=i.filter(d=>!!d).slice().reverse();for(const d of h)u=d(l,{data:e,defaultError:u}).message;return{...s,path:o,message:u}};function addIssueToContext(n,e){const t=getErrorMap(),i=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(s=>!!s)});n.common.issues.push(i)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const o=await s.key,l=await s.value;i.push({key:o,value:l})}return ParseStatus.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:o,value:l}=s;if(o.status==="aborted"||l.status==="aborted")return INVALID;o.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(i[o.value]=l.value)}return{status:e.value,value:i}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=n=>({status:"dirty",value:n}),OK=n=>({status:"valid",value:n}),isAborted=n=>n.status==="aborted",isDirty=n=>n.status==="dirty",isValid=n=>n.status==="valid",isAsync=n=>typeof Promise<"u"&&n instanceof Promise;var errorUtil;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(n,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(n.common.issues);return this._error=t,this._error}}};function processCreateParams(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{const{message:h}=n;return l.code==="invalid_enum_value"?{message:h??u.defaultError}:typeof u.data>"u"?{message:h??i??u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:h??t??u.defaultError}},description:s}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parseSync({data:e,path:i.path,parent:i});return handleResult(i,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return isValid(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>isValid(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parse({data:e,path:i.path,parent:i}),o=await(isAsync(s)?s:Promise.resolve(s));return handleResult(i,o)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,o)=>{const l=e(s),u=()=>o.addIssue({code:ZodIssueCode.custom,...i(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(h=>h?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(n){return new RegExp(`^${timeRegexSource(n)}$`)}function datetimeRegex(n){let e=`${dateRegexSource}T${timeRegexSource(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(n,e){return!!((e==="v4"||!e)&&ipv4Regex.test(n)||(e==="v6"||!e)&&ipv6Regex.test(n))}function isValidJWT(n,e){if(!jwtRegex.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function isValidCidr(n,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(n)||(e==="v6"||!e)&&ipv6CidrRegex.test(n))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:o.parsedType}),INVALID}const i=new ParseStatus;let s;for(const o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),i.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),i.dirty());else if(o.kind==="length"){const l=e.data.length>o.value,u=e.data.length<o.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):u&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),i.dirty())}else if(o.kind==="email")emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="uuid")uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="nanoid")nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="cuid")cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="cuid2")cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="ulid")ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),i.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),i.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),i.dirty()):o.kind==="datetime"?datetimeRegex(o).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),i.dirty()):o.kind==="date"?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),i.dirty()):o.kind==="time"?timeRegex(o).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),i.dirty()):o.kind==="duration"?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="ip"?isValidIP(e.data,o.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="jwt"?isValidJWT(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="cidr"?isValidCidr(e.data,o.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="base64"?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):o.kind==="base64url"?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),i.dirty()):util.assertNever(o);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(i)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=n=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:n?.coerce??!1,...processCreateParams(n)});function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,o=Number.parseInt(n.toFixed(s).replace(".","")),l=Number.parseInt(e.toFixed(s).replace(".",""));return o%l/10**s}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:o.parsedType}),INVALID}let i;const s=new ParseStatus;for(const o of this._def.checks)o.kind==="int"?util.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?floatSafeRemainder(e.data,o.value)!==0&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_finite,message:o.message}),s.dirty()):util.assertNever(o);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=n=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let i;const s=new ParseStatus;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):util.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=n=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:n?.coerce??!1,...processCreateParams(n)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:i.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=n=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:o.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const o=this._getOrReturnCtx(e);return addIssueToContext(o,{code:ZodIssueCode.invalid_date}),INVALID}const i=new ParseStatus;let s;for(const o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),i.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),i.dirty()):util.assertNever(o);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=n=>new ZodDate({checks:[],coerce:n?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(n)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:i.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=n=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(n)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:i.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=n=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(n)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:i.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=n=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(n)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=n=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(n)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=n=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(n)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=n=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(n)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:i.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=n=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(n)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(s.exactLength!==null){const l=t.data.length>s.exactLength.value,u=t.data.length<s.exactLength.value;(l||u)&&(addIssueToContext(t,{code:l?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,u)=>s.type._parseAsync(new ParseInputLazyPath(t,l,t.path,u)))).then(l=>ParseStatus.mergeArray(i,l));const o=[...t.data].map((l,u)=>s.type._parseSync(new ParseInputLazyPath(t,l,t.path,u)));return ParseStatus.mergeArray(i,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(n,e)=>new ZodArray({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(n){if(n instanceof ZodObject){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=ZodOptional.create(deepPartialify(i))}return new ZodObject({...n._def,shape:()=>e})}else return n instanceof ZodArray?new ZodArray({...n._def,type:deepPartialify(n.element)}):n instanceof ZodOptional?ZodOptional.create(deepPartialify(n.unwrap())):n instanceof ZodNullable?ZodNullable.create(deepPartialify(n.unwrap())):n instanceof ZodTuple?ZodTuple.create(n.items.map(e=>deepPartialify(e))):n}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:i,ctx:s}=this._processInputParams(e),{shape:o,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in s.data)l.includes(d)||u.push(d);const h=[];for(const d of l){const p=o[d],g=s.data[d];h.push({key:{status:"valid",value:d},value:p._parse(new ParseInputLazyPath(s,g,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ZodNever){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of u)h.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")u.length>0&&(addIssueToContext(s,{code:ZodIssueCode.unrecognized_keys,keys:u}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of u){const g=s.data[p];h.push({key:{status:"valid",value:p},value:d._parse(new ParseInputLazyPath(s,g,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of h){const g=await p.key,y=await p.value;d.push({key:g,value:y,alwaysSet:p.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(i,d)):ParseStatus.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const s=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const i of util.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const i of util.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const i of util.objectKeys(this.shape)){const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const i of util.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let o=this.shape[i];for(;o instanceof ZodOptional;)o=o._def.innerType;t[i]=o}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(n,e)=>new ZodObject({shape:n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(o){for(const u of o)if(u.result.status==="valid")return u.result;for(const u of o)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;const l=o.map(u=>new ZodError(u.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:l}),INVALID}if(t.common.async)return Promise.all(i.map(async o=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(s);{let o;const l=[];for(const h of i){const d={...t,common:{...t.common,issues:[]},parent:null},p=h._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!o&&(o={result:p,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const u=l.map(h=>new ZodError(h));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:u}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(n,e)=>new ZodUnion({options:n,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(n,e){const t=getParsedType(n),i=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&i===ZodParsedType.object){const s=util.objectKeys(e),o=util.objectKeys(n).filter(u=>s.indexOf(u)!==-1),l={...n,...e};for(const u of o){const h=mergeValues(n[u],e[u]);if(!h.valid)return{valid:!1};l[u]=h.data}return{valid:!0,data:l}}else if(t===ZodParsedType.array&&i===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let o=0;o<n.length;o++){const l=n[o],u=e[o],h=mergeValues(l,u);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return t===ZodParsedType.date&&i===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(o,l)=>{if(isAborted(o)||isAborted(l))return INVALID;const u=mergeValues(o.value,l.value);return u.valid?((isDirty(o)||isDirty(l))&&t.dirty(),{status:t.value,value:u.data}):(addIssueToContext(i,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([o,l])=>s(o,l)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ZodIntersection.create=(n,e,t)=>new ZodIntersection({left:n,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.array)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:i.parsedType}),INVALID;if(i.data.length<this._def.items.length)return addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&i.data.length>this._def.items.length&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const o=[...i.data].map((l,u)=>{const h=this._def.items[u]||this._def.rest;return h?h._parse(new ParseInputLazyPath(i,l,i.path,u)):null}).filter(l=>!!l);return i.common.async?Promise.all(o).then(l=>ParseStatus.mergeArray(t,l)):ParseStatus.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:n,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.object)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:i.parsedType}),INVALID;const s=[],o=this._def.keyType,l=this._def.valueType;for(const u in i.data)s.push({key:o._parse(new ParseInputLazyPath(i,u,i.path,u)),value:l._parse(new ParseInputLazyPath(i,i.data[u],i.path,u)),alwaysSet:u in i.data});return i.common.async?ParseStatus.mergeObjectAsync(t,s):ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(i)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.map)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:i.parsedType}),INVALID;const s=this._def.keyType,o=this._def.valueType,l=[...i.data.entries()].map(([u,h],d)=>({key:s._parse(new ParseInputLazyPath(i,u,i.path,[d,"key"])),value:o._parse(new ParseInputLazyPath(i,h,i.path,[d,"value"]))}));if(i.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const h of l){const d=await h.key,p=await h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}})}else{const u=new Map;for(const h of l){const d=h.key,p=h.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}}}}ZodMap.create=(n,e,t)=>new ZodMap({valueType:e,keyType:n,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.set)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:i.parsedType}),INVALID;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const o=this._def.valueType;function l(h){const d=new Set;for(const p of h){if(p.status==="aborted")return INVALID;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const u=[...i.data.values()].map((h,d)=>o._parse(new ParseInputLazyPath(i,h,i.path,d)));return i.common.async?Promise.all(u).then(h=>l(h)):l(u)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(n,e)=>new ZodSet({valueType:n,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(n,e)=>new ZodLazy({getter:n,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(n,e)=>new ZodLiteral({value:n,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(n,e){return new ZodEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{expected:util.joinValues(i),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==ZodParsedType.string&&i.parsedType!==ZodParsedType.number){const s=util.objectValues(t);return addIssueToContext(i,{expected:util.joinValues(s),received:i.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=util.objectValues(t);return addIssueToContext(i,{received:i.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(n,e)=>new ZodNativeEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const i=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(n,e)=>new ZodPromise({type:n,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:l=>{addIssueToContext(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){const l=s.transform(i.data,o);if(i.common.async)return Promise.resolve(l).then(async u=>{if(t.value==="aborted")return INVALID;const h=await this._def.schema._parseAsync({data:u,path:i.path,parent:i});return h.status==="aborted"?INVALID:h.status==="dirty"||t.value==="dirty"?DIRTY(h.value):h});{if(t.value==="aborted")return INVALID;const u=this._def.schema._parseSync({data:l,path:i.path,parent:i});return u.status==="aborted"?INVALID:u.status==="dirty"||t.value==="dirty"?DIRTY(u.value):u}}if(s.type==="refinement"){const l=u=>{const h=s.refinement(u,o);if(i.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(i.common.async===!1){const u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value).then(()=>({status:t.value,value:u.value}))))}if(s.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!isValid(l))return INVALID;const u=s.transform(l.value,o);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>isValid(l)?Promise.resolve(s.transform(l.value,o)).then(u=>({status:t.value,value:u})):INVALID);util.assertNever(s)}}ZodEffects.create=(n,e,t)=>new ZodEffects({schema:n,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(n,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:n},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(n,e)=>new ZodOptional({innerType:n,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(n,e)=>new ZodNullable({innerType:n,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===ZodParsedType.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(n,e)=>new ZodDefault({innerType:n,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return isAsync(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(n,e)=>new ZodCatch({innerType:n,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:i.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=n=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(n)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?INVALID:o.status==="dirty"?(t.dirty(),DIRTY(o.value)):this._def.out._parseAsync({data:o.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),i=s=>(isValid(s)&&(s.value=Object.freeze(s.value)),s);return isAsync(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(n,e)=>new ZodReadonly({innerType:n,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel};new Set(AI_MODEL_MODALITIES);new Set(AI_MODEL_CAPABILITIES);new Set(Object.values(AI_MODEL_CAPABILITY));new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(n){const e=n;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const i of Object.values(t??{}))typeof i.options?.predicate=="string"&&(i.getPredicate=()=>i.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(n=>[n.id,n]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(n){return n.trim().toLowerCase()}function normalizeAIConfigResourceId(n){if(!n)return"";const e=n.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),i=t.split("/").pop()||t;return i.endsWith(".ttl")?i.slice(0,-4):i}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[i,...s]=t.split("/");return s.length===0||!e?t:normalizeAIConfigProviderId(i)===normalizeAIConfigProviderId(e)?s.join("/"):t}function normalizeAIConfigProviderId(n){const e=normalizeText(normalizeAIConfigResourceId(n));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(n,e){return aiConfigResourceRefToModelId(n,e)}function aiConfigModelRef(n,e){if(e===void 0)return normalizeAIConfigResourceId(n);const t=normalizeAIConfigProviderId(n),i=normalizeAIConfigModelStorageId(e,t);return t&&i?`/settings/providers/${t}.ttl#${i}`:i}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:"Local credential id."},service:{type:"string",predicate:UDFS.service,required:!0,description:"Credential service grouping, for example ai or infra."},providerId:{type:"string",predicate:UDFS.provider,required:!0,description:"Provider identifier such as openai or cloudflare."},secretType:{type:"string",predicate:UDFS.secretType,required:!0,description:"Provider-specific secret kind such as api-key or tunnel-token."},label:{type:"string",predicate:UDFS.label,description:"User-facing credential label."},apiKey:{type:"string",predicate:UDFS.apiKey,secret:!0,description:"Secret token or API key material."},authMode:{type:"string",predicate:UDFS.authMode,description:"Authentication mode such as apiKey, oauth, deviceCode, or console."},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."},status:{type:"string",predicate:UDFS.status,description:"Credential health status."}},uniqueBy:["service","providerId","secretType"],writableFields:["label","apiKey","authMode","storageMode","secretPayload","encryptedSecret","wrappedDataKey","encryptionAlgorithm","keyVersion","scopes","expiresAt","accountLabel","lastRefreshAt","reauthRequired","status"],mergePolicy:"upsert",examples:[{request:"保存 Cloudflare tunnel token",match:{service:"infra",providerId:"cloudflare",secretType:"tunnel-token"}},{request:"保存 OpenAI API key",match:{service:"ai",providerId:"openai",secretType:"api-key"}}]},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,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"}}]},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,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,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,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},run:{type:"uri",predicate:UDFS.run,description:"Run waiting for input."},task:{type:"uri",predicate:UDFS.task,description:"Task whose execution requires input."},requester:{type:"uri",predicate:UDFS.requester,description:"Runtime, worker, or Secretary resource that requested input."},requestKind:{type:"string",predicate:UDFS.requestKind,required:!0,description:"Input request category such as user-input, clarification, binding, or selection."},prompt:{type:"text",predicate:UDFS.prompt,required:!0,description:"Question or missing-information prompt."},context:{type:"text",predicate:UDFS.context,description:"Concise request context. Long evidence belongs in linked files/resources."},inputOptions:{type:"text",predicate:UDFS.inputOptions,description:"Serialized options offered for the input request."},status:{type:"string",predicate:UDFS.status,description:"Input request lifecycle status such as pending, handling, resolved, expired, or cancelled."},leaseOwner:{type:"string",predicate:UDFS.leaseOwner,description:"Client/runtime id that currently owns the Inbox/input handling lease."},leaseExpiresAt:{type:"timestamp",predicate:UDFS.leaseExpiresAt,description:"Expiration timestamp for the handling lease."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"WebID or agent resource assigned to answer the request."},response:{type:"text",predicate:UDFS.response,description:"Answer, selected option, or input supplied to unblock the run."},answeredBy:{type:"uri",predicate:UDFS.answeredBy,description:"WebID or agent resource that supplied the response."},onBehalfOf:{type:"uri",predicate:UDFS.onBehalfOf,description:"User WebID or principal on whose behalf the response applies."},reason:{type:"text",predicate:UDFS.reason,description:"Reason or explanation for the response."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque protocol-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."},expiresAt:{type:"timestamp",predicate:UDFS.expiresAt,description:"Business deadline after which the request should no longer be acted on."},resolvedAt:{type:"timestamp",predicate:UDFS.resolvedAt,description:"Resolution timestamp."}},uniqueBy:["id"],writableFields:["session","chat","thread","run","task","requester","requestKind","prompt","context","inputOptions","status","leaseOwner","leaseExpiresAt","assignedTo","response","answeredBy","onBehalfOf","reason","metadata","expiresAt","resolvedAt"],mergePolicy:"upsert",examples:[{request:"Claim a pending input request from Inbox subscription",match:{id:"2026/06/12.ttl#input_1"}}]};function exactIdStorage(n="/.data/"){return{base:n,resourceIdPattern:"{id}"}}const idField={type:"string",predicate:UDFS.term("id"),required:!0,description:"Base-relative resource id. For exact-id descriptors this includes the full document path and optional fragment."},captureCandidateDescriptor={uri:UDFS.CaptureCandidate,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.CaptureCandidate,resourceKind:"capture-candidate",description:"Temporary capture suggestion created from observed or ambiguous content. It is not formal memory until promoted through the appropriate typed resource and control flow.",storage:exactIdStorage("/.data/capture/"),fields:{id:idField,source:{type:"uri",predicate:DCTerms.source,required:!0,description:"Original message, file, URL, fetched document, or resource being considered."},summary:{type:"text",predicate:DCTerms.abstract,required:!0,description:"Concise statement of what might be worth saving."},suggestedType:{type:"uri",predicate:UDFS.suggestedType,description:"Proposed formal resource class such as Idea, Evidence, Note, Decision, Preference, Link, or ContactInfo."},suggestedTarget:{type:"uri",predicate:UDFS.suggestedTarget,description:"Proposed folder, collection, project, task, issue, chat, or other scope."},confidence:{type:"string",predicate:UDFS.confidence,description:"Classifier confidence: high, medium, or low."},reason:{type:"text",predicate:UDFS.reason,description:"Short rationale for why this source might be worth capturing."},status:{type:"string",predicate:UDFS.status,description:"Candidate lifecycle status such as candidate, promoted, rejected, duplicate, ignored, or superseded."},sourceHash:{type:"string",predicate:UDFS.sourceHash,description:"Optional source digest for duplicate detection."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},run:{type:"uri",predicate:UDFS.run,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,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,description:"ApprovalRequest controlling an authority gate, if any."},inputRequest:{type:"uri",predicate:UDFS.inputRequest,description:"InputRequest controlling missing information, if any."},chat:{type:"uri",predicate:UDFS.conversation,description:"Related chat command surface."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related concrete thread/work site."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},actor:{type:"uri",predicate:DCTerms.creator,description:"Secretary, user, or worker that made or recorded the decision."},about:{type:"uri",predicate:SCHEMA.about,description:"Control object or semantic subject the event is about."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter-local metadata; shared relations must be explicit fields."},createdAt:{type:"timestamp",predicate:DCTerms.created,description:"Creation timestamp."}},uniqueBy:["id"],writableFields:["source","captureCandidate","targetResource","decision","suggestedType","suggestedTarget","confidence","reason","userCorrection","approval","inputRequest","chat","thread","task","run","actor","about","metadata"],mergePolicy:"append",examples:[{request:"Record that a chat message became a capture candidate",match:{id:"events/2026/06/16.ttl#event_1"}}]},contactDescriptor={uri:UDFS.Contact,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:VCARD.Individual,resourceKind:"contact",description:"Unified address-book projection for Solid users, external users, groups, and AI agents.",storage:exactIdStorage("/.data/contacts/"),fields:{id:idField,name:{type:"string",predicate:VCARD.fn,required:!0,description:"Display name."},avatarUrl:{type:"uri",predicate:VCARD.hasPhoto,description:"Avatar image URI."},about:{type:"uri",predicate:SCHEMA.about,required:!0,description:"Person, Agent, Chat, or external resource this contact card is about."},rdfType:{type:"uri",predicate:RDF$1.type,required:!0,description:"Semantic classifier for the represented resource."},contactType:{type:"string",predicate:UDFS.contactType,required:!0,description:"Runtime/source hint for handler selection."},isPublic:{type:"boolean",predicate:AS.audience,description:"Whether the contact is public."},externalPlatform:{type:"string",predicate:UDFS.externalPlatform,description:"External platform namespace."},externalId:{type:"string",predicate:UDFS.externalId,description:"Opaque external platform id; not a resource relation."},alias:{type:"string",predicate:UDFS.alias,description:"Private display alias."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},note:{type:"text",predicate:VCARD.note,description:"Private note."},sortKey:{type:"string",predicate:UDFS.sortKey,description:"Stable sort key."},gender:{type:"string",predicate:VCARD.hasGender,description:"Demographic hint."},province:{type:"string",predicate:VCARD.region,description:"Region."},city:{type:"string",predicate:VCARD.locality,description:"Locality."},deletedAt:{type:"timestamp",predicate:UDFS.deletedAt,description:"Deletion timestamp."},lastSyncedAt:{type:"timestamp",predicate:UDFS.lastSyncedAt,description:"Last sync timestamp."}},uniqueBy:["id"],writableFields:["name","avatarUrl","about","rdfType","contactType","isPublic","externalPlatform","externalId","alias","starred","note","sortKey","gender","province","city","deletedAt","lastSyncedAt"],mergePolicy:"upsert",examples:[{request:"Create an AI agent contact projection",match:{id:"agent-secretary.ttl"}}]},chatDescriptor={uri:MEETING.LongChat,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:MEETING.LongChat,resourceKind:"chat",description:"Interactive command surface/counterpart: who or what the user is talking with.",storage:exactIdStorage("/.data/chat/"),fields:{id:idField,title:{type:"string",predicate:DCTerms.title,required:!0,description:"Chat title."},description:{type:"string",predicate:DCTerms.description,description:"Chat description."},avatarUrl:{type:"uri",predicate:SCHEMA.image,description:"Avatar image URI."},author:{type:"uri",predicate:DCTerms.creator,description:"Creator WebID or agent URI."},status:{type:"string",predicate:UDFS.status,description:"Chat lifecycle status."},starred:{type:"boolean",predicate:UDFS.favorite,description:"Favorite flag."},muted:{type:"boolean",predicate:UDFS.muted,description:"Muted flag."},unreadCount:{type:"number",predicate:UDFS.unreadCount,description:"Unread message count."},contact:{type:"uri",predicate:UDFS.hasContact,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,description:"Solid Chat compatibility containment relation."},thread:{type:"uri",predicate:SIOC.has_member,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,description:"Source chat."},thread:{type:"uri",predicate:UDFS.inThread,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,description:"Owning or source chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Owning or source thread."},parentIssue:{type:"uri",predicate:UDFS.parentIssue,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,description:"Originating issue."},message:{type:"uri",predicate:UDFS.message,description:"Message that produced this task."},workspace:{type:"uri",predicate:UDFS.workspace,required:!0,description:"Workspace URI."},status:{type:"string",predicate:UDFS.status,description:"Task lifecycle status."},priority:{type:"string",predicate:UDFS.priority,description:"Priority."},assignedTo:{type:"uri",predicate:UDFS.assignedTo,description:"Assignee WebID or agent URI."},source:{type:"uri",predicate:DCTerms.source,description:"Source resource."},metadata:{type:"json",predicate:UDFS.metadata,description:"Opaque adapter metadata."}},uniqueBy:["id"],writableFields:["title","instruction","prompt","issue","message","workspace","status","priority","assignedTo","source","metadata"],mergePolicy:"upsert",examples:[{request:"Create an executable task under an issue",match:{id:"task_symphony_worker_projection"}}]},scheduleDescriptor={uri:UDFS.Schedule,version:"1.0.0",source:"official",trustLevel:"high",namespace:UDFS.NAMESPACE,class:UDFS.Schedule,resourceKind:"schedule",description:"Time-based trigger configuration for a Task.",storage:exactIdStorage(),fields:{id:idField,task:{type:"uri",predicate:UDFS.task,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,description:"Task dispatched by this rule."},schedule:{type:"uri",predicate:UDFS.schedule,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,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,description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,description:"Source thread."},targetThread:{type:"uri",predicate:UDFS.targetThread,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,description:"Task being executed."},delivery:{type:"uri",predicate:UDFS.delivery,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,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,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,description:"Related issue."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,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,description:"Related issue."},task:{type:"uri",predicate:UDFS.task,description:"Related task."},delivery:{type:"uri",predicate:UDFS.delivery,description:"Related delivery."},run:{type:"uri",predicate:UDFS.run,description:"Related run."},thread:{type:"uri",predicate:UDFS.inThread,description:"Related thread."},evidence:{type:"uri",predicate:UDFS.evidence,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,description:"Related chat."},thread:{type:"uri",predicate:UDFS.inThread,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,contactDescriptor,chatDescriptor,threadDescriptor,messageDescriptor,chatProjectContextDescriptor,chatProjectMemoryDescriptor,conversationShareDescriptor,ideaDescriptor,issueDescriptor,taskDescriptor,scheduleDescriptor,automationRuleDescriptor,deliveryDescriptor,runDescriptor,runStepDescriptor,evidenceDescriptor,reportDescriptor,captureCandidateDescriptor,captureEventDescriptor,sessionDescriptor,approvalDescriptor,inputRequestDescriptor];function createPodModelDescriptorRegistry(n=officialPodModelDescriptors){const e=new Map(n.map(t=>[t.uri,t]));return{list(t={}){return n.filter(i=>!(t.source&&i.source!==t.source||t.resourceKind&&i.resourceKind!==t.resourceKind))},describe(t){return e.get(t)??null}}}createPodSchema();function createPodSchema(n=createPodModelDescriptorRegistry()){const e=(t={})=>{const i=t.uri??t.schemaUri;if(!i)return n.list();const s=n.describe(i);return s?[s]:[]};return{list:n.list,describe(t){const i=typeof t=="string"?t:"uri"in t?t.uri:t.schemaUri;return n.describe(i)},classes(t={}){return e(t).map(i=>({schemaUri:i.uri,resourceKind:i.resourceKind,class:i.class,namespace:i.namespace,source:i.source,trustLevel:i.trustLevel,description:i.description}))},search(t){const i=normalizeSearchTerms(t.query);return i.length===0?[]:n.list({source:t.source,resourceKind:t.resourceKind}).map(s=>scoreDescriptorSearch(s,i)).filter(s=>s!==null).sort((s,o)=>o.score-s.score||s.uri.localeCompare(o.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(i=>Object.entries(i.fields).filter(([s])=>!t.field||s===t.field).map(([s,o])=>({schemaUri:i.uri,field:s,predicate:o.predicate,type:o.type,required:!!o.required,secret:!!o.secret,array:!!o.array,description:o.description})))}}}function normalizeSearchTerms(n){return n.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(n,e){const t=new Set;let i=0;const s=(o,l,u)=>{if(!l)return;const h=l.toLowerCase();for(const d of e)h.includes(d)&&(t.add(o),i+=u)};s("uri",n.uri,10),s("class",n.class,10),s("namespace",n.namespace,4),s("resourceKind",n.resourceKind,8),s("description",n.description,4),s("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[o,l]of Object.entries(n.fields))s(`field:${o}`,o,6),s(`predicate:${o}`,l.predicate,6),s(`description:${o}`,l.description,3);for(const o of n.examples){s("example",o.request,3);for(const[l,u]of Object.entries(o.match))s(`example:${l}`,String(u),3)}return i<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:i,matchedFields:[...t].sort()}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(n,e){const t=await n(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const i=t.headers?.get?.("content-type")??"",s=await t.text().catch(()=>"");if(!s)return[];if(i.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(s)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(s))}function extractStorageUrlsFromTurtle(n){return Array.from(n.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(n){const e=new Set,t=new WeakSet,i=(s,o=!1)=>{if(typeof s=="string"){o&&e.add(s);return}if(!(!s||typeof s!="object")&&!t.has(s)){if(t.add(s),Array.isArray(s)){for(const l of s)i(l,o);return}for(const[l,u]of Object.entries(s)){const h=SOLID_STORAGE_KEYS.has(l);if(o&&l==="@id"){i(u,!0);continue}i(u,o||h)}}};return i(n),Array.from(e)}function normalizeStorageUrl(n){try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}function uniqueNormalizedStorageUrls(n){const e=new Set;for(const t of n){const i=normalizeStorageUrl(t);i&&e.add(i)}return Array.from(e)}function ensureTrailingSlash(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_RETURN_PATH_PREFIXES=["/dashboard","/status","/network","/settings","/ai-config","/ai-connections"];function normalizeXpodReturnPath(n){if(n===void 0)return;if(typeof n!="string"||n.trim()==="")throw new TypeError("returnTo must be a non-empty application path");const e=n.trim(),t=decodeForValidation(e),i=t.split(/[?#]/,1)[0];if(!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||t.includes("\\")||/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith("//")||i.split("/").some(s=>s==="..")||!XPOD_RETURN_PATH_PREFIXES.some(s=>i===s||i.startsWith(`${s}/`)))throw new TypeError("returnTo must be a safe path within the application allow-list");return e}function decodeForValidation(n){let e=n;for(let t=0;t<4;t+=1){let i;try{i=decodeURIComponent(e)}catch{throw new TypeError("returnTo contains malformed percent encoding")}if(i===e)return e;e=i}return e}const XPOD_LOGIN_ROUTE_ID="xpod-current-origin";function createXpodLoginRoute(n=typeof window>"u"?"http://localhost":window.location){const e=toLocation(n),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(n){return normalizeXpodReturnPath(n)}function assertXpodLoginRoute(n,e){const t=normalizeWebIdLoginRoute(n),i=new URL(e).origin,s=new URL(t.identityProvider.url).origin,o=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||s!==i||o!==i||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:i},storageProvider:t.storageProvider?{...t.storageProvider,url:i}:void 0}}function toLocation(n){if(typeof n=="string"){const e=new URL(n,typeof window>"u"?void 0:window.location.href);return{origin:e.origin,host:e.host,href:e.href}}return n instanceof URL?{origin:n.origin,host:n.host,href:n.href}:{origin:n.origin,host:n.host,href:n.href}}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_SOLID_SESSION_ID_STORAGE_KEY="xpod.solid.sessionId",INRUPT_CURRENT_SESSION_STORAGE_KEY="solidClientAuthn:currentSession",INRUPT_SESSION_STORAGE_KEY_PREFIX="solidClientAuthenticationUser:",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",INRUPT_DYNAMIC_CLIENT_FIELDS=["clientId","clientSecret","clientName","clientType","expiresAt","idTokenSignedResponseAlg"],INRUPT_STORAGE_NAMESPACES=["secure","insecure"],XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(n,e,t){return n.status==="initializing"?{status:"loading",issuer:t}:n.status==="anonymous"?{status:"anonymous",issuer:t}:n.status==="expired"?{status:"expired",webId:n.webId,issuer:t}:n.status==="error"?{status:"error",webId:n.webId,error:n.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:n.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:n,fetch:e}){const t=await fetchProfileStorageUrls(e,n);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[];const i=createSolidLocalRouteFetch({fetch:globalThis.fetch,routes:()=>t}),s=n.sessionFactory?.({fetch:i})??createInruptSession(e.sessionId,e.oidcSession,i);let o=readStoredOidcIssuer(e.issuer);const l=createSolidSessionRuntime({session:s}),u=l.handleIncomingRedirect,h=g=>{const y=readIssuerFromSessionInfo(s.info)??o??readStoredOidcIssuer(e.issuer),v=o??expectedSameOriginIssuer(y);return g.status==="authenticated"&&isCurrentXpodSessionSnapshot(g,y,v)&&rememberInruptCurrentSession(e),g},d={...l,initialize:async g=>h(await l.initialize(g)),...u?{handleIncomingRedirect:async g=>h(await u(g))}:{}},p=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:g,fetch:y})=>drizzle({get info(){return s.info},fetch:y},{podUrl:g,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:d,pod:p,storage:e,getIssuer:()=>readIssuerFromSessionInfo(s.info)??o??readStoredOidcIssuer(e.issuer),getExpectedIssuer:()=>o??expectedSameOriginIssuer(readIssuerFromSessionInfo(s.info)),setIssuer:g=>{const y=normalizeXpodOidcIssuer(g);o=y,y&&writeStoredOidcIssuer(y,e.issuer)},setLocalPodRoute:g=>{t=g?[g,...["/api/","/v1/"].map(y=>({canonicalBaseUrl:new URL(y,g.canonicalBaseUrl).href,localBaseUrl:new URL(y,g.localBaseUrl).href}))]:[]}}}function createInruptSession(n=getOptionalPersistentStorage$1(),e=getOptionalPersistentStorage$1(),t=globalThis.fetch){let i;try{i=n?.getItem(XPOD_SOLID_SESSION_ID_STORAGE_KEY)??void 0,i||(i=globalThis.crypto?.randomUUID?.()??`xpod-${Date.now().toString(36)}`,n?.setItem(XPOD_SOLID_SESSION_ID_STORAGE_KEY,i))}catch{}const s=n??getOptionalPersistentStorage$1();for(const o of new Set([e,s].filter(Boolean)))migrateLegacyInruptSessionRecords(o);return e?new Session({secureStorage:toInruptStorage(e,"secure"),insecureStorage:toInruptStorage(s??e,"insecure"),fetch:t},i):new Session({fetch:t},i)}function toInruptStorage(n,e){const t=i=>e?inruptStorageKey(e,i):i;return{get:async i=>n.getItem(t(i))??void 0,set:async(i,s)=>{n.setItem(t(i),s)},delete:async i=>{n.removeItem(t(i))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}function migrateLegacyInruptSessionRecords(n){if(n)try{const e=storageKeys(n).filter(t=>t.startsWith(INRUPT_SESSION_STORAGE_KEY_PREFIX));for(const t of e){const i=n.getItem(t);if(i!==null){for(const s of INRUPT_STORAGE_NAMESPACES){const o=inruptStorageKey(s,t);n.getItem(o)===null&&n.setItem(o,i)}n.removeItem(t)}}}catch{}}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function clearCachedInruptDynamicClientRegistration(n){const e=n.oidcSession;if(!e)return;const t=storageKeys(e).filter(isInruptSessionStorageRecordKey);for(const i of t){const s=e.getItem(i);if(s)try{const o=JSON.parse(s);for(const l of INRUPT_DYNAMIC_CLIENT_FIELDS)delete o[l];e.setItem(i,JSON.stringify(o))}catch{e.removeItem(i)}}}function rememberInruptCurrentSession(n){try{const e=n.sessionId?.getItem(XPOD_SOLID_SESSION_ID_STORAGE_KEY);if(!e)return;getOptionalPersistentStorage$1()?.setItem(INRUPT_CURRENT_SESSION_STORAGE_KEY,e)}catch{}}function withXpodProvisionScope(n,e){const t=new URL(n);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(n,e){try{const t=await e("/provision/status",{headers:{Accept:"application/json"},credentials:"include"});if(t.ok){const i=await t.json(),s=normalizeXpodOidcIssuer(i.oidcIssuer);if(s)return{oidcIssuer:s,provisionCode:typeof i.provisionCode=="string"&&i.provisionCode.trim()?i.provisionCode.trim():void 0}}}catch{}return{oidcIssuer:normalizeXpodOidcIssuer(n)}}function isInruptSessionStorageRecordKey(n){return n.startsWith(INRUPT_SESSION_STORAGE_KEY_PREFIX)?!0:INRUPT_STORAGE_NAMESPACES.some(e=>n.startsWith(`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${e}:${INRUPT_SESSION_STORAGE_KEY_PREFIX}`))}function storageKeys(n){return Array.from({length:n.length},(e,t)=>n.key(t)).filter(e=>!!e)}function safeAuthError(n){return n.message==="Solid session expired"?n:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(n,e=typeof window>"u"?"http://localhost":window.location.origin){if(!n||typeof n!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(n),i=assertXpodLoginRoute(t.route,e),s=normalizeXpodReturnTo(t.returnTo);return{...t,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function useXpodSolidRuntimeContext(){const n=reactExports.useContext(XpodSolidRuntimeContext);if(!n)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return n}function readIssuerFromSessionInfo(n){const e=n.issuer??n.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(n){if(!(typeof n!="string"||!n.trim()))try{const e=new URL(n.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(n,e,t){if(n.status!=="authenticated")return!0;const i=normalizeXpodOidcIssuer(e),s=normalizeXpodOidcIssuer(t);return!i||!s||i!==s?!1:isHttpResourceUrl(n.webId)}function expectedSameOriginIssuer(n,e=typeof window>"u"?"http://localhost":window.location.origin){const t=normalizeXpodOidcIssuer(n);return t&&hasOrigin(t,e)?t:void 0}function hasOrigin(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function isHttpResourceUrl(n){try{const e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(n=getOptionalPersistentStorage$1()){try{return normalizeXpodOidcIssuer(n?.getItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY))}catch{return}}function clearStoredXpodOidcIssuer(n){try{n?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalPersistentStorage$1()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage$1()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(n,e=getOptionalPersistentStorage$1()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,n)}catch{}}function createXpodSolidRuntimeStoragePolicy(n={}){const e=getOptionalPersistentStorage$1();return{sessionId:n.sessionId??e,oidcSession:n.oidcSession??e,issuer:n.issuer??e,selectedStorage:n.selectedStorage??e}}function getOptionalPersistentStorage$1(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage$1(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}const useXpodSolidRuntime=useXpodSolidRuntimeContext,XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=normalizedUrl(n.webId),i=normalizedUrl(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),o=normalizedUrl(e.webId),l=normalizedUrl(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!o||!l||!u||t!==i||o!==l||t!==o||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,o=normalizedEmail(i.email),l=normalizedUrl(t.webId),u=normalizedUrl(s.webId),h=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!o||!l||!u||!h||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,h,e]);return{account:{...o?{email:o}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:h},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const o=normalizedUrl(s);return o&&new URL(o).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,o=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??o?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||o&&!rememberedXpodLoginMatchesActive(o,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??o?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??o?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,o,e.currentPod,t,s]),null}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function storeAccountSessionToken(n){n&&writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"}){return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:t.href}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const h=new URL(t,window.location.origin),d=new URL(n.trim(),h);if(d.origin===h.origin&&h.pathname.startsWith("/.account/")&&d.pathname.startsWith("/.account/")&&["http:","https:"].includes(d.protocol)&&!d.username&&!d.password)return d.href}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const h=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(h)return h.href}const o={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,o.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...o,fetch:async()=>l.clone()}):void 0;return u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin),u?resolveSolidLocalRouteUrl(s,[u])?.href:void 0}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[o,l]=reactExports.useState(!0),[u,h]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,y]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),x=g.status==="authenticated",A=o||g.status==="submitting",I=reactExports.useRef(x);reactExports.useEffect(()=>{let j=!0;return resolveXpodAccountIndex().then(ee=>{j&&t(ee)}),()=>{j=!1}},[]),reactExports.useEffect(()=>{I.current=x},[x]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,E.current+=1}),[]);const T=reactExports.useCallback(j=>S.current&&j===E.current,[]),F=reactExports.useCallback(async()=>{const j=new AbortController,ee=setTimeout(()=>j.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{if(!e)return!1;const me=await fetch(new URL("oidc/consent/",e),{headers:storedAccountTokenHeaders(),credentials:"include",signal:j.signal});return me.ok?!!(await me.json()).client:!1}catch{return!1}finally{clearTimeout(ee)}},[e]),P=reactExports.useCallback(async({exposeTransientError:j,generation:ee,confirmUnauthenticated:me})=>{if(!e)return"stale";try{const te=await fetch(e,{headers:storedAccountTokenHeaders(),credentials:"include"});if(!T(ee))return"stale";if(te.ok){const Ce=await te.json().catch(()=>({}));if(!T(ee))return"stale";const Oe=Ce.controls||{},ye=++v.current;p(!1),s(Oe),h(null);const qe=accountStateForControls(Oe);return I.current=qe.status==="authenticated",y(qe),Oe.account?.logout&&isAccountSpaPath()&&F().then(de=>{T(ee)&&ye===v.current&&p(de)}),"ok"}else{if(te.status===401||te.status===403)return me?(v.current+=1,clearAccountSessionToken(),I.current=!1,p(!1),s({}),y({status:"anonymous",mode:"login"}),h(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(te.status))return h(null),y(Oe=>Oe.status==="authenticated"?Oe:transientAccountState(j)),"transient-error";const Ce=`Failed to load account controls (Status: ${te.status})`;return h(Ce),y({status:"error",mode:"login",message:Ce}),"terminal-error"}}catch{return T(ee)?(v.current+=1,p(!1),h(null),y(te=>te.status==="authenticated"?te:transientAccountState(j)),"transient-error"):"stale"}},[F,e,T]),V=reactExports.useCallback(async()=>{const j=++E.current;for(let ee=0;ee<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;ee+=1){const me=ee===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,te=await P({exposeTransientError:me,generation:j});if(te==="unauthenticated")return!T(j)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!T(j))?"stale":P({exposeTransientError:!0,generation:j,confirmUnauthenticated:!0});if(te!=="transient-error")return te;if(!T(j)||!me&&(y(Ce=>Ce.status==="authenticated"?Ce:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[ee]),!T(j)))return"stale"}return"transient-error"},[P,T]);reactExports.useEffect(()=>{if(!e)return;let j=!0;return(async()=>(await V(),j&&S.current&&l(!1)))(),()=>{j=!1}},[V,e]);const B=reactExports.useCallback(async()=>{await V()},[V]),Y=reactExports.useCallback(async()=>{const j=i?.account?.logout,ee=await resolveHostedAccountControlUrl(j,fetch,e);let me=!!(j&&!ee);if(ee)try{const te=await fetch(ee,{method:"POST",headers:storedAccountTokenHeaders(),credentials:"include"});me=!te.ok&&te.status!==401&&te.status!==403}catch{me=!0}if(me){y({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}I.current=!1,clearAccountSessionToken(),p(!1),s({}),h(null),y({status:"anonymous",mode:"login"})},[i?.account?.logout,e]),_e=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:o,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:x,isAnonymous:()=>!I.current,authenticating:A,hasOidcPending:d,refetchControls:B,retry:B,logout:Y,accountState:g,identity:_e},children:n})}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX;if(!isLoopbackHostname$1(window.location.hostname))return new URL(LOCAL_ACCOUNT_INDEX,window.location.origin).href;try{const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(!e.ok)return new URL(LOCAL_ACCOUNT_INDEX,window.location.origin).href;const t=await e.json();if(t.managed===!0&&typeof t.oidcIssuer=="string"){const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return new URL(LOCAL_ACCOUNT_INDEX,i).href}}catch{}return new URL(LOCAL_ACCOUNT_INDEX,window.location.origin).href}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const o=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:o,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}const XPOD_DEFAULT_RETURN_PATH="/dashboard/overview",canonicalRoutes={status:"/status/overview",network:"/network",aiConnections:"/ai-connections",aiConfig:"/ai-config/model-assignments",settings:"/settings/pod"},legacyProductRedirects={"/dashboard":canonicalRoutes.status,[XPOD_DEFAULT_RETURN_PATH]:canonicalRoutes.status,"/dashboard/network":canonicalRoutes.network,"/dashboard/models":canonicalRoutes.aiConnections,"/dashboard/pod":canonicalRoutes.settings,"/dashboard/services":canonicalRoutes.status,"/dashboard/settings":canonicalRoutes.settings,"/settings/models":canonicalRoutes.aiConnections,"/settings/ai-connections":canonicalRoutes.aiConnections,"/settings/ai-config":canonicalRoutes.aiConfig,"/settings/pod":canonicalRoutes.settings,"/settings/network":canonicalRoutes.network,"/settings/services":canonicalRoutes.status,"/settings/system":canonicalRoutes.settings};function canonicalProductPathname(n){return legacyProductRedirects[n]??n}const XPOD_LOGIN_TRANSACTION_VERSION=1,XPOD_LOGIN_TRANSACTION_PREFIX="xpod.auth.transaction.v1",XPOD_LOGIN_TRANSACTION_TTL_MS=600*1e3,XPOD_SELECTED_STORAGE_BINDING_VERSION=1,XPOD_SELECTED_STORAGE_BINDING_KEY="xpod.auth.selected-storage.v1";class XpodLoginTransactionError extends Error{code;constructor(e,t){super(t),this.name="XpodLoginTransactionError",this.code=e}}function readXpodSelectedStorage(n={}){return n.storage?readXpodSelectedStorageFrom(n.storage,n):readXpodSelectedStorageFrom(getOptionalPersistentStorage(),n)??readXpodSelectedStorageFrom(getOptionalSessionStorage(),n)}function readXpodSelectedStorageFrom(n,e){if(!n)return;const t=n.getItem(XPOD_SELECTED_STORAGE_BINDING_KEY);if(!t)return;const i=()=>n.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);let s;try{s=JSON.parse(t)}catch{i();return}if(!isStoredSelectedStorageBinding(s)){i();return}const o=e.now??(()=>Date.now());if(s.expiresAt<=o()){i();return}let l;try{l=normalizeSelectedStorageBinding(s.binding,s.storageRoot??new URL(e.origin??getWindowOrigin()).origin,s.storageRoot===void 0)}catch{i();return}if(e.webId!==void 0&&l.webId!==e.webId){i();return}return l}function clearXpodSelectedStorage(n={}){n.storage?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY);try{getOptionalPersistentStorage()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY),getOptionalSessionStorage()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY)}catch{}}function createOpaqueTransactionId(){const n=globalThis.crypto;if(typeof n?.randomUUID=="function")return n.randomUUID();if(typeof n?.getRandomValues=="function"){const e=new Uint8Array(24);return n.getRandomValues(e),`xpod-${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}throw new XpodLoginTransactionError("storage_unavailable","Secure transaction id generation is unavailable")}function createXpodLoginTransactionStore(n={}){const e=n.storage??getSessionStorage(),t=new URL(n.origin??getWindowOrigin()).origin,i=n.now??(()=>Date.now()),s=n.ttlMs??XPOD_LOGIN_TRANSACTION_TTL_MS,o=n.prefix??XPOD_LOGIN_TRANSACTION_PREFIX,l=`${o}.active`,u=y=>`${o}.record.${y}`,h=y=>`${o}.consumed.${y}`,d=y=>{e.getItem(l)===y&&e.removeItem(l),e.removeItem(u(y))},p=(y,v=!0)=>{if(!isSafeTransactionId(y))throw new XpodLoginTransactionError("malformed","Transaction id is malformed");if(e.getItem(h(y))==="1")throw new XpodLoginTransactionError("consumed","Transaction has already been consumed");if(v&&e.getItem(l)!==y)throw new XpodLoginTransactionError("unknown","Transaction is not the active Xpod login transaction");const S=e.getItem(u(y));if(!S)throw v&&e.getItem(l)===y&&e.removeItem(l),new XpodLoginTransactionError("unknown","Xpod login transaction was not found");let E;try{E=JSON.parse(S)}catch{throw d(y),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}if(!isStoredTransaction(E)||E.transaction.id!==y)throw d(y),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed");if(E.expiresAt<=i())throw d(y),new XpodLoginTransactionError("expired","Xpod login transaction has expired");try{const x=normalizePublicTransaction({...E.transaction,authorizationSurface:"redirect",discovery:"strict"},t);return E.transaction={id:x.id,route:x.route,...x.returnTo===void 0?{}:{returnTo:x.returnTo},...x.selectedStorage===void 0?{}:{selectedStorage:x.selectedStorage}},E}catch(x){throw d(y),x instanceof XpodLoginTransactionError?x:new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}};return{begin:y=>{const v=e.getItem(l);if(v){try{p(v)}catch(T){if(!(T instanceof XpodLoginTransactionError&&(T.code==="expired"||T.code==="malformed"||T.code==="unknown")))throw T}if(e.getItem(l)===v)throw new XpodLoginTransactionError("already_active","An Xpod login transaction is already pending in this tab")}const S=isSafeTransactionId(y.id)?y.id:createOpaqueTransactionId(),E=normalizePublicTransaction({...y,id:S},t),x=i(),A=x+s,I={version:XPOD_LOGIN_TRANSACTION_VERSION,createdAt:x,expiresAt:A,transaction:{id:E.id,route:E.route,...E.returnTo===void 0?{}:{returnTo:E.returnTo},...E.selectedStorage===void 0?{}:{selectedStorage:E.selectedStorage}}};return e.setItem(u(E.id),JSON.stringify(I)),e.setItem(l,E.id),E},readSinglePending(){const y=e.getItem(l);if(y)return materialize(p(y).transaction)},updateSelectedStorage(y,v){const S=p(y),E=materialize(S.transaction),x=normalizeBinding(v,t,E.route.storageProvider?.url),A={...S,transaction:{...S.transaction,selectedStorage:x}};e.setItem(u(y),JSON.stringify(A))},consume(y){const v=p(y),S=materialize(v.transaction);return e.removeItem(l),e.removeItem(u(y)),e.setItem(h(y),"1"),S},cancel(y){p(y),e.removeItem(l),e.removeItem(u(y)),e.setItem(h(y),"1")}}}function normalizePublicTransaction(n,e){let t;try{t=normalizeWebIdLoginTransaction(n)}catch(o){throw new XpodLoginTransactionError("malformed",o instanceof Error?o.message:"Transaction is malformed")}let i;try{i=assertXpodLoginRoute(t.route,e)}catch(o){throw new XpodLoginTransactionError("cross_origin",o instanceof Error?o.message:"Transaction route is not local")}let s;try{s=normalizeXpodReturnTo(t.returnTo)}catch(o){throw new XpodLoginTransactionError("mismatch",o instanceof Error?o.message:"Transaction return path is unsafe")}if(t.selectedStorage!==void 0)try{const o=normalizeBinding(t.selectedStorage,e,i.storageProvider?.url);return{id:t.id,route:i,selectedStorage:o,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}catch(o){throw o instanceof XpodLoginTransactionError?o:new XpodLoginTransactionError("mismatch","Selected storage binding is invalid")}return{id:t.id,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function normalizeBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string")throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(i.origin!==e||s.origin!==e||t&&i.origin!==new URL(t).origin)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");if(i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("malformed","Selected storage binding contains unsafe URL data");return{storageUrl:i.href,webId:s.href,...n.label===void 0?{}:{label:n.label}}}function materialize(n){return{id:n.id,route:n.route,authorizationSurface:"redirect",discovery:"strict",...n.returnTo===void 0?{}:{returnTo:n.returnTo},...n.selectedStorage===void 0?{}:{selectedStorage:n.selectedStorage}}}function normalizeSelectedStorageBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string")throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed");let i,s;try{i=new URL(n.storageUrl),s=new URL(n.webId)}catch{throw new XpodLoginTransactionError("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol))throw new XpodLoginTransactionError("cross_origin","Selected storage binding must use web URLs");if(!urlBelongsToRoot(i,e)||t&&s.origin!==new URL(e).origin||i.username||i.password||i.hash||s.username||s.password)throw new XpodLoginTransactionError("cross_origin","Selected storage binding is not local to this Xpod");return{storageUrl:i.href,webId:s.href}}function normalizeStorageRoot(n){const e=new URL(n);return e.hash="",e.search="",e.pathname.endsWith("/")||(e.pathname+="/"),e.href}function urlBelongsToRoot(n,e){const t=new URL(normalizeStorageRoot(e));if(n.origin!==t.origin)return!1;const i=t.pathname;return n.pathname===i.slice(0,-1)||n.pathname.startsWith(i)}function isSafeTransactionId(n){return typeof n=="string"&&/^[A-Za-z0-9_-]{16,128}$/.test(n)}function isStoredTransaction(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_LOGIN_TRANSACTION_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.transaction&&typeof e.transaction=="object")}function isStoredSelectedStorageBinding(n){if(!n||typeof n!="object")return!1;const e=n;return e.version===XPOD_SELECTED_STORAGE_BINDING_VERSION&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.binding&&typeof e.binding=="object")}function getSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable")}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getWindowOrigin(){return typeof window<"u"&&window.location.origin!=="null"?window.location.origin:"http://localhost"}async function currentHostLocalPodRoute(n,e){if(typeof window>"u")return;const t=desktopLocalPodRoute(n);if(t)return t;if(storageUrlUsesCurrentOrigin(n))return;const i=await fetchCurrentProvisionRouteStatus(e);return currentProvisionLocalPodRoute(n,i)}function currentProvisionLocalPodRoute(n,e){if(!(typeof window>"u")&&!(e.managed!==!0||typeof e.storageRoot!="string")&&managedPublicRouteCoversStorage(n,e.storageRoot))return podScopedLocalRoute(n)}function desktopLocalPodRoute(n){if(!(typeof window>"u"||!window.xpodDesktop))return podScopedLocalRoute(n)}async function fetchCurrentProvisionRouteStatus(n){let e;try{e=await n(new URL("/provision/status",window.location.origin).href,{credentials:"include",headers:{accept:"application/json"}})}catch{return{}}if(!e.ok||!e.headers.get("content-type")?.includes("application/json"))return await e.arrayBuffer().catch(()=>{}),{};const t=await e.json().catch(()=>{});return{managed:t?.managed===!0,storageRoot:typeof t?.publicUrl=="string"?t.publicUrl:void 0}}function podScopedLocalRoute(n){try{const e=new URL(n),t=new URL(e.pathname,window.location.origin);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:(e.search="",e.hash="",t.search="",t.hash="",{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:t.href.endsWith("/")?t.href:`${t.href}/`})}catch{return}}function managedPublicRouteCoversStorage(n,e){try{const t=new URL(e),i=new URL(t.pathname,window.location.origin);return resolveSolidLocalRouteUrl(n,[{canonicalBaseUrl:t.href,localBaseUrl:i.href}])!==void 0}catch{return!1}}function storageUrlUsesCurrentOrigin(n){try{return new URL(n).origin===window.location.origin}catch{return!1}}function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[o,l]=reactExports.useState(s.snapshot),[u,h]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,y]=reactExports.useState(),[v,S]=reactExports.useState(),[E,x]=reactExports.useState(0),[A,I]=reactExports.useState(),T=reactExports.useRef(o),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),V=reactExports.useCallback(async(me,te)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):te===void 0?t.session.fetch(me):t.session.fetch(me,te),[t.session]),B=reactExports.useCallback(()=>{if(P.current)return P.current;const me=(async()=>{try{await t.session.logout();const te=t.session.getSnapshot();(te.status!=="authenticated"||isCurrentXpodSessionSnapshot(te,t.getIssuer(),t.getExpectedIssuer?.()??window.location.origin))&&(F.current=!1)}catch{}finally{const te={status:"anonymous"};t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),t.setIssuer(void 0),T.current=te,l(te),h(void 0),p(void 0),y(void 0),S(void 0),I(void 0)}})().finally(()=>{P.current===me&&(P.current=void 0)});return P.current=me,me},[t,i.issuer,i.selectedStorage]),Y=reactExports.useMemo(()=>({...t.session,fetch:V,getSnapshot:()=>T.current}),[V,t.session]);reactExports.useEffect(()=>{const me=Ce=>{const Oe=t.getIssuer();if(!isCurrentXpodSessionSnapshot(Ce,Oe,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,B();return}Ce.status==="authenticated"&&(F.current=!1);const ye=T.current;T.current=Ce,l(Ce),h(Oe),Ce.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),Ce.status!=="expired"&&y(void 0),S(void 0),I(void 0),t.pod.clear()):(ye.status!=="authenticated"||Ce.webId!==ye.webId)&&(p(void 0),y(void 0),S(void 0),I(void 0),t.pod.clear(ye.status==="authenticated"?{webId:ye.webId}:void 0))},te=t.session.subscribe(me);return me(t.session.getSnapshot()),te},[B,t,i]),reactExports.useEffect(()=>{F.current&&B()},[B]),reactExports.useEffect(()=>{if(o.status!=="authenticated")return;let me=!1;const te=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:o.webId}),Ce={webId:o.webId,...te?{podUrl:te.storageUrl}:{},fetch:V};return(async()=>{try{const Oe=await t.pod.open(Ce),ye=await currentHostLocalPodRoute(Oe.podUrl,fetch);if(me)return;if(t.setLocalPodRoute?.(ye),!me){if(te&&(Oe.webId!==te.webId||!sameUrl$2(Oe.podUrl,te.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),y(void 0),S({webId:o.webId,error:new Error("Selected Pod binding mismatch")});return}p(Oe),y(te??{webId:Oe.webId,storageUrl:Oe.podUrl}),S(void 0)}}catch(Oe){me||S({webId:o.webId,error:Oe instanceof Error?Oe:new Error(String(Oe))})}})(),()=>{me=!0}},[V,E,t,i.selectedStorage,o]);const _e=reactExports.useCallback(()=>{S(void 0),x(me=>me+1)},[]),j=o.status==="authenticated"?o.webId:void 0;reactExports.useEffect(()=>{if(!j)return;let me=!1;return discoverAiClientConfigurationCapability(V).then(te=>{!me&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===j&&I(te)}),()=>{me=!0}},[j,V,t]);const ee=reactExports.useMemo(()=>{const me=u??t.getIssuer(),te=o.status==="authenticated"&&v?.webId===o.webId?v:void 0,Ce=snapshotToState(o,d,me);return{session:Y,pod:t.pod,fetch:V,state:Ce.status==="error"?{...Ce,error:safeAuthError(Ce.error)}:Ce,webId:Ce.webId,podUrl:Ce.podUrl,issuer:Ce.issuer,currentPod:d,selectedStorage:g,...te?{podError:te}:{},retryPodOpen:_e,aiClientConfiguration:A,login:async Oe=>{const ye=normalizeXpodLoginTransaction(Oe),qe=await resolveXpodLoginContext(ye.route.identityProvider.url,fetch),de=qe.oidcIssuer;if(!de)throw new TypeError("Xpod login route has no valid issuer");const Fe=new URL("/auth/callback",window.location.origin);t.setIssuer(de),h(de),clearCachedInruptDynamicClientRegistration(i);try{await t.session.login({oidcIssuer:de,redirectUrl:Fe.toString(),handleRedirect:qe.provisionCode?O=>{window.location.assign(withXpodProvisionScope(O,qe.provisionCode))}:void 0})}catch(O){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",O,O instanceof Error?O.cause:void 0),O}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),y(void 0),I(void 0)}}},[A,d,V,Y,u,v,_e,t,i,g,o]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:Y,pod:t.pod,currentPod:d},children:jsxRuntimeExports.jsx(XpodSolidRuntimeContext.Provider,{value:ee,children:n})})}const ANONYMOUS_SNAPSHOT={status:"anonymous"},REJECTED_SESSION_FETCH_ERROR=new Error("Xpod session is unavailable");function currentProviderSession(n){const e=n.session.getSnapshot(),t=n.getIssuer();return isCurrentXpodSessionSnapshot(e,t,n.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:t,rejected:!1}:{snapshot:ANONYMOUS_SNAPSHOT,issuer:void 0,rejected:!0}}function sameUrl$2(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}async function discoverAiClientConfigurationCapability(n){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),t=await n(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!t.ok||!t.headers.get("content-type")?.includes("application/json"))return await t.arrayBuffer().catch(()=>{}),manualAiClientConfigurationCapability();const i=await t.json();if(isRecord(i)&&i.available===!0&&i.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof i.manualInstructions=="string"?i.manualInstructions:manualAiClientConfigurationCapability().manualInstructions}}catch{}return manualAiClientConfigurationCapability()}function manualAiClientConfigurationCapability(){return{available:!1,manualInstructions:"manual client setup is available"}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),o=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const h=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",h),()=>u.removeEventListener("change",h)):(u.addListener?.(h),()=>u.removeListener?.(h))},[]),reactExports.useEffect(()=>{applyXpodTheme(o)},[o]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:o,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,o]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const mergeClasses=(...n)=>n.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim();const toKebabCase=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const toCamelCase=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,i)=>i?i.toUpperCase():t.toLowerCase());const toPascalCase=n=>{const e=toCamelCase(n);return e.charAt(0).toUpperCase()+e.slice(1)};var defaultAttributes={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const hasA11yProp=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const Icon=reactExports.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:s="",children:o,iconNode:l,...u},h)=>reactExports.createElement("svg",{ref:h,...defaultAttributes,width:e,height:e,stroke:n,strokeWidth:i?Number(t)*24/Number(e):t,className:mergeClasses("lucide",s),...!o&&!hasA11yProp(u)&&{"aria-hidden":"true"},...u},[...l.map(([d,p])=>reactExports.createElement(d,p)),...Array.isArray(o)?o:[o]]));const createLucideIcon=(n,e)=>{const t=reactExports.forwardRef(({className:i,...s},o)=>reactExports.createElement(Icon,{ref:o,iconNode:e,className:mergeClasses(`lucide-${toKebabCase(toPascalCase(n))}`,`lucide-${n}`,i),...s}));return t.displayName=toPascalCase(n),t};const __iconNode$d=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]],BrainCircuit=createLucideIcon("brain-circuit",__iconNode$d);const __iconNode$c=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ChevronRight=createLucideIcon("chevron-right",__iconNode$c);const __iconNode$b=[["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("circle-alert",__iconNode$b);const __iconNode$a=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],CircleCheckBig=createLucideIcon("circle-check-big",__iconNode$a);const __iconNode$9=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],CircleCheck=createLucideIcon("circle-check",__iconNode$9);const __iconNode$8=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Copy=createLucideIcon("copy",__iconNode$8);const __iconNode$7=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Database=createLucideIcon("database",__iconNode$7);const __iconNode$6=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Gauge=createLucideIcon("gauge",__iconNode$6);const __iconNode$5=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Globe=createLucideIcon("globe",__iconNode$5);const __iconNode$4=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],LoaderCircle=createLucideIcon("loader-circle",__iconNode$4);const __iconNode$3=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],LogOut=createLucideIcon("log-out",__iconNode$3);const __iconNode$2=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],RefreshCw=createLucideIcon("refresh-cw",__iconNode$2);const __iconNode$1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Settings=createLucideIcon("settings",__iconNode$1);const __iconNode=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Sparkles=createLucideIcon("sparkles",__iconNode),globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const h=Math.max(72,t-n.top+12);return{left:8,bottom:h,width:u,maxHeight:Math.max(240,t-h-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",[i,s]=reactExports.useState(accountCardRequestedByUrl(t)),[o,l]=reactExports.useState(),[u,h]=reactExports.useState(),[d,p]=reactExports.useState(),g=reactExports.useRef(null),y=reactExports.useRef(null),v=reactExports.useRef(void 0),S=reactExports.useId(),E=n.identity,x=readPendingXpodAccountEmail(),A=readRememberedXpodLogin()?.account,I=accountCardIdentityFallback(E,x,A),T=useXpodProfileCardIdentity({accountIdentity:t?I:void 0,runtime:t?e:void 0}),F=T.displayName,P=initialsFor(T.displayName),V=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),B=e?.selectedStorage?.storageUrl??e?.podUrl,Y=e?.selectedStorage,_e=e?.currentPod,j=reactExports.useMemo(()=>B?podNameFromUrl(B):void 0,[B]),ee=e?.state.status==="authenticated"&&!!(V&&B&&Y&&_e)&&Y?.webId===V&&sameUrl$1(Y?.storageUrl??"",B??"")&&_e?.webId===V&&sameUrl$1(_e?.podUrl??"",B??""),me=t,te=i&&me,Ce=reactExports.useCallback(de=>{s(de),de||(p(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!te)return;const de=()=>{const Fe=y.current;Fe&&p(accountCardPosition(Fe.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return de(),window.addEventListener("resize",de),window.addEventListener("scroll",de,!0),window.visualViewport?.addEventListener("resize",de),()=>{window.removeEventListener("resize",de),window.removeEventListener("scroll",de,!0),window.visualViewport?.removeEventListener("resize",de)}},[te]),reactExports.useEffect(()=>{if(!me){clearAccountCardRequest();return}if(!te)return;const de=O=>{const Z=O.target;Z instanceof Node&&(g.current?.contains(Z)||y.current?.contains(Z)||Ce(!1))},Fe=O=>{O.key==="Escape"&&(Ce(!1),y.current?.focus())};return document.addEventListener("pointerdown",de),document.addEventListener("keydown",Fe),()=>{document.removeEventListener("pointerdown",de),document.removeEventListener("keydown",Fe)}},[me,te,Ce]),reactExports.useEffect(()=>{!te||!d||g.current?.focus({preventScroll:!0})},[te,d]),reactExports.useEffect(()=>()=>{v.current!==void 0&&window.clearTimeout(v.current)},[]);const Oe=async()=>{l("logout");try{await n.logout(),(n.isAnonymous?.()??!0)&&Ce(!1)}finally{l(void 0)}},ye=async()=>{l("switch");try{if(await n.logout(),!(n.isAnonymous?.()??!0))return;clearRememberedXpodLogin(),Ce(!1),window.location.assign(new URL("/status/overview",window.location.origin))}finally{l(void 0)}},qe=async()=>{const de=T.webId??accountHandle(T.username,I?.id,V);try{await navigator.clipboard.writeText(de),h("Copied")}catch{h("Copy failed")}v.current!==void 0&&window.clearTimeout(v.current),v.current=window.setTimeout(()=>h(void 0),1800)};return me?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:y,type:"button","aria-label":t?`Open account menu for ${F}`:"Open account menu","aria-expanded":te,"aria-controls":te?S:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":ee?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Ce(!te),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[T.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:T.avatarUrl,alt:F}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:P})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:t?F:"Not signed in"})]}),te&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:g,id:S,role:"region",tabIndex:-1,"aria-label":t?F:"Xpod account","data-avatar-card":"true","data-selected-pod-url":B,style:d,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${d?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[T.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:T.avatarUrl,alt:F}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:P})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:F}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:accountHandle(T.username,I?.id,V)}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"Copy Xpod ID",onClick:()=>{qe()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),u?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:u}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${ee?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:ee?"Pod connected":"Account connected"})]})]})]}),T.note||T.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[T.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:T.note}):null,T.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:T.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(j)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(B)]})]}),ee?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-emerald-500","aria-label":"Pod ready"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),jsxRuntimeExports.jsx(Separator,{}),jsxRuntimeExports.jsxs("div",{className:"p-2",children:[jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{ye()},disabled:o!==void 0,children:[o==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{Oe()},disabled:o!==void 0,children:[o==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const o=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(o,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-Bq2o0Bif.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-Bq2o0Bif.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-Bq2o0Bif.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-Dcpcvg15.js"),__vite__mapDeps([7,8,9,2,10,3,11,12,5]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-CPNXuD12.js"),__vite__mapDeps([13,2,9,8,10]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-UOxp_XVL.js"),__vite__mapDeps([14,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-BQdSCkk4.js"),__vite__mapDeps([15,1,16])));function lazyRoute$1(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}const statusContentRoutes=[{path:"overview",element:lazyRoute$1(jsxRuntimeExports.jsx(StatusPage,{}))},{path:"services/gateway",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"gateway",title:"Gateway"}))},{path:"services/solid-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"css",title:"Solid Server"}))},{path:"services/api-server",element:lazyRoute$1(jsxRuntimeExports.jsx(ServiceStatusPanel,{serviceId:"api",title:"API Server"}))},{path:"logs",element:lazyRoute$1(jsxRuntimeExports.jsx(LogsPage,{}))},{path:"index",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"overview"}))},{path:"index/rdf",element:lazyRoute$1(jsxRuntimeExports.jsx(RdfPage,{}))},{path:"index/fts",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"fts"}))},{path:"index/vector",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"vector"}))},{path:"index/retrieval-points",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"retrieval-points"}))},{path:"index/cache",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"cache"}))},{path:"index/slow-queries",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"slow-queries"}))},{path:"index/benchmark",element:lazyRoute$1(jsxRuntimeExports.jsx(IndexSubjectPanel,{kind:"benchmark"}))}];function statusWorkspaceRoute(n){return{element:lazyRoute$1(jsxRuntimeExports.jsx(StatusWorkspace,{})),children:n}}const dashboardRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),o=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),y=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(y)}catch{return}};let u=!1;const h=p=>{try{return o.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const y=o.readSinglePending();y&&o.cancel(y.id)}catch{}return o.begin(p)}},d=async(p,g)=>{const y=l(p),v={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...y===void 0?{}:{returnTo:y},...g===void 0?{}:{selectedStorage:g}},S=h(v);u=!0;try{await n.runtime.login(S)}catch(E){try{o.cancel(S.id)}catch{}throw E}finally{u=!1}return S};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=o.readSinglePending();p&&o.cancel(p.id)},readPending:()=>o.readSinglePending(),callbackUrl(p){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}const xpodIconUrl="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2064%2064'%20fill='none'%3e%3cpath%20d='M32%207%2051%2016.5v13.8c0%2012.4-7.4%2021.2-19%2027.7-11.6-6.5-19-15.3-19-27.7V16.5L32%207Z'%20stroke='%238A72BE'%20stroke-width='5'%20stroke-linecap='round'%20stroke-linejoin='round'%20/%3e%3c/svg%3e";function XpodLoginBrand({compact:n=!1,showSubtitle:e=!n,subtitle:t="使用 WebID 登录"}){const i=n&&e;return jsxRuntimeExports.jsxs("div",{"data-testid":"xpod-login-brand","data-presentation":n?"compact":"standard",className:i?"flex flex-col items-center justify-center gap-1 text-center":n?"flex items-center justify-center gap-2 text-center":"flex flex-col items-center gap-3 text-center",children:[jsxRuntimeExports.jsx("img",{src:xpodIconUrl,alt:"",className:n?i?"h-16 w-16":"h-7 w-7":"h-11 w-11"}),jsxRuntimeExports.jsxs("div",{className:i?"space-y-1 text-center":n?"text-left":"space-y-1",children:[jsxRuntimeExports.jsx("h1",{className:n?"text-base font-semibold leading-none text-foreground":"text-lg font-semibold text-foreground",children:"Xpod"}),e?jsxRuntimeExports.jsx("p",{className:"text-xs text-primary/80",children:t}):null]})]})}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),s=runtimeState(t.state),o=storageSelectionState(t,s),[l,u]=reactExports.useState(),[h,d]=reactExports.useState(!1),p=reactExports.useRef(0),g=reactExports.useRef(!1),y=reactExports.useRef(!1),v=_e=>{console.error("[WebIdAuthBoundary] authentication action failed",_e),u(actionFailureMessage)},S=_e=>{const j=++p.current;u(void 0),d(!0),_e().catch(ee=>{j===p.current&&v(ee)}).finally(()=>{j===p.current&&d(!1)})},E=()=>S(()=>i.startLogin()),x=()=>{s.status==="authenticated"?t.retryPodOpen?.():S(()=>i.retryLogin())},A=()=>{i.cancelLogin(),p.current+=1,d(!1),u(void 0)},I=()=>S(async()=>{await t.logout(),await i.startLogin()});if(reactExports.useEffect(()=>{t.state.status!=="loading"||g.current||(g.current=!0,t.session.initialize({restorePreviousSession:!0}).catch(v))},[t.session,t.state.status]),reactExports.useEffect(()=>{!e||y.current||s.status!=="anonymous"||(y.current=!0,E())},[e,s.status]),s.status==="authenticated"&&o?.status==="ready")return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const T="remembered"in s?s.remembered:void 0,F=s.status==="restoring",P=h||e&&s.status==="anonymous"&&!l,V=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let B,Y;return l?B=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:l,primaryLabel:"重试",onPrimary:x,secondaryLabel:"取消当前登录",onSecondary:A}):F?(Y=T?void 0:V,B=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:T?.displayName,avatarUrl:T?.avatarUrl,label:rememberedCopy.restoringLabel})):P?B=jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:A}):s.status==="authenticated"?B=o?.status==="conflict"||o?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:o.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:o.message,primaryLabel:"重试",onPrimary:x}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):T?B=jsxRuntimeExports.jsx(LoginAccountView,{name:T.displayName,avatarUrl:T.avatarUrl,bindingLabel:"Xpod",expired:s.status==="expired",expiredTitle:rememberedCopy.expiredTitle,enterLabel:s.status==="expired"?rememberedCopy.reauthenticateLabel(T.displayName):rememberedCopy.continueLabel(T.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:E,onReauthenticate:x,onSwitchAccount:I}):s.status==="error"||s.status==="expired"?B=jsxRuntimeExports.jsx(LoginFailureView,{title:s.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:s.status==="error"?s.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:x}):B=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:V,onStart:E}),jsxRuntimeExports.jsx(AuthSurface,{mode:"page",title:"登录 Xpod",presentation:"compact",host:"document",lead:Y,children:B})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin"}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-UZkZGqor.js"),__vite__mapDeps([17,18,10,4,11,19]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-WIE95S28.js"),__vite__mapDeps([20,8,21,18,10]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-P8QcVB0F.js").then(n=>n.M),__vite__mapDeps([22,21,18])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-KG8Sq999.js"),__vite__mapDeps([23,22,21,18])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-DdgJSJYQ.js"),__vite__mapDeps([24,22,21,18])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-iKvtHDXY.js"),__vite__mapDeps([25,22,21,18])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-B6ySeVPw.js"),__vite__mapDeps([26,6,1,8,10]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-I7zWmpiI.js"),__vite__mapDeps([27,1,18,12,16,3])).then(n=>({default:n.PodSettingsSubjectPanel})));function lazyRoute(n){return jsxRuntimeExports.jsx(RouteLoadingBoundary,{children:n})}function systemSettingsPage(n){return{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(SystemSettingsPage,{})),children:n}]}}const aiConnectionsSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{index:!0,element:lazyRoute(jsxRuntimeExports.jsx(ModelsPage,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:".",replace:!0})}]}],aiConfigSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodSettingsLayout,{}),children:[{element:lazyRoute(jsxRuntimeExports.jsx(AiConfigPage,{})),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})},{path:"model-assignments",element:lazyRoute(jsxRuntimeExports.jsx(ModelAssignmentsPanel,{}))},{path:"document-processing",element:lazyRoute(jsxRuntimeExports.jsx(DocumentProcessingPanel,{}))},{path:"search-indexing",element:lazyRoute(jsxRuntimeExports.jsx(SearchIndexingPanel,{}))},{path:"index-lifecycle",element:lazyRoute(jsxRuntimeExports.jsx(IndexLifecyclePanel,{}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"model-assignments",replace:!0})}]}]}],systemSettingsSurfaceRoutes=[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})},{element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:[systemSettingsPage([{path:"pod",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"pod"}))},{path:"identity-access",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"identity-access"}))}])]},systemSettingsPage([{path:"storage",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"storage"}))},{path:"runtime",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"runtime"}))},{path:"cloud",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"cloud"}))},{path:"advanced",element:lazyRoute(jsxRuntimeExports.jsx(PodSettingsSubjectPanel,{kind:"advanced"}))},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"pod",replace:!0})}])];function AccountCredentialsFrame({frame:n,children:e}){return n==="bare"?jsxRuntimeExports.jsx("div",{"data-account-credentials-frame":"bare",className:"w-full text-card-foreground",children:e}):jsxRuntimeExports.jsx(Card,{"data-account-credentials-frame":"card",className:"w-full border-border bg-card text-card-foreground",children:e})}function setCredentialValue(n,e,t,i,s){i({...n,[e]:t}),s?.(e,t)}function FieldError({id:n,message:e}){return e?jsxRuntimeExports.jsxs("p",{id:n,role:"alert","aria-live":"polite",className:"flex items-center gap-1.5 text-sm text-destructive",children:[jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-4 w-4 shrink-0"}),e]}):null}function FloatingCredentialField({id:n,label:e,error:t,children:i}){return jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{"data-floating-field":"true",className:"relative",children:[i,jsxRuntimeExports.jsx(Label,{htmlFor:n,className:"pointer-events-none absolute left-3 top-0 z-[1] -translate-y-1/2 bg-card px-1 text-xs leading-none text-muted-foreground transition-[color,font-size,top,transform] duration-150 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:text-sm peer-focus:top-0 peer-focus:-translate-y-1/2 peer-focus:text-xs peer-focus:text-ring peer-disabled:opacity-50 peer-aria-[invalid=true]:text-destructive",children:e})]}),jsxRuntimeExports.jsx(FieldError,{id:`${n}-error`,message:t})]})}function StackedCredentialField({id:n,label:e,error:t,children:i}){return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:n,children:e}),i,jsxRuntimeExports.jsx(FieldError,{id:`${n}-error`,message:t})]})}function CredentialField({id:n,label:e,error:t,floating:i,children:s}){const o=i?FloatingCredentialField:StackedCredentialField;return jsxRuntimeExports.jsx(o,{id:n,label:e,error:t,children:s})}function AccountCredentialsView({mode:n,values:e,onChange:t,onSubmit:i,onFieldChange:s,onModeChange:o,pending:l=!1,errors:u,usernameAvailability:h="idle",usernameSuggestions:d=[],copy:p,frame:g="card",showHeader:y=!0,presentation:v="standard"}){const[S,E]=reactExports.useState(!1),x=reactExports.useId(),A=reactExports.useId(),I=reactExports.useId(),T=reactExports.useId(),F=reactExports.useId(),P=n==="register",V=typeof h=="string"?h:h.status,B=P&&e.password.length>0&&e.confirmation!==void 0&&e.password!==e.confirmation,Y=B&&(S||e.confirmation!==void 0)?p.mismatchError:void 0,_e=P?p.registerAction:p.loginAction,j=v==="compact",ee=j?"peer h-11 rounded-xl px-3 pb-2 pt-4":void 0,me=Ce=>{if(Ce?.preventDefault(),!l){if(P&&B){E(!0);return}E(!1),i(e)}},te=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[y?jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{children:P?p.registerTitle:p.loginTitle}),jsxRuntimeExports.jsx(CardDescription,{children:p.productName})]}):null,jsxRuntimeExports.jsx(CardContent,{className:cn(g==="bare"?"p-0":y?void 0:"pt-6"),children:jsxRuntimeExports.jsxs("form",{onSubmit:me,className:j?"space-y-3":"space-y-4",children:[P?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(CredentialField,{floating:j,id:x,label:p.usernameLabel,error:u?.username,children:jsxRuntimeExports.jsx(Input,{id:x,name:"username",autoComplete:"username",placeholder:j?" ":p.usernamePlaceholder,title:p.usernamePlaceholder,value:e.username??"",disabled:l,"aria-invalid":u?.username?!0:void 0,"aria-describedby":u?.username?`${x}-error`:void 0,className:ee,onChange:Ce=>setCredentialValue(e,"username",Ce.currentTarget.value,t,s)})}),V==="checking"?jsxRuntimeExports.jsxs("p",{role:"status","aria-live":"polite",className:"text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"mr-1 inline h-3.5 w-3.5 animate-spin"}),p.usernameChecking]}):null,V==="available"?jsxRuntimeExports.jsxs("p",{"aria-live":"polite",className:"flex items-center gap-1 text-sm text-primary",children:[jsxRuntimeExports.jsx(CircleCheckBig,{"aria-hidden":"true",className:"h-4 w-4"}),p.usernameAvailable]}):null,V==="unavailable"&&!u?.username?jsxRuntimeExports.jsx("p",{"aria-live":"polite",className:"text-sm text-destructive",children:typeof h=="object"&&h.message?h.message:p.usernameUnavailable}):null,!j&&d.length>0?jsxRuntimeExports.jsxs("div",{className:"space-y-2","aria-label":p.suggestionsLabel,children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:p.suggestionsLabel}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(Ce=>jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",size:"sm",disabled:l,onClick:()=>setCredentialValue(e,"username",Ce,t,s),children:Ce},Ce))})]}):null]}):null,jsxRuntimeExports.jsx(CredentialField,{floating:j,id:A,label:p.emailLabel,error:u?.email,children:jsxRuntimeExports.jsx(Input,{id:A,name:"email",type:"email",autoComplete:"email",placeholder:j?" ":p.emailPlaceholder,title:p.emailPlaceholder,value:e.email??"",disabled:l,"aria-invalid":u?.email?!0:void 0,"aria-describedby":u?.email?`${A}-error`:void 0,className:ee,onChange:Ce=>setCredentialValue(e,"email",Ce.currentTarget.value,t,s)})}),jsxRuntimeExports.jsx(CredentialField,{floating:j,id:I,label:p.passwordLabel,error:u?.password,children:jsxRuntimeExports.jsx(Input,{id:I,name:"password",type:"password",autoComplete:P?"new-password":"current-password",placeholder:j?" ":p.passwordPlaceholder,title:p.passwordPlaceholder,value:e.password,disabled:l,"aria-invalid":u?.password?!0:void 0,"aria-describedby":u?.password?`${I}-error`:void 0,className:ee,onChange:Ce=>setCredentialValue(e,"password",Ce.currentTarget.value,t,s)})}),P?jsxRuntimeExports.jsx(CredentialField,{floating:j,id:T,label:p.confirmationLabel,error:Y??u?.confirmation,children:jsxRuntimeExports.jsx(Input,{id:T,name:"confirmation",type:"password",autoComplete:"new-password",placeholder:j?" ":p.confirmationPlaceholder,title:p.confirmationPlaceholder,value:e.confirmation??"",disabled:l,"aria-invalid":Y||u?.confirmation?!0:void 0,"aria-describedby":Y||u?.confirmation?`${T}-error`:void 0,className:ee,onChange:Ce=>{E(!1),setCredentialValue(e,"confirmation",Ce.currentTarget.value,t,s)}})}):null,jsxRuntimeExports.jsx(FieldError,{id:F,message:u?.form}),jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs(Button,{type:"submit",className:cn("w-full",j&&"h-10 rounded-xl"),disabled:l,children:[l?jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"mr-2 h-4 w-4 animate-spin"}):null,_e]}),o?jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:cn("w-full",j&&"h-9 rounded-lg text-xs"),disabled:l,onClick:()=>o(P?"login":"register"),children:P?p.switchToLogin:p.switchToRegister}):null]})]})})]});return jsxRuntimeExports.jsx(AccountCredentialsFrame,{frame:g,children:te})}function AccountCredentialsSurface({surface:n,surfaceTitle:e,presentation:t,host:i,lead:s,footer:o,onClose:l,closeLabel:u,closeOnEscape:h,surfaceClassName:d,contentClassName:p,...g}){return jsxRuntimeExports.jsx(AuthSurface,{mode:n,title:e,presentation:t,host:i,lead:s,onClose:l,closeLabel:u,closeOnEscape:h,className:d,children:jsxRuntimeExports.jsxs("div",{className:p??(t==="compact"?"flex h-full min-h-0 flex-1 flex-col justify-center px-5 pb-5 pt-4":"p-4"),children:[jsxRuntimeExports.jsx(AccountCredentialsView,{...g,frame:"bare",showHeader:!1,presentation:t}),o?jsxRuntimeExports.jsx("div",{className:t==="compact"?"mt-3 space-y-2":"mt-4 space-y-2",children:o}):null]})})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodRegistrationCopy={emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(n.loginUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const o=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(o||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}function getXpodAuthSurfaceHost(){return"document"}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,presentation:e="standard",host:t,lead:i,onAuthenticated:s,onClose:o,surfaceClassName:l,contentClassName:u,initialEmail:h}){const{controls:d,idpIndex:p,isAnonymous:g,refetchControls:y}=useAuth(),[v,S]=reactExports.useState({email:h!==void 0?h:readPendingXpodAccountEmail(void 0,p)??"",password:""}),[E,x]=reactExports.useState(),[A,I]=reactExports.useState(!1),T=reactExports.useRef(!1),F=async V=>{if(!T.current){T.current=!0,I(!0),x(void 0);try{const B=await resolveHostedAccountControlUrl(d?.password?.login,fetch,p)??"/.account/login/password/",Y=await loginAccountPassword({email:V.email?.trim()??"",password:V.password,loginUrl:B,remember:!0,fetchImpl:async(_e,j)=>{const ee=await fetch(_e,j);if(!ee.ok)throw new PasswordLoginStatusError(ee.status);return ee}});if(storeAccountSessionToken(Y.accountToken),rememberPendingXpodAccountEmail(V.email?.trim()??"",void 0,p),await y(),g?.()){clearAccountSessionToken(),x("登录失败,请重试。");return}await s?.()}catch(B){x(B instanceof PasswordLoginStatusError?safeXpodLoginMessage(B.status):safeXpodLoginMessage(500))}finally{T.current=!1,I(!1)}}},P=V=>{S(V),E&&x(void 0)};return jsxRuntimeExports.jsx(AccountCredentialsSurface,{surface:n,surfaceTitle:"登录 Xpod",presentation:e,host:t??(n==="modal"?getXpodAuthSurfaceHost():"document"),lead:i??(e==="compact"?jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}):void 0),copy:xpodAccountCredentialsCopy,surfaceClassName:l,contentClassName:u??(e==="compact"?"flex h-full min-h-0 flex-1 flex-col justify-center px-5 pb-5 pt-4":void 0),onClose:n==="modal"?o:void 0,closeLabel:n==="modal"&&o?"关闭登录":void 0,mode:"login",values:v,onChange:P,onSubmit:F,pending:A,errors:E?{form:E}:void 0})}function AccountAuthBoundary({children:n,accountState:e,retry:t}){const i=useAuth(),s=e??i.accountState,o=t??i.retry;return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setWindowMode?.(s.status==="authenticated"?"workspace":"auth")},[s.status]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setWindowMode?.("workspace")},[]),s.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):s.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):s.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):s.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:s.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{o()},children:"重试"})]})}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"modal",presentation:"compact",host:"document",lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0,subtitle:"使用 Xpod 账号登录 Dashboard"})})}function LoginSurface({children:n}){return jsxRuntimeExports.jsx(AuthSurface,{mode:"modal",title:"登录 Xpod",presentation:"compact",host:"document",lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0}),children:n})}const xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountAuthBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountAuthBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"/status/overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"/status/overview",replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodShellRoutes,{}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??"/status/overview")}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}initializeXpodTheme();clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodShellApp,{})})}));export{removeIri as $,getDefaultExportFromCjs as A,Button as B,Card as C,Database as D,createSlottable as E,getLinkedResourceUrlAll as F,Gauge as G,acp as H,internal_cloneResource as I,getSolidDataset as J,freeze as K,Link as L,getSourceUrl as M,NavLink as N,Outlet as O,Primitive as P,getResourceInfo as Q,RefreshCw as R,Sparkles as S,getSourceIri as T,getThingAll as U,getIriAll as V,rdf$3 as W,X,acl as Y,setThing as Z,setIri as _,CardHeader as a,removeAll as a0,createThing as a1,addIri as a2,removeThing as a3,subjectToRdfJsQuads as a4,DataFactory$1 as a5,getIri as a6,saveSolidDatasetAt as a7,createSolidDataset as a8,foaf as a9,getThing as aa,getUrlAll as ab,buildThing as ac,Avatar as ad,AvatarImage as ae,AvatarFallback as af,LoginFailureView as ag,LoginConnectingView as ah,Input as ai,Label as aj,Toaster as ak,credentialResource as al,aiProviderResource as am,aiModelResource as an,configureSparqlEngine as ao,createXpodLoginController as ap,requireBuffer as aq,requireLink as ar,getAugmentedNamespace as as,requireBrowser$2 as at,requireSparql as au,requireEvents as av,requireBrowser$3 as aw,requireString_decoder as ax,bufferExports as ay,commonjsGlobal as az,CardTitle as b,createLucideIcon as c,CardDescription as d,CardContent as e,cn as f,cva as g,aiConfigModelRef as h,interactiveFocusClass as i,jsxRuntimeExports as j,useLocation as k,handleListNavigationKeyDown as l,getListNavItemClass as m,Copy as n,useLayoutEffect2 as o,React4 as p,useComposedRefs as q,reactExports as r,useCallbackRef as s,toast as t,useXpodSolidRuntime as u,dispatchDiscreteCustomEvent as v,reactDomExports as w,createContextScope as x,clsx as y,createSlot as z};
|