@undefineds.co/xpod 0.4.7 → 0.4.9

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.
Files changed (90) hide show
  1. package/node_modules/@undefineds.co/solid-sdk/dist/index.cjs +178 -194
  2. package/node_modules/@undefineds.co/solid-sdk/dist/pod-runtime.js +6 -13
  3. package/node_modules/@undefineds.co/solid-sdk/dist/storage-selection.js +6 -21
  4. package/node_modules/@undefineds.co/solid-sdk/dist/webid-auth.d.ts +2 -0
  5. package/node_modules/@undefineds.co/solid-sdk/dist/webid-auth.js +8 -3
  6. package/package.json +14 -2
  7. package/static/app/assets/main.js +10 -10
  8. package/static/auth-callback/assets/{AiConfigContext-CRxnTyNS.js → AiConfigContext-DJKvxduw.js} +1 -1
  9. package/static/auth-callback/assets/{AiConfigPage-aidVtDAU.js → AiConfigPage-DgGmHb18.js} +1 -1
  10. package/static/auth-callback/assets/{DocumentProcessingPanel-C-lnRpEy.js → DocumentProcessingPanel-CJmxu8x1.js} +1 -1
  11. package/static/auth-callback/assets/{IndexLifecyclePanel-8oscxWj2.js → IndexLifecyclePanel-byCa7h7L.js} +1 -1
  12. package/static/auth-callback/assets/{IndexSubjectPanel-ybKkidfS.js → IndexSubjectPanel-CDwT4Yx1.js} +1 -1
  13. package/static/auth-callback/assets/{ModelAssignmentsPanel-DmxLA1Da.js → ModelAssignmentsPanel-CwM3k8w7.js} +1 -1
  14. package/static/auth-callback/assets/{ModelsPage-B-G4YfTv.js → ModelsPage-DapY2Dwf.js} +1 -1
  15. package/static/auth-callback/assets/{NetworkPage-W890Vczu.js → NetworkPage-DkVgxtNj.js} +1 -1
  16. package/static/auth-callback/assets/{PaneListHeader-Aj8ayvMU.js → PaneListHeader-DRI0hjmt.js} +1 -1
  17. package/static/auth-callback/assets/{SearchIndexingPanel-DTyOKrU1.js → SearchIndexingPanel-mbppDZFE.js} +1 -1
  18. package/static/auth-callback/assets/{StatusSubjectPanel-DT1Aw7YO.js → StatusSubjectPanel-DNsW76aC.js} +1 -1
  19. package/static/auth-callback/assets/{StatusWorkspace-BO7YcO6a.js → StatusWorkspace-DGcTbHT5.js} +1 -1
  20. package/static/auth-callback/assets/{SystemSettingsPage-DfU_qHHq.js → SystemSettingsPage-C6qklJ9k.js} +1 -1
  21. package/static/auth-callback/assets/{SystemSettingsSubjectPanel-nfcG67Tx.js → SystemSettingsSubjectPanel-B4VV9xkG.js} +1 -1
  22. package/static/auth-callback/assets/{activity-CPUh0Hwy.js → activity-Ck-Mfxxo.js} +1 -1
  23. package/static/auth-callback/assets/{auth-callback-rq-93B6I.js → auth-callback-DG4Ge40c.js} +6 -6
  24. package/static/auth-callback/assets/{badge-C8cHw8zP.js → badge-GSSnw1VV.js} +1 -1
  25. package/static/auth-callback/assets/{download-C7i9MWS2.js → download-BYyRX-K2.js} +1 -1
  26. package/static/auth-callback/assets/{external-link-BrwSigZD.js → external-link-WEC0Ki-0.js} +1 -1
  27. package/static/auth-callback/assets/{index-DSY0DCJV.js → index-DlsMCgo8.js} +1 -1
  28. package/static/auth-callback/assets/{index-browser-CMOmp0rf.js → index-browser-D8YW6coF.js} +1 -1
  29. package/static/auth-callback/assets/{index-Drnlv8Gw.js → index-kju2k4Dp.js} +1 -1
  30. package/static/auth-callback/assets/{key-round-DO8fiDNf.js → key-round-DJUT5Nh0.js} +1 -1
  31. package/static/auth-callback/assets/{rotate-ccw-DAOErQ0P.js → rotate-ccw-CXwfZUKU.js} +1 -1
  32. package/static/auth-callback/assets/{skeleton-poTd6JSC.js → skeleton-DWPtNhUB.js} +1 -1
  33. package/static/auth-callback/assets/{waypoints-Bg9TQvJS.js → waypoints-l1oDnRJ0.js} +1 -1
  34. package/static/auth-callback/assets/{workspace-layout-Dmb-DfHy.js → workspace-layout-B7iKpK-Q.js} +1 -1
  35. package/static/auth-callback/auth-callback.html +1 -1
  36. package/static/dashboard/assets/{AiConfigContext-Ds7MIAm6.js → AiConfigContext-U0cCSY28.js} +1 -1
  37. package/static/dashboard/assets/{AiConfigPage-CRrI_NnS.js → AiConfigPage-CMi0uJdo.js} +1 -1
  38. package/static/dashboard/assets/{DocumentProcessingPanel-BVFIT_Zl.js → DocumentProcessingPanel-DEZiEpft.js} +1 -1
  39. package/static/dashboard/assets/{IndexLifecyclePanel-BSzivp60.js → IndexLifecyclePanel-CGZfLUog.js} +1 -1
  40. package/static/dashboard/assets/{IndexSubjectPanel-B5zQeqWl.js → IndexSubjectPanel-DiDZauHk.js} +1 -1
  41. package/static/dashboard/assets/{ModelAssignmentsPanel-B-1FWxn0.js → ModelAssignmentsPanel-DaGGZKuf.js} +1 -1
  42. package/static/dashboard/assets/{ModelsPage-B3VYhX9h.js → ModelsPage-DZgAOdxO.js} +1 -1
  43. package/static/dashboard/assets/{NetworkPage-HJqcYjfO.js → NetworkPage-DI5-O7GT.js} +1 -1
  44. package/static/dashboard/assets/{PaneListHeader-DiFB-pBl.js → PaneListHeader-4oa7uf59.js} +1 -1
  45. package/static/dashboard/assets/{SearchIndexingPanel-BnA0kOD9.js → SearchIndexingPanel-DoqEwocD.js} +1 -1
  46. package/static/dashboard/assets/{StatusSubjectPanel-tAB7Scqn.js → StatusSubjectPanel-CLzBC5fu.js} +1 -1
  47. package/static/dashboard/assets/{StatusWorkspace-kNMe8nOB.js → StatusWorkspace-UyKADZoM.js} +1 -1
  48. package/static/dashboard/assets/{SystemSettingsPage-8U1VrI_f.js → SystemSettingsPage-qP0hLHNV.js} +1 -1
  49. package/static/dashboard/assets/{SystemSettingsSubjectPanel-goh78mjo.js → SystemSettingsSubjectPanel-EaWax9Ot.js} +1 -1
  50. package/static/dashboard/assets/{activity-DNXbcx1t.js → activity-CjIoNU4S.js} +1 -1
  51. package/static/dashboard/assets/{badge-DR3YwIcl.js → badge-dcDZpKh3.js} +1 -1
  52. package/static/dashboard/assets/{dashboard-C64rEkaL.js → dashboard-BY8GdnEI.js} +5 -5
  53. package/static/dashboard/assets/{download-BwyvySqB.js → download-BeYCrc-_.js} +1 -1
  54. package/static/dashboard/assets/{external-link-Dmez6yTy.js → external-link-626-5KVx.js} +1 -1
  55. package/static/dashboard/assets/{index-N1onOEV6.js → index-CBbk6hx-.js} +1 -1
  56. package/static/dashboard/assets/{index-BAkEY7c3.js → index-CsxH6Hmz.js} +1 -1
  57. package/static/dashboard/assets/{key-round-BM6zS_FJ.js → key-round-B9IL4Wua.js} +1 -1
  58. package/static/dashboard/assets/{rotate-ccw-D6BDXyhE.js → rotate-ccw-DM4vCfiI.js} +1 -1
  59. package/static/dashboard/assets/{skeleton-Dy9nFkSL.js → skeleton-ChlFAPvP.js} +1 -1
  60. package/static/dashboard/assets/{waypoints-GzW4F2Ei.js → waypoints-CvpZzf_I.js} +1 -1
  61. package/static/dashboard/assets/{workspace-layout-D6jwN-1q.js → workspace-layout-Bxv7V-tt.js} +1 -1
  62. package/static/dashboard/dashboard.html +1 -1
  63. package/static/settings/assets/{AiConfigContext-CwPOEIt2.js → AiConfigContext-CDVIHLBb.js} +1 -1
  64. package/static/settings/assets/{AiConfigPage-BSUTkt12.js → AiConfigPage-C7qfiiaJ.js} +1 -1
  65. package/static/settings/assets/{DocumentProcessingPanel-Bsrmh_jc.js → DocumentProcessingPanel-B59QTe-V.js} +1 -1
  66. package/static/settings/assets/{IndexLifecyclePanel-CqG9oal4.js → IndexLifecyclePanel-C-e-3eVi.js} +1 -1
  67. package/static/settings/assets/{IndexSubjectPanel-C81n07Gj.js → IndexSubjectPanel-B-scRZ1u.js} +1 -1
  68. package/static/settings/assets/{ModelAssignmentsPanel-CwUbqhcc.js → ModelAssignmentsPanel-Wy8jzVg4.js} +1 -1
  69. package/static/settings/assets/{ModelsPage-BMs6BLrm.js → ModelsPage-DHNiaodk.js} +1 -1
  70. package/static/settings/assets/{NetworkPage-DtjeHtL4.js → NetworkPage-tBB-4Ox8.js} +1 -1
  71. package/static/settings/assets/{PaneListHeader-CO0oaVu8.js → PaneListHeader-DuD6glzn.js} +1 -1
  72. package/static/settings/assets/{SearchIndexingPanel-BgQfRVsf.js → SearchIndexingPanel-CiDHc0nx.js} +1 -1
  73. package/static/settings/assets/{StatusSubjectPanel-DJn3ZOvK.js → StatusSubjectPanel-OF5cgWwt.js} +1 -1
  74. package/static/settings/assets/{StatusWorkspace-C_CSF842.js → StatusWorkspace-CZ8Oa0gV.js} +1 -1
  75. package/static/settings/assets/{SystemSettingsPage-Oigv0uvH.js → SystemSettingsPage-DT2tC0F_.js} +1 -1
  76. package/static/settings/assets/{SystemSettingsSubjectPanel-Bc8qCKlD.js → SystemSettingsSubjectPanel-Bkta1oDw.js} +1 -1
  77. package/static/settings/assets/{activity-D0ZeHnaN.js → activity-2M1f5eBS.js} +1 -1
  78. package/static/settings/assets/{badge-qUNztkFM.js → badge-CRKan0qX.js} +1 -1
  79. package/static/settings/assets/{download-Cqf-BduE.js → download-PCHldCdu.js} +1 -1
  80. package/static/settings/assets/{external-link-IuWJ6OjY.js → external-link-tmKe7eYO.js} +1 -1
  81. package/static/settings/assets/{index-D3o0Tuj2.js → index-BDCNTwWz.js} +1 -1
  82. package/static/settings/assets/{index-DRjSKNcs.js → index-Cek02M79.js} +1 -1
  83. package/static/settings/assets/{index-browser-D9qFZqYE.js → index-browser-EVDVm9T5.js} +1 -1
  84. package/static/settings/assets/{key-round-KxL3N2jU.js → key-round-CUGvQCkt.js} +1 -1
  85. package/static/settings/assets/{rotate-ccw-BiW1Onno.js → rotate-ccw-BRA3lIHM.js} +1 -1
  86. package/static/settings/assets/{settings-DH2ML86C.js → settings-BdlKrzJ3.js} +6 -6
  87. package/static/settings/assets/{skeleton-CsUPnZPX.js → skeleton-CuDeifWb.js} +1 -1
  88. package/static/settings/assets/{waypoints-xuODoy-1.js → waypoints-w6LxsFY1.js} +1 -1
  89. package/static/settings/assets/{workspace-layout-O7swKpQ6.js → workspace-layout-TN-BWmT5.js} +1 -1
  90. 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-Drnlv8Gw.js","assets/admin-BU4m6Ko2.js","assets/activity-CPUh0Hwy.js","assets/external-link-BrwSigZD.js","assets/index-DSY0DCJV.js","assets/download-C7i9MWS2.js","assets/key-round-DO8fiDNf.js","assets/NetworkPage-W890Vczu.js","assets/PaneListHeader-Aj8ayvMU.js","assets/waypoints-Bg9TQvJS.js","assets/workspace-layout-Dmb-DfHy.js","assets/badge-C8cHw8zP.js","assets/rotate-ccw-DAOErQ0P.js","assets/StatusWorkspace-BO7YcO6a.js","assets/StatusSubjectPanel-DT1Aw7YO.js","assets/IndexSubjectPanel-ybKkidfS.js","assets/skeleton-poTd6JSC.js","assets/ModelsPage-B-G4YfTv.js","assets/ai-connections-CHNTKemd.js","assets/index-browser-CMOmp0rf.js","assets/AiConfigPage-aidVtDAU.js","assets/AiConfigContext-CRxnTyNS.js","assets/ModelAssignmentsPanel-DmxLA1Da.js","assets/DocumentProcessingPanel-C-lnRpEy.js","assets/SearchIndexingPanel-DTyOKrU1.js","assets/IndexLifecyclePanel-8oscxWj2.js","assets/SystemSettingsPage-DfU_qHHq.js","assets/SystemSettingsSubjectPanel-nfcG67Tx.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-kju2k4Dp.js","assets/admin-BU4m6Ko2.js","assets/activity-Ck-Mfxxo.js","assets/external-link-WEC0Ki-0.js","assets/index-DlsMCgo8.js","assets/download-BYyRX-K2.js","assets/key-round-DJUT5Nh0.js","assets/NetworkPage-DkVgxtNj.js","assets/PaneListHeader-DRI0hjmt.js","assets/waypoints-l1oDnRJ0.js","assets/workspace-layout-B7iKpK-Q.js","assets/badge-GSSnw1VV.js","assets/rotate-ccw-CXwfZUKU.js","assets/StatusWorkspace-DGcTbHT5.js","assets/StatusSubjectPanel-DNsW76aC.js","assets/IndexSubjectPanel-CDwT4Yx1.js","assets/skeleton-DWPtNhUB.js","assets/ModelsPage-DapY2Dwf.js","assets/ai-connections-CHNTKemd.js","assets/index-browser-D8YW6coF.js","assets/AiConfigPage-DgGmHb18.js","assets/AiConfigContext-DJKvxduw.js","assets/ModelAssignmentsPanel-CwM3k8w7.js","assets/DocumentProcessingPanel-CJmxu8x1.js","assets/SearchIndexingPanel-mbppDZFE.js","assets/IndexLifecyclePanel-byCa7h7L.js","assets/SystemSettingsPage-C6qklJ9k.js","assets/SystemSettingsSubjectPanel-B4VV9xkG.js"])))=>i.map(i=>d[i]);
2
2
  function _mergeNamespaces(n,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in n)){const a=Object.getOwnPropertyDescriptor(i,s);a&&Object.defineProperty(n,s,a.get?a:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function t(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(s){if(s.ep)return;s.ep=!0;const a=t(s);fetch(s.href,a)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var e=n.default;if(typeof e=="function"){var t=function i(){var s=!1;try{s=this instanceof i}catch{}return s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var s=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return n[i]}})}),t}var jsxRuntime={exports:{}},reactJsxRuntime_production={};var hasRequiredReactJsxRuntime_production;function requireReactJsxRuntime_production(){if(hasRequiredReactJsxRuntime_production)return reactJsxRuntime_production;hasRequiredReactJsxRuntime_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,s,a){var l=null;if(a!==void 0&&(l=""+a),s.key!==void 0&&(l=""+s.key),"key"in s){a={};for(var u in s)u!=="key"&&(a[u]=s[u])}else a=s;return s=a.ref,{$$typeof:n,type:i,key:l,ref:s!==void 0?s:null,props:a}}return reactJsxRuntime_production.Fragment=e,reactJsxRuntime_production.jsx=t,reactJsxRuntime_production.jsxs=t,reactJsxRuntime_production}var hasRequiredJsxRuntime;function requireJsxRuntime(){return hasRequiredJsxRuntime||(hasRequiredJsxRuntime=1,jsxRuntime.exports=requireReactJsxRuntime_production()),jsxRuntime.exports}var jsxRuntimeExports=requireJsxRuntime(),client={exports:{}},reactDomClient_production={},scheduler={exports:{}},scheduler_production={};var hasRequiredScheduler_production;function requireScheduler_production(){return hasRequiredScheduler_production||(hasRequiredScheduler_production=1,(function(n){function e(de,Oe){var le=de.length;de.push(Oe);e:for(;0<le;){var Ae=le-1>>>1,$=de[Ae];if(0<s($,Oe))de[Ae]=Oe,de[le]=$,le=Ae;else break e}}function t(de){return de.length===0?null:de[0]}function i(de){if(de.length===0)return null;var Oe=de[0],le=de.pop();if(le!==Oe){de[0]=le;e:for(var Ae=0,$=de.length,H=$>>>1;Ae<H;){var fe=2*(Ae+1)-1,ae=de[fe],Pe=fe+1,Me=de[Pe];if(0>s(ae,le))Pe<$&&0>s(Me,ae)?(de[Ae]=Me,de[Pe]=le,Ae=Pe):(de[Ae]=ae,de[fe]=le,Ae=fe);else if(Pe<$&&0>s(Me,le))de[Ae]=Me,de[Pe]=le,Ae=Pe;else break e}}return Oe}function s(de,Oe){var le=de.sortIndex-Oe.sortIndex;return le!==0?le:de.id-Oe.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var a=performance;n.unstable_now=function(){return a.now()}}else{var l=Date,u=l.now();n.unstable_now=function(){return l.now()-u}}var f=[],d=[],p=1,g=null,m=3,v=!1,S=!1,E=!1,w=!1,A=typeof setTimeout=="function"?setTimeout:null,C=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function F(de){for(var Oe=t(d);Oe!==null;){if(Oe.callback===null)i(d);else if(Oe.startTime<=de)i(d),Oe.sortIndex=Oe.expirationTime,e(f,Oe);else break;Oe=t(d)}}function P(de){if(E=!1,F(de),!S)if(t(f)!==null)S=!0,M||(M=!0,_e());else{var Oe=t(d);Oe!==null&&De(P,Oe.startTime-de)}}var M=!1,O=-1,Q=5,pe=-1;function q(){return w?!0:!(n.unstable_now()-pe<Q)}function ee(){if(w=!1,M){var de=n.unstable_now();pe=de;var Oe=!0;try{e:{S=!1,E&&(E=!1,C(O),O=-1),v=!0;var le=m;try{t:{for(F(de),g=t(f);g!==null&&!(g.expirationTime>de&&q());){var Ae=g.callback;if(typeof Ae=="function"){g.callback=null,m=g.priorityLevel;var $=Ae(g.expirationTime<=de);if(de=n.unstable_now(),typeof $=="function"){g.callback=$,F(de),Oe=!0;break t}g===t(f)&&i(f),F(de)}else i(f);g=t(f)}if(g!==null)Oe=!0;else{var H=t(d);H!==null&&De(P,H.startTime-de),Oe=!1}}break e}finally{g=null,m=le,v=!1}Oe=void 0}}finally{Oe?_e():M=!1}}}var _e;if(typeof T=="function")_e=function(){T(ee)};else if(typeof MessageChannel<"u"){var te=new MessageChannel,Ie=te.port2;te.port1.onmessage=ee,_e=function(){Ie.postMessage(null)}}else _e=function(){A(ee,0)};function De(de,Oe){O=A(function(){de(n.unstable_now())},Oe)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(de){de.callback=null},n.unstable_forceFrameRate=function(de){0>de||125<de?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Q=0<de?Math.floor(1e3/de):5},n.unstable_getCurrentPriorityLevel=function(){return m},n.unstable_next=function(de){switch(m){case 1:case 2:case 3:var Oe=3;break;default:Oe=m}var le=m;m=Oe;try{return de()}finally{m=le}},n.unstable_requestPaint=function(){w=!0},n.unstable_runWithPriority=function(de,Oe){switch(de){case 1:case 2:case 3:case 4:case 5:break;default:de=3}var le=m;m=de;try{return Oe()}finally{m=le}},n.unstable_scheduleCallback=function(de,Oe,le){var Ae=n.unstable_now();switch(typeof le=="object"&&le!==null?(le=le.delay,le=typeof le=="number"&&0<le?Ae+le:Ae):le=Ae,de){case 1:var $=-1;break;case 2:$=250;break;case 5:$=1073741823;break;case 4:$=1e4;break;default:$=5e3}return $=le+$,de={id:p++,callback:Oe,priorityLevel:de,startTime:le,expirationTime:$,sortIndex:-1},le>Ae?(de.sortIndex=le,e(d,de),t(f)===null&&de===t(d)&&(E?(C(O),O=-1):E=!0,De(P,le-Ae))):(de.sortIndex=$,e(f,de),S||v||(S=!0,M||(M=!0,_e()))),de},n.unstable_shouldYield=q,n.unstable_wrapCallback=function(de){var Oe=m;return function(){var le=m;m=Oe;try{return de.apply(this,arguments)}finally{m=le}}}})(scheduler_production)),scheduler_production}var hasRequiredScheduler;function requireScheduler(){return hasRequiredScheduler||(hasRequiredScheduler=1,scheduler.exports=requireScheduler_production()),scheduler.exports}var react={exports:{}},react_production={};var hasRequiredReact_production;function requireReact_production(){if(hasRequiredReact_production)return react_production;hasRequiredReact_production=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),m=Symbol.iterator;function v(H){return H===null||typeof H!="object"?null:(H=m&&H[m]||H["@@iterator"],typeof H=="function"?H:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,w={};function A(H,fe,ae){this.props=H,this.context=fe,this.refs=w,this.updater=ae||S}A.prototype.isReactComponent={},A.prototype.setState=function(H,fe){if(typeof H!="object"&&typeof H!="function"&&H!=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,H,fe,"setState")},A.prototype.forceUpdate=function(H){this.updater.enqueueForceUpdate(this,H,"forceUpdate")};function C(){}C.prototype=A.prototype;function T(H,fe,ae){this.props=H,this.context=fe,this.refs=w,this.updater=ae||S}var F=T.prototype=new C;F.constructor=T,E(F,A.prototype),F.isPureReactComponent=!0;var P=Array.isArray;function M(){}var O={H:null,A:null,T:null,S:null},Q=Object.prototype.hasOwnProperty;function pe(H,fe,ae){var Pe=ae.ref;return{$$typeof:n,type:H,key:fe,ref:Pe!==void 0?Pe:null,props:ae}}function q(H,fe){return pe(H.type,fe,H.props)}function ee(H){return typeof H=="object"&&H!==null&&H.$$typeof===n}function _e(H){var fe={"=":"=0",":":"=2"};return"$"+H.replace(/[=:]/g,function(ae){return fe[ae]})}var te=/\/+/g;function Ie(H,fe){return typeof H=="object"&&H!==null&&H.key!=null?_e(""+H.key):fe.toString(36)}function De(H){switch(H.status){case"fulfilled":return H.value;case"rejected":throw H.reason;default:switch(typeof H.status=="string"?H.then(M,M):(H.status="pending",H.then(function(fe){H.status==="pending"&&(H.status="fulfilled",H.value=fe)},function(fe){H.status==="pending"&&(H.status="rejected",H.reason=fe)})),H.status){case"fulfilled":return H.value;case"rejected":throw H.reason}}throw H}function de(H,fe,ae,Pe,Me){var Xe=typeof H;(Xe==="undefined"||Xe==="boolean")&&(H=null);var We=!1;if(H===null)We=!0;else switch(Xe){case"bigint":case"string":case"number":We=!0;break;case"object":switch(H.$$typeof){case n:case e:We=!0;break;case p:return We=H._init,de(We(H._payload),fe,ae,Pe,Me)}}if(We)return Me=Me(H),We=Pe===""?"."+Ie(H,0):Pe,P(Me)?(ae="",We!=null&&(ae=We.replace(te,"$&/")+"/"),de(Me,fe,ae,"",function(Be){return Be})):Me!=null&&(ee(Me)&&(Me=q(Me,ae+(Me.key==null||H&&H.key===Me.key?"":(""+Me.key).replace(te,"$&/")+"/")+We)),fe.push(Me)),1;We=0;var ye=Pe===""?".":Pe+":";if(P(H))for(var me=0;me<H.length;me++)Pe=H[me],Xe=ye+Ie(Pe,me),We+=de(Pe,fe,ae,Xe,Me);else if(me=v(H),typeof me=="function")for(H=me.call(H),me=0;!(Pe=H.next()).done;)Pe=Pe.value,Xe=ye+Ie(Pe,me++),We+=de(Pe,fe,ae,Xe,Me);else if(Xe==="object"){if(typeof H.then=="function")return de(De(H),fe,ae,Pe,Me);throw fe=String(H),Error("Objects are not valid as a React child (found: "+(fe==="[object Object]"?"object with keys {"+Object.keys(H).join(", ")+"}":fe)+"). If you meant to render a collection of children, use an array instead.")}return We}function Oe(H,fe,ae){if(H==null)return H;var Pe=[],Me=0;return de(H,Pe,"","",function(Xe){return fe.call(ae,Xe,Me++)}),Pe}function le(H){if(H._status===-1){var fe=H._result;fe=fe(),fe.then(function(ae){(H._status===0||H._status===-1)&&(H._status=1,H._result=ae)},function(ae){(H._status===0||H._status===-1)&&(H._status=2,H._result=ae)}),H._status===-1&&(H._status=0,H._result=fe)}if(H._status===1)return H._result.default;throw H._result}var Ae=typeof reportError=="function"?reportError:function(H){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var fe=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof H=="object"&&H!==null&&typeof H.message=="string"?String(H.message):String(H),error:H});if(!window.dispatchEvent(fe))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",H);return}console.error(H)},$={map:Oe,forEach:function(H,fe,ae){Oe(H,function(){fe.apply(this,arguments)},ae)},count:function(H){var fe=0;return Oe(H,function(){fe++}),fe},toArray:function(H){return Oe(H,function(fe){return fe})||[]},only:function(H){if(!ee(H))throw Error("React.Children.only expected to receive a single React element child.");return H}};return react_production.Activity=g,react_production.Children=$,react_production.Component=A,react_production.Fragment=t,react_production.Profiler=s,react_production.PureComponent=T,react_production.StrictMode=i,react_production.Suspense=f,react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=O,react_production.__COMPILER_RUNTIME={__proto__:null,c:function(H){return O.H.useMemoCache(H)}},react_production.cache=function(H){return function(){return H.apply(null,arguments)}},react_production.cacheSignal=function(){return null},react_production.cloneElement=function(H,fe,ae){if(H==null)throw Error("The argument must be a React element, but you passed "+H+".");var Pe=E({},H.props),Me=H.key;if(fe!=null)for(Xe in fe.key!==void 0&&(Me=""+fe.key),fe)!Q.call(fe,Xe)||Xe==="key"||Xe==="__self"||Xe==="__source"||Xe==="ref"&&fe.ref===void 0||(Pe[Xe]=fe[Xe]);var Xe=arguments.length-2;if(Xe===1)Pe.children=ae;else if(1<Xe){for(var We=Array(Xe),ye=0;ye<Xe;ye++)We[ye]=arguments[ye+2];Pe.children=We}return pe(H.type,Me,Pe)},react_production.createContext=function(H){return H={$$typeof:l,_currentValue:H,_currentValue2:H,_threadCount:0,Provider:null,Consumer:null},H.Provider=H,H.Consumer={$$typeof:a,_context:H},H},react_production.createElement=function(H,fe,ae){var Pe,Me={},Xe=null;if(fe!=null)for(Pe in fe.key!==void 0&&(Xe=""+fe.key),fe)Q.call(fe,Pe)&&Pe!=="key"&&Pe!=="__self"&&Pe!=="__source"&&(Me[Pe]=fe[Pe]);var We=arguments.length-2;if(We===1)Me.children=ae;else if(1<We){for(var ye=Array(We),me=0;me<We;me++)ye[me]=arguments[me+2];Me.children=ye}if(H&&H.defaultProps)for(Pe in We=H.defaultProps,We)Me[Pe]===void 0&&(Me[Pe]=We[Pe]);return pe(H,Xe,Me)},react_production.createRef=function(){return{current:null}},react_production.forwardRef=function(H){return{$$typeof:u,render:H}},react_production.isValidElement=ee,react_production.lazy=function(H){return{$$typeof:p,_payload:{_status:-1,_result:H},_init:le}},react_production.memo=function(H,fe){return{$$typeof:d,type:H,compare:fe===void 0?null:fe}},react_production.startTransition=function(H){var fe=O.T,ae={};O.T=ae;try{var Pe=H(),Me=O.S;Me!==null&&Me(ae,Pe),typeof Pe=="object"&&Pe!==null&&typeof Pe.then=="function"&&Pe.then(M,Ae)}catch(Xe){Ae(Xe)}finally{fe!==null&&ae.types!==null&&(fe.types=ae.types),O.T=fe}},react_production.unstable_useCacheRefresh=function(){return O.H.useCacheRefresh()},react_production.use=function(H){return O.H.use(H)},react_production.useActionState=function(H,fe,ae){return O.H.useActionState(H,fe,ae)},react_production.useCallback=function(H,fe){return O.H.useCallback(H,fe)},react_production.useContext=function(H){return O.H.useContext(H)},react_production.useDebugValue=function(){},react_production.useDeferredValue=function(H,fe){return O.H.useDeferredValue(H,fe)},react_production.useEffect=function(H,fe){return O.H.useEffect(H,fe)},react_production.useEffectEvent=function(H){return O.H.useEffectEvent(H)},react_production.useId=function(){return O.H.useId()},react_production.useImperativeHandle=function(H,fe,ae){return O.H.useImperativeHandle(H,fe,ae)},react_production.useInsertionEffect=function(H,fe){return O.H.useInsertionEffect(H,fe)},react_production.useLayoutEffect=function(H,fe){return O.H.useLayoutEffect(H,fe)},react_production.useMemo=function(H,fe){return O.H.useMemo(H,fe)},react_production.useOptimistic=function(H,fe){return O.H.useOptimistic(H,fe)},react_production.useReducer=function(H,fe,ae){return O.H.useReducer(H,fe,ae)},react_production.useRef=function(H){return O.H.useRef(H)},react_production.useState=function(H){return O.H.useState(H)},react_production.useSyncExternalStore=function(H,fe,ae){return O.H.useSyncExternalStore(H,fe,ae)},react_production.useTransition=function(){return O.H.useTransition()},react_production.version="19.2.8",react_production}var hasRequiredReact;function requireReact(){return hasRequiredReact||(hasRequiredReact=1,react.exports=requireReact_production()),react.exports}var reactDom={exports:{}},reactDom_production={};var hasRequiredReactDom_production;function requireReactDom_production(){if(hasRequiredReactDom_production)return reactDom_production;hasRequiredReactDom_production=1;var n=requireReact();function e(f){var d="https://react.dev/errors/"+f;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 #"+f+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function t(){}var i={d:{f:t,r:function(){throw Error(e(522))},D:t,C:t,L:t,m:t,X:t,S:t,M:t},p:0,findDOMNode:null},s=Symbol.for("react.portal");function a(f,d,p){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:g==null?null:""+g,children:f,containerInfo:d,implementation:p}}var l=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function u(f,d){if(f==="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(f,d){var p=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return a(f,d,null,p)},reactDom_production.flushSync=function(f){var d=l.T,p=i.p;try{if(l.T=null,i.p=2,f)return f()}finally{l.T=d,i.p=p,i.d.f()}},reactDom_production.preconnect=function(f,d){typeof f=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,i.d.C(f,d))},reactDom_production.prefetchDNS=function(f){typeof f=="string"&&i.d.D(f)},reactDom_production.preinit=function(f,d){if(typeof f=="string"&&d&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin),m=typeof d.integrity=="string"?d.integrity:void 0,v=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;p==="style"?i.d.S(f,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:g,integrity:m,fetchPriority:v}):p==="script"&&i.d.X(f,{crossOrigin:g,integrity:m,fetchPriority:v,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},reactDom_production.preinitModule=function(f,d){if(typeof f=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var p=u(d.as,d.crossOrigin);i.d.M(f,{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(f)},reactDom_production.preload=function(f,d){if(typeof f=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var p=d.as,g=u(p,d.crossOrigin);i.d.L(f,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(f,d){if(typeof f=="string")if(d){var p=u(d.as,d.crossOrigin);i.d.m(f,{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(f)},reactDom_production.requestFormReset=function(f){i.d.r(f)},reactDom_production.unstable_batchedUpdates=function(f,d){return f(d)},reactDom_production.useFormState=function(f,d,p){return l.H.useFormState(f,d,p)},reactDom_production.useFormStatus=function(){return l.H.useHostTransitionStatus()},reactDom_production.version="19.2.8",reactDom_production}var hasRequiredReactDom;function requireReactDom(){if(hasRequiredReactDom)return reactDom.exports;hasRequiredReactDom=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),reactDom.exports=requireReactDom_production(),reactDom.exports}var hasRequiredReactDomClient_production;function requireReactDomClient_production(){if(hasRequiredReactDomClient_production)return reactDomClient_production;hasRequiredReactDomClient_production=1;var n=requireScheduler(),e=requireReact(),t=requireReactDom();function i(o){var c="https://react.dev/errors/"+o;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var h=2;h<arguments.length;h++)c+="&args[]="+encodeURIComponent(arguments[h])}return"Minified React error #"+o+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(o){return!(!o||o.nodeType!==1&&o.nodeType!==9&&o.nodeType!==11)}function a(o){var c=o,h=o;if(o.alternate)for(;c.return;)c=c.return;else{o=c;do c=o,(c.flags&4098)!==0&&(h=c.return),o=c.return;while(o)}return c.tag===3?h:null}function l(o){if(o.tag===13){var c=o.memoizedState;if(c===null&&(o=o.alternate,o!==null&&(c=o.memoizedState)),c!==null)return c.dehydrated}return null}function u(o){if(o.tag===31){var c=o.memoizedState;if(c===null&&(o=o.alternate,o!==null&&(c=o.memoizedState)),c!==null)return c.dehydrated}return null}function f(o){if(a(o)!==o)throw Error(i(188))}function d(o){var c=o.alternate;if(!c){if(c=a(o),c===null)throw Error(i(188));return c!==o?null:o}for(var h=o,y=c;;){var R=h.return;if(R===null)break;var D=R.alternate;if(D===null){if(y=R.return,y!==null){h=y;continue}break}if(R.child===D.child){for(D=R.child;D;){if(D===h)return f(R),o;if(D===y)return f(R),c;D=D.sibling}throw Error(i(188))}if(h.return!==y.return)h=R,y=D;else{for(var Z=!1,ue=R.child;ue;){if(ue===h){Z=!0,h=R,y=D;break}if(ue===y){Z=!0,y=R,h=D;break}ue=ue.sibling}if(!Z){for(ue=D.child;ue;){if(ue===h){Z=!0,h=D,y=R;break}if(ue===y){Z=!0,y=D,h=R;break}ue=ue.sibling}if(!Z)throw Error(i(189))}}if(h.alternate!==y)throw Error(i(190))}if(h.tag!==3)throw Error(i(188));return h.stateNode.current===h?o:c}function p(o){var c=o.tag;if(c===5||c===26||c===27||c===6)return o;for(o=o.child;o!==null;){if(c=p(o),c!==null)return c;o=o.sibling}return null}var g=Object.assign,m=Symbol.for("react.element"),v=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),w=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),C=Symbol.for("react.consumer"),T=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),M=Symbol.for("react.suspense_list"),O=Symbol.for("react.memo"),Q=Symbol.for("react.lazy"),pe=Symbol.for("react.activity"),q=Symbol.for("react.memo_cache_sentinel"),ee=Symbol.iterator;function _e(o){return o===null||typeof o!="object"?null:(o=ee&&o[ee]||o["@@iterator"],typeof o=="function"?o:null)}var te=Symbol.for("react.client.reference");function Ie(o){if(o==null)return null;if(typeof o=="function")return o.$$typeof===te?null:o.displayName||o.name||null;if(typeof o=="string")return o;switch(o){case E:return"Fragment";case A:return"Profiler";case w:return"StrictMode";case P:return"Suspense";case M:return"SuspenseList";case pe:return"Activity"}if(typeof o=="object")switch(o.$$typeof){case S:return"Portal";case T:return o.displayName||"Context";case C:return(o._context.displayName||"Context")+".Consumer";case F:var c=o.render;return o=o.displayName,o||(o=c.displayName||c.name||"",o=o!==""?"ForwardRef("+o+")":"ForwardRef"),o;case O:return c=o.displayName||null,c!==null?c:Ie(o.type)||"Memo";case Q:c=o._payload,o=o._init;try{return Ie(o(c))}catch{}}return null}var De=Array.isArray,de=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Oe=t.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,le={pending:!1,data:null,method:null,action:null},Ae=[],$=-1;function H(o){return{current:o}}function fe(o){0>$||(o.current=Ae[$],Ae[$]=null,$--)}function ae(o,c){$++,Ae[$]=o.current,o.current=c}var Pe=H(null),Me=H(null),Xe=H(null),We=H(null);function ye(o,c){switch(ae(Xe,c),ae(Me,o),ae(Pe,null),c.nodeType){case 9:case 11:o=(o=c.documentElement)&&(o=o.namespaceURI)?Of(o):0;break;default:if(o=c.tagName,c=c.namespaceURI)c=Of(c),o=Mf(c,o);else switch(o){case"svg":o=1;break;case"math":o=2;break;default:o=0}}fe(Pe),ae(Pe,o)}function me(){fe(Pe),fe(Me),fe(Xe)}function Be(o){o.memoizedState!==null&&ae(We,o);var c=Pe.current,h=Mf(c,o.type);c!==h&&(ae(Me,o),ae(Pe,h))}function se(o){Me.current===o&&(fe(Pe),fe(Me)),We.current===o&&(fe(We),ao._currentValue=le)}var B,N;function L(o){if(B===void 0)try{throw Error()}catch(h){var c=h.stack.trim().match(/\n( *(at )?)/);B=c&&c[1]||"",N=-1<h.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<h.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+B+o+N}var W=!1;function re(o,c){if(!o||W)return"";W=!0;var h=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var y={DetermineComponentFrameRoot:function(){try{if(c){var ft=function(){throw Error()};if(Object.defineProperty(ft.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ft,[])}catch(st){var rt=st}Reflect.construct(o,[],ft)}else{try{ft.call()}catch(st){rt=st}o.call(ft.prototype)}}else{try{throw Error()}catch(st){rt=st}(ft=o())&&typeof ft.catch=="function"&&ft.catch(function(){})}}catch(st){if(st&&rt&&typeof st.stack=="string")return[st.stack,rt.stack]}return[null,null]}};y.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var R=Object.getOwnPropertyDescriptor(y.DetermineComponentFrameRoot,"name");R&&R.configurable&&Object.defineProperty(y.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var D=y.DetermineComponentFrameRoot(),Z=D[0],ue=D[1];if(Z&&ue){var je=Z.split(`
@@ -84,7 +84,7 @@ Error generating stack: `+y.message+`
84
84
  `},typeof _=="string"&&(_.indexOf("-----BEGIN")!=-1?this.readCertPEM(_):j.lang.String.isHex(_)&&this.readCertHex(_))}Ge.prototype.sign=function(_,b){var x=(function(k){return j.crypto.Util.hashString(k,b)})(_);return this.signWithMessageHash(x,b)},Ge.prototype.signWithMessageHash=function(_,b){var x=at(j.crypto.Util.getPaddedDigestInfoHex(_,b,this.n.bitLength()),16);return gr(this.doPrivate(x).toString(16),this.n.bitLength())},Ge.prototype.signPSS=function(_,b,x){var I=(function(J){return j.crypto.Util.hashHex(J,b)})(ir(_));return x===void 0&&(x=-1),this.signWithMessageHashPSS(I,b,x)},Ge.prototype.signWithMessageHashPSS=function(_,b,x){var I,k=hr(_),J=k.length,ne=this.n.bitLength()-1,xe=Math.ceil(ne/8),be=function(ie){return j.crypto.Util.hashHex(ie,b)};if(x===-1||x===void 0)x=J;else if(x===-2)x=xe-J-2;else if(x<-2)throw new Error("invalid salt length");if(xe<J+x+2)throw new Error("data too long");var ve="";x>0&&(ve=new Array(x),new ge().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(I=0;I<xe-x-J-2;I+=1)Te[I]=0;var Ue=String.fromCharCode.apply(String,Te)+""+ve,$e=li(we,Ue.length,be),Ke=[];for(I=0;I<Ue.length;I+=1)Ke[I]=Ue.charCodeAt(I)^$e.charCodeAt(I);var Ye=65280>>8*xe-ne&255;for(Ke[0]&=~Ye,I=0;I<J;I++)Ke.push(we.charCodeAt(I));return Ke.push(188),gr(this.doPrivate(new q(Ke)).toString(16),this.n.bitLength())},Ge.prototype.verify=function(_,b){if((b=b.toLowerCase()).match(/^[0-9a-f]+$/)==null)return!1;var x=at(b,16),I=this.n.bitLength();if(x.bitLength()>I)return!1;var k=this.doPublic(x).toString(16);if(k.length+3!=I/4)return!1;var J=Sr(k.replace(/^1f+00/,""));if(J.length==0)return!1;var ne=J[0];return J[1]==(function(be){return j.crypto.Util.hashString(be,ne)})(_)},Ge.prototype.verifyWithMessageHash=function(_,b){if(b.length!=Math.ceil(this.n.bitLength()/4))return!1;var x=at(b,16);if(x.bitLength()>this.n.bitLength())return 0;var I=Sr(this.doPublic(x).toString(16).replace(/^1f+00/,""));return I.length==0?!1:(I[0],I[1]==_)},Ge.prototype.verifyPSS=function(_,b,x,I){var k=(function(ne){return j.crypto.Util.hashHex(ne,x)})(ir(_));return I===void 0&&(I=-1),this.verifyWithMessageHashPSS(k,b,x,I)},Ge.prototype.verifyWithMessageHashPSS=function(_,b,x,I){if(b.length!=Math.ceil(this.n.bitLength()/4))return!1;var k,J=new q(b,16),ne=function(Ne){return j.crypto.Util.hashHex(Ne,x)},xe=hr(_),be=xe.length,ve=this.n.bitLength()-1,we=Math.ceil(ve/8);if(I===-1||I===void 0)I=be;else if(I===-2)I=we-be-2;else if(I<-2)throw new Error("invalid salt length");if(we<be+I+2)throw new Error("data too long");var Te=this.doPublic(J).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 Ue=(Te=String.fromCharCode.apply(String,Te)).substr(0,we-be-1),$e=Te.substr(Ue.length,be),Ke=65280>>8*we-ve&255;if((Ue.charCodeAt(0)&Ke)!=0)throw new Error("bits beyond keysize not zero");var Ye=li($e,Ue.length,ne),tt=[];for(k=0;k<Ue.length;k+=1)tt[k]=Ue.charCodeAt(k)^Ye.charCodeAt(k);tt[0]&=~Ke;var ie=we-be-I-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(-I)))))},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 x=new lr;return Le.getTLV(_,b),x.getX500Name(_).str},lr.hex2rdn=function(_,b){if(b===void 0&&(b=0),_.substr(b,2)!=="31")throw new Error("malformed RDN");for(var x=new Array,I=Le.getChildIdx(_,b),k=0;k<I.length;k++)x.push(lr.hex2attrTypeValue(_,I[k]));return(x=x.map((function(J){return J.replace("+","\\+")}))).join("+")},lr.hex2attrTypeValue=function(_,b){var x=Le,I=x.getV;if(b===void 0&&(b=0),_.substr(b,2)!=="30")throw new Error("malformed attribute type and value");var k=x.getChildIdx(_,b);k.length!==2||_.substr(k[0],2);var J=I(_,k[0]),ne=j.asn1.ASN1Util.oidHexToInt(J);return j.asn1.x509.OID.oid2atype(ne)+"="+hr(I(_,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,x,I=Le.getVbyList,k={};return k.algparam=null,(b=new lr).readCertPEM(_),x=b.getPublicKeyHex(),k.keyhex=I(x,0,[1],"03").substr(2),k.algoid=I(x,0,[0,0],"06"),k.algoid==="2a8648ce3d0201"&&(k.algparam=I(x,0,[0,1],"06")),k},lr.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],j!==void 0&&j||(i.KJUR=j={}),j.jws!==void 0&&j.jws||(j.jws={}),j.jws.JWS=function(){var _=j.jws.JWS.isSafeJSONString;this.parseJWS=function(b,x){if(this.parsedJWS===void 0||!x&&this.parsedJWS.sigvalH===void 0){var I=b.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(I==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var k=I[1],J=I[2],ne=I[3],xe=k+"."+J;if(this.parsedJWS={},this.parsedJWS.headB64U=k,this.parsedJWS.payloadB64U=J,this.parsedJWS.sigvalB64U=ne,this.parsedJWS.si=xe,!x){var be=Ut(ne),ve=at(be,16);this.parsedJWS.sigvalH=be,this.parsedJWS.sigvalBI=ve}var we=Ve(k),Te=Ve(J);if(this.parsedJWS.headS=we,this.parsedJWS.payloadS=Te,!_(we,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+we}}},j.jws.JWS.sign=function(_,b,x,I,k){var J,ne,xe,be=j,ve=be.jws.JWS,we=ve.readSafeJSONString,Te=ve.isSafeJSONString,Ue=be.crypto,$e=(Ue.ECDSA,Ue.Mac),Ke=Ue.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,J=Ye.stringify(ne)),typeof b=="string"){if(!Te(J=b))throw"JWS Head is not safe JSON string: "+J;ne=we(J)}if(xe=x,(x===void 0?"undefined":A(x))=="object"&&(xe=Ye.stringify(x)),_!=""&&_!=null||ne.alg===void 0||(_=ne.alg),_!=""&&_!=null&&ne.alg===void 0&&(ne.alg=_,J=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=Fe(J)+"."+Fe(xe),Re="";if(tt.substr(0,4)=="Hmac"){if(I===void 0)throw"mac key shall be specified for HS* alg";var Ne=new $e({alg:tt,prov:"cryptojs",pass:I});Ne.updateString(ie),Re=Ne.doFinal()}else if(tt.indexOf("withECDSA")!=-1){(Je=new Ke({alg:tt})).init(I,k),Je.updateString(ie);var ke=Je.sign();Re=j.crypto.ECDSA.asn1SigToConcatSig(ke)}else{var Je;tt!="none"&&((Je=new Ke({alg:tt})).init(I,k),Je.updateString(ie),Re=Je.sign())}return ie+"."+er(Re)},j.jws.JWS.verify=function(_,b,x){var I,k=j,J=k.jws.JWS,ne=J.readSafeJSONString,xe=k.crypto,be=xe.ECDSA,ve=xe.Mac,we=xe.Signature;A(Ge)!==void 0&&(I=Ge);var Te=_.split(".");if(Te.length!==3)return!1;var Ue=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),x!=null&&Object.prototype.toString.call(x)==="[object Array]"&&x.length>0&&(":"+x.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 I))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(J.jwsalg2sigalg[Ke.alg]===void 0)throw"unsupported alg name: "+Ye;if((ie=J.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(Ue),$e==Re.doFinal()}if(ie.indexOf("withECDSA")!=-1){var Ne,ke=null;try{ke=be.concatSigToASN1Sig($e)}catch{return!1}return(Ne=new we({alg:ie})).init(b),Ne.updateString(Ue),Ne.verify(ke)}return(Ne=new we({alg:ie})).init(b),Ne.updateString(Ue),Ne.verify($e)},j.jws.JWS.parse=function(_){var b,x,I,k=_.split("."),J={};if(k.length!=2&&k.length!=3)throw"malformed sJWS: wrong number of '.' splitted elements";return b=k[0],x=k[1],k.length==3&&(I=k[2]),J.headerObj=j.jws.JWS.readSafeJSONString(Ve(b)),J.payloadObj=j.jws.JWS.readSafeJSONString(Ve(x)),J.headerPP=JSON.stringify(J.headerObj,null," "),J.payloadObj==null?J.payloadPP=Ve(x):J.payloadPP=JSON.stringify(J.payloadObj,null," "),I!==void 0&&(J.sigHex=Ut(I)),J},j.jws.JWS.verifyJWT=function(_,b,x){var I=j.jws,k=I.JWS,J=k.readSafeJSONString,ne=k.inArray,xe=k.includedArray,be=_.split("."),ve=be[0],we=be[1],Te=(Ut(be[2]),J(Ve(ve))),Ue=J(Ve(we));if(Te.alg===void 0)return!1;if(x.alg===void 0)throw"acceptField.alg shall be specified";if(!ne(Te.alg,x.alg)||Ue.iss!==void 0&&A(x.iss)==="object"&&!ne(Ue.iss,x.iss)||Ue.sub!==void 0&&A(x.sub)==="object"&&!ne(Ue.sub,x.sub))return!1;if(Ue.aud!==void 0&&A(x.aud)==="object"){if(typeof Ue.aud=="string"){if(!ne(Ue.aud,x.aud))return!1}else if(A(Ue.aud)=="object"&&!xe(Ue.aud,x.aud))return!1}var $e=I.IntDate.getNow();return x.verifyAt!==void 0&&typeof x.verifyAt=="number"&&($e=x.verifyAt),x.gracePeriod!==void 0&&typeof x.gracePeriod=="number"||(x.gracePeriod=0),!(Ue.exp!==void 0&&typeof Ue.exp=="number"&&Ue.exp+x.gracePeriod<$e)&&!(Ue.nbf!==void 0&&typeof Ue.nbf=="number"&&$e<Ue.nbf-x.gracePeriod)&&!(Ue.iat!==void 0&&typeof Ue.iat=="number"&&$e<Ue.iat-x.gracePeriod)&&(Ue.jti===void 0||x.jti===void 0||Ue.jti===x.jti)&&!!k.verify(_,b,x.alg)},j.jws.JWS.includedArray=function(_,b){var x=j.jws.JWS.inArray;if(_===null||(_===void 0?"undefined":A(_))!=="object"||typeof _.length!="number")return!1;for(var I=0;I<_.length;I++)if(!x(_[I],b))return!1;return!0},j.jws.JWS.inArray=function(_,b){if(b===null||(b===void 0?"undefined":A(b))!=="object"||typeof b.length!="number")return!1;for(var x=0;x<b.length;x++)if(b[x]==_)return!0;return!1},j.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"},j.jws.JWS.isSafeJSONString=function(_,b,x){var I=null;try{return((I=z(_))===void 0?"undefined":A(I))!="object"||I.constructor===Array?0:(b&&(b[x]=I),1)}catch{return 0}},j.jws.JWS.readSafeJSONString=function(_){var b=null;try{return((b=z(_))===void 0?"undefined":A(b))!="object"||b.constructor===Array?null:b}catch{return null}},j.jws.JWS.getEncodedSignatureValueFromJWS=function(_){var b=_.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(b==null)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return b[1]},j.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 x=ir(b);return er(j.crypto.Util.hashHex(x,"sha256"))},j.jws.IntDate={},j.jws.IntDate.get=function(_){var b=j.jws.IntDate,x=b.getNow,I=b.getZulu;if(_=="now")return x();if(_=="now + 1hour")return x()+3600;if(_=="now + 1day")return x()+86400;if(_=="now + 1month")return x()+2592e3;if(_=="now + 1year")return x()+31536e3;if(_.match(/Z$/))return I(_);if(_.match(/^[0-9]+$/))return parseInt(_);throw"unsupported format: "+_},j.jws.IntDate.getZulu=function(_){return jt(_)},j.jws.IntDate.getNow=function(){return~~(new Date/1e3)},j.jws.IntDate.intDate2UTCString=function(_){return new Date(1e3*_).toUTCString()},j.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=ge,i.rng_seed_time=re,i.BigInteger=q,i.RSAKey=Ge;var ci=j.crypto.EDSA;i.EDSA=ci;var kr=j.crypto.DSA;i.DSA=kr;var xn=j.crypto.Signature;i.Signature=xn;var Rr=j.crypto.MessageDigest;i.MessageDigest=Rr;var vi=j.crypto.Mac;i.Mac=vi;var wi=j.crypto.Cipher;i.Cipher=wi,i.KEYUTIL=Tt,i.ASN1HEX=Le,i.X509=lr,i.CryptoJS=F,i.b64tohex=Q,i.b64toBA=pe,i.stoBA=mt,i.BAtos=St,i.BAtohex=Rt,i.stohex=kt,i.stob64=function(b){return O(kt(b))},i.stob64u=function(b){return Ft(O(kt(b)))},i.b64utos=function(b){return St(pe(on(b)))},i.b64tob64u=Ft,i.b64utob64=on,i.hex2b64=O,i.hextob64u=er,i.b64utohex=Ut,i.utf8tob64u=Fe,i.b64utoutf8=Ve,i.utf8tob64=function(b){return O(Wt(zt(b)))},i.b64toutf8=function(b){return decodeURIComponent(ln(Q(b)))},i.utf8tohex=xr,i.hextoutf8=Bt,i.hextorstr=hr,i.rstrtohex=ir,i.hextob64=Wr,i.hextob64nl=V,i.b64nltohex=K,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 x=new ArrayBuffer(b.length/2),I=new DataView(x),k=0;k<b.length/2;k++)I.setUint8(k,parseInt(b.substr(2*k,2),16));return x},i.ArrayBuffertohex=function(b){for(var x="",I=new DataView(b),k=0;k<b.byteLength;k++)x+=("00"+I.getUint8(k).toString(16)).slice(-2);return x},i.zulutomsec=lt,i.zulutosec=jt,i.zulutodate=function(b){return new Date(lt(b))},i.datetozulu=function(b,x,I){var k,J=b.getUTCFullYear();if(x){if(J<1950||2049<J)throw"not proper year for UTCTime: "+J;k=(""+J).slice(-2)}else k=("000"+J).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),I){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 x="malformed IP address";if(!(b=b.toLowerCase(b)).match(/^[0-9.]+$/)){if(b.match(/^[0-9a-f:]+$/)&&b.indexOf(":")!==-1)return Er(b);throw x}var I=b.split(".");if(I.length!==4)throw x;var k="";try{for(var J=0;J<4;J++)k+=("0"+parseInt(I[J]).toString(16)).slice(-2);return k}catch{throw x}},i.encodeURIComponentAll=zt,i.newline_toUnix=function(b){return b=b.replace(/\r\n/gm,`
85
85
  `)},i.newline_toDos=function(b){return b=(b=b.replace(/\r\n/gm,`
86
86
  `)).replace(/\n/gm,`\r
87
- `)},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(x,I,k){var J=parseInt(x);if(J<0||255<J)throw"integer not in range 0-255";return("00"+J.toString(16)).slice(-2)})).join("")}catch(x){throw"malformed integer array string: "+x}},i.strdiffidx=function(b,x){var I=b.length;b.length>x.length&&(I=x.length);for(var k=0;k<I;k++)if(b.charCodeAt(k)!=x.charCodeAt(k))return k;return b.length!=x.length?I:-1},i.KJUR=j;var En=j.crypto;i.crypto=En;var gn=j.asn1;i.asn1=gn;var Rn=j.jws;i.jws=Rn;var ws=j.lang;i.lang=ws}).call(this,s(28).Buffer)},function(t,i,s){(function(a){var l=s(30),u=s(31),f=s(32);function d(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function p(se,B){if(d()<B)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(se=new Uint8Array(B)).__proto__=g.prototype:(se===null&&(se=new g(B)),se.length=B),se}function g(se,B,N){if(!(g.TYPED_ARRAY_SUPPORT||this instanceof g))return new g(se,B,N);if(typeof se=="number"){if(typeof B=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,se)}return m(this,se,B,N)}function m(se,B,N,L){if(typeof B=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&B instanceof ArrayBuffer?(function(re,ce,Ee,G){if(ce.byteLength,Ee<0||ce.byteLength<Ee)throw new RangeError("'offset' is out of bounds");if(ce.byteLength<Ee+(G||0))throw new RangeError("'length' is out of bounds");return ce=Ee===void 0&&G===void 0?new Uint8Array(ce):G===void 0?new Uint8Array(ce,Ee):new Uint8Array(ce,Ee,G),g.TYPED_ARRAY_SUPPORT?(re=ce).__proto__=g.prototype:re=E(re,ce),re})(se,B,N,L):typeof B=="string"?(function(re,ce,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(ce,Ee),Se=(re=p(re,G)).write(ce,Ee);return Se!==G&&(re=re.slice(0,Se)),re})(se,B,N):(function(re,ce){if(g.isBuffer(ce)){var Ee=0|w(ce.length);return(re=p(re,Ee)).length===0||ce.copy(re,0,0,Ee),re}if(ce){if(typeof ArrayBuffer<"u"&&ce.buffer instanceof ArrayBuffer||"length"in ce)return typeof ce.length!="number"||(function(Se){return Se!=Se})(ce.length)?p(re,0):E(re,ce);if(ce.type==="Buffer"&&f(ce.data))return E(re,ce.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(se,B)}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,B){if(v(B),se=p(se,B<0?0:0|w(B)),!g.TYPED_ARRAY_SUPPORT)for(var N=0;N<B;++N)se[N]=0;return se}function E(se,B){var N=B.length<0?0:0|w(B.length);se=p(se,N);for(var L=0;L<N;L+=1)se[L]=255&B[L];return se}function w(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,B){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(B){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":case void 0:return ye(se).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*N;case"hex":return N>>>1;case"base64":return me(se).length;default:if(L)return ye(se).length;B=(""+B).toLowerCase(),L=!0}}function C(se,B,N){var L=!1;if((B===void 0||B<0)&&(B=0),B>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0)<=(B>>>=0))return"";for(se||(se="utf8");;)switch(se){case"hex":return Oe(this,B,N);case"utf8":case"utf-8":return te(this,B,N);case"ascii":return De(this,B,N);case"latin1":case"binary":return de(this,B,N);case"base64":return _e(this,B,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return le(this,B,N);default:if(L)throw new TypeError("Unknown encoding: "+se);se=(se+"").toLowerCase(),L=!0}}function T(se,B,N){var L=se[B];se[B]=se[N],se[N]=L}function F(se,B,N,L,W){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=W?0:se.length-1),N<0&&(N=se.length+N),N>=se.length){if(W)return-1;N=se.length-1}else if(N<0){if(!W)return-1;N=0}if(typeof B=="string"&&(B=g.from(B,L)),g.isBuffer(B))return B.length===0?-1:P(se,B,N,L,W);if(typeof B=="number")return B&=255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?W?Uint8Array.prototype.indexOf.call(se,B,N):Uint8Array.prototype.lastIndexOf.call(se,B,N):P(se,[B],N,L,W);throw new TypeError("val must be string, number or Buffer")}function P(se,B,N,L,W){var re,ce=1,Ee=se.length,G=B.length;if(L!==void 0&&((L=String(L).toLowerCase())==="ucs2"||L==="ucs-2"||L==="utf16le"||L==="utf-16le")){if(se.length<2||B.length<2)return-1;ce=2,Ee/=2,G/=2,N/=2}function Se(ht,Ge){return ce===1?ht[Ge]:ht.readUInt16BE(Ge*ce)}if(W){var Ce=-1;for(re=N;re<Ee;re++)if(Se(se,re)===Se(B,Ce===-1?0:re-Ce)){if(Ce===-1&&(Ce=re),re-Ce+1===G)return Ce*ce}else Ce!==-1&&(re-=re-Ce),Ce=-1}else for(N+G>Ee&&(N=Ee-G),re=N;re>=0;re--){for(var ge=!0,at=0;at<G;at++)if(Se(se,re+at)!==Se(B,at)){ge=!1;break}if(ge)return re}return-1}function M(se,B,N,L){N=Number(N)||0;var W=se.length-N;L?(L=Number(L))>W&&(L=W):L=W;var re=B.length;if(re%2!=0)throw new TypeError("Invalid hex string");L>re/2&&(L=re/2);for(var ce=0;ce<L;++ce){var Ee=parseInt(B.substr(2*ce,2),16);if(isNaN(Ee))return ce;se[N+ce]=Ee}return ce}function O(se,B,N,L){return Be(ye(B,se.length-N),se,N,L)}function Q(se,B,N,L){return Be((function(re){for(var ce=[],Ee=0;Ee<re.length;++Ee)ce.push(255&re.charCodeAt(Ee));return ce})(B),se,N,L)}function pe(se,B,N,L){return Q(se,B,N,L)}function q(se,B,N,L){return Be(me(B),se,N,L)}function ee(se,B,N,L){return Be((function(re,ce){for(var Ee,G,Se,Ce=[],ge=0;ge<re.length&&!((ce-=2)<0);++ge)G=(Ee=re.charCodeAt(ge))>>8,Se=Ee%256,Ce.push(Se),Ce.push(G);return Ce})(B,se.length-N),se,N,L)}function _e(se,B,N){return B===0&&N===se.length?l.fromByteArray(se):l.fromByteArray(se.slice(B,N))}function te(se,B,N){N=Math.min(se.length,N);for(var L=[],W=B;W<N;){var re,ce,Ee,G,Se=se[W],Ce=null,ge=Se>239?4:Se>223?3:Se>191?2:1;if(W+ge<=N)switch(ge){case 1:Se<128&&(Ce=Se);break;case 2:(192&(re=se[W+1]))==128&&(G=(31&Se)<<6|63&re)>127&&(Ce=G);break;case 3:re=se[W+1],ce=se[W+2],(192&re)==128&&(192&ce)==128&&(G=(15&Se)<<12|(63&re)<<6|63&ce)>2047&&(G<55296||G>57343)&&(Ce=G);break;case 4:re=se[W+1],ce=se[W+2],Ee=se[W+3],(192&re)==128&&(192&ce)==128&&(192&Ee)==128&&(G=(15&Se)<<18|(63&re)<<12|(63&ce)<<6|63&Ee)>65535&&G<1114112&&(Ce=G)}Ce===null?(Ce=65533,ge=1):Ce>65535&&(Ce-=65536,L.push(Ce>>>10&1023|55296),Ce=56320|1023&Ce),L.push(Ce),W+=ge}return(function(ht){var Ge=ht.length;if(Ge<=Ie)return String.fromCharCode.apply(String,ht);for(var gt="",Y=0;Y<Ge;)gt+=String.fromCharCode.apply(String,ht.slice(Y,Y+=Ie));return gt})(L)}i.Buffer=g,i.SlowBuffer=function(B){return+B!=B&&(B=0),g.alloc(+B)},i.INSPECT_MAX_BYTES=50,g.TYPED_ARRAY_SUPPORT=a.TYPED_ARRAY_SUPPORT!==void 0?a.TYPED_ARRAY_SUPPORT:(function(){try{var B=new Uint8Array(1);return B.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},B.foo()===42&&typeof B.subarray=="function"&&B.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,B,N){return m(null,se,B,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,B,N){return(function(W,re,ce,Ee){return v(re),re<=0?p(W,re):ce!==void 0?typeof Ee=="string"?p(W,re).fill(ce,Ee):p(W,re).fill(ce):p(W,re)})(null,se,B,N)},g.allocUnsafe=function(se){return S(null,se)},g.allocUnsafeSlow=function(se){return S(null,se)},g.isBuffer=function(B){return!(B==null||!B._isBuffer)},g.compare=function(B,N){if(!g.isBuffer(B)||!g.isBuffer(N))throw new TypeError("Arguments must be Buffers");if(B===N)return 0;for(var L=B.length,W=N.length,re=0,ce=Math.min(L,W);re<ce;++re)if(B[re]!==N[re]){L=B[re],W=N[re];break}return L<W?-1:W<L?1:0},g.isEncoding=function(B){switch(String(B).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(B,N){if(!f(B))throw new TypeError('"list" argument must be an Array of Buffers');if(B.length===0)return g.alloc(0);var L;if(N===void 0)for(N=0,L=0;L<B.length;++L)N+=B[L].length;var W=g.allocUnsafe(N),re=0;for(L=0;L<B.length;++L){var ce=B[L];if(!g.isBuffer(ce))throw new TypeError('"list" argument must be an Array of Buffers');ce.copy(W,re),re+=ce.length}return W},g.byteLength=A,g.prototype._isBuffer=!0,g.prototype.swap16=function(){var B=this.length;if(B%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var N=0;N<B;N+=2)T(this,N,N+1);return this},g.prototype.swap32=function(){var B=this.length;if(B%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var N=0;N<B;N+=4)T(this,N,N+3),T(this,N+1,N+2);return this},g.prototype.swap64=function(){var B=this.length;if(B%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var N=0;N<B;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 B=0|this.length;return B===0?"":arguments.length===0?te(this,0,B):C.apply(this,arguments)},g.prototype.equals=function(B){if(!g.isBuffer(B))throw new TypeError("Argument must be a Buffer");return this===B||g.compare(this,B)===0},g.prototype.inspect=function(){var B="",N=i.INSPECT_MAX_BYTES;return this.length>0&&(B=this.toString("hex",0,N).match(/.{2}/g).join(" "),this.length>N&&(B+=" ... ")),"<Buffer "+B+">"},g.prototype.compare=function(B,N,L,W,re){if(!g.isBuffer(B))throw new TypeError("Argument must be a Buffer");if(N===void 0&&(N=0),L===void 0&&(L=B?B.length:0),W===void 0&&(W=0),re===void 0&&(re=this.length),N<0||L>B.length||W<0||re>this.length)throw new RangeError("out of range index");if(W>=re&&N>=L)return 0;if(W>=re)return-1;if(N>=L)return 1;if(this===B)return 0;for(var ce=(re>>>=0)-(W>>>=0),Ee=(L>>>=0)-(N>>>=0),G=Math.min(ce,Ee),Se=this.slice(W,re),Ce=B.slice(N,L),ge=0;ge<G;++ge)if(Se[ge]!==Ce[ge]){ce=Se[ge],Ee=Ce[ge];break}return ce<Ee?-1:Ee<ce?1:0},g.prototype.includes=function(B,N,L){return this.indexOf(B,N,L)!==-1},g.prototype.indexOf=function(B,N,L){return F(this,B,N,L,!0)},g.prototype.lastIndexOf=function(B,N,L){return F(this,B,N,L,!1)},g.prototype.write=function(B,N,L,W){if(N===void 0)W="utf8",L=this.length,N=0;else if(L===void 0&&typeof N=="string")W=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,W===void 0&&(W="utf8")):(W=L,L=void 0)}var re=this.length-N;if((L===void 0||L>re)&&(L=re),B.length>0&&(L<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");W||(W="utf8");for(var ce=!1;;)switch(W){case"hex":return M(this,B,N,L);case"utf8":case"utf-8":return O(this,B,N,L);case"ascii":return Q(this,B,N,L);case"latin1":case"binary":return pe(this,B,N,L);case"base64":return q(this,B,N,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,B,N,L);default:if(ce)throw new TypeError("Unknown encoding: "+W);W=(""+W).toLowerCase(),ce=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ie=4096;function De(se,B,N){var L="";N=Math.min(se.length,N);for(var W=B;W<N;++W)L+=String.fromCharCode(127&se[W]);return L}function de(se,B,N){var L="";N=Math.min(se.length,N);for(var W=B;W<N;++W)L+=String.fromCharCode(se[W]);return L}function Oe(se,B,N){var L=se.length;(!B||B<0)&&(B=0),(!N||N<0||N>L)&&(N=L);for(var W="",re=B;re<N;++re)W+=We(se[re]);return W}function le(se,B,N){for(var L=se.slice(B,N),W="",re=0;re<L.length;re+=2)W+=String.fromCharCode(L[re]+256*L[re+1]);return W}function Ae(se,B,N){if(se%1!=0||se<0)throw new RangeError("offset is not uint");if(se+B>N)throw new RangeError("Trying to access beyond buffer length")}function $(se,B,N,L,W,re){if(!g.isBuffer(se))throw new TypeError('"buffer" argument must be a Buffer instance');if(B>W||B<re)throw new RangeError('"value" argument is out of bounds');if(N+L>se.length)throw new RangeError("Index out of range")}function H(se,B,N,L){B<0&&(B=65535+B+1);for(var W=0,re=Math.min(se.length-N,2);W<re;++W)se[N+W]=(B&255<<8*(L?W:1-W))>>>8*(L?W:1-W)}function fe(se,B,N,L){B<0&&(B=4294967295+B+1);for(var W=0,re=Math.min(se.length-N,4);W<re;++W)se[N+W]=B>>>8*(L?W:3-W)&255}function ae(se,B,N,L,W,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,B,N,L,W){return W||ae(se,0,N,4),u.write(se,B,N,L,23,4),N+4}function Me(se,B,N,L,W){return W||ae(se,0,N,8),u.write(se,B,N,L,52,8),N+8}g.prototype.slice=function(B,N){var L,W=this.length;if((B=~~B)<0?(B+=W)<0&&(B=0):B>W&&(B=W),(N=N===void 0?W:~~N)<0?(N+=W)<0&&(N=0):N>W&&(N=W),N<B&&(N=B),g.TYPED_ARRAY_SUPPORT)(L=this.subarray(B,N)).__proto__=g.prototype;else{var re=N-B;L=new g(re,void 0);for(var ce=0;ce<re;++ce)L[ce]=this[ce+B]}return L},g.prototype.readUIntLE=function(B,N,L){B|=0,N|=0,L||Ae(B,N,this.length);for(var W=this[B],re=1,ce=0;++ce<N&&(re*=256);)W+=this[B+ce]*re;return W},g.prototype.readUIntBE=function(B,N,L){B|=0,N|=0,L||Ae(B,N,this.length);for(var W=this[B+--N],re=1;N>0&&(re*=256);)W+=this[B+--N]*re;return W},g.prototype.readUInt8=function(B,N){return N||Ae(B,1,this.length),this[B]},g.prototype.readUInt16LE=function(B,N){return N||Ae(B,2,this.length),this[B]|this[B+1]<<8},g.prototype.readUInt16BE=function(B,N){return N||Ae(B,2,this.length),this[B]<<8|this[B+1]},g.prototype.readUInt32LE=function(B,N){return N||Ae(B,4,this.length),(this[B]|this[B+1]<<8|this[B+2]<<16)+16777216*this[B+3]},g.prototype.readUInt32BE=function(B,N){return N||Ae(B,4,this.length),16777216*this[B]+(this[B+1]<<16|this[B+2]<<8|this[B+3])},g.prototype.readIntLE=function(B,N,L){B|=0,N|=0,L||Ae(B,N,this.length);for(var W=this[B],re=1,ce=0;++ce<N&&(re*=256);)W+=this[B+ce]*re;return W>=(re*=128)&&(W-=Math.pow(2,8*N)),W},g.prototype.readIntBE=function(B,N,L){B|=0,N|=0,L||Ae(B,N,this.length);for(var W=N,re=1,ce=this[B+--W];W>0&&(re*=256);)ce+=this[B+--W]*re;return ce>=(re*=128)&&(ce-=Math.pow(2,8*N)),ce},g.prototype.readInt8=function(B,N){return N||Ae(B,1,this.length),128&this[B]?-1*(255-this[B]+1):this[B]},g.prototype.readInt16LE=function(B,N){N||Ae(B,2,this.length);var L=this[B]|this[B+1]<<8;return 32768&L?4294901760|L:L},g.prototype.readInt16BE=function(B,N){N||Ae(B,2,this.length);var L=this[B+1]|this[B]<<8;return 32768&L?4294901760|L:L},g.prototype.readInt32LE=function(B,N){return N||Ae(B,4,this.length),this[B]|this[B+1]<<8|this[B+2]<<16|this[B+3]<<24},g.prototype.readInt32BE=function(B,N){return N||Ae(B,4,this.length),this[B]<<24|this[B+1]<<16|this[B+2]<<8|this[B+3]},g.prototype.readFloatLE=function(B,N){return N||Ae(B,4,this.length),u.read(this,B,!0,23,4)},g.prototype.readFloatBE=function(B,N){return N||Ae(B,4,this.length),u.read(this,B,!1,23,4)},g.prototype.readDoubleLE=function(B,N){return N||Ae(B,8,this.length),u.read(this,B,!0,52,8)},g.prototype.readDoubleBE=function(B,N){return N||Ae(B,8,this.length),u.read(this,B,!1,52,8)},g.prototype.writeUIntLE=function(B,N,L,W){B=+B,N|=0,L|=0,W||$(this,B,N,L,Math.pow(2,8*L)-1,0);var re=1,ce=0;for(this[N]=255&B;++ce<L&&(re*=256);)this[N+ce]=B/re&255;return N+L},g.prototype.writeUIntBE=function(B,N,L,W){B=+B,N|=0,L|=0,W||$(this,B,N,L,Math.pow(2,8*L)-1,0);var re=L-1,ce=1;for(this[N+re]=255&B;--re>=0&&(ce*=256);)this[N+re]=B/ce&255;return N+L},g.prototype.writeUInt8=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,1,255,0),g.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),this[N]=255&B,N+1},g.prototype.writeUInt16LE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8):H(this,B,N,!0),N+2},g.prototype.writeUInt16BE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>8,this[N+1]=255&B):H(this,B,N,!1),N+2},g.prototype.writeUInt32LE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N+3]=B>>>24,this[N+2]=B>>>16,this[N+1]=B>>>8,this[N]=255&B):fe(this,B,N,!0),N+4},g.prototype.writeUInt32BE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>24,this[N+1]=B>>>16,this[N+2]=B>>>8,this[N+3]=255&B):fe(this,B,N,!1),N+4},g.prototype.writeIntLE=function(B,N,L,W){if(B=+B,N|=0,!W){var re=Math.pow(2,8*L-1);$(this,B,N,L,re-1,-re)}var ce=0,Ee=1,G=0;for(this[N]=255&B;++ce<L&&(Ee*=256);)B<0&&G===0&&this[N+ce-1]!==0&&(G=1),this[N+ce]=(B/Ee>>0)-G&255;return N+L},g.prototype.writeIntBE=function(B,N,L,W){if(B=+B,N|=0,!W){var re=Math.pow(2,8*L-1);$(this,B,N,L,re-1,-re)}var ce=L-1,Ee=1,G=0;for(this[N+ce]=255&B;--ce>=0&&(Ee*=256);)B<0&&G===0&&this[N+ce+1]!==0&&(G=1),this[N+ce]=(B/Ee>>0)-G&255;return N+L},g.prototype.writeInt8=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,1,127,-128),g.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),B<0&&(B=255+B+1),this[N]=255&B,N+1},g.prototype.writeInt16LE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8):H(this,B,N,!0),N+2},g.prototype.writeInt16BE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>8,this[N+1]=255&B):H(this,B,N,!1),N+2},g.prototype.writeInt32LE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8,this[N+2]=B>>>16,this[N+3]=B>>>24):fe(this,B,N,!0),N+4},g.prototype.writeInt32BE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,4,2147483647,-2147483648),B<0&&(B=4294967295+B+1),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>24,this[N+1]=B>>>16,this[N+2]=B>>>8,this[N+3]=255&B):fe(this,B,N,!1),N+4},g.prototype.writeFloatLE=function(B,N,L){return Pe(this,B,N,!0,L)},g.prototype.writeFloatBE=function(B,N,L){return Pe(this,B,N,!1,L)},g.prototype.writeDoubleLE=function(B,N,L){return Me(this,B,N,!0,L)},g.prototype.writeDoubleBE=function(B,N,L){return Me(this,B,N,!1,L)},g.prototype.copy=function(B,N,L,W){if(L||(L=0),W||W===0||(W=this.length),N>=B.length&&(N=B.length),N||(N=0),W>0&&W<L&&(W=L),W===L||B.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(W<0)throw new RangeError("sourceEnd out of bounds");W>this.length&&(W=this.length),B.length-N<W-L&&(W=B.length-N+L);var re,ce=W-L;if(this===B&&L<N&&N<W)for(re=ce-1;re>=0;--re)B[re+N]=this[re+L];else if(ce<1e3||!g.TYPED_ARRAY_SUPPORT)for(re=0;re<ce;++re)B[re+N]=this[re+L];else Uint8Array.prototype.set.call(B,this.subarray(L,L+ce),N);return ce},g.prototype.fill=function(B,N,L,W){if(typeof B=="string"){if(typeof N=="string"?(W=N,N=0,L=this.length):typeof L=="string"&&(W=L,L=this.length),B.length===1){var re=B.charCodeAt(0);re<256&&(B=re)}if(W!==void 0&&typeof W!="string")throw new TypeError("encoding must be a string");if(typeof W=="string"&&!g.isEncoding(W))throw new TypeError("Unknown encoding: "+W)}else typeof B=="number"&&(B&=255);if(N<0||this.length<N||this.length<L)throw new RangeError("Out of range index");if(L<=N)return this;var ce;if(N>>>=0,L=L===void 0?this.length:L>>>0,B||(B=0),typeof B=="number")for(ce=N;ce<L;++ce)this[ce]=B;else{var Ee=g.isBuffer(B)?B:ye(new g(B,W).toString()),G=Ee.length;for(ce=0;ce<L-N;++ce)this[ce+N]=Ee[ce%G]}return this};var Xe=/[^+\/0-9A-Za-z-_]/g;function We(se){return se<16?"0"+se.toString(16):se.toString(16)}function ye(se,B){var N;B=B||1/0;for(var L=se.length,W=null,re=[],ce=0;ce<L;++ce){if((N=se.charCodeAt(ce))>55295&&N<57344){if(!W){if(N>56319){(B-=3)>-1&&re.push(239,191,189);continue}if(ce+1===L){(B-=3)>-1&&re.push(239,191,189);continue}W=N;continue}if(N<56320){(B-=3)>-1&&re.push(239,191,189),W=N;continue}N=65536+(W-55296<<10|N-56320)}else W&&(B-=3)>-1&&re.push(239,191,189);if(W=null,N<128){if((B-=1)<0)break;re.push(N)}else if(N<2048){if((B-=2)<0)break;re.push(N>>6|192,63&N|128)}else if(N<65536){if((B-=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((B-=4)<0)break;re.push(N>>18|240,N>>12&63|128,N>>6&63|128,63&N|128)}}return re}function me(se){return l.toByteArray((function(N){if((N=(function(W){return W.trim?W.trim():W.replace(/^\s+|\s+$/g,"")})(N).replace(Xe,"")).length<2)return"";for(;N.length%4!=0;)N+="=";return N})(se))}function Be(se,B,N,L){for(var W=0;W<L&&!(W+N>=B.length||W>=se.length);++W)B[W+N]=se[W];return W}}).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),w=E[0],A=E[1];return 3*(w+A)/4-A},i.toByteArray=function(S){var E,w,A=g(S),C=A[0],T=A[1],F=new u((function(Q,pe,q){return 3*(pe+q)/4-q})(0,C,T)),P=0,M=T>0?C-4:C;for(w=0;w<M;w+=4)E=l[S.charCodeAt(w)]<<18|l[S.charCodeAt(w+1)]<<12|l[S.charCodeAt(w+2)]<<6|l[S.charCodeAt(w+3)],F[P++]=E>>16&255,F[P++]=E>>8&255,F[P++]=255&E;return T===2&&(E=l[S.charCodeAt(w)]<<2|l[S.charCodeAt(w+1)]>>4,F[P++]=255&E),T===1&&(E=l[S.charCodeAt(w)]<<10|l[S.charCodeAt(w+1)]<<4|l[S.charCodeAt(w+2)]>>2,F[P++]=E>>8&255,F[P++]=255&E),F},i.fromByteArray=function(S){for(var E,w=S.length,A=w%3,C=[],T=16383,F=0,P=w-A;F<P;F+=T)C.push(m(S,F,F+T>P?P:F+T));return A===1?(E=S[w-1],C.push(a[E>>2]+a[E<<4&63]+"==")):A===2&&(E=(S[w-2]<<8)+S[w-1],C.push(a[E>>10]+a[E>>4&63]+a[E<<2&63]+"=")),C.join("")};for(var a=[],l=[],u=typeof Uint8Array<"u"?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=f.length;d<p;++d)a[d]=f[d],l[f.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 m(v,S,E){for(var w,A,C=[],T=S;T<E;T+=3)w=(v[T]<<16&16711680)+(v[T+1]<<8&65280)+(255&v[T+2]),C.push(a[(A=w)>>18&63]+a[A>>12&63]+a[A>>6&63]+a[63&A]);return C.join("")}l[45]=62,l[95]=63},function(t,i){i.read=function(s,a,l,u,f){var d,p,g=8*f-u-1,m=(1<<g)-1,v=m>>1,S=-7,E=l?f-1:0,w=l?-1:1,A=s[a+E];for(E+=w,d=A&(1<<-S)-1,A>>=-S,S+=g;S>0;d=256*d+s[a+E],E+=w,S-=8);for(p=d&(1<<-S)-1,d>>=-S,S+=u;S>0;p=256*p+s[a+E],E+=w,S-=8);if(d===0)d=1-v;else{if(d===m)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,a,l,u,f,d){var p,g,m,v=8*d-f-1,S=(1<<v)-1,E=S>>1,w=f===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=u?0:d-1,C=u?1:-1,T=a<0||a===0&&1/a<0?1:0;for(a=Math.abs(a),isNaN(a)||a===1/0?(g=isNaN(a)?1:0,p=S):(p=Math.floor(Math.log(a)/Math.LN2),a*(m=Math.pow(2,-p))<1&&(p--,m*=2),(a+=p+E>=1?w/m:w*Math.pow(2,1-E))*m>=2&&(p++,m/=2),p+E>=S?(g=0,p=S):p+E>=1?(g=(a*m-1)*Math.pow(2,f),p+=E):(g=a*Math.pow(2,E-1)*Math.pow(2,f),p=0));f>=8;s[l+A]=255&g,A+=C,g/=256,f-=8);for(p=p<<f|g,v+=f;v>0;s[l+A]=255&p,A+=C,p/=256,v-=8);s[l+A-C]|=128*T}},function(t,i){var s={}.toString;t.exports=Array.isArray||function(a){return s.call(a)=="[object Array]"}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(u){var f=u.jws,d=u.KeyUtil,p=u.X509,g=u.crypto,m=u.hextob64u,v=u.b64tohex,S=u.AllowedSigningAlgs;return(function(){function E(){(function(A,C){if(!(A instanceof C))throw new TypeError("Cannot call a class as a function")})(this,E)}return E.parseJwt=function(A){a.Log.debug("JoseUtil.parseJwt");try{var C=f.JWS.parse(A);return{header:C.headerObj,payload:C.payloadObj}}catch(T){a.Log.error(T)}},E.validateJwt=function(A,C,T,F,P,M,O){a.Log.debug("JoseUtil.validateJwt");try{if(C.kty==="RSA")if(C.e&&C.n)C=d.getKey(C);else{if(!C.x5c||!C.x5c.length)return a.Log.error("JoseUtil.validateJwt: RSA key missing key material",C),Promise.reject(new Error("RSA key missing key material"));var Q=v(C.x5c[0]);C=p.getPublicKeyFromCertHex(Q)}else{if(C.kty!=="EC")return a.Log.error("JoseUtil.validateJwt: Unsupported key type",C&&C.kty),Promise.reject(new Error(C.kty));if(!(C.crv&&C.x&&C.y))return a.Log.error("JoseUtil.validateJwt: EC key missing key material",C),Promise.reject(new Error("EC key missing key material"));C=d.getKey(C)}return E._validateJwt(A,C,T,F,P,M,O)}catch(pe){return a.Log.error(pe&&pe.message||pe),Promise.reject("JWT validation failed")}},E.validateJwtAttributes=function(A,C,T,F,P,M){F||(F=0),P||(P=parseInt(Date.now()/1e3));var O=E.parseJwt(A).payload;if(!O.iss)return a.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(O.iss!==C)return a.Log.error("JoseUtil._validateJwt: Invalid issuer in token",O.iss),Promise.reject(new Error("Invalid issuer in token: "+O.iss));if(!O.aud)return a.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(O.aud===T||Array.isArray(O.aud)&&O.aud.indexOf(T)>=0))return a.Log.error("JoseUtil._validateJwt: Invalid audience in token",O.aud),Promise.reject(new Error("Invalid audience in token: "+O.aud));if(O.azp&&O.azp!==T)return a.Log.error("JoseUtil._validateJwt: Invalid azp in token",O.azp),Promise.reject(new Error("Invalid azp in token: "+O.azp));if(!M){var Q=P+F,pe=P-F;if(!O.iat)return a.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(Q<O.iat)return a.Log.error("JoseUtil._validateJwt: iat is in the future",O.iat),Promise.reject(new Error("iat is in the future: "+O.iat));if(O.nbf&&Q<O.nbf)return a.Log.error("JoseUtil._validateJwt: nbf is in the future",O.nbf),Promise.reject(new Error("nbf is in the future: "+O.nbf));if(!O.exp)return a.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(O.exp<pe)return a.Log.error("JoseUtil._validateJwt: exp is in the past",O.exp),Promise.reject(new Error("exp is in the past:"+O.exp))}return Promise.resolve(O)},E._validateJwt=function(A,C,T,F,P,M,O){return E.validateJwtAttributes(A,T,F,P,M,O).then((function(Q){try{return f.JWS.verify(A,C,S)?Q:(a.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(pe){return a.Log.error(pe&&pe.message||pe),Promise.reject(new Error("signature validation failed"))}}))},E.hashString=function(A,C){try{return g.Util.hashString(A,C)}catch(T){a.Log.error(T)}},E.hexToBase64Url=function(A){try{return m(A)}catch(C){a.Log.error(C)}},E})()};var a=s(0);t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninResponse=void 0;var a=(function(){function f(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&f(d.prototype,p),g&&f(d,g),d}})(),l=s(3);function u(f,d){if(!(f instanceof d))throw new TypeError("Cannot call a class as a function")}i.SigninResponse=(function(){function f(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";u(this,f);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 a(f,[{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 m=parseInt(Date.now()/1e3);this.expires_at=m+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}}]),f})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutRequest=void 0;var a=s(0),l=s(3),u=s(9);i.SignoutRequest=function f(d){var p=d.url,g=d.id_token_hint,m=d.post_logout_redirect_uri,v=d.data,S=d.extraQueryParams,E=d.request_type;if((function(C,T){if(!(C instanceof T))throw new TypeError("Cannot call a class as a function")})(this,f),!p)throw a.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var w in g&&(p=l.UrlUtility.addQueryParam(p,"id_token_hint",g)),m&&(p=l.UrlUtility.addQueryParam(p,"post_logout_redirect_uri",m),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,w,S[w]);this.url=p}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutResponse=void 0;var a=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 f=a.UrlUtility.parseUrlFragment(u,"?");this.error=f.error,this.error_description=f.error_description,this.error_uri=f.error_uri,this.state=f.state}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.InMemoryWebStorage=void 0;var a=(function(){function u(f,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(f,g.key,g)}}return function(f,d,p){return d&&u(f.prototype,d),p&&u(f,p),f}})(),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]},a(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 a=(function(){function T(F,P){for(var M=0;M<P.length;M++){var O=P[M];O.enumerable=O.enumerable||!1,O.configurable=!0,"value"in O&&(O.writable=!0),Object.defineProperty(F,O.key,O)}}return function(F,P,M){return P&&T(F.prototype,P),M&&T(F,M),F}})(),l=s(0),u=s(10),f=s(39),d=s(15),p=s(45),g=s(47),m=s(18),v=s(8),S=s(20),E=s(11),w=s(4);function A(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function C(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]:{},M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:g.SilentRenewService,O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:m.SessionMonitor,Q=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,pe=arguments.length>4&&arguments[4]!==void 0?arguments[4]:E.TokenClient,q=arguments.length>5&&arguments[5]!==void 0?arguments[5]:w.JoseUtil;A(this,F),P instanceof f.UserManagerSettings||(P=new f.UserManagerSettings(P));var ee=C(this,T.call(this,P));return ee._events=new p.UserManagerEvents(P),ee._silentRenewService=new M(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 O(ee)),ee._tokenRevocationClient=new Q(ee._settings),ee._tokenClient=new pe(ee._settings),ee._joseUtil=q,ee}return(function(M,O){if(typeof O!="function"&&O!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof O);M.prototype=Object.create(O&&O.prototype,{constructor:{value:M,enumerable:!1,writable:!0,configurable:!0}}),O&&(Object.setPrototypeOf?Object.setPrototypeOf(M,O):M.__proto__=O)})(F,T),F.prototype.getUser=function(){var M=this;return this._loadUser().then((function(O){return O?(l.Log.info("UserManager.getUser: user loaded"),M._events.load(O,!1),O):(l.Log.info("UserManager.getUser: user not found in storage"),null)}))},F.prototype.removeUser=function(){var M=this;return this.storeUser(null).then((function(){l.Log.info("UserManager.removeUser: user removed from storage"),M._events.unload()}))},F.prototype.signinRedirect=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="si:r";var O={useReplaceToNavigate:M.useReplaceToNavigate};return this._signinStart(M,this._redirectNavigator,O).then((function(){l.Log.info("UserManager.signinRedirect: successful")}))},F.prototype.signinRedirectCallback=function(M){return this._signinEnd(M||this._redirectNavigator.url).then((function(O){return O.profile&&O.profile.sub?l.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinRedirectCallback: no sub"),O}))},F.prototype.signinPopup=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="si:p";var O=M.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return O?(M.redirect_uri=O,M.display="popup",this._signin(M,this._popupNavigator,{startUrl:O,popupWindowFeatures:M.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:M.popupWindowTarget||this.settings.popupWindowTarget}).then((function(Q){return Q&&(Q.profile&&Q.profile.sub?l.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",Q.profile.sub):l.Log.info("UserManager.signinPopup: no sub")),Q}))):(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(M){return this._signinCallback(M,this._popupNavigator).then((function(O){return O&&(O.profile&&O.profile.sub?l.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinPopupCallback: no sub")),O})).catch((function(O){l.Log.error(O.message)}))},F.prototype.signinSilent=function(){var M=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return O=Object.assign({},O),this._loadUser().then((function(Q){return Q&&Q.refresh_token?(O.refresh_token=Q.refresh_token,M._useRefreshToken(O)):(O.request_type="si:s",O.id_token_hint=O.id_token_hint||M.settings.includeIdTokenInSilentRenew&&Q&&Q.id_token,Q&&M._settings.validateSubOnSilentRenew&&(l.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",Q.profile.sub),O.current_sub=Q.profile.sub),M._signinSilentIframe(O))}))},F.prototype._useRefreshToken=function(){var M=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(O).then((function(Q){return Q?Q.access_token?M._loadUser().then((function(pe){if(pe){var q=Promise.resolve();return Q.id_token&&(q=M._validateIdTokenFromTokenRefreshToken(pe.profile,Q.id_token)),q.then((function(){return l.Log.debug("UserManager._useRefreshToken: refresh token response success"),pe.id_token=Q.id_token||pe.id_token,pe.access_token=Q.access_token,pe.refresh_token=Q.refresh_token||pe.refresh_token,pe.expires_in=Q.expires_in,M.storeUser(pe).then((function(){return M._events.load(pe),pe}))}))}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(M,O){var Q=this;return this._metadataService.getIssuer().then((function(pe){return Q.settings.getEpochTime().then((function(q){return Q._joseUtil.validateJwtAttributes(O,pe,Q._settings.client_id,Q._settings.clockSkew,q).then((function(ee){return ee?ee.sub!==M.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!==M.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!==M.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&&M.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 M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=M.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return O?(M.redirect_uri=O,M.prompt=M.prompt||"none",this._signin(M,this._iframeNavigator,{startUrl:O,silentRequestTimeout:M.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(Q){return Q&&(Q.profile&&Q.profile.sub?l.Log.info("UserManager.signinSilent: successful, signed in sub: ",Q.profile.sub):l.Log.info("UserManager.signinSilent: no sub")),Q}))):(l.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype.signinSilentCallback=function(M){return this._signinCallback(M,this._iframeNavigator).then((function(O){return O&&(O.profile&&O.profile.sub?l.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinSilentCallback: no sub")),O}))},F.prototype.signinCallback=function(M){var O=this;return this.readSigninResponseState(M).then((function(Q){var pe=Q.state;return Q.response,pe.request_type==="si:r"?O.signinRedirectCallback(M):pe.request_type==="si:p"?O.signinPopupCallback(M):pe.request_type==="si:s"?O.signinSilentCallback(M):Promise.reject(new Error("invalid response_type in state"))}))},F.prototype.signoutCallback=function(M,O){var Q=this;return this.readSignoutResponseState(M).then((function(pe){var q=pe.state,ee=pe.response;return q?q.request_type==="so:r"?Q.signoutRedirectCallback(M):q.request_type==="so:p"?Q.signoutPopupCallback(M,O):Promise.reject(new Error("invalid response_type in state")):ee}))},F.prototype.querySessionStatus=function(){var M=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(O=Object.assign({},O)).request_type="si:s";var Q=O.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return Q?(O.redirect_uri=Q,O.prompt="none",O.response_type=O.response_type||this.settings.query_status_response_type,O.scope=O.scope||"openid",O.skipUserInfo=!0,this._signinStart(O,this._iframeNavigator,{startUrl:Q,silentRequestTimeout:O.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(pe){return M.processSigninResponse(pe.url).then((function(q){if(l.Log.debug("UserManager.querySessionStatus: got signin response"),q.session_state&&q.profile.sub)return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",q.profile.sub),{session_state:q.session_state,sub:q.profile.sub,sid:q.profile.sid};l.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(q){if(q.session_state&&M.settings.monitorAnonymousSession&&(q.message=="login_required"||q.message=="consent_required"||q.message=="interaction_required"||q.message=="account_selection_required"))return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:q.session_state};throw q}))}))):(l.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype._signin=function(M,O){var Q=this,pe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(M,O,pe).then((function(q){return Q._signinEnd(q.url,M)}))},F.prototype._signinStart=function(M,O){var Q=this,pe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return O.prepare(pe).then((function(q){return l.Log.debug("UserManager._signinStart: got navigator window handle"),Q.createSigninRequest(M).then((function(ee){return l.Log.debug("UserManager._signinStart: got signin request"),pe.url=ee.url,pe.id=ee.state.id,q.navigate(pe)})).catch((function(ee){throw q.close&&(l.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),q.close()),ee}))}))},F.prototype._signinEnd=function(M){var O=this,Q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(M).then((function(pe){l.Log.debug("UserManager._signinEnd: got signin response");var q=new d.User(pe);if(Q.current_sub){if(Q.current_sub!==q.profile.sub)return l.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",q.profile.sub),Promise.reject(new Error("login_required"));l.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return O.storeUser(q).then((function(){return l.Log.debug("UserManager._signinEnd: user stored"),O._events.load(q),q}))}))},F.prototype._signinCallback=function(M,O){l.Log.debug("UserManager._signinCallback");var Q=this._settings.response_mode==="query"||!this._settings.response_mode&&v.SigninRequest.isCode(this._settings.response_type)?"?":"#";return O.callback(M,void 0,Q)},F.prototype.signoutRedirect=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="so:r";var O=M.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;O&&(M.post_logout_redirect_uri=O);var Q={useReplaceToNavigate:M.useReplaceToNavigate};return this._signoutStart(M,this._redirectNavigator,Q).then((function(){l.Log.info("UserManager.signoutRedirect: successful")}))},F.prototype.signoutRedirectCallback=function(M){return this._signoutEnd(M||this._redirectNavigator.url).then((function(O){return l.Log.info("UserManager.signoutRedirectCallback: successful"),O}))},F.prototype.signoutPopup=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="so:p";var O=M.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return M.post_logout_redirect_uri=O,M.display="popup",M.post_logout_redirect_uri&&(M.state=M.state||{}),this._signout(M,this._popupNavigator,{startUrl:O,popupWindowFeatures:M.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:M.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){l.Log.info("UserManager.signoutPopup: successful")}))},F.prototype.signoutPopupCallback=function(M,O){return O===void 0&&typeof M=="boolean"&&(O=M,M=null),this._popupNavigator.callback(M,O,"?").then((function(){l.Log.info("UserManager.signoutPopupCallback: successful")}))},F.prototype._signout=function(M,O){var Q=this,pe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(M,O,pe).then((function(q){return Q._signoutEnd(q.url)}))},F.prototype._signoutStart=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=this,Q=arguments[1],pe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return Q.prepare(pe).then((function(q){return l.Log.debug("UserManager._signoutStart: got navigator window handle"),O._loadUser().then((function(ee){return l.Log.debug("UserManager._signoutStart: loaded current user from storage"),(O._settings.revokeAccessTokenOnSignout?O._revokeInternal(ee):Promise.resolve()).then((function(){var _e=M.id_token_hint||ee&&ee.id_token;return _e&&(l.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),M.id_token_hint=_e),O.removeUser().then((function(){return l.Log.debug("UserManager._signoutStart: user removed, creating signout request"),O.createSignoutRequest(M).then((function(te){return l.Log.debug("UserManager._signoutStart: got signout request"),pe.url=te.url,te.state&&(pe.id=te.state.id),q.navigate(pe)}))}))}))})).catch((function(ee){throw q.close&&(l.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),q.close()),ee}))}))},F.prototype._signoutEnd=function(M){return this.processSignoutResponse(M).then((function(O){return l.Log.debug("UserManager._signoutEnd: got signout response"),O}))},F.prototype.revokeAccessToken=function(){var M=this;return this._loadUser().then((function(O){return M._revokeInternal(O,!0).then((function(Q){if(Q)return l.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),O.access_token=null,O.refresh_token=null,O.expires_at=null,O.token_type=null,M.storeUser(O).then((function(){l.Log.debug("UserManager.revokeAccessToken: user stored"),M._events.load(O)}))}))})).then((function(){l.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},F.prototype._revokeInternal=function(M,O){var Q=this;if(M){var pe=M.access_token,q=M.refresh_token;return this._revokeAccessTokenInternal(pe,O).then((function(ee){return Q._revokeRefreshTokenInternal(q,O).then((function(_e){return ee||_e||l.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),ee||_e}))}))}return Promise.resolve(!1)},F.prototype._revokeAccessTokenInternal=function(M,O){return!M||M.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(M,O).then((function(){return!0}))},F.prototype._revokeRefreshTokenInternal=function(M,O){return M?this._tokenRevocationClient.revoke(M,O,"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(M){return M?(l.Log.debug("UserManager._loadUser: user storageString loaded"),d.User.fromStorageString(M)):(l.Log.debug("UserManager._loadUser: no user storageString"),null)}))},F.prototype.storeUser=function(M){if(M){l.Log.debug("UserManager.storeUser: storing user");var O=M.toStorageString();return this._userStore.set(this._userStoreKey,O)}return l.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},a(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 a=(function(){function E(w,A){for(var C=0;C<A.length;C++){var T=A[C];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(w,T.key,T)}}return function(w,A,C){return A&&E(w.prototype,A),C&&E(w,C),w}})(),l=(s(0),s(5)),u=s(40),f=s(41),d=s(43),p=s(6),g=s(1),m=s(8);function v(E,w){if(!(E instanceof w))throw new TypeError("Cannot call a class as a function")}function S(E,w){if(!E)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!w||typeof w!="object"&&typeof w!="function"?E:w}i.UserManagerSettings=(function(E){function w(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},C=A.popup_redirect_uri,T=A.popup_post_logout_redirect_uri,F=A.popupWindowFeatures,P=A.popupWindowTarget,M=A.silent_redirect_uri,O=A.silentRequestTimeout,Q=A.automaticSilentRenew,pe=Q!==void 0&&Q,q=A.validateSubOnSilentRenew,ee=q!==void 0&&q,_e=A.includeIdTokenInSilentRenew,te=_e===void 0||_e,Ie=A.monitorSession,De=Ie===void 0||Ie,de=A.monitorAnonymousSession,Oe=de!==void 0&&de,le=A.checkSessionInterval,Ae=le===void 0?2e3:le,$=A.stopCheckSessionOnError,H=$===void 0||$,fe=A.query_status_response_type,ae=A.revokeAccessTokenOnSignout,Pe=ae!==void 0&&ae,Me=A.accessTokenExpiringNotificationTime,Xe=Me===void 0?60:Me,We=A.redirectNavigator,ye=We===void 0?new u.RedirectNavigator:We,me=A.popupNavigator,Be=me===void 0?new f.PopupNavigator:me,se=A.iframeNavigator,B=se===void 0?new d.IFrameNavigator:se,N=A.userStore,L=N===void 0?new p.WebStorageStateStore({store:g.Global.sessionStorage}):N;v(this,w);var W=S(this,E.call(this,arguments[0]));return W._popup_redirect_uri=C,W._popup_post_logout_redirect_uri=T,W._popupWindowFeatures=F,W._popupWindowTarget=P,W._silent_redirect_uri=M,W._silentRequestTimeout=O,W._automaticSilentRenew=pe,W._validateSubOnSilentRenew=ee,W._includeIdTokenInSilentRenew=te,W._accessTokenExpiringNotificationTime=Xe,W._monitorSession=De,W._monitorAnonymousSession=Oe,W._checkSessionInterval=Ae,W._stopCheckSessionOnError=H,fe?W._query_status_response_type=fe:arguments[0]&&arguments[0].response_type?W._query_status_response_type=m.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":W._query_status_response_type="id_token",W._revokeAccessTokenOnSignout=Pe,W._redirectNavigator=ye,W._popupNavigator=Be,W._iframeNavigator=B,W._userStore=L,W}return(function(C,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof T);C.prototype=Object.create(T&&T.prototype,{constructor:{value:C,enumerable:!1,writable:!0,configurable:!0}}),T&&(Object.setPrototypeOf?Object.setPrototypeOf(C,T):C.__proto__=T)})(w,E),a(w,[{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}}]),w})(l.OidcClientSettings)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.RedirectNavigator=void 0;var a=(function(){function u(f,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(f,g.key,g)}}return function(f,d,p){return d&&u(f.prototype,d),p&&u(f,p),f}})(),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")))},a(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 a=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){a.Log.debug("PopupNavigator.callback");try{return l.PopupWindow.notifyOpener(d,p,g),Promise.resolve()}catch(m){return Promise.reject(m)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupWindow=void 0;var a=(function(){function f(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&f(d.prototype,p),g&&f(d,g),d}})(),l=s(0),u=s(3);i.PopupWindow=(function(){function f(d){var p=this;(function(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")})(this,f),this._promise=new Promise((function(v,S){p._resolve=v,p._reject=S}));var g=d.popupWindowTarget||"_blank",m=d.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",g,m),this._popup&&(l.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return f.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},f.prototype._success=function(p){l.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(p)},f.prototype._error=function(p){l.Log.error("PopupWindow.error: ",p),this._cleanup(),this._reject(new Error(p))},f.prototype.close=function(){this._cleanup(!1)},f.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},f.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},f.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"))},f.notifyOpener=function(p,g,m){if(window.opener){if(p=p||window.location.href){var v=u.UrlUtility.parseUrlFragment(p,m);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.")},a(f,[{key:"promise",get:function(){return this._promise}}]),f})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameNavigator=void 0;var a=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){a.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 a=(function(){function u(f,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(f,g.key,g)}}return function(f,d,p){return d&&u(f.prototype,d),p&&u(f,p),f}})(),l=s(0);i.IFrameWindow=(function(){function u(f){var d=this;(function(g,m){if(!(g instanceof m))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))},a(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 a=s(0),l=s(16),u=s(17);i.UserManagerEvents=(function(f){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,f.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,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof m);g.prototype=Object.create(m&&m.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),m&&(Object.setPrototypeOf?Object.setPrototypeOf(g,m):g.__proto__=m)})(d,f),d.prototype.load=function(g){var m=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];a.Log.debug("UserManagerEvents.load"),f.prototype.load.call(this,g),m&&this._userLoaded.raise(g)},d.prototype.unload=function(){a.Log.debug("UserManagerEvents.unload"),f.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){a.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(){a.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(){a.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(){a.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 a=(function(){function g(m,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(m,E.key,E)}}return function(m,v,S){return v&&g(m.prototype,v),S&&g(m,S),m}})(),l=s(0),u=s(1),f=s(17);function d(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")}function p(g,m){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!m||typeof m!="object"&&typeof m!="function"?g:m}i.Timer=(function(g){function m(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,m);var w=p(this,g.call(this,v));return w._timer=S,w._nowFunc=E||function(){return Date.now()/1e3},w}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)})(m,g),m.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 w=5;S<w&&(w=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*w)}},m.prototype.cancel=function(){this._timerHandle&&(l.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},m.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))},a(m,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),m})(f.Event)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SilentRenewService=void 0;var a=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(f){})).catch((function(f){a.Log.error("SilentRenewService.start: Error from getUser:",f.message)})))},l.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},l.prototype._tokenExpiring=function(){var f=this;this._userManager.signinSilent().then((function(d){a.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(d){a.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",d.message),f._userManager.events._raiseSilentRenewError(d)}))},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupNavigator=void 0;var a=s(21);i.CordovaPopupNavigator=(function(){function l(){(function(f,d){if(!(f instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(f){var d=new a.CordovaPopupWindow(f);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaIFrameNavigator=void 0;var a=s(21);i.CordovaIFrameNavigator=(function(){function l(){(function(f,d){if(!(f instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(f){f.popupWindowFeatures="hidden=yes";var d=new a.CordovaPopupWindow(f);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"},a=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:s,body:JSON.stringify(i)});if(a.ok){const l=await a.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 a.status===400&&processErrorResponse(await a.json(),n),new Error(`Dynamic client registration failed: the server returned ${a.status} ${a.statusText} - ${await a.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 a;i&&(a=await generateDpopKeyPair(),s.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",a)),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:m}=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:m,dpopKey:a,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 a={};i!==void 0&&(a={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:{...a,...l,"Content-Type":"application/x-www-form-urlencoded"}});let f;try{f=await u.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const d=validateTokenEndpointResponse(f,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(a){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${a.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,a,l,u,f,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:f,clientAppId:s,clientAppSecret:a,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,a,l){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=a,this.fetch=l,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=a}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"),a=await this.storageUtility.getForUser(s,"sessionId",{errorIfNull:!0}),{issuerConfig:l,codeVerifier:u,redirectUrl:f,dpop:d}=await loadOidcContextFromStorage(a,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 ${a} is missing from storage.`);if(f===void 0)throw new Error(`The redirect URL for session ${a} is missing from storage.`);const g=await this.clientRegistrar.getClient({sessionId:a},l),m=Date.now(),v=await getTokens(l,g,{grantType:"authorization_code",code:i.searchParams.get("code"),codeVerifier:u,redirectUrl:f},d);window.localStorage.removeItem(`oidc.${s}`);let S;v.refreshToken!==void 0&&(S={sessionId:a,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,a,v.webId,v.clientId,"true",void 0,!0);const w=await this.sessionInfoManager.get(a);if(!w)throw new Error(`Could not retrieve session: [${a}].`);return Object.assign(w,{fetch:E,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:v.idToken,endSessionEndpoint:l.endSessionEndpoint}),expirationDate:typeof v.expiresIn=="number"?m+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,a,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})]),f=a!==void 0?Number.parseInt(a,10):-1,d=s!==void 0&&f!==0&&Math.floor(Date.now()/1e3)>f;if(i&&isKnownClientType(u)&&!d)return s!==void 0?{clientId:i,clientSecret:s,clientName:l,clientType:"dynamic",expiresAt:f}:{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"),a=i.searchParams.get("error_description");t.emit(EVENTS.ERROR,s,a)}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 a=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),l=await this.clientRegistrar.getClient({sessionId:e},a.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(a.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,a.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),a=new IssuerConfigFetcher(s),l=new ClientRegistrar(s),u=new SessionInfoManager(s),f=new TokenRefresher(s,a,l),d=new Redirector,p=new OidcLoginHandler(s,new AuthorizationCodeWithPkceOidcHandler(s,d),a,l),g=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(s,u,a,l,f,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(p,g,new IWaterfallLogoutHandler(u,d),u,a)}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;xpodErrorLogout=Promise.resolve();constructor(e={},t=void 0){this.events=new EventEmitter,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=getClientAuthenticationWithDependencies({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage,fetch:e.fetch}):this.clientAuthentication=getClientAuthenticationWithDependencies({fetch:e.fetch}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??v4(),isLoggedIn:!1},this.events.on(EVENTS.LOGIN,()=>window.localStorage.setItem(KEY_CURRENT_SESSION,this.info.sessionId)),this.events.on(EVENTS.SESSION_EXPIRED,()=>this.internalLogout(!1)),this.events.on(EVENTS.ERROR,()=>{this.xpodErrorLogout=this.xpodErrorLogout.then(()=>this.internalLogout(!1),()=>this.internalLogout(!1)),this.xpodErrorLogout.catch(()=>{})})}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(KEY_CURRENT_SESSION),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(EVENTS.LOGOUT)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t=typeof e=="string"?{url:e}:e,i=t.url??window.location.href;this.tokenRequestInProgress=!0;const s=await this.clientAuthentication.handleIncomingRedirect(i,this.events);try{await this.xpodErrorLogout}catch(a){throw this.tokenRequestInProgress=!1,a}if(isLoggedIn(s)){this.setSessionInfo(s);const a=window.localStorage.getItem(KEY_CURRENT_URL);a===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,a))}else if(t.restorePreviousSession===!0){const a=window.localStorage.getItem(KEY_CURRENT_SESSION);if(a!==null&&await silentlyAuthenticate(a,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,a,l=!1,u=!1,f,d=!1;const p=w=>{if(i=w,d||areSnapshotsEqual(s,i))return i;s=i;for(const A of t)A(i);return i},g=()=>p(snapshotFromSessionInfo(e.info)),m=()=>p({status:"anonymous"}),v=()=>p(snapshotFromSessionExpired(e.info)),S=(w,A)=>{const C=snapshotFromSessionError(A??w??"Solid session error",e.info);u&&(f=C),p(C)};e.events.on(EVENTS.LOGIN,g),e.events.on(EVENTS.SESSION_RESTORED,g),e.events.on(EVENTS.LOGOUT,m),e.events.on(EVENTS.SESSION_EXPIRED,v);const E=e.events;return E.on(EVENTS.ERROR,S),{fetch:e.fetch,getSnapshot(){return i},initialize(w={}){if(a)return a;if(l)return Promise.resolve(i);u=!0,f=void 0,p({status:"initializing"});const A=e.handleIncomingRedirect({restorePreviousSession:w.restorePreviousSession??!0}).then(C=>{const T=snapshotFromSessionInfo(C??e.info);return T.status==="anonymous"&&f?.status==="error"?f:(l=!0,p(T))}).catch(C=>p(snapshotFromSessionError(C,e.info))).finally(()=>{a===A&&(a=void 0,u=!1,f=void 0)});return a=A,a},handleIncomingRedirect(w){if(a)return a;u=!0,f=void 0,p({status:"initializing"});const A=e.handleIncomingRedirect(w).then(C=>{const T=snapshotFromSessionInfo(C??e.info);return T.status==="anonymous"&&f?.status==="error"?f:(l=!0,p(T))}).catch(C=>p(snapshotFromSessionError(C,e.info))).finally(()=>{a===A&&(a=void 0,u=!1,f=void 0)});return a=A,A},login(w){return e.login(w)},async logout(w){await e.logout(w),p({status:"anonymous"})},subscribe(w){return t.add(w),()=>{t.delete(w)}},dispose(){d=!0,t.clear(),e.events.off(EVENTS.LOGIN,g),e.events.off(EVENTS.SESSION_RESTORED,g),e.events.off(EVENTS.LOGOUT,m),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,a=new Map,l=new Map,u=new Map,f=(g,m)=>{const v=normalizeIdentityPart(g);if(m!==void 0){const w=normalizePodUrl(m),A=compositeKey(g,w);nextGeneration(u,A),a.get(A)?.controller.abort(),a.delete(A),i.delete(A);const C=t.get(v);C&&compositeKey(C.webId,C.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 w of[...i.keys()])w.startsWith(E)&&i.delete(w);for(const[w,A]of[...a.entries()])w.startsWith(E)&&(nextGeneration(u,w),A.controller.abort(),a.delete(w))},d=g=>{if(!g){t.clear(),i.clear();for(const m of s.values())m.controller.abort();for(const m of a.values())m.controller.abort();s.clear(),a.clear();for(const m of l.keys())nextGeneration(l,m);for(const m of u.keys())nextGeneration(u,m);return}if(typeof g=="string"){f(g);return}f(g.webId,g.podUrl)};return{open(g){const m=normalizeIdentityPart(g.webId),v=g.podUrl===void 0?void 0:normalizePodUrl(g.podUrl);if(v!==void 0){const M=compositeKey(g.webId,v),O=i.get(M);if(O)return Promise.resolve(O);const Q=a.get(M);if(Q)return Q.promise;const pe=u.get(M)??0;u.set(M,pe);const q=new AbortController,ee=()=>!q.signal.aborted&&(u.get(M)??0)===pe,_e=()=>{if(!ee())throw createAbortedOpenError()},te=p({webId:g.webId,podUrl:v,fetch:g.fetch,signal:q.signal,isCurrent:ee,assertCurrent:_e});a.set(M,{generation:pe,promise:te,controller:q});const Ie=()=>{const De=a.get(M);De?.generation===pe&&De.promise===te&&a.delete(M)};return te.then(Ie,Ie),te}const S=t.get(m);if(S)return Promise.resolve(S);const E=s.get(m);if(E)return E.promise;const w=l.get(m)??0;l.set(m,w);const A=new AbortController,C=()=>!A.signal.aborted&&(l.get(m)??0)===w,T=()=>{if(!C())throw createAbortedOpenError()},F=(async()=>{const M=await e.discoverPod({webId:g.webId,fetch:g.fetch,signal:A.signal,isCurrent:C});return T(),p({webId:g.webId,podUrl:normalizePodUrl(M),fetch:g.fetch,signal:A.signal,isCurrent:C,assertCurrent:T,generation:w,webIdKey:m,discovered:!0})})();s.set(m,{generation:w,promise:F,controller:A});const P=()=>{const M=s.get(m);M?.generation===w&&M.promise===F&&s.delete(m)};return F.then(P,P),F},clear:d,dispose(){d()}};async function p(g){const m=compositeKey(g.webId,g.podUrl),v=i.get(m);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(m,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(a=>a==="..")||!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,a)=>a.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(),a=resolveSolidLocalRouteUrl(i,s);if(!a)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const l=routedHeaders(e,t,i,a);let u;if(e instanceof Request){const d=new Request(new Request(a,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,a,{...t,headers:l});const f=resolveSolidLocalRouteUrl(u.url,s.map(d=>({canonicalBaseUrl:d.localBaseUrl,localBaseUrl:d.canonicalBaseUrl})));return f?withResponseUrl(u,f.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),a=new URL(s,i);return a.search=n.search,a.hash=n.hash,a}function routedHeaders(n,e,t,i){const s=n instanceof Request?n:void 0,a=new Headers(s?.headers??void 0);return new Headers(e?.headers??void 0).forEach((l,u)=>a.set(u,l)),a.set(SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER,t.toString()),a.set(SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER,t.origin),a.set(SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER,t.host),a.set(SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER,i.toString()),a}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,a=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||s!==i||a!==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_DEFAULT_RETURN_PATH="/ai-connections",LEGACY_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,[LEGACY_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},productSurfaceRoots=[{app:"dashboard",basename:"/dashboard"},{app:"dashboard",basename:"/status"},{app:"dashboard",basename:"/network"},{app:"settings",basename:"/settings"},{app:"settings",basename:"/ai-connections"},{app:"settings",basename:"/ai-config"}];function canonicalProductPathname(n){return legacyProductRedirects[n]??n}function hasInvalidWebIdWhitespace(n){return n!==n.trim()||/[\r\n\t]/.test(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",XPOD_SELECTED_STORAGE_BINDING_TTL_MS=1440*60*1e3;class XpodLoginTransactionError extends Error{code;constructor(e,t){super(t),this.name="XpodLoginTransactionError",this.code=e}}function rememberXpodSelectedStorage(n,e={}){const t=e.storage??getOptionalPersistentStorage$1()??getOptionalSessionStorage$1();if(!t)throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable");const i=new URL(e.origin??getWindowOrigin()).origin,s=e.storageRoot??i,a=normalizeSelectedStorageBinding(n,s,e.storageRoot===void 0),u=(e.now??(()=>Date.now()))(),f={version:XPOD_SELECTED_STORAGE_BINDING_VERSION,createdAt:u,expiresAt:u+(e.ttlMs??XPOD_SELECTED_STORAGE_BINDING_TTL_MS),binding:a,...e.storageRoot===void 0?{}:{storageRoot:normalizeStorageRoot$1(e.storageRoot)}};t.setItem(XPOD_SELECTED_STORAGE_BINDING_KEY,JSON.stringify(f))}function readXpodSelectedStorage(n={}){return n.storage?readXpodSelectedStorageFrom(n.storage,n):readXpodSelectedStorageFrom(getOptionalPersistentStorage$1(),n)??readXpodSelectedStorageFrom(getOptionalSessionStorage$1(),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 a=e.now??(()=>Date.now());if(s.expiresAt<=a()){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$1()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY),getOptionalSessionStorage$1()?.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,a=n.prefix??XPOD_LOGIN_TRANSACTION_PREFIX,l=`${a}.active`,u=m=>`${a}.record.${m}`,f=m=>`${a}.consumed.${m}`,d=m=>{e.getItem(l)===m&&e.removeItem(l),e.removeItem(u(m))},p=(m,v=!0)=>{if(!isSafeTransactionId(m))throw new XpodLoginTransactionError("malformed","Transaction id is malformed");if(e.getItem(f(m))==="1")throw new XpodLoginTransactionError("consumed","Transaction has already been consumed");if(v&&e.getItem(l)!==m)throw new XpodLoginTransactionError("unknown","Transaction is not the active Xpod login transaction");const S=e.getItem(u(m));if(!S)throw v&&e.getItem(l)===m&&e.removeItem(l),new XpodLoginTransactionError("unknown","Xpod login transaction was not found");let E;try{E=JSON.parse(S)}catch{throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}if(!isStoredTransaction(E)||E.transaction.id!==m)throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed");if(E.expiresAt<=i())throw d(m),new XpodLoginTransactionError("expired","Xpod login transaction has expired");try{const w=normalizePublicTransaction({...E.transaction,authorizationSurface:"redirect",discovery:"strict"},t);return E.transaction={id:w.id,route:w.route,...w.returnTo===void 0?{}:{returnTo:w.returnTo},...w.prompt===void 0?{}:{prompt:w.prompt},...w.selectedStorage===void 0?{}:{selectedStorage:w.selectedStorage}},E}catch(w){throw d(m),w instanceof XpodLoginTransactionError?w:new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}};return{begin:m=>{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(m.id)?m.id:createOpaqueTransactionId(),E=normalizePublicTransaction({...m,id:S},t),w=i(),A=w+s,C={version:XPOD_LOGIN_TRANSACTION_VERSION,createdAt:w,expiresAt:A,transaction:{id:E.id,route:E.route,...E.returnTo===void 0?{}:{returnTo:E.returnTo},...E.prompt===void 0?{}:{prompt:E.prompt},...E.selectedStorage===void 0?{}:{selectedStorage:E.selectedStorage}}};return e.setItem(u(E.id),JSON.stringify(C)),e.setItem(l,E.id),E},readSinglePending(){const m=e.getItem(l);if(m)return materialize(p(m).transaction)},updateSelectedStorage(m,v){const S=p(m),E=materialize(S.transaction),w=normalizeBinding$1(v,t,E.route.storageProvider?.url),A={...S,transaction:{...S.transaction,selectedStorage:w}};e.setItem(u(m),JSON.stringify(A))},consume(m){const v=p(m),S=materialize(v.transaction);return e.removeItem(l),e.removeItem(u(m)),e.setItem(f(m),"1"),S},cancel(m){p(m),e.removeItem(l),e.removeItem(u(m)),e.setItem(f(m),"1")}}}function normalizePublicTransaction(n,e){let t;try{t=normalizeWebIdLoginTransaction(n)}catch(a){throw new XpodLoginTransactionError("malformed",a instanceof Error?a.message:"Transaction is malformed")}let i;try{i=assertXpodLoginRoute(t.route,e)}catch(a){throw new XpodLoginTransactionError("cross_origin",a instanceof Error?a.message:"Transaction route is not local")}let s;try{s=normalizeXpodReturnTo(t.returnTo)}catch(a){throw new XpodLoginTransactionError("mismatch",a instanceof Error?a.message:"Transaction return path is unsafe")}if(t.selectedStorage!==void 0)try{const a=normalizeBinding$1(t.selectedStorage,e,i.storageProvider?.url);return{id:t.id,route:i,selectedStorage:a,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}catch(a){throw a instanceof XpodLoginTransactionError?a:new XpodLoginTransactionError("mismatch","Selected storage binding is invalid")}return{id:t.id,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}function normalizeBinding$1(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))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:n.webId,...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.prompt===void 0?{}:{prompt:n.prompt},...n.selectedStorage===void 0?{}:{selectedStorage:n.selectedStorage}}}function normalizeSelectedStorageBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))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:n.webId}}function normalizeStorageRoot$1(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$1(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$1(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function getOptionalPersistentStorage$1(){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"}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(n=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(n));for(let i=0;i<n;i++)e+=urlAlphabet[t[i]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<n;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=n=>typeof n=="object"&&n!==null&&typeof n.value=="string",hasTermValue=n=>typeof n=="object"&&n!==null&&typeof n.term=="object"&&n.term!==null&&typeof n.term?.value=="string",resolveTermIri=n=>{if(typeof n=="string")return n;if(hasStringValue$2(n))return n.value;if(hasTermValue(n))return n.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=n.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:i,query:s}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:i,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,i,s=!1){this[SubqueryConfig]={sql:e,selection:t,alias:i,isWith:s}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const s=(is(e,Subquery)?e[SubqueryConfig].selection:is(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is(s,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;const a=s.clone();return a.isSelectionField=!0,a}if(is(s,SQL)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(s,Column)?this.config.alias?new Proxy(s,new ColumnAliasProxyHandler(new Proxy(s.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new SelectionProxyHandler(this.config))}}function orderSelectedFields(n,e){return Object.entries(n).reduce((t,[i,s])=>{if(typeof i!="string")return t;const a=e?[...e,i]:[i];return is(s,Column)||is(s,SQL)||is(s,SQL.Aliased)?t.push({path:a,field:s}):is(s,Table)?t.push(...orderSelectedFields(s[Table.Symbol.Columns],a)):t.push(...orderSelectedFields(s,a)),t},[])}function applyMixins(n,e){for(const t of e)for(const i of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(n.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))}function getTableLikeName(n){return is(n,Subquery)?n[SubqueryConfig].alias:is(n,View)?n[ViewBaseConfig].name:is(n,SQL)?void 0:n[Table.Symbol.IsAlias]?n[Table.Symbol.Name]:n[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,i){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=i}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(n,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:a,withList:l,distinct:u}){super(),this.config={withList:l,table:e,fields:{...t},distinct:u},this.isPartialSelect=i,this.session=s,this.dialect=a,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,i)=>{const s=this.tableName,a=getTableLikeName(t);if(typeof a=="string"&&this.config.joins?.some(l=>l.alias===a))throw new Error(`Alias "${a}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof a=="string"&&!is(t,SQL))){const l=is(t,Subquery)?t[SubqueryConfig].selection:is(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[a]=l}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:t,joinType:e,alias:a}),typeof a=="string")switch(e){case"left":{this.joinsNotNullableMap[a]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[a]=!0;break}case"inner":{this.joinsNotNullableMap[a]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[a]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:i,dialect:s,joinsNotNullableMap:a}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const l=orderSelectedFields(i.fields),u=t.prepareQuery(s.sqlToQuery(this.getSQL()),l,e);return u.joinsNotNullableMap=a,u})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,i){this.sourceTable=e,this.referencedTable=t,this.relationName=i,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(n){return typeof n=="object"&&n!==null&&"getSQL"in n&&typeof n.getSQL=="function"}function mergeQueries(n){const e={sql:"",params:[]};for(const t of n)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const i=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){const i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:s,escapeParam:a,prepareTyping:l,inlineParams:u,paramStartIndex:f}=i;return mergeQueries(e.map(d=>{if(is(d,StringChunk))return{sql:d.value.join(""),params:[]};if(is(d,Name))return{sql:s(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){const p=[new StringChunk("(")];for(const[g,m]of d.entries())p.push(m),g<d.length-1&&p.push(new StringChunk(", "));return p.push(new StringChunk(")")),this.buildQueryFromSourceParams(p,i)}if(is(d,SQL))return this.buildQueryFromSourceParams(d.queryChunks,{...i,inlineParams:u||d.shouldInlineParams});if(is(d,Table)){const p=d[Table.Symbol.Schema],g=d[Table.Symbol.Name];return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Column))return{sql:s(d.table[Table.Symbol.Name])+"."+s(d.name),params:[]};if(is(d,View)){const p=d[ViewBaseConfig].schema,g=d[ViewBaseConfig].name;return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Param)){const p=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(is(p,SQL))return this.buildQueryFromSourceParams([p],i);if(u)return{sql:this.mapInlineParam(p,i),params:[]};let g;return l!==void 0&&(g=[l(d.encoder)]),{sql:a(f.value++,p),params:[p],typings:g}}return is(d,Placeholder)?{sql:a(f.value++,d),params:[d]}:is(d,SQL.Aliased)&&d.fieldAlias!==void 0?{sql:s(d.fieldAlias),params:[]}:is(d,Subquery)?d[SubqueryConfig].isWith?{sql:s(d[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),d[SubqueryConfig].sql,new StringChunk(") "),new Name(d[SubqueryConfig].alias)],i):isSQLWrapper(d)?this.buildQueryFromSourceParams([new StringChunk("("),d.getSQL(),new StringChunk(")")],i):is(d,Relation)?this.buildQueryFromSourceParams([d.sourceTable,new StringChunk("."),sql.identifier(d.fieldName)],i):u?{sql:this.mapInlineParam(d,i),params:[]}:{sql:a(f.value++,d),params:[d]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:n=>n},noopEncoder={mapToDriverValue:n=>n};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new StringChunk(n[0]));for(const[i,s]of e.entries())t.push(s,new StringChunk(n[i+1]));return new SQL(t)}(function(n){function e(){return new SQL([])}n.empty=e;function t(f){return new SQL(f)}n.fromList=t;function i(f){return new SQL([new StringChunk(f)])}n.raw=i;function s(f,d){const p=[];for(const[g,m]of f.entries())g>0&&d!==void 0&&p.push(d),p.push(m);return new SQL(p)}n.join=s;function a(f){return new Name(f)}n.identifier=a;function l(f){return new Placeholder(f)}n.placeholder=l;function u(f,d){return new Param(f,d)}n.param=u})(sql||(sql={}));(function(n){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(i,s){this.sql=i,this.fieldAlias=s}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}n.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const s=e[Table.Symbol.Columns];if(!s)return s;const a={};return Object.keys(s).map(l=>{a[l]=new Proxy(s[l],new ColumnAliasProxyHandler(new Proxy(e,this)))}),a}const i=e[t];return is(i,Column)?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(e,this))):i}}var _a$b;class ColumnBuilder{constructor(e,t,i={},s,a){this.name=e,this.dataType=t,this.options={...i},this._predicateUri=s,this.elementType=a??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,i={},s){this.name=e,this.dataType=t,this.options=i,this.tableName=s}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,i={}){super(e,"array",i),this.elementType=t}}function boolean$2(n,e={}){return new ColumnBuilder(n,"boolean",e)}function timestamp(n,e={}){return new ColumnBuilder(n,"datetime",e)}function object$1(n,e={}){return new ColumnBuilder(n,"object",e)}function uri(n,e={}){return new ColumnBuilder(n,"uri",e)}function id(n="id",e={}){const t=new PodStringColumn(n,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(n,e={}){return new ColumnBuilder(n,"string",e)}function integer$1(n,e={}){return new ColumnBuilder(n,"integer",e)}function date$3(n,e={}){return new ColumnBuilder(n,"datetime",e)}function text(n,e={}){return new ColumnBuilder(n,"string",e)}function real(n,e={}){return new ColumnBuilder(n,"integer",e)}function validateColumnOverride(n,e,t){const i=n.getPredicateUri?.()??n.options?.predicate,s=e.options?.predicate;if(i&&s&&i!==s)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${s}",子 schema 尝试改为 "${i}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(n,e){const t={};for(const[i,s]of Object.entries(n.columns))t[i]=s;for(const[i,s]of Object.entries(e)){const a=n.columns[i];if(a&&!(s instanceof PodColumnBase)){validateColumnOverride(s,a,i);const l=s;!l.getPredicateUri?.()&&!l.options?.predicate&&(l.options={...l.options,predicate:a.options?.predicate})}t[i]=s}return t}function renderDefaultIdTemplate(n,e){if(!/\{[^{}]+\}/.test(n))return n;if(/\{\s*id\s*\}/.test(n))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},i=resolveDate(t,e.now),s={yyyy:String(i.getUTCFullYear()),MM:String(i.getUTCMonth()+1).padStart(2,"0"),dd:String(i.getUTCDate()).padStart(2,"0")};return n.replace(/\{([^{}]+)\}/g,(a,l)=>{const u=l.trim();if(u==="key")return e.key;if(u==="yyyy")return s.yyyy;if(u==="MM")return s.MM;if(u==="dd")return s.dd;const f=resolveExpression(u,t,e);return f==null?"":String(f)})}function resolveDate(n,e=new Date){const t=n.createdAt??n.favoredAt??n.indexedAt??e,i=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(i.getTime())?i:e}function resolveExpression(n,e,t){const i=parseExpression(n);let s=resolveTemplatePath(i.path,e,t);for(const a of i.transforms)s=applyTransform(s,a,i.path,t);return i.selector?applyPathSelector(s,i.selector):s}function parseExpression(n){const e=n.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():n,[i,...s]=t.split("|").map(a=>a.trim()).filter(Boolean);return{path:i??n,transforms:s,selector:e?.[2]?.trim()}}function resolveTemplatePath(n,e,t){const i=n.split("."),s=i[0];return i.reduce((a,l,u)=>{if(typeof a=="string")return s?resolveResourceProperty(a,s,l,t):void 0;if(!(!a||typeof a!="object"))return s&&isResourceProperty(l)&&!((l==="id"||l==="key")&&l in a)?resolveResourceProperty(a,s,l,t):u>0&&l==="id"&&readRef(a)?extractResourceId(a,s??"",t):a[l]},e)}function isResourceProperty(n){return n==="id"||n==="key"||n==="doc"||n==="document"||n==="dir"||n==="owner"}function resolveResourceProperty(n,e,t,i){if(t==="id")return extractResourceId(n,e,i);const s=extractResourceId(n,e,i);if(s){if(t==="key"){const a=extractTemplateValuesForField(n,e,i);return a?.key??a?.id??deriveResourceKey(s)}if(t==="doc"||t==="document")return resourceDocument(s);if(t==="dir"||t==="owner")return deriveOwnerDir(s)}}function applyTransform(n,e,t,i){if(e==="slug")return slugifyValue(String(n??""));const s=extractResourceId(n,t,i);if(e==="resource")return s;if(e==="document")return s?resourceDocument(s):"";if(e==="owner")return s?deriveOwnerDir(s):"";const a=extractTemplateValuesForField(n,t,i);return e==="id"?a?.id??a?.key??s??"":a?.[e]??""}function extractResourceId(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return normalizePodDataResourceId$1(i);if(!isCompleteResourceId$1(i))return renderLinkedResourceId(s,i);const a=relativeSubjectFromRef$1(s,i);return normalizePodDataResourceId$1(a??i)}function extractTemplateValuesForField(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return null;const a=relativeSubjectFromRef$1(s,i)??(isCompleteResourceId$1(i)?null:renderLinkedResourceId(s,i));if(!a)return null;const l=resourceTemplate(s);return l?extractVarsFromTemplate(normalizePodDataResourceId$1(a),l):{id:normalizePodDataResourceId$1(a)}}function resolveLinkedResource(n,e){const t=e.links?.[n];if(t)return t;const i=e.resource?.columns?.[n];return i?.getLinkTable?.()??i?.options?.linkTable??null}function resourceTemplate(n){const e=n.getSubjectTemplate?.()??n.config?.subjectTemplate;if(e)return e;const t=n.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(n,e){const t=resourceTemplate(n);if(!t)return e;const i=n.columns?.id?.options?.defaultValue;return typeof i=="function"?String(i(e,{})):t.replace(/\{([^}]+)\}/g,(s,a)=>{const l=parseTemplateField(a);return l==="id"||l==="key"?e:""})}function readRef(n){if(typeof n=="string"&&n.length>0)return n;if(!n||typeof n!="object")return null;const e=n,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(n){return normalizeResourcePath$1(n.getResourcePath?.()??n.config?.base??"")}function relativeSubjectFromRef$1(n,e){const t=resourcePath(n);if(!t)return normalizePodDataResourceId$1(e);const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const a=e.indexOf(s);if(a<0)continue;let l=e.slice(a+s.length);return l.startsWith("/")&&(l=l.slice(1)),l.length>0?l:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(n,e){let t=0;const i=new Map,s=[];let a=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp$1(e.slice(a,u.index)));const f=`var${t++}`;i.set(f,parseTemplateField(u[1]??"")),s.push(`(?<${f}>.+?)`),a=u.index+u[0].length}s.push(escapeRegExp$1(e.slice(a)));const l=s.join("");try{const u=n.match(new RegExp(`^${l}$`));if(!u?.groups)return null;const f={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);!g||p===void 0||(f[g]=decodeURIComponent(p))}return f}catch{return null}}function parseTemplateField(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(n,e){const t=splitResourcePath(n);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const i=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!i)throw new Error(`Invalid id default path selector [${e}]`);const s=i[1]===""?0:normalizeSliceIndex(Number(i[1]),t.length),a=i[2]===""?t.length:normalizeSliceIndex(Number(i[2]),t.length);return t.slice(s,a).join("/")}function splitResourcePath(n){const e=readRef(n);if(!e)return null;const t=normalizePodDataResourceId$1(e),[i,s]=t.split("#"),a=(i??t).split("/").filter(Boolean);return s&&a.push(s),a}function normalizePodDataResourceId$1(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function normalizeResourcePath$1(n){return n.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function deriveOwnerDir(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#"),i=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):"",a=i.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(a?.[1])return a[1];if(i==="task/index.ttl"&&s&&s!=="this")return`task/${s}`;const l=i.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(l?.[1])return l[1];const u=i.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(u?.[1])return u[1];const f=i.split("/").filter(Boolean);return f.length>1?f.slice(0,-1).join("/"):i}function resourceDocument(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");if(t>=0){const u=e.slice(t+1);if(u&&u!=="this"&&u!=="me"&&u!=="it")return u}const i=resourceDocument(e).replace(/\/+$/u,""),s=i.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const a=i.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(a?.[1])return a[1];const l=i.split("/").filter(Boolean);return l.length>0?l[l.length-1]:e}function slugifyValue(n){return n.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(n,e){return n<0?e+n:n}function normalizeSliceIndex(n,e){const t=n<0?e+n:n;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(n){return n.trim().replace(/^(\.\/)+/,"")}function podResourcePath(n){return normalizeResourcePath(n.getResourcePath?.()??n.config?.base??"")}function podResourceSubjectTemplate(n){return n.getSubjectTemplate?.()??n.config?.subjectTemplate}function podResourceIdDefaultTemplate(n){const e=n.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(n){const e=podResourcePath(n),t=normalizeResourcePath(n.getContainerPath?.()??n.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(n,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(n);return t?`${t}${e}`:e}function templateRelativeSubject(n,e){if((podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n))?.startsWith("#")&&!e.startsWith("#")){const i=e.indexOf("#");if(i>=0)return e.slice(i)}return e}function isBaseRelativeSubjectId$1(n){return!n||/^https?:\/\//.test(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTemplateCompleteResourceId(n,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n);return t?extractTemplateValues(templateRelativeSubject(n,e),t)!==null:!1}function isResourceRelativeSubjectId(n,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)}function relativeSubjectFromRef(n,e){const t=podResourcePath(n);if(!t)return null;const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const a=e.indexOf(s);if(a<0)continue;let l=e.slice(a+s.length);if(l.startsWith("/")&&(l=l.slice(1)),l.length>0)return l}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)?normalizeResourcePath(e):null}function extractTemplateValues(n,e){if(!e.includes("{"))return n===e?{}:null;let t=0;const i=new Map,s=[];let a=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp(e.slice(a,u.index)));const f=`var${t++}`;i.set(f,parseTemplateVariableField$1(u[1]??"")),s.push(`(?<${f}>.+?)`),a=u.index+u[0].length}s.push(escapeRegExp(e.slice(a)));const l=`^${s.join("")}$`;try{const u=n.match(new RegExp(l));if(!u?.groups)return null;const f={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);if(!g||p===void 0)continue;const m=decodeURIComponent(p);if(g in f&&f[g]!==m)return null;f[g]=m}return f}catch{return null}}function escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(n,e){if(!e)return null;const t=relativeSubjectFromRef(n,e);if(!t)return null;const i=qualifyFragmentResourceId(n,t),s=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n),a=s?extractTemplateValues(templateRelativeSubject(n,i),s):{id:decodeURIComponent(i)};return a?{resourceId:decodeURIComponent(i),templateValues:a}:null}function extractPodResourceTemplateValue(n,e,t="id"){return parsePodResourceRef(n,e)?.templateValues[t]??null}function resolvePodBaseUrl(n){const e=n.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getDialect=="function"?e.getDialect():null,i=readPodUrl(t);if(i)return resolvePodBaseUrl(i);const s=typeof e.getSession=="function"?e.getSession():e.session,a=readPodUrl(s);if(a)return resolvePodBaseUrl(a);const l=readWebId(s);return l&&l.includes("/profile/card#me")?resolvePodBaseUrl(l):null}function normalizePodDataResourceId(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function resolvePodResourceId(n,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(n,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(n,e),normalizePodDataResourceId(e);const i=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!i)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(i)||isTemplateCompleteResourceId(n,i))return normalizePodDataResourceId(i);const s=resolveDefaultResourceId(n,i,e);if(s)return normalizePodDataResourceId(s);const a=podResourceSubjectTemplate(n);return normalizePodDataResourceId(a?renderSubjectTemplateResourceId(a,i,e):i)}function buildPodResourceIri(n,e){const t=resolvePodBaseUrl(n);if(!t||/^https?:\/\//u.test(e))return e;const i=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(i.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(n,e,t){const i=resolveKnownTargetIri(t);if(i)return i;const s=resolvePodRootTargetPath(t);if(s)return buildPodResourceIri(n,s);const a=resolvePodResourceId(e,t),l=isResourceRelativeSubjectId(e,a)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(a)}`:e.resolveUri?.(a)??`/.data/${normalizePodDataResourceId(a)}`;return buildPodResourceIri(n,l)}function buildPodResourceIriForDatabase(n,e,t){const i=resolvePodBaseUrlFromDatabase(n);if(!i)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(i,e,t)}function resolvePodResourceIriForDatabase(n,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(n,e,t)}catch{return null}}function resolveKnownTargetIri(n){if(typeof n=="string")return/^https?:\/\//u.test(n)?n:null;const e=n["@id"]??n.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(n){if(typeof n=="string")return n.startsWith("/")?n:null;const e=typeof n.id=="string"?n.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function assertCompleteStringResourceId(n,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(n,e))return;const t=n.columns?.id?.options?.defaultValue!==void 0,i=podResourceSubjectTemplate(n);if(t||i)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(n,e,t){const i=n.columns?.id?.options?.defaultValue;if(i===void 0)return null;if(typeof i=="string")return renderDefaultIdTemplate(i,{key:e,row:t,resource:n});if(typeof i!="function")return String(i);const s=i;return s.length===0?String(s()):String(s(e,t))}function renderSubjectTemplateResourceId(n,e,t){const i=n.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(i,{key:encodeURIComponent(e),row:t})}function readPodUrl(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(n){if(!n||typeof n!="object")return null;const e=n,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,i){this.initialized=!1;const s=i.type;if(!s)throw new Error("podTable requires a type (RDF class) via options.type");const a=i.typeIndex,l=a==="private"||a==="public",u=this.resolveBase(i.base,e);this.resourcePath=u.resourcePath,this.containerPath=u.containerPath;const f=this.resolveSubjectTemplate(i.subjectTemplate,u.resourcePath,u.containerPath,e);this.subjectTemplate=f.template,this.hasCustomSubjectTemplate=f.isCustom,this.resourceMode=i.resourceMode??(i.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=i.sparqlEndpoint,this.registerTypeIndexEnabled=l&&i.autoRegister!==!1,this.config={name:e,base:u.resourcePath,type:resolveTermIri(s),namespace:i.namespace,typeIndex:l?a:void 0,saiRegistryPath:i.saiRegistryPath,autoRegister:i.autoRegister,containerPath:u.containerPath,hooks:i.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(i.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let d=0;for(const p of Object.values(t))if(p.options.primaryKey&&d++,p.table=this,p.tableName=e,!p.options.predicate&&!p._virtualId&&!i.namespace)throw new Error(`Column "${p.name}" in table "${e}" is missing a predicate.`);if(d!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${d}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const i=t.replace(/\{id\}/g,e);return i.startsWith("#")?`${this.resourcePath}${i}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${i}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const i=this.normalizeBaseInput(e),s=this.normalizeResourcePath(i);if(s.endsWith("/")){const l=this.ensureTrailingSlash(s);return{resourcePath:l,containerPath:l}}const a=this.ensureTrailingSlash(this.deriveContainerPath(s));return{resourcePath:s,containerPath:a}}normalizeBaseInput(e){const t=e.trim(),i=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(i){const[,s,a]=i,l=s.toLowerCase(),u=a.trim();return l==="http"||l==="https"?`${l}://${u}`:u.startsWith("/")?u:`/${u}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const i=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return i.startsWith("/")?i:`/${i}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,i=t.lastIndexOf("/");return i===-1?"/":t.slice(0,i+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,i,s){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const i=(Array.isArray(e)?e:[e]).map(s=>resolveTermIri(s)).filter(s=>s&&s.length>0);return Array.from(new Set(i))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(n,e,t){const i={};for(const[s,a]of Object.entries(e)){if(a instanceof PodColumnBase){i[s]=a;continue}let l;switch(a.dataType){case"integer":l=new PodIntegerColumn(a.name,a.options);break;case"datetime":l=new PodDateTimeColumn(a.name,a.options);break;case"boolean":l=new PodBooleanColumn(a.name,a.options);break;case"json":l=new PodJsonColumn(a.name,a.options);break;case"object":l=new PodObjectColumn(a.name,a.options);break;case"array":{const f=a.elementType??a.options.baseType??"string";l=new PodArrayColumn(a.name,f,a.options);break}case"uri":l=new PodUriColumn(a.name,a.options);break;default:l=new PodStringColumn(a.name,a.options);break}const u=a.getPredicateUri?.();u&&l.predicate(u),i[s]=l}return new PodTable(n,i,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const i=mergeSchemaColumns(this,e),s=[this.type];return this.subClassOf&&s.push(...this.subClassOf),solidSchema(i,{...t,subClassOf:s})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(n,e){const t={};for(const[i,s]of Object.entries(n)){if(s instanceof PodColumnBase){t[i]=s;continue}let a;switch(s.dataType){case"integer":a=new PodIntegerColumn(s.name,s.options);break;case"datetime":a=new PodDateTimeColumn(s.name,s.options);break;case"boolean":a=new PodBooleanColumn(s.name,s.options);break;case"json":a=new PodJsonColumn(s.name,s.options);break;case"object":a=new PodObjectColumn(s.name,s.options);break;case"array":{const u=s.elementType??s.options.baseType??"string";a=new PodArrayColumn(s.name,u,s.options);break}case"uri":a=new PodUriColumn(s.name,s.options);break;default:a=new PodStringColumn(s.name,s.options);break}const l=s.getPredicateUri?.();l&&a.predicate(l),t[i]=a}return new SolidSchema(t,e)}function isSolidSchema(n){return n instanceof SolidSchema||n?.$kind==="SolidSchema"}const index=Object.freeze(Object.defineProperty({__proto__:null,ColumnBuilder,PodArrayColumn,PodBooleanColumn,PodColumnBase,PodDateTimeColumn,PodIntegerColumn,PodJsonColumn,PodObjectColumn,PodStringColumn,PodTable,PodUriColumn,SolidSchema,boolean:boolean$2,date:date$3,generateNanoId,hasStringValue:hasStringValue$2,hasTermValue,id,integer:integer$1,isSolidSchema,mergeSchemaColumns,object:object$1,podTable,real,resolveTermIri,solidSchema,string:string$2,text,timestamp,uri,validateColumnOverride},Symbol.toStringTag,{value:"Module"})),XSD$9="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(n,e){if(!n)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const s=e.getMapping()?.columns?.[n.name];if(s?.predicate)return s.predicate}if(typeof n.getPredicateUri=="function")return n.getPredicateUri();if(n._predicateUri)return n._predicateUri;if(n.predicate&&typeof n.predicate=="string")return n.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof n.getPredicate=="function")try{return n.getPredicate(t)}catch{}return n.options?.predicate?n.options.predicate:t?`${typeof t=="string"?t:t.uri}${n.name}`:(n.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",n),`http://example.org/${n.name}`)}function formatValue(n,e,t,i){return Array.isArray(n)?n.map(s=>formatSingleValue(s,e,t,i)):formatSingleValue(n,e,t,i)}function formatSingleValue(n,e,t,i){if(n==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const s=String(n);if(s.startsWith("<")&&s.endsWith(">")){const a=s.slice(1,-1);return t&&!t.isAbsoluteUri(a)?`<${t.resolveLink(a,e,i)}>`:s}return t?`<${t.resolveLink(s,e,i)}>`:s.startsWith("<")?s:`<${s}>`}return typeof n=="string"?!e&&(n.startsWith("http://")||n.startsWith("https://"))?`<${n}>`:`"${n.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof n=="number"?Number.isInteger(n)?String(n):`"${n}"^^<${XSD$9}decimal>`:typeof n=="boolean"?`"${n}"^^<${XSD$9}boolean>`:n instanceof Date?`"${n.toISOString()}"^^<${XSD$9}dateTime>`:`"${String(n)}"`}function resolveColumn(n,e){if(n&&typeof n=="object"&&n instanceof PodColumnBase)return n;if(n&&typeof n=="object"&&"name"in n){const t=n.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof n=="string"){const t=e.columns[n];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(n)}`)}function generateSubjectUri(n,e,t){const i=t.resolveSubject(e,n);if(!i)throw new Error("Failed to generate subject URI");return i}const scriptRel="modulepreload",assetsURL=function(n){return"/auth/callback/"+n},seen={},__vitePreload=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let f=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=l?.nonce||l?.getAttribute("nonce");s=f(t.map(d=>{if(d=assetsURL(d),d in seen)return;seen[d]=!0;const p=d.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${g}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":scriptRel,p||(m.as="script"),m.crossOrigin="",m.href=d,u&&m.setAttribute("nonce",u),document.head.appendChild(m),p)return new Promise((v,S)=>{m.addEventListener("load",v),m.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&a(u.reason);return e().catch(a)})};var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,i){super(),this.left=e,this.operator=t,this.right=i,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(n,e){return new BinaryExpression(n,"=",e)}function like(n,e){return new BinaryExpression(n,"LIKE",e)}function inArray(n,e){return new BinaryExpression(n,"IN",e)}function and(...n){return new LogicalExpression("AND",n.filter(Boolean))}function or(...n){return new LogicalExpression("OR",n.filter(Boolean))}function parseActivityStreamsMessage(n){const e=JSON.parse(n);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,i=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!i.ok)throw new Error(`SSE connection failed: ${i.status} ${i.statusText}`);if(!i.body)throw new Error("SSE response has no body");this.contentType=i.headers.get("content-type")||"",this._connected=!0,this.reader=i.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:i,value:s}=await this.reader.read();if(i){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const a=e.decode(s,{stream:!0});t+=a,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(i){i.name!=="AbortError"&&this.handleError(i)}}processTurtleBuffer(e){const t=e.split(`
87
+ `)},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(x,I,k){var J=parseInt(x);if(J<0||255<J)throw"integer not in range 0-255";return("00"+J.toString(16)).slice(-2)})).join("")}catch(x){throw"malformed integer array string: "+x}},i.strdiffidx=function(b,x){var I=b.length;b.length>x.length&&(I=x.length);for(var k=0;k<I;k++)if(b.charCodeAt(k)!=x.charCodeAt(k))return k;return b.length!=x.length?I:-1},i.KJUR=j;var En=j.crypto;i.crypto=En;var gn=j.asn1;i.asn1=gn;var Rn=j.jws;i.jws=Rn;var ws=j.lang;i.lang=ws}).call(this,s(28).Buffer)},function(t,i,s){(function(a){var l=s(30),u=s(31),f=s(32);function d(){return g.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function p(se,B){if(d()<B)throw new RangeError("Invalid typed array length");return g.TYPED_ARRAY_SUPPORT?(se=new Uint8Array(B)).__proto__=g.prototype:(se===null&&(se=new g(B)),se.length=B),se}function g(se,B,N){if(!(g.TYPED_ARRAY_SUPPORT||this instanceof g))return new g(se,B,N);if(typeof se=="number"){if(typeof B=="string")throw new Error("If encoding is specified then the first argument must be a string");return S(this,se)}return m(this,se,B,N)}function m(se,B,N,L){if(typeof B=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&B instanceof ArrayBuffer?(function(re,ce,Ee,G){if(ce.byteLength,Ee<0||ce.byteLength<Ee)throw new RangeError("'offset' is out of bounds");if(ce.byteLength<Ee+(G||0))throw new RangeError("'length' is out of bounds");return ce=Ee===void 0&&G===void 0?new Uint8Array(ce):G===void 0?new Uint8Array(ce,Ee):new Uint8Array(ce,Ee,G),g.TYPED_ARRAY_SUPPORT?(re=ce).__proto__=g.prototype:re=E(re,ce),re})(se,B,N,L):typeof B=="string"?(function(re,ce,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(ce,Ee),Se=(re=p(re,G)).write(ce,Ee);return Se!==G&&(re=re.slice(0,Se)),re})(se,B,N):(function(re,ce){if(g.isBuffer(ce)){var Ee=0|w(ce.length);return(re=p(re,Ee)).length===0||ce.copy(re,0,0,Ee),re}if(ce){if(typeof ArrayBuffer<"u"&&ce.buffer instanceof ArrayBuffer||"length"in ce)return typeof ce.length!="number"||(function(Se){return Se!=Se})(ce.length)?p(re,0):E(re,ce);if(ce.type==="Buffer"&&f(ce.data))return E(re,ce.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(se,B)}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,B){if(v(B),se=p(se,B<0?0:0|w(B)),!g.TYPED_ARRAY_SUPPORT)for(var N=0;N<B;++N)se[N]=0;return se}function E(se,B){var N=B.length<0?0:0|w(B.length);se=p(se,N);for(var L=0;L<N;L+=1)se[L]=255&B[L];return se}function w(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,B){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(B){case"ascii":case"latin1":case"binary":return N;case"utf8":case"utf-8":case void 0:return ye(se).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*N;case"hex":return N>>>1;case"base64":return me(se).length;default:if(L)return ye(se).length;B=(""+B).toLowerCase(),L=!0}}function C(se,B,N){var L=!1;if((B===void 0||B<0)&&(B=0),B>this.length||((N===void 0||N>this.length)&&(N=this.length),N<=0)||(N>>>=0)<=(B>>>=0))return"";for(se||(se="utf8");;)switch(se){case"hex":return Oe(this,B,N);case"utf8":case"utf-8":return te(this,B,N);case"ascii":return De(this,B,N);case"latin1":case"binary":return de(this,B,N);case"base64":return _e(this,B,N);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return le(this,B,N);default:if(L)throw new TypeError("Unknown encoding: "+se);se=(se+"").toLowerCase(),L=!0}}function T(se,B,N){var L=se[B];se[B]=se[N],se[N]=L}function F(se,B,N,L,W){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=W?0:se.length-1),N<0&&(N=se.length+N),N>=se.length){if(W)return-1;N=se.length-1}else if(N<0){if(!W)return-1;N=0}if(typeof B=="string"&&(B=g.from(B,L)),g.isBuffer(B))return B.length===0?-1:P(se,B,N,L,W);if(typeof B=="number")return B&=255,g.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?W?Uint8Array.prototype.indexOf.call(se,B,N):Uint8Array.prototype.lastIndexOf.call(se,B,N):P(se,[B],N,L,W);throw new TypeError("val must be string, number or Buffer")}function P(se,B,N,L,W){var re,ce=1,Ee=se.length,G=B.length;if(L!==void 0&&((L=String(L).toLowerCase())==="ucs2"||L==="ucs-2"||L==="utf16le"||L==="utf-16le")){if(se.length<2||B.length<2)return-1;ce=2,Ee/=2,G/=2,N/=2}function Se(ht,Ge){return ce===1?ht[Ge]:ht.readUInt16BE(Ge*ce)}if(W){var Ce=-1;for(re=N;re<Ee;re++)if(Se(se,re)===Se(B,Ce===-1?0:re-Ce)){if(Ce===-1&&(Ce=re),re-Ce+1===G)return Ce*ce}else Ce!==-1&&(re-=re-Ce),Ce=-1}else for(N+G>Ee&&(N=Ee-G),re=N;re>=0;re--){for(var ge=!0,at=0;at<G;at++)if(Se(se,re+at)!==Se(B,at)){ge=!1;break}if(ge)return re}return-1}function M(se,B,N,L){N=Number(N)||0;var W=se.length-N;L?(L=Number(L))>W&&(L=W):L=W;var re=B.length;if(re%2!=0)throw new TypeError("Invalid hex string");L>re/2&&(L=re/2);for(var ce=0;ce<L;++ce){var Ee=parseInt(B.substr(2*ce,2),16);if(isNaN(Ee))return ce;se[N+ce]=Ee}return ce}function O(se,B,N,L){return Be(ye(B,se.length-N),se,N,L)}function Q(se,B,N,L){return Be((function(re){for(var ce=[],Ee=0;Ee<re.length;++Ee)ce.push(255&re.charCodeAt(Ee));return ce})(B),se,N,L)}function pe(se,B,N,L){return Q(se,B,N,L)}function q(se,B,N,L){return Be(me(B),se,N,L)}function ee(se,B,N,L){return Be((function(re,ce){for(var Ee,G,Se,Ce=[],ge=0;ge<re.length&&!((ce-=2)<0);++ge)G=(Ee=re.charCodeAt(ge))>>8,Se=Ee%256,Ce.push(Se),Ce.push(G);return Ce})(B,se.length-N),se,N,L)}function _e(se,B,N){return B===0&&N===se.length?l.fromByteArray(se):l.fromByteArray(se.slice(B,N))}function te(se,B,N){N=Math.min(se.length,N);for(var L=[],W=B;W<N;){var re,ce,Ee,G,Se=se[W],Ce=null,ge=Se>239?4:Se>223?3:Se>191?2:1;if(W+ge<=N)switch(ge){case 1:Se<128&&(Ce=Se);break;case 2:(192&(re=se[W+1]))==128&&(G=(31&Se)<<6|63&re)>127&&(Ce=G);break;case 3:re=se[W+1],ce=se[W+2],(192&re)==128&&(192&ce)==128&&(G=(15&Se)<<12|(63&re)<<6|63&ce)>2047&&(G<55296||G>57343)&&(Ce=G);break;case 4:re=se[W+1],ce=se[W+2],Ee=se[W+3],(192&re)==128&&(192&ce)==128&&(192&Ee)==128&&(G=(15&Se)<<18|(63&re)<<12|(63&ce)<<6|63&Ee)>65535&&G<1114112&&(Ce=G)}Ce===null?(Ce=65533,ge=1):Ce>65535&&(Ce-=65536,L.push(Ce>>>10&1023|55296),Ce=56320|1023&Ce),L.push(Ce),W+=ge}return(function(ht){var Ge=ht.length;if(Ge<=Ie)return String.fromCharCode.apply(String,ht);for(var gt="",Y=0;Y<Ge;)gt+=String.fromCharCode.apply(String,ht.slice(Y,Y+=Ie));return gt})(L)}i.Buffer=g,i.SlowBuffer=function(B){return+B!=B&&(B=0),g.alloc(+B)},i.INSPECT_MAX_BYTES=50,g.TYPED_ARRAY_SUPPORT=a.TYPED_ARRAY_SUPPORT!==void 0?a.TYPED_ARRAY_SUPPORT:(function(){try{var B=new Uint8Array(1);return B.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},B.foo()===42&&typeof B.subarray=="function"&&B.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,B,N){return m(null,se,B,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,B,N){return(function(W,re,ce,Ee){return v(re),re<=0?p(W,re):ce!==void 0?typeof Ee=="string"?p(W,re).fill(ce,Ee):p(W,re).fill(ce):p(W,re)})(null,se,B,N)},g.allocUnsafe=function(se){return S(null,se)},g.allocUnsafeSlow=function(se){return S(null,se)},g.isBuffer=function(B){return!(B==null||!B._isBuffer)},g.compare=function(B,N){if(!g.isBuffer(B)||!g.isBuffer(N))throw new TypeError("Arguments must be Buffers");if(B===N)return 0;for(var L=B.length,W=N.length,re=0,ce=Math.min(L,W);re<ce;++re)if(B[re]!==N[re]){L=B[re],W=N[re];break}return L<W?-1:W<L?1:0},g.isEncoding=function(B){switch(String(B).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(B,N){if(!f(B))throw new TypeError('"list" argument must be an Array of Buffers');if(B.length===0)return g.alloc(0);var L;if(N===void 0)for(N=0,L=0;L<B.length;++L)N+=B[L].length;var W=g.allocUnsafe(N),re=0;for(L=0;L<B.length;++L){var ce=B[L];if(!g.isBuffer(ce))throw new TypeError('"list" argument must be an Array of Buffers');ce.copy(W,re),re+=ce.length}return W},g.byteLength=A,g.prototype._isBuffer=!0,g.prototype.swap16=function(){var B=this.length;if(B%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var N=0;N<B;N+=2)T(this,N,N+1);return this},g.prototype.swap32=function(){var B=this.length;if(B%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var N=0;N<B;N+=4)T(this,N,N+3),T(this,N+1,N+2);return this},g.prototype.swap64=function(){var B=this.length;if(B%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var N=0;N<B;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 B=0|this.length;return B===0?"":arguments.length===0?te(this,0,B):C.apply(this,arguments)},g.prototype.equals=function(B){if(!g.isBuffer(B))throw new TypeError("Argument must be a Buffer");return this===B||g.compare(this,B)===0},g.prototype.inspect=function(){var B="",N=i.INSPECT_MAX_BYTES;return this.length>0&&(B=this.toString("hex",0,N).match(/.{2}/g).join(" "),this.length>N&&(B+=" ... ")),"<Buffer "+B+">"},g.prototype.compare=function(B,N,L,W,re){if(!g.isBuffer(B))throw new TypeError("Argument must be a Buffer");if(N===void 0&&(N=0),L===void 0&&(L=B?B.length:0),W===void 0&&(W=0),re===void 0&&(re=this.length),N<0||L>B.length||W<0||re>this.length)throw new RangeError("out of range index");if(W>=re&&N>=L)return 0;if(W>=re)return-1;if(N>=L)return 1;if(this===B)return 0;for(var ce=(re>>>=0)-(W>>>=0),Ee=(L>>>=0)-(N>>>=0),G=Math.min(ce,Ee),Se=this.slice(W,re),Ce=B.slice(N,L),ge=0;ge<G;++ge)if(Se[ge]!==Ce[ge]){ce=Se[ge],Ee=Ce[ge];break}return ce<Ee?-1:Ee<ce?1:0},g.prototype.includes=function(B,N,L){return this.indexOf(B,N,L)!==-1},g.prototype.indexOf=function(B,N,L){return F(this,B,N,L,!0)},g.prototype.lastIndexOf=function(B,N,L){return F(this,B,N,L,!1)},g.prototype.write=function(B,N,L,W){if(N===void 0)W="utf8",L=this.length,N=0;else if(L===void 0&&typeof N=="string")W=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,W===void 0&&(W="utf8")):(W=L,L=void 0)}var re=this.length-N;if((L===void 0||L>re)&&(L=re),B.length>0&&(L<0||N<0)||N>this.length)throw new RangeError("Attempt to write outside buffer bounds");W||(W="utf8");for(var ce=!1;;)switch(W){case"hex":return M(this,B,N,L);case"utf8":case"utf-8":return O(this,B,N,L);case"ascii":return Q(this,B,N,L);case"latin1":case"binary":return pe(this,B,N,L);case"base64":return q(this,B,N,L);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ee(this,B,N,L);default:if(ce)throw new TypeError("Unknown encoding: "+W);W=(""+W).toLowerCase(),ce=!0}},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ie=4096;function De(se,B,N){var L="";N=Math.min(se.length,N);for(var W=B;W<N;++W)L+=String.fromCharCode(127&se[W]);return L}function de(se,B,N){var L="";N=Math.min(se.length,N);for(var W=B;W<N;++W)L+=String.fromCharCode(se[W]);return L}function Oe(se,B,N){var L=se.length;(!B||B<0)&&(B=0),(!N||N<0||N>L)&&(N=L);for(var W="",re=B;re<N;++re)W+=We(se[re]);return W}function le(se,B,N){for(var L=se.slice(B,N),W="",re=0;re<L.length;re+=2)W+=String.fromCharCode(L[re]+256*L[re+1]);return W}function Ae(se,B,N){if(se%1!=0||se<0)throw new RangeError("offset is not uint");if(se+B>N)throw new RangeError("Trying to access beyond buffer length")}function $(se,B,N,L,W,re){if(!g.isBuffer(se))throw new TypeError('"buffer" argument must be a Buffer instance');if(B>W||B<re)throw new RangeError('"value" argument is out of bounds');if(N+L>se.length)throw new RangeError("Index out of range")}function H(se,B,N,L){B<0&&(B=65535+B+1);for(var W=0,re=Math.min(se.length-N,2);W<re;++W)se[N+W]=(B&255<<8*(L?W:1-W))>>>8*(L?W:1-W)}function fe(se,B,N,L){B<0&&(B=4294967295+B+1);for(var W=0,re=Math.min(se.length-N,4);W<re;++W)se[N+W]=B>>>8*(L?W:3-W)&255}function ae(se,B,N,L,W,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,B,N,L,W){return W||ae(se,0,N,4),u.write(se,B,N,L,23,4),N+4}function Me(se,B,N,L,W){return W||ae(se,0,N,8),u.write(se,B,N,L,52,8),N+8}g.prototype.slice=function(B,N){var L,W=this.length;if((B=~~B)<0?(B+=W)<0&&(B=0):B>W&&(B=W),(N=N===void 0?W:~~N)<0?(N+=W)<0&&(N=0):N>W&&(N=W),N<B&&(N=B),g.TYPED_ARRAY_SUPPORT)(L=this.subarray(B,N)).__proto__=g.prototype;else{var re=N-B;L=new g(re,void 0);for(var ce=0;ce<re;++ce)L[ce]=this[ce+B]}return L},g.prototype.readUIntLE=function(B,N,L){B|=0,N|=0,L||Ae(B,N,this.length);for(var W=this[B],re=1,ce=0;++ce<N&&(re*=256);)W+=this[B+ce]*re;return W},g.prototype.readUIntBE=function(B,N,L){B|=0,N|=0,L||Ae(B,N,this.length);for(var W=this[B+--N],re=1;N>0&&(re*=256);)W+=this[B+--N]*re;return W},g.prototype.readUInt8=function(B,N){return N||Ae(B,1,this.length),this[B]},g.prototype.readUInt16LE=function(B,N){return N||Ae(B,2,this.length),this[B]|this[B+1]<<8},g.prototype.readUInt16BE=function(B,N){return N||Ae(B,2,this.length),this[B]<<8|this[B+1]},g.prototype.readUInt32LE=function(B,N){return N||Ae(B,4,this.length),(this[B]|this[B+1]<<8|this[B+2]<<16)+16777216*this[B+3]},g.prototype.readUInt32BE=function(B,N){return N||Ae(B,4,this.length),16777216*this[B]+(this[B+1]<<16|this[B+2]<<8|this[B+3])},g.prototype.readIntLE=function(B,N,L){B|=0,N|=0,L||Ae(B,N,this.length);for(var W=this[B],re=1,ce=0;++ce<N&&(re*=256);)W+=this[B+ce]*re;return W>=(re*=128)&&(W-=Math.pow(2,8*N)),W},g.prototype.readIntBE=function(B,N,L){B|=0,N|=0,L||Ae(B,N,this.length);for(var W=N,re=1,ce=this[B+--W];W>0&&(re*=256);)ce+=this[B+--W]*re;return ce>=(re*=128)&&(ce-=Math.pow(2,8*N)),ce},g.prototype.readInt8=function(B,N){return N||Ae(B,1,this.length),128&this[B]?-1*(255-this[B]+1):this[B]},g.prototype.readInt16LE=function(B,N){N||Ae(B,2,this.length);var L=this[B]|this[B+1]<<8;return 32768&L?4294901760|L:L},g.prototype.readInt16BE=function(B,N){N||Ae(B,2,this.length);var L=this[B+1]|this[B]<<8;return 32768&L?4294901760|L:L},g.prototype.readInt32LE=function(B,N){return N||Ae(B,4,this.length),this[B]|this[B+1]<<8|this[B+2]<<16|this[B+3]<<24},g.prototype.readInt32BE=function(B,N){return N||Ae(B,4,this.length),this[B]<<24|this[B+1]<<16|this[B+2]<<8|this[B+3]},g.prototype.readFloatLE=function(B,N){return N||Ae(B,4,this.length),u.read(this,B,!0,23,4)},g.prototype.readFloatBE=function(B,N){return N||Ae(B,4,this.length),u.read(this,B,!1,23,4)},g.prototype.readDoubleLE=function(B,N){return N||Ae(B,8,this.length),u.read(this,B,!0,52,8)},g.prototype.readDoubleBE=function(B,N){return N||Ae(B,8,this.length),u.read(this,B,!1,52,8)},g.prototype.writeUIntLE=function(B,N,L,W){B=+B,N|=0,L|=0,W||$(this,B,N,L,Math.pow(2,8*L)-1,0);var re=1,ce=0;for(this[N]=255&B;++ce<L&&(re*=256);)this[N+ce]=B/re&255;return N+L},g.prototype.writeUIntBE=function(B,N,L,W){B=+B,N|=0,L|=0,W||$(this,B,N,L,Math.pow(2,8*L)-1,0);var re=L-1,ce=1;for(this[N+re]=255&B;--re>=0&&(ce*=256);)this[N+re]=B/ce&255;return N+L},g.prototype.writeUInt8=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,1,255,0),g.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),this[N]=255&B,N+1},g.prototype.writeUInt16LE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8):H(this,B,N,!0),N+2},g.prototype.writeUInt16BE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,2,65535,0),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>8,this[N+1]=255&B):H(this,B,N,!1),N+2},g.prototype.writeUInt32LE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N+3]=B>>>24,this[N+2]=B>>>16,this[N+1]=B>>>8,this[N]=255&B):fe(this,B,N,!0),N+4},g.prototype.writeUInt32BE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,4,4294967295,0),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>24,this[N+1]=B>>>16,this[N+2]=B>>>8,this[N+3]=255&B):fe(this,B,N,!1),N+4},g.prototype.writeIntLE=function(B,N,L,W){if(B=+B,N|=0,!W){var re=Math.pow(2,8*L-1);$(this,B,N,L,re-1,-re)}var ce=0,Ee=1,G=0;for(this[N]=255&B;++ce<L&&(Ee*=256);)B<0&&G===0&&this[N+ce-1]!==0&&(G=1),this[N+ce]=(B/Ee>>0)-G&255;return N+L},g.prototype.writeIntBE=function(B,N,L,W){if(B=+B,N|=0,!W){var re=Math.pow(2,8*L-1);$(this,B,N,L,re-1,-re)}var ce=L-1,Ee=1,G=0;for(this[N+ce]=255&B;--ce>=0&&(Ee*=256);)B<0&&G===0&&this[N+ce+1]!==0&&(G=1),this[N+ce]=(B/Ee>>0)-G&255;return N+L},g.prototype.writeInt8=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,1,127,-128),g.TYPED_ARRAY_SUPPORT||(B=Math.floor(B)),B<0&&(B=255+B+1),this[N]=255&B,N+1},g.prototype.writeInt16LE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8):H(this,B,N,!0),N+2},g.prototype.writeInt16BE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,2,32767,-32768),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>8,this[N+1]=255&B):H(this,B,N,!1),N+2},g.prototype.writeInt32LE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,4,2147483647,-2147483648),g.TYPED_ARRAY_SUPPORT?(this[N]=255&B,this[N+1]=B>>>8,this[N+2]=B>>>16,this[N+3]=B>>>24):fe(this,B,N,!0),N+4},g.prototype.writeInt32BE=function(B,N,L){return B=+B,N|=0,L||$(this,B,N,4,2147483647,-2147483648),B<0&&(B=4294967295+B+1),g.TYPED_ARRAY_SUPPORT?(this[N]=B>>>24,this[N+1]=B>>>16,this[N+2]=B>>>8,this[N+3]=255&B):fe(this,B,N,!1),N+4},g.prototype.writeFloatLE=function(B,N,L){return Pe(this,B,N,!0,L)},g.prototype.writeFloatBE=function(B,N,L){return Pe(this,B,N,!1,L)},g.prototype.writeDoubleLE=function(B,N,L){return Me(this,B,N,!0,L)},g.prototype.writeDoubleBE=function(B,N,L){return Me(this,B,N,!1,L)},g.prototype.copy=function(B,N,L,W){if(L||(L=0),W||W===0||(W=this.length),N>=B.length&&(N=B.length),N||(N=0),W>0&&W<L&&(W=L),W===L||B.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(W<0)throw new RangeError("sourceEnd out of bounds");W>this.length&&(W=this.length),B.length-N<W-L&&(W=B.length-N+L);var re,ce=W-L;if(this===B&&L<N&&N<W)for(re=ce-1;re>=0;--re)B[re+N]=this[re+L];else if(ce<1e3||!g.TYPED_ARRAY_SUPPORT)for(re=0;re<ce;++re)B[re+N]=this[re+L];else Uint8Array.prototype.set.call(B,this.subarray(L,L+ce),N);return ce},g.prototype.fill=function(B,N,L,W){if(typeof B=="string"){if(typeof N=="string"?(W=N,N=0,L=this.length):typeof L=="string"&&(W=L,L=this.length),B.length===1){var re=B.charCodeAt(0);re<256&&(B=re)}if(W!==void 0&&typeof W!="string")throw new TypeError("encoding must be a string");if(typeof W=="string"&&!g.isEncoding(W))throw new TypeError("Unknown encoding: "+W)}else typeof B=="number"&&(B&=255);if(N<0||this.length<N||this.length<L)throw new RangeError("Out of range index");if(L<=N)return this;var ce;if(N>>>=0,L=L===void 0?this.length:L>>>0,B||(B=0),typeof B=="number")for(ce=N;ce<L;++ce)this[ce]=B;else{var Ee=g.isBuffer(B)?B:ye(new g(B,W).toString()),G=Ee.length;for(ce=0;ce<L-N;++ce)this[ce+N]=Ee[ce%G]}return this};var Xe=/[^+\/0-9A-Za-z-_]/g;function We(se){return se<16?"0"+se.toString(16):se.toString(16)}function ye(se,B){var N;B=B||1/0;for(var L=se.length,W=null,re=[],ce=0;ce<L;++ce){if((N=se.charCodeAt(ce))>55295&&N<57344){if(!W){if(N>56319){(B-=3)>-1&&re.push(239,191,189);continue}if(ce+1===L){(B-=3)>-1&&re.push(239,191,189);continue}W=N;continue}if(N<56320){(B-=3)>-1&&re.push(239,191,189),W=N;continue}N=65536+(W-55296<<10|N-56320)}else W&&(B-=3)>-1&&re.push(239,191,189);if(W=null,N<128){if((B-=1)<0)break;re.push(N)}else if(N<2048){if((B-=2)<0)break;re.push(N>>6|192,63&N|128)}else if(N<65536){if((B-=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((B-=4)<0)break;re.push(N>>18|240,N>>12&63|128,N>>6&63|128,63&N|128)}}return re}function me(se){return l.toByteArray((function(N){if((N=(function(W){return W.trim?W.trim():W.replace(/^\s+|\s+$/g,"")})(N).replace(Xe,"")).length<2)return"";for(;N.length%4!=0;)N+="=";return N})(se))}function Be(se,B,N,L){for(var W=0;W<L&&!(W+N>=B.length||W>=se.length);++W)B[W+N]=se[W];return W}}).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),w=E[0],A=E[1];return 3*(w+A)/4-A},i.toByteArray=function(S){var E,w,A=g(S),C=A[0],T=A[1],F=new u((function(Q,pe,q){return 3*(pe+q)/4-q})(0,C,T)),P=0,M=T>0?C-4:C;for(w=0;w<M;w+=4)E=l[S.charCodeAt(w)]<<18|l[S.charCodeAt(w+1)]<<12|l[S.charCodeAt(w+2)]<<6|l[S.charCodeAt(w+3)],F[P++]=E>>16&255,F[P++]=E>>8&255,F[P++]=255&E;return T===2&&(E=l[S.charCodeAt(w)]<<2|l[S.charCodeAt(w+1)]>>4,F[P++]=255&E),T===1&&(E=l[S.charCodeAt(w)]<<10|l[S.charCodeAt(w+1)]<<4|l[S.charCodeAt(w+2)]>>2,F[P++]=E>>8&255,F[P++]=255&E),F},i.fromByteArray=function(S){for(var E,w=S.length,A=w%3,C=[],T=16383,F=0,P=w-A;F<P;F+=T)C.push(m(S,F,F+T>P?P:F+T));return A===1?(E=S[w-1],C.push(a[E>>2]+a[E<<4&63]+"==")):A===2&&(E=(S[w-2]<<8)+S[w-1],C.push(a[E>>10]+a[E>>4&63]+a[E<<2&63]+"=")),C.join("")};for(var a=[],l=[],u=typeof Uint8Array<"u"?Uint8Array:Array,f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,p=f.length;d<p;++d)a[d]=f[d],l[f.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 m(v,S,E){for(var w,A,C=[],T=S;T<E;T+=3)w=(v[T]<<16&16711680)+(v[T+1]<<8&65280)+(255&v[T+2]),C.push(a[(A=w)>>18&63]+a[A>>12&63]+a[A>>6&63]+a[63&A]);return C.join("")}l[45]=62,l[95]=63},function(t,i){i.read=function(s,a,l,u,f){var d,p,g=8*f-u-1,m=(1<<g)-1,v=m>>1,S=-7,E=l?f-1:0,w=l?-1:1,A=s[a+E];for(E+=w,d=A&(1<<-S)-1,A>>=-S,S+=g;S>0;d=256*d+s[a+E],E+=w,S-=8);for(p=d&(1<<-S)-1,d>>=-S,S+=u;S>0;p=256*p+s[a+E],E+=w,S-=8);if(d===0)d=1-v;else{if(d===m)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,a,l,u,f,d){var p,g,m,v=8*d-f-1,S=(1<<v)-1,E=S>>1,w=f===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=u?0:d-1,C=u?1:-1,T=a<0||a===0&&1/a<0?1:0;for(a=Math.abs(a),isNaN(a)||a===1/0?(g=isNaN(a)?1:0,p=S):(p=Math.floor(Math.log(a)/Math.LN2),a*(m=Math.pow(2,-p))<1&&(p--,m*=2),(a+=p+E>=1?w/m:w*Math.pow(2,1-E))*m>=2&&(p++,m/=2),p+E>=S?(g=0,p=S):p+E>=1?(g=(a*m-1)*Math.pow(2,f),p+=E):(g=a*Math.pow(2,E-1)*Math.pow(2,f),p=0));f>=8;s[l+A]=255&g,A+=C,g/=256,f-=8);for(p=p<<f|g,v+=f;v>0;s[l+A]=255&p,A+=C,p/=256,v-=8);s[l+A-C]|=128*T}},function(t,i){var s={}.toString;t.exports=Array.isArray||function(a){return s.call(a)=="[object Array]"}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(u){var f=u.jws,d=u.KeyUtil,p=u.X509,g=u.crypto,m=u.hextob64u,v=u.b64tohex,S=u.AllowedSigningAlgs;return(function(){function E(){(function(A,C){if(!(A instanceof C))throw new TypeError("Cannot call a class as a function")})(this,E)}return E.parseJwt=function(A){a.Log.debug("JoseUtil.parseJwt");try{var C=f.JWS.parse(A);return{header:C.headerObj,payload:C.payloadObj}}catch(T){a.Log.error(T)}},E.validateJwt=function(A,C,T,F,P,M,O){a.Log.debug("JoseUtil.validateJwt");try{if(C.kty==="RSA")if(C.e&&C.n)C=d.getKey(C);else{if(!C.x5c||!C.x5c.length)return a.Log.error("JoseUtil.validateJwt: RSA key missing key material",C),Promise.reject(new Error("RSA key missing key material"));var Q=v(C.x5c[0]);C=p.getPublicKeyFromCertHex(Q)}else{if(C.kty!=="EC")return a.Log.error("JoseUtil.validateJwt: Unsupported key type",C&&C.kty),Promise.reject(new Error(C.kty));if(!(C.crv&&C.x&&C.y))return a.Log.error("JoseUtil.validateJwt: EC key missing key material",C),Promise.reject(new Error("EC key missing key material"));C=d.getKey(C)}return E._validateJwt(A,C,T,F,P,M,O)}catch(pe){return a.Log.error(pe&&pe.message||pe),Promise.reject("JWT validation failed")}},E.validateJwtAttributes=function(A,C,T,F,P,M){F||(F=0),P||(P=parseInt(Date.now()/1e3));var O=E.parseJwt(A).payload;if(!O.iss)return a.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(O.iss!==C)return a.Log.error("JoseUtil._validateJwt: Invalid issuer in token",O.iss),Promise.reject(new Error("Invalid issuer in token: "+O.iss));if(!O.aud)return a.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));if(!(O.aud===T||Array.isArray(O.aud)&&O.aud.indexOf(T)>=0))return a.Log.error("JoseUtil._validateJwt: Invalid audience in token",O.aud),Promise.reject(new Error("Invalid audience in token: "+O.aud));if(O.azp&&O.azp!==T)return a.Log.error("JoseUtil._validateJwt: Invalid azp in token",O.azp),Promise.reject(new Error("Invalid azp in token: "+O.azp));if(!M){var Q=P+F,pe=P-F;if(!O.iat)return a.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(Q<O.iat)return a.Log.error("JoseUtil._validateJwt: iat is in the future",O.iat),Promise.reject(new Error("iat is in the future: "+O.iat));if(O.nbf&&Q<O.nbf)return a.Log.error("JoseUtil._validateJwt: nbf is in the future",O.nbf),Promise.reject(new Error("nbf is in the future: "+O.nbf));if(!O.exp)return a.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(O.exp<pe)return a.Log.error("JoseUtil._validateJwt: exp is in the past",O.exp),Promise.reject(new Error("exp is in the past:"+O.exp))}return Promise.resolve(O)},E._validateJwt=function(A,C,T,F,P,M,O){return E.validateJwtAttributes(A,T,F,P,M,O).then((function(Q){try{return f.JWS.verify(A,C,S)?Q:(a.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed")))}catch(pe){return a.Log.error(pe&&pe.message||pe),Promise.reject(new Error("signature validation failed"))}}))},E.hashString=function(A,C){try{return g.Util.hashString(A,C)}catch(T){a.Log.error(T)}},E.hexToBase64Url=function(A){try{return m(A)}catch(C){a.Log.error(C)}},E})()};var a=s(0);t.exports=i.default},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SigninResponse=void 0;var a=(function(){function f(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&f(d.prototype,p),g&&f(d,g),d}})(),l=s(3);function u(f,d){if(!(f instanceof d))throw new TypeError("Cannot call a class as a function")}i.SigninResponse=(function(){function f(d){var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"#";u(this,f);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 a(f,[{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 m=parseInt(Date.now()/1e3);this.expires_at=m+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}}]),f})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutRequest=void 0;var a=s(0),l=s(3),u=s(9);i.SignoutRequest=function f(d){var p=d.url,g=d.id_token_hint,m=d.post_logout_redirect_uri,v=d.data,S=d.extraQueryParams,E=d.request_type;if((function(C,T){if(!(C instanceof T))throw new TypeError("Cannot call a class as a function")})(this,f),!p)throw a.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");for(var w in g&&(p=l.UrlUtility.addQueryParam(p,"id_token_hint",g)),m&&(p=l.UrlUtility.addQueryParam(p,"post_logout_redirect_uri",m),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,w,S[w]);this.url=p}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SignoutResponse=void 0;var a=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 f=a.UrlUtility.parseUrlFragment(u,"?");this.error=f.error,this.error_description=f.error_description,this.error_uri=f.error_uri,this.state=f.state}},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.InMemoryWebStorage=void 0;var a=(function(){function u(f,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(f,g.key,g)}}return function(f,d,p){return d&&u(f.prototype,d),p&&u(f,p),f}})(),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]},a(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 a=(function(){function T(F,P){for(var M=0;M<P.length;M++){var O=P[M];O.enumerable=O.enumerable||!1,O.configurable=!0,"value"in O&&(O.writable=!0),Object.defineProperty(F,O.key,O)}}return function(F,P,M){return P&&T(F.prototype,P),M&&T(F,M),F}})(),l=s(0),u=s(10),f=s(39),d=s(15),p=s(45),g=s(47),m=s(18),v=s(8),S=s(20),E=s(11),w=s(4);function A(T,F){if(!(T instanceof F))throw new TypeError("Cannot call a class as a function")}function C(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]:{},M=arguments.length>1&&arguments[1]!==void 0?arguments[1]:g.SilentRenewService,O=arguments.length>2&&arguments[2]!==void 0?arguments[2]:m.SessionMonitor,Q=arguments.length>3&&arguments[3]!==void 0?arguments[3]:S.TokenRevocationClient,pe=arguments.length>4&&arguments[4]!==void 0?arguments[4]:E.TokenClient,q=arguments.length>5&&arguments[5]!==void 0?arguments[5]:w.JoseUtil;A(this,F),P instanceof f.UserManagerSettings||(P=new f.UserManagerSettings(P));var ee=C(this,T.call(this,P));return ee._events=new p.UserManagerEvents(P),ee._silentRenewService=new M(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 O(ee)),ee._tokenRevocationClient=new Q(ee._settings),ee._tokenClient=new pe(ee._settings),ee._joseUtil=q,ee}return(function(M,O){if(typeof O!="function"&&O!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof O);M.prototype=Object.create(O&&O.prototype,{constructor:{value:M,enumerable:!1,writable:!0,configurable:!0}}),O&&(Object.setPrototypeOf?Object.setPrototypeOf(M,O):M.__proto__=O)})(F,T),F.prototype.getUser=function(){var M=this;return this._loadUser().then((function(O){return O?(l.Log.info("UserManager.getUser: user loaded"),M._events.load(O,!1),O):(l.Log.info("UserManager.getUser: user not found in storage"),null)}))},F.prototype.removeUser=function(){var M=this;return this.storeUser(null).then((function(){l.Log.info("UserManager.removeUser: user removed from storage"),M._events.unload()}))},F.prototype.signinRedirect=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="si:r";var O={useReplaceToNavigate:M.useReplaceToNavigate};return this._signinStart(M,this._redirectNavigator,O).then((function(){l.Log.info("UserManager.signinRedirect: successful")}))},F.prototype.signinRedirectCallback=function(M){return this._signinEnd(M||this._redirectNavigator.url).then((function(O){return O.profile&&O.profile.sub?l.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinRedirectCallback: no sub"),O}))},F.prototype.signinPopup=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="si:p";var O=M.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return O?(M.redirect_uri=O,M.display="popup",this._signin(M,this._popupNavigator,{startUrl:O,popupWindowFeatures:M.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:M.popupWindowTarget||this.settings.popupWindowTarget}).then((function(Q){return Q&&(Q.profile&&Q.profile.sub?l.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",Q.profile.sub):l.Log.info("UserManager.signinPopup: no sub")),Q}))):(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(M){return this._signinCallback(M,this._popupNavigator).then((function(O){return O&&(O.profile&&O.profile.sub?l.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinPopupCallback: no sub")),O})).catch((function(O){l.Log.error(O.message)}))},F.prototype.signinSilent=function(){var M=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return O=Object.assign({},O),this._loadUser().then((function(Q){return Q&&Q.refresh_token?(O.refresh_token=Q.refresh_token,M._useRefreshToken(O)):(O.request_type="si:s",O.id_token_hint=O.id_token_hint||M.settings.includeIdTokenInSilentRenew&&Q&&Q.id_token,Q&&M._settings.validateSubOnSilentRenew&&(l.Log.debug("UserManager.signinSilent, subject prior to silent renew: ",Q.profile.sub),O.current_sub=Q.profile.sub),M._signinSilentIframe(O))}))},F.prototype._useRefreshToken=function(){var M=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._tokenClient.exchangeRefreshToken(O).then((function(Q){return Q?Q.access_token?M._loadUser().then((function(pe){if(pe){var q=Promise.resolve();return Q.id_token&&(q=M._validateIdTokenFromTokenRefreshToken(pe.profile,Q.id_token)),q.then((function(){return l.Log.debug("UserManager._useRefreshToken: refresh token response success"),pe.id_token=Q.id_token||pe.id_token,pe.access_token=Q.access_token,pe.refresh_token=Q.refresh_token||pe.refresh_token,pe.expires_in=Q.expires_in,M.storeUser(pe).then((function(){return M._events.load(pe),pe}))}))}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(M,O){var Q=this;return this._metadataService.getIssuer().then((function(pe){return Q.settings.getEpochTime().then((function(q){return Q._joseUtil.validateJwtAttributes(O,pe,Q._settings.client_id,Q._settings.clockSkew,q).then((function(ee){return ee?ee.sub!==M.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!==M.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!==M.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&&M.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 M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=M.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return O?(M.redirect_uri=O,M.prompt=M.prompt||"none",this._signin(M,this._iframeNavigator,{startUrl:O,silentRequestTimeout:M.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(Q){return Q&&(Q.profile&&Q.profile.sub?l.Log.info("UserManager.signinSilent: successful, signed in sub: ",Q.profile.sub):l.Log.info("UserManager.signinSilent: no sub")),Q}))):(l.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype.signinSilentCallback=function(M){return this._signinCallback(M,this._iframeNavigator).then((function(O){return O&&(O.profile&&O.profile.sub?l.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",O.profile.sub):l.Log.info("UserManager.signinSilentCallback: no sub")),O}))},F.prototype.signinCallback=function(M){var O=this;return this.readSigninResponseState(M).then((function(Q){var pe=Q.state;return Q.response,pe.request_type==="si:r"?O.signinRedirectCallback(M):pe.request_type==="si:p"?O.signinPopupCallback(M):pe.request_type==="si:s"?O.signinSilentCallback(M):Promise.reject(new Error("invalid response_type in state"))}))},F.prototype.signoutCallback=function(M,O){var Q=this;return this.readSignoutResponseState(M).then((function(pe){var q=pe.state,ee=pe.response;return q?q.request_type==="so:r"?Q.signoutRedirectCallback(M):q.request_type==="so:p"?Q.signoutPopupCallback(M,O):Promise.reject(new Error("invalid response_type in state")):ee}))},F.prototype.querySessionStatus=function(){var M=this,O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(O=Object.assign({},O)).request_type="si:s";var Q=O.redirect_uri||this.settings.silent_redirect_uri||this.settings.redirect_uri;return Q?(O.redirect_uri=Q,O.prompt="none",O.response_type=O.response_type||this.settings.query_status_response_type,O.scope=O.scope||"openid",O.skipUserInfo=!0,this._signinStart(O,this._iframeNavigator,{startUrl:Q,silentRequestTimeout:O.silentRequestTimeout||this.settings.silentRequestTimeout}).then((function(pe){return M.processSigninResponse(pe.url).then((function(q){if(l.Log.debug("UserManager.querySessionStatus: got signin response"),q.session_state&&q.profile.sub)return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",q.profile.sub),{session_state:q.session_state,sub:q.profile.sub,sid:q.profile.sid};l.Log.info("querySessionStatus successful, user not authenticated")})).catch((function(q){if(q.session_state&&M.settings.monitorAnonymousSession&&(q.message=="login_required"||q.message=="consent_required"||q.message=="interaction_required"||q.message=="account_selection_required"))return l.Log.info("UserManager.querySessionStatus: querySessionStatus success for anonymous user"),{session_state:q.session_state};throw q}))}))):(l.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},F.prototype._signin=function(M,O){var Q=this,pe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signinStart(M,O,pe).then((function(q){return Q._signinEnd(q.url,M)}))},F.prototype._signinStart=function(M,O){var Q=this,pe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return O.prepare(pe).then((function(q){return l.Log.debug("UserManager._signinStart: got navigator window handle"),Q.createSigninRequest(M).then((function(ee){return l.Log.debug("UserManager._signinStart: got signin request"),pe.url=ee.url,pe.id=ee.state.id,q.navigate(pe)})).catch((function(ee){throw q.close&&(l.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),q.close()),ee}))}))},F.prototype._signinEnd=function(M){var O=this,Q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return this.processSigninResponse(M).then((function(pe){l.Log.debug("UserManager._signinEnd: got signin response");var q=new d.User(pe);if(Q.current_sub){if(Q.current_sub!==q.profile.sub)return l.Log.debug("UserManager._signinEnd: current user does not match user returned from signin. sub from signin: ",q.profile.sub),Promise.reject(new Error("login_required"));l.Log.debug("UserManager._signinEnd: current user matches user returned from signin")}return O.storeUser(q).then((function(){return l.Log.debug("UserManager._signinEnd: user stored"),O._events.load(q),q}))}))},F.prototype._signinCallback=function(M,O){l.Log.debug("UserManager._signinCallback");var Q=this._settings.response_mode==="query"||!this._settings.response_mode&&v.SigninRequest.isCode(this._settings.response_type)?"?":"#";return O.callback(M,void 0,Q)},F.prototype.signoutRedirect=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="so:r";var O=M.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;O&&(M.post_logout_redirect_uri=O);var Q={useReplaceToNavigate:M.useReplaceToNavigate};return this._signoutStart(M,this._redirectNavigator,Q).then((function(){l.Log.info("UserManager.signoutRedirect: successful")}))},F.prototype.signoutRedirectCallback=function(M){return this._signoutEnd(M||this._redirectNavigator.url).then((function(O){return l.Log.info("UserManager.signoutRedirectCallback: successful"),O}))},F.prototype.signoutPopup=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};(M=Object.assign({},M)).request_type="so:p";var O=M.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return M.post_logout_redirect_uri=O,M.display="popup",M.post_logout_redirect_uri&&(M.state=M.state||{}),this._signout(M,this._popupNavigator,{startUrl:O,popupWindowFeatures:M.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:M.popupWindowTarget||this.settings.popupWindowTarget}).then((function(){l.Log.info("UserManager.signoutPopup: successful")}))},F.prototype.signoutPopupCallback=function(M,O){return O===void 0&&typeof M=="boolean"&&(O=M,M=null),this._popupNavigator.callback(M,O,"?").then((function(){l.Log.info("UserManager.signoutPopupCallback: successful")}))},F.prototype._signout=function(M,O){var Q=this,pe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this._signoutStart(M,O,pe).then((function(q){return Q._signoutEnd(q.url)}))},F.prototype._signoutStart=function(){var M=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},O=this,Q=arguments[1],pe=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return Q.prepare(pe).then((function(q){return l.Log.debug("UserManager._signoutStart: got navigator window handle"),O._loadUser().then((function(ee){return l.Log.debug("UserManager._signoutStart: loaded current user from storage"),(O._settings.revokeAccessTokenOnSignout?O._revokeInternal(ee):Promise.resolve()).then((function(){var _e=M.id_token_hint||ee&&ee.id_token;return _e&&(l.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),M.id_token_hint=_e),O.removeUser().then((function(){return l.Log.debug("UserManager._signoutStart: user removed, creating signout request"),O.createSignoutRequest(M).then((function(te){return l.Log.debug("UserManager._signoutStart: got signout request"),pe.url=te.url,te.state&&(pe.id=te.state.id),q.navigate(pe)}))}))}))})).catch((function(ee){throw q.close&&(l.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),q.close()),ee}))}))},F.prototype._signoutEnd=function(M){return this.processSignoutResponse(M).then((function(O){return l.Log.debug("UserManager._signoutEnd: got signout response"),O}))},F.prototype.revokeAccessToken=function(){var M=this;return this._loadUser().then((function(O){return M._revokeInternal(O,!0).then((function(Q){if(Q)return l.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),O.access_token=null,O.refresh_token=null,O.expires_at=null,O.token_type=null,M.storeUser(O).then((function(){l.Log.debug("UserManager.revokeAccessToken: user stored"),M._events.load(O)}))}))})).then((function(){l.Log.info("UserManager.revokeAccessToken: access token revoked successfully")}))},F.prototype._revokeInternal=function(M,O){var Q=this;if(M){var pe=M.access_token,q=M.refresh_token;return this._revokeAccessTokenInternal(pe,O).then((function(ee){return Q._revokeRefreshTokenInternal(q,O).then((function(_e){return ee||_e||l.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no token(s), or JWT format"),ee||_e}))}))}return Promise.resolve(!1)},F.prototype._revokeAccessTokenInternal=function(M,O){return!M||M.indexOf(".")>=0?Promise.resolve(!1):this._tokenRevocationClient.revoke(M,O).then((function(){return!0}))},F.prototype._revokeRefreshTokenInternal=function(M,O){return M?this._tokenRevocationClient.revoke(M,O,"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(M){return M?(l.Log.debug("UserManager._loadUser: user storageString loaded"),d.User.fromStorageString(M)):(l.Log.debug("UserManager._loadUser: no user storageString"),null)}))},F.prototype.storeUser=function(M){if(M){l.Log.debug("UserManager.storeUser: storing user");var O=M.toStorageString();return this._userStore.set(this._userStoreKey,O)}return l.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},a(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 a=(function(){function E(w,A){for(var C=0;C<A.length;C++){var T=A[C];T.enumerable=T.enumerable||!1,T.configurable=!0,"value"in T&&(T.writable=!0),Object.defineProperty(w,T.key,T)}}return function(w,A,C){return A&&E(w.prototype,A),C&&E(w,C),w}})(),l=(s(0),s(5)),u=s(40),f=s(41),d=s(43),p=s(6),g=s(1),m=s(8);function v(E,w){if(!(E instanceof w))throw new TypeError("Cannot call a class as a function")}function S(E,w){if(!E)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!w||typeof w!="object"&&typeof w!="function"?E:w}i.UserManagerSettings=(function(E){function w(){var A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},C=A.popup_redirect_uri,T=A.popup_post_logout_redirect_uri,F=A.popupWindowFeatures,P=A.popupWindowTarget,M=A.silent_redirect_uri,O=A.silentRequestTimeout,Q=A.automaticSilentRenew,pe=Q!==void 0&&Q,q=A.validateSubOnSilentRenew,ee=q!==void 0&&q,_e=A.includeIdTokenInSilentRenew,te=_e===void 0||_e,Ie=A.monitorSession,De=Ie===void 0||Ie,de=A.monitorAnonymousSession,Oe=de!==void 0&&de,le=A.checkSessionInterval,Ae=le===void 0?2e3:le,$=A.stopCheckSessionOnError,H=$===void 0||$,fe=A.query_status_response_type,ae=A.revokeAccessTokenOnSignout,Pe=ae!==void 0&&ae,Me=A.accessTokenExpiringNotificationTime,Xe=Me===void 0?60:Me,We=A.redirectNavigator,ye=We===void 0?new u.RedirectNavigator:We,me=A.popupNavigator,Be=me===void 0?new f.PopupNavigator:me,se=A.iframeNavigator,B=se===void 0?new d.IFrameNavigator:se,N=A.userStore,L=N===void 0?new p.WebStorageStateStore({store:g.Global.sessionStorage}):N;v(this,w);var W=S(this,E.call(this,arguments[0]));return W._popup_redirect_uri=C,W._popup_post_logout_redirect_uri=T,W._popupWindowFeatures=F,W._popupWindowTarget=P,W._silent_redirect_uri=M,W._silentRequestTimeout=O,W._automaticSilentRenew=pe,W._validateSubOnSilentRenew=ee,W._includeIdTokenInSilentRenew=te,W._accessTokenExpiringNotificationTime=Xe,W._monitorSession=De,W._monitorAnonymousSession=Oe,W._checkSessionInterval=Ae,W._stopCheckSessionOnError=H,fe?W._query_status_response_type=fe:arguments[0]&&arguments[0].response_type?W._query_status_response_type=m.SigninRequest.isOidc(arguments[0].response_type)?"id_token":"code":W._query_status_response_type="id_token",W._revokeAccessTokenOnSignout=Pe,W._redirectNavigator=ye,W._popupNavigator=Be,W._iframeNavigator=B,W._userStore=L,W}return(function(C,T){if(typeof T!="function"&&T!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof T);C.prototype=Object.create(T&&T.prototype,{constructor:{value:C,enumerable:!1,writable:!0,configurable:!0}}),T&&(Object.setPrototypeOf?Object.setPrototypeOf(C,T):C.__proto__=T)})(w,E),a(w,[{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}}]),w})(l.OidcClientSettings)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.RedirectNavigator=void 0;var a=(function(){function u(f,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(f,g.key,g)}}return function(f,d,p){return d&&u(f.prototype,d),p&&u(f,p),f}})(),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")))},a(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 a=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){a.Log.debug("PopupNavigator.callback");try{return l.PopupWindow.notifyOpener(d,p,g),Promise.resolve()}catch(m){return Promise.reject(m)}},u})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.PopupWindow=void 0;var a=(function(){function f(d,p){for(var g=0;g<p.length;g++){var m=p[g];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(d,m.key,m)}}return function(d,p,g){return p&&f(d.prototype,p),g&&f(d,g),d}})(),l=s(0),u=s(3);i.PopupWindow=(function(){function f(d){var p=this;(function(S,E){if(!(S instanceof E))throw new TypeError("Cannot call a class as a function")})(this,f),this._promise=new Promise((function(v,S){p._resolve=v,p._reject=S}));var g=d.popupWindowTarget||"_blank",m=d.popupWindowFeatures||"location=no,toolbar=no,width=500,height=500,left=100,top=100;";this._popup=window.open("",g,m),this._popup&&(l.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),500))}return f.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},f.prototype._success=function(p){l.Log.debug("PopupWindow.callback: Successful response from popup window"),this._cleanup(),this._resolve(p)},f.prototype._error=function(p){l.Log.error("PopupWindow.error: ",p),this._cleanup(),this._reject(new Error(p))},f.prototype.close=function(){this._cleanup(!1)},f.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},f.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("Popup window closed")},f.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"))},f.notifyOpener=function(p,g,m){if(window.opener){if(p=p||window.location.href){var v=u.UrlUtility.parseUrlFragment(p,m);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.")},a(f,[{key:"promise",get:function(){return this._promise}}]),f})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.IFrameNavigator=void 0;var a=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){a.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 a=(function(){function u(f,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(f,g.key,g)}}return function(f,d,p){return d&&u(f.prototype,d),p&&u(f,p),f}})(),l=s(0);i.IFrameWindow=(function(){function u(f){var d=this;(function(g,m){if(!(g instanceof m))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))},a(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 a=s(0),l=s(16),u=s(17);i.UserManagerEvents=(function(f){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,f.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,m){if(typeof m!="function"&&m!==null)throw new TypeError("Super expression must either be null or a function, not "+typeof m);g.prototype=Object.create(m&&m.prototype,{constructor:{value:g,enumerable:!1,writable:!0,configurable:!0}}),m&&(Object.setPrototypeOf?Object.setPrototypeOf(g,m):g.__proto__=m)})(d,f),d.prototype.load=function(g){var m=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];a.Log.debug("UserManagerEvents.load"),f.prototype.load.call(this,g),m&&this._userLoaded.raise(g)},d.prototype.unload=function(){a.Log.debug("UserManagerEvents.unload"),f.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){a.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(){a.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(){a.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(){a.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 a=(function(){function g(m,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(m,E.key,E)}}return function(m,v,S){return v&&g(m.prototype,v),S&&g(m,S),m}})(),l=s(0),u=s(1),f=s(17);function d(g,m){if(!(g instanceof m))throw new TypeError("Cannot call a class as a function")}function p(g,m){if(!g)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!m||typeof m!="object"&&typeof m!="function"?g:m}i.Timer=(function(g){function m(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,m);var w=p(this,g.call(this,v));return w._timer=S,w._nowFunc=E||function(){return Date.now()/1e3},w}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)})(m,g),m.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 w=5;S<w&&(w=S),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*w)}},m.prototype.cancel=function(){this._timerHandle&&(l.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},m.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))},a(m,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),m})(f.Event)},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.SilentRenewService=void 0;var a=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(f){})).catch((function(f){a.Log.error("SilentRenewService.start: Error from getUser:",f.message)})))},l.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},l.prototype._tokenExpiring=function(){var f=this;this._userManager.signinSilent().then((function(d){a.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")}),(function(d){a.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",d.message),f._userManager.events._raiseSilentRenewError(d)}))},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaPopupNavigator=void 0;var a=s(21);i.CordovaPopupNavigator=(function(){function l(){(function(f,d){if(!(f instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(f){var d=new a.CordovaPopupWindow(f);return Promise.resolve(d)},l})()},function(t,i,s){Object.defineProperty(i,"__esModule",{value:!0}),i.CordovaIFrameNavigator=void 0;var a=s(21);i.CordovaIFrameNavigator=(function(){function l(){(function(f,d){if(!(f instanceof d))throw new TypeError("Cannot call a class as a function")})(this,l)}return l.prototype.prepare=function(f){f.popupWindowFeatures="hidden=yes";var d=new a.CordovaPopupWindow(f);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"},a=await fetch(e.registrationEndpoint.toString(),{method:"POST",headers:s,body:JSON.stringify(i)});if(a.ok){const l=await a.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 a.status===400&&processErrorResponse(await a.json(),n),new Error(`Dynamic client registration failed: the server returned ${a.status} ${a.statusText} - ${await a.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 a;i&&(a=await generateDpopKeyPair(),s.DPoP=await createDpopHeader(n.tokenEndpoint,"POST",a)),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:m}=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:m,dpopKey:a,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 a={};i!==void 0&&(a={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:{...a,...l,"Content-Type":"application/x-www-form-urlencoded"}});let f;try{f=await u.json()}catch{throw new Error(`The token endpoint of issuer ${e.issuer} returned a malformed response.`)}const d=validateTokenEndpointResponse(f,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(a){throw new ConfigurationError(`[${e.toString()}] has an invalid configuration: ${a.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,a,l,u,f,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:f,clientAppId:s,clientAppSecret:a,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,a,l){this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=a,this.fetch=l,this.storageUtility=e,this.sessionInfoManager=t,this.issuerConfigFetcher=i,this.clientRegistrar=s,this.tokerRefresher=a}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"),a=await this.storageUtility.getForUser(s,"sessionId",{errorIfNull:!0}),{issuerConfig:l,codeVerifier:u,redirectUrl:f,dpop:d}=await loadOidcContextFromStorage(a,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 ${a} is missing from storage.`);if(f===void 0)throw new Error(`The redirect URL for session ${a} is missing from storage.`);const g=await this.clientRegistrar.getClient({sessionId:a},l),m=Date.now(),v=await getTokens(l,g,{grantType:"authorization_code",code:i.searchParams.get("code"),codeVerifier:u,redirectUrl:f},d);window.localStorage.removeItem(`oidc.${s}`);let S;v.refreshToken!==void 0&&(S={sessionId:a,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,a,v.webId,v.clientId,"true",void 0,!0);const w=await this.sessionInfoManager.get(a);if(!w)throw new Error(`Could not retrieve session: [${a}].`);return Object.assign(w,{fetch:E,getLogoutUrl:maybeBuildRpInitiatedLogout({idTokenHint:v.idToken,endSessionEndpoint:l.endSessionEndpoint}),expirationDate:typeof v.expiresIn=="number"?m+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,a,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})]),f=a!==void 0?Number.parseInt(a,10):-1,d=s!==void 0&&f!==0&&Math.floor(Date.now()/1e3)>f;if(i&&isKnownClientType(u)&&!d)return s!==void 0?{clientId:i,clientSecret:s,clientName:l,clientType:"dynamic",expiresAt:f}:{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"),a=i.searchParams.get("error_description");t.emit(EVENTS.ERROR,s,a)}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 a=await loadOidcContextFromStorage(e,this.storageUtility,this.issuerConfigFetcher),l=await this.clientRegistrar.getClient({sessionId:e},a.issuerConfig);if(t===void 0)throw new Error(`Session [${e}] has no refresh token to allow it to refresh its access token.`);if(a.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,a.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),a=new IssuerConfigFetcher(s),l=new ClientRegistrar(s),u=new SessionInfoManager(s),f=new TokenRefresher(s,a,l),d=new Redirector,p=new OidcLoginHandler(s,new AuthorizationCodeWithPkceOidcHandler(s,d),a,l),g=new AggregateRedirectHandler([new ErrorOidcHandler,new AuthCodeRedirectHandler(s,u,a,l,f,n.fetch),new FallbackRedirectHandler]);return new ClientAuthentication(p,g,new IWaterfallLogoutHandler(u,d),u,a)}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;xpodErrorLogout=Promise.resolve();constructor(e={},t=void 0){this.events=new EventEmitter,e.clientAuthentication?this.clientAuthentication=e.clientAuthentication:e.secureStorage&&e.insecureStorage?this.clientAuthentication=getClientAuthenticationWithDependencies({secureStorage:e.secureStorage,insecureStorage:e.insecureStorage,fetch:e.fetch}):this.clientAuthentication=getClientAuthenticationWithDependencies({fetch:e.fetch}),e.sessionInfo?this.info={sessionId:e.sessionInfo.sessionId,isLoggedIn:!1,webId:e.sessionInfo.webId,clientAppId:e.sessionInfo.clientAppId}:this.info={sessionId:t??v4(),isLoggedIn:!1},this.events.on(EVENTS.LOGIN,()=>window.localStorage.setItem(KEY_CURRENT_SESSION,this.info.sessionId)),this.events.on(EVENTS.SESSION_EXPIRED,()=>this.internalLogout(!1)),this.events.on(EVENTS.ERROR,()=>{this.xpodErrorLogout=this.xpodErrorLogout.then(()=>this.internalLogout(!1),()=>this.internalLogout(!1)),this.xpodErrorLogout.catch(()=>{})})}login=async e=>(await this.clientAuthentication.login({sessionId:this.info.sessionId,...e,tokenType:e.tokenType??"DPoP"},this.events),new Promise(()=>{}));fetch=(e,t)=>this.clientAuthentication.fetch(e,t);internalLogout=async(e,t)=>{window.localStorage.removeItem(KEY_CURRENT_SESSION),await this.clientAuthentication.logout(this.info.sessionId,t),this.info.isLoggedIn=!1,e&&this.events.emit(EVENTS.LOGOUT)};logout=async e=>this.internalLogout(!0,e);handleIncomingRedirect=async(e={})=>{if(this.info.isLoggedIn)return this.info;if(this.tokenRequestInProgress)return;const t=typeof e=="string"?{url:e}:e,i=t.url??window.location.href;this.tokenRequestInProgress=!0;const s=await this.clientAuthentication.handleIncomingRedirect(i,this.events);try{await this.xpodErrorLogout}catch(a){throw this.tokenRequestInProgress=!1,a}if(isLoggedIn(s)){this.setSessionInfo(s);const a=window.localStorage.getItem(KEY_CURRENT_URL);a===null?this.events.emit(EVENTS.LOGIN):(window.localStorage.removeItem(KEY_CURRENT_URL),this.events.emit(EVENTS.SESSION_RESTORED,a))}else if(t.restorePreviousSession===!0){const a=window.localStorage.getItem(KEY_CURRENT_SESSION);if(a!==null&&await silentlyAuthenticate(a,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,a,l=!1,u=!1,f,d=!1;const p=w=>{if(i=w,d||areSnapshotsEqual(s,i))return i;s=i;for(const A of t)A(i);return i},g=()=>p(snapshotFromSessionInfo(e.info)),m=()=>p({status:"anonymous"}),v=()=>p(snapshotFromSessionExpired(e.info)),S=(w,A)=>{const C=snapshotFromSessionError(A??w??"Solid session error",e.info);u&&(f=C),p(C)};e.events.on(EVENTS.LOGIN,g),e.events.on(EVENTS.SESSION_RESTORED,g),e.events.on(EVENTS.LOGOUT,m),e.events.on(EVENTS.SESSION_EXPIRED,v);const E=e.events;return E.on(EVENTS.ERROR,S),{fetch:e.fetch,getSnapshot(){return i},initialize(w={}){if(a)return a;if(l)return Promise.resolve(i);u=!0,f=void 0,p({status:"initializing"});const A=e.handleIncomingRedirect({restorePreviousSession:w.restorePreviousSession??!0}).then(C=>{const T=snapshotFromSessionInfo(C??e.info);return T.status==="anonymous"&&f?.status==="error"?f:(l=!0,p(T))}).catch(C=>p(snapshotFromSessionError(C,e.info))).finally(()=>{a===A&&(a=void 0,u=!1,f=void 0)});return a=A,a},handleIncomingRedirect(w){if(a)return a;u=!0,f=void 0,p({status:"initializing"});const A=e.handleIncomingRedirect(w).then(C=>{const T=snapshotFromSessionInfo(C??e.info);return T.status==="anonymous"&&f?.status==="error"?f:(l=!0,p(T))}).catch(C=>p(snapshotFromSessionError(C,e.info))).finally(()=>{a===A&&(a=void 0,u=!1,f=void 0)});return a=A,A},login(w){return e.login(w)},async logout(w){await e.logout(w),p({status:"anonymous"})},subscribe(w){return t.add(w),()=>{t.delete(w)}},dispose(){d=!0,t.clear(),e.events.off(EVENTS.LOGIN,g),e.events.off(EVENTS.SESSION_RESTORED,g),e.events.off(EVENTS.LOGOUT,m),e.events.off(EVENTS.SESSION_EXPIRED,v),E.off(EVENTS.ERROR,S)}}}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 validateWebId(n){if(typeof n!="string"||n===""||/[\s\u0000-\u001f\u007f-\u009f]/u.test(n))throw new TypeError("webId must be a non-empty identifier without whitespace or control characters");return n}function normalizeStorageBinding(n){if(!n||typeof n.storageUrl!="string"||n.storageUrl.trim()==="")throw new TypeError("selectedStorage.storageUrl must be a non-empty absolute URL");validateWebId(n.webId);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(a=>a==="..")||!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 KEY_SEPARATOR="\0";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`${n}${KEY_SEPARATOR}${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,a=new Map,l=new Map,u=new Map,f=(g,m)=>{const v=validateWebId(g);if(m!==void 0){const w=normalizePodUrl(m),A=compositeKey(g,w);nextGeneration(u,A),a.get(A)?.controller.abort(),a.delete(A),i.delete(A);const C=t.get(v);C&&compositeKey(C.webId,C.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 w of[...i.keys()])w.startsWith(E)&&i.delete(w);for(const[w,A]of[...a.entries()])w.startsWith(E)&&(nextGeneration(u,w),A.controller.abort(),a.delete(w))},d=g=>{if(g===void 0){t.clear(),i.clear();for(const m of s.values())m.controller.abort();for(const m of a.values())m.controller.abort();s.clear(),a.clear();for(const m of l.keys())nextGeneration(l,m);for(const m of u.keys())nextGeneration(u,m);return}if(typeof g=="string"){f(g);return}f(g.webId,g.podUrl)};return{open(g){const m=validateWebId(g.webId),v=g.podUrl===void 0?void 0:normalizePodUrl(g.podUrl);if(v!==void 0){const M=compositeKey(g.webId,v),O=i.get(M);if(O)return Promise.resolve(O);const Q=a.get(M);if(Q)return Q.promise;const pe=u.get(M)??0;u.set(M,pe);const q=new AbortController,ee=()=>!q.signal.aborted&&(u.get(M)??0)===pe,_e=()=>{if(!ee())throw createAbortedOpenError()},te=p({webId:g.webId,podUrl:v,fetch:g.fetch,signal:q.signal,isCurrent:ee,assertCurrent:_e});a.set(M,{generation:pe,promise:te,controller:q});const Ie=()=>{const De=a.get(M);De?.generation===pe&&De.promise===te&&a.delete(M)};return te.then(Ie,Ie),te}const S=t.get(m);if(S)return Promise.resolve(S);const E=s.get(m);if(E)return E.promise;const w=l.get(m)??0;l.set(m,w);const A=new AbortController,C=()=>!A.signal.aborted&&(l.get(m)??0)===w,T=()=>{if(!C())throw createAbortedOpenError()},F=(async()=>{const M=await e.discoverPod({webId:g.webId,fetch:g.fetch,signal:A.signal,isCurrent:C});return T(),p({webId:g.webId,podUrl:normalizePodUrl(M),fetch:g.fetch,signal:A.signal,isCurrent:C,assertCurrent:T,generation:w,webIdKey:m,discovered:!0})})();s.set(m,{generation:w,promise:F,controller:A});const P=()=>{const M=s.get(m);M?.generation===w&&M.promise===F&&s.delete(m)};return F.then(P,P),F},clear:d,dispose(){d()}};async function p(g){const m=compositeKey(g.webId,g.podUrl),v=i.get(m);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(m,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 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,a)=>a.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(),a=resolveSolidLocalRouteUrl(i,s);if(!a)return t===void 0?n.fetch.call(globalThis,e):n.fetch.call(globalThis,e,t);const l=routedHeaders(e,t,i,a);let u;if(e instanceof Request){const d=new Request(new Request(a,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,a,{...t,headers:l});const f=resolveSolidLocalRouteUrl(u.url,s.map(d=>({canonicalBaseUrl:d.localBaseUrl,localBaseUrl:d.canonicalBaseUrl})));return f?withResponseUrl(u,f.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),a=new URL(s,i);return a.search=n.search,a.hash=n.hash,a}function routedHeaders(n,e,t,i){const s=n instanceof Request?n:void 0,a=new Headers(s?.headers??void 0);return new Headers(e?.headers??void 0).forEach((l,u)=>a.set(u,l)),a.set(SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER,t.toString()),a.set(SOLID_LOCAL_ROUTE_CANONICAL_ORIGIN_HEADER,t.origin),a.set(SOLID_LOCAL_ROUTE_CANONICAL_HOST_HEADER,t.host),a.set(SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER,i.toString()),a}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,a=t.storageProvider?new URL(t.storageProvider.url).origin:void 0;if(t.id!==XPOD_LOGIN_ROUTE_ID||s!==i||a!==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_DEFAULT_RETURN_PATH="/ai-connections",LEGACY_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,[LEGACY_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},productSurfaceRoots=[{app:"dashboard",basename:"/dashboard"},{app:"dashboard",basename:"/status"},{app:"dashboard",basename:"/network"},{app:"settings",basename:"/settings"},{app:"settings",basename:"/ai-connections"},{app:"settings",basename:"/ai-config"}];function canonicalProductPathname(n){return legacyProductRedirects[n]??n}function hasInvalidWebIdWhitespace(n){return n!==n.trim()||/[\r\n\t]/.test(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",XPOD_SELECTED_STORAGE_BINDING_TTL_MS=1440*60*1e3;class XpodLoginTransactionError extends Error{code;constructor(e,t){super(t),this.name="XpodLoginTransactionError",this.code=e}}function rememberXpodSelectedStorage(n,e={}){const t=e.storage??getOptionalPersistentStorage$1()??getOptionalSessionStorage$1();if(!t)throw new XpodLoginTransactionError("storage_unavailable","Session storage is unavailable");const i=new URL(e.origin??getWindowOrigin()).origin,s=e.storageRoot??i,a=normalizeSelectedStorageBinding(n,s,e.storageRoot===void 0),u=(e.now??(()=>Date.now()))(),f={version:XPOD_SELECTED_STORAGE_BINDING_VERSION,createdAt:u,expiresAt:u+(e.ttlMs??XPOD_SELECTED_STORAGE_BINDING_TTL_MS),binding:a,...e.storageRoot===void 0?{}:{storageRoot:normalizeStorageRoot$1(e.storageRoot)}};t.setItem(XPOD_SELECTED_STORAGE_BINDING_KEY,JSON.stringify(f))}function readXpodSelectedStorage(n={}){return n.storage?readXpodSelectedStorageFrom(n.storage,n):readXpodSelectedStorageFrom(getOptionalPersistentStorage$1(),n)??readXpodSelectedStorageFrom(getOptionalSessionStorage$1(),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 a=e.now??(()=>Date.now());if(s.expiresAt<=a()){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$1()?.removeItem(XPOD_SELECTED_STORAGE_BINDING_KEY),getOptionalSessionStorage$1()?.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,a=n.prefix??XPOD_LOGIN_TRANSACTION_PREFIX,l=`${a}.active`,u=m=>`${a}.record.${m}`,f=m=>`${a}.consumed.${m}`,d=m=>{e.getItem(l)===m&&e.removeItem(l),e.removeItem(u(m))},p=(m,v=!0)=>{if(!isSafeTransactionId(m))throw new XpodLoginTransactionError("malformed","Transaction id is malformed");if(e.getItem(f(m))==="1")throw new XpodLoginTransactionError("consumed","Transaction has already been consumed");if(v&&e.getItem(l)!==m)throw new XpodLoginTransactionError("unknown","Transaction is not the active Xpod login transaction");const S=e.getItem(u(m));if(!S)throw v&&e.getItem(l)===m&&e.removeItem(l),new XpodLoginTransactionError("unknown","Xpod login transaction was not found");let E;try{E=JSON.parse(S)}catch{throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}if(!isStoredTransaction(E)||E.transaction.id!==m)throw d(m),new XpodLoginTransactionError("malformed","Xpod login transaction is malformed");if(E.expiresAt<=i())throw d(m),new XpodLoginTransactionError("expired","Xpod login transaction has expired");try{const w=normalizePublicTransaction({...E.transaction,authorizationSurface:"redirect",discovery:"strict"},t);return E.transaction={id:w.id,route:w.route,...w.returnTo===void 0?{}:{returnTo:w.returnTo},...w.prompt===void 0?{}:{prompt:w.prompt},...w.selectedStorage===void 0?{}:{selectedStorage:w.selectedStorage}},E}catch(w){throw d(m),w instanceof XpodLoginTransactionError?w:new XpodLoginTransactionError("malformed","Xpod login transaction is malformed")}};return{begin:m=>{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(m.id)?m.id:createOpaqueTransactionId(),E=normalizePublicTransaction({...m,id:S},t),w=i(),A=w+s,C={version:XPOD_LOGIN_TRANSACTION_VERSION,createdAt:w,expiresAt:A,transaction:{id:E.id,route:E.route,...E.returnTo===void 0?{}:{returnTo:E.returnTo},...E.prompt===void 0?{}:{prompt:E.prompt},...E.selectedStorage===void 0?{}:{selectedStorage:E.selectedStorage}}};return e.setItem(u(E.id),JSON.stringify(C)),e.setItem(l,E.id),E},readSinglePending(){const m=e.getItem(l);if(m)return materialize(p(m).transaction)},updateSelectedStorage(m,v){const S=p(m),E=materialize(S.transaction),w=normalizeBinding$1(v,t,E.route.storageProvider?.url),A={...S,transaction:{...S.transaction,selectedStorage:w}};e.setItem(u(m),JSON.stringify(A))},consume(m){const v=p(m),S=materialize(v.transaction);return e.removeItem(l),e.removeItem(u(m)),e.setItem(f(m),"1"),S},cancel(m){p(m),e.removeItem(l),e.removeItem(u(m)),e.setItem(f(m),"1")}}}function normalizePublicTransaction(n,e){let t;try{t=normalizeWebIdLoginTransaction(n)}catch(a){throw new XpodLoginTransactionError("malformed",a instanceof Error?a.message:"Transaction is malformed")}let i;try{i=assertXpodLoginRoute(t.route,e)}catch(a){throw new XpodLoginTransactionError("cross_origin",a instanceof Error?a.message:"Transaction route is not local")}let s;try{s=normalizeXpodReturnTo(t.returnTo)}catch(a){throw new XpodLoginTransactionError("mismatch",a instanceof Error?a.message:"Transaction return path is unsafe")}if(t.selectedStorage!==void 0)try{const a=normalizeBinding$1(t.selectedStorage,e,i.storageProvider?.url);return{id:t.id,route:i,selectedStorage:a,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}catch(a){throw a instanceof XpodLoginTransactionError?a:new XpodLoginTransactionError("mismatch","Selected storage binding is invalid")}return{id:t.id,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s},...t.prompt===void 0?{}:{prompt:t.prompt}}}function normalizeBinding$1(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))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:n.webId,...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.prompt===void 0?{}:{prompt:n.prompt},...n.selectedStorage===void 0?{}:{selectedStorage:n.selectedStorage}}}function normalizeSelectedStorageBinding(n,e,t){if(!n||typeof n.storageUrl!="string"||typeof n.webId!="string"||hasInvalidWebIdWhitespace(n.webId))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:n.webId}}function normalizeStorageRoot$1(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$1(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$1(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function getOptionalPersistentStorage$1(){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"}const urlAlphabet="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",generateNanoId=(n=21)=>{let e="";if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.getRandomValues=="function"){const t=globalThis.crypto.getRandomValues(new Uint8Array(n));for(let i=0;i<n;i++)e+=urlAlphabet[t[i]%urlAlphabet.length]}else{console.warn("Using Math.random fallback for NanoID generation.");for(let t=0;t<n;t++)e+=urlAlphabet[Math.floor(Math.random()*256)%urlAlphabet.length]}return e},hasStringValue$2=n=>typeof n=="object"&&n!==null&&typeof n.value=="string",hasTermValue=n=>typeof n=="object"&&n!==null&&typeof n.term=="object"&&n.term!==null&&typeof n.term?.value=="string",resolveTermIri=n=>{if(typeof n=="string")return n;if(hasStringValue$2(n))return n.value;if(hasTermValue(n))return n.term.value;throw new Error("Term must be a string or VocabTerm with a string value")},entityKind=Symbol.for("drizzle:entityKind");function is(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,entityKind))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=n.constructor;if(t)for(;t;){if(entityKind in t&&t[entityKind]===e[entityKind])return!0;t=Object.getPrototypeOf(t)}return!1}class Column{table;static[entityKind]="Column";name;primary;notNull;default;defaultFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}const ViewBaseConfig=Symbol.for("drizzle:ViewBaseConfig");class View{static[entityKind]="View";[ViewBaseConfig];constructor({name:e,schema:t,selectedFields:i,query:s}){this[ViewBaseConfig]={name:e,originalName:e,schema:t,selectedFields:i,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new SQL([this])}}const SubqueryConfig=Symbol.for("drizzle:SubqueryConfig");class Subquery{static[entityKind]="Subquery";[SubqueryConfig];constructor(e,t,i,s=!1){this[SubqueryConfig]={sql:e,selection:t,alias:i,isWith:s}}getSQL(){return new SQL([this])}}class SelectionProxyHandler{static[entityKind]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t===SubqueryConfig)return{...e[SubqueryConfig],selection:new Proxy(e[SubqueryConfig].selection,this)};if(t===ViewBaseConfig)return{...e[ViewBaseConfig],selectedFields:new Proxy(e[ViewBaseConfig].selectedFields,this)};if(typeof t=="symbol")return e[t];const s=(is(e,Subquery)?e[SubqueryConfig].selection:is(e,View)?e[ViewBaseConfig].selectedFields:e)[t];if(is(s,SQL.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;const a=s.clone();return a.isSelectionField=!0,a}if(is(s,SQL)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return is(s,Column)?this.config.alias?new Proxy(s,new ColumnAliasProxyHandler(new Proxy(s.table,new TableAliasProxyHandler(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new SelectionProxyHandler(this.config))}}function orderSelectedFields(n,e){return Object.entries(n).reduce((t,[i,s])=>{if(typeof i!="string")return t;const a=e?[...e,i]:[i];return is(s,Column)||is(s,SQL)||is(s,SQL.Aliased)?t.push({path:a,field:s}):is(s,Table)?t.push(...orderSelectedFields(s[Table.Symbol.Columns],a)):t.push(...orderSelectedFields(s,a)),t},[])}function applyMixins(n,e){for(const t of e)for(const i of Object.getOwnPropertyNames(t.prototype))Object.defineProperty(n.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))}function getTableLikeName(n){return is(n,Subquery)?n[SubqueryConfig].alias:is(n,View)?n[ViewBaseConfig].name:is(n,SQL)?void 0:n[Table.Symbol.IsAlias]?n[Table.Symbol.Name]:n[Table.Symbol.BaseName]}const TableName=Symbol.for("drizzle:Name"),Schema=Symbol.for("drizzle:Schema"),Columns=Symbol.for("drizzle:Columns"),OriginalName=Symbol.for("drizzle:OriginalName"),BaseName=Symbol.for("drizzle:BaseName"),IsAlias=Symbol.for("drizzle:IsAlias"),ExtraConfigBuilder=Symbol.for("drizzle:ExtraConfigBuilder"),IsDrizzleTable=Symbol.for("drizzle:IsDrizzleTable");class Table{static[entityKind]="Table";static Symbol={Name:TableName,Schema,OriginalName,Columns,BaseName,IsAlias,ExtraConfigBuilder};[TableName];[OriginalName];[Schema];[Columns];[BaseName];[IsAlias]=!1;[ExtraConfigBuilder]=void 0;[IsDrizzleTable]=!0;constructor(e,t,i){this[TableName]=this[OriginalName]=e,this[Schema]=t,this[BaseName]=i}getSQL(){return new SQL([this])}}class QueryPromise{static[entityKind]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}const tracer={startActiveSpan(n,e){return e()}},InlineForeignKeys=Symbol.for("drizzle:PgInlineForeignKeys");class PgTable extends Table{static[entityKind]="PgTable";static Symbol=Object.assign({},Table.Symbol,{InlineForeignKeys});[InlineForeignKeys]=[];[Table.Symbol.ExtraConfigBuilder]=void 0}class TypedQueryBuilder{static[entityKind]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class PgSelectQueryBuilder extends TypedQueryBuilder{static[entityKind]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:a,withList:l,distinct:u}){super(),this.config={withList:l,table:e,fields:{...t},distinct:u},this.isPartialSelect=i,this.session=s,this.dialect=a,this._={selectedFields:t},this.tableName=getTableLikeName(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(t,i)=>{const s=this.tableName,a=getTableLikeName(t);if(typeof a=="string"&&this.config.joins?.some(l=>l.alias===a))throw new Error(`Alias "${a}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof a=="string"&&!is(t,SQL))){const l=is(t,Subquery)?t[SubqueryConfig].selection:is(t,View)?t[ViewBaseConfig].selectedFields:t[Table.Symbol.Columns];this.config.fields[a]=l}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:t,joinType:e,alias:a}),typeof a=="string")switch(e){case"left":{this.joinsNotNullableMap[a]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[a]=!0;break}case"inner":{this.joinsNotNullableMap[a]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([l])=>[l,!1])),this.joinsNotNullableMap[a]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const t=e[0](new Proxy(this.config.fields,new SelectionProxyHandler({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.orderBy=Array.isArray(t)?t:[t]}else this.config.orderBy=e;return this}limit(e){return this.config.limit=e,this}offset(e){return this.config.offset=e,this}for(e,t={}){return this.config.lockingClauses||(this.config.lockingClauses=[]),this.config.lockingClauses.push({strength:e,config:t}),this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){return new Proxy(new Subquery(this.getSQL(),this.config.fields,e),new SelectionProxyHandler({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}class PgSelect extends PgSelectQueryBuilder{static[entityKind]="PgSelect";_prepare(e){const{session:t,config:i,dialect:s,joinsNotNullableMap:a}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return tracer.startActiveSpan("drizzle.prepareQuery",()=>{const l=orderSelectedFields(i.fields),u=t.prepareQuery(s.sqlToQuery(this.getSQL()),l,e);return u.joinsNotNullableMap=a,u})}prepare(e){return this._prepare(e)}execute=e=>tracer.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e))}applyMixins(PgSelect,[QueryPromise]);class Relation{sourceTable;referencedTable;relationName;static[entityKind]="Relation";referencedTableName;fieldName;constructor(e,t,i){this.sourceTable=e,this.referencedTable=t,this.relationName=i,this.referencedTableName=t[Table.Symbol.Name]}}function isSQLWrapper(n){return typeof n=="object"&&n!==null&&"getSQL"in n&&typeof n.getSQL=="function"}function mergeQueries(n){const e={sql:"",params:[]};for(const t of n)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class StringChunk{static[entityKind]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new SQL([this])}}class SQL{queryChunks;static[entityKind]="SQL";decoder=noopDecoder;shouldInlineParams=!1;constructor(e){this.queryChunks=e}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return tracer.startActiveSpan("drizzle.buildSQL",t=>{const i=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){const i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:s,escapeParam:a,prepareTyping:l,inlineParams:u,paramStartIndex:f}=i;return mergeQueries(e.map(d=>{if(is(d,StringChunk))return{sql:d.value.join(""),params:[]};if(is(d,Name))return{sql:s(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){const p=[new StringChunk("(")];for(const[g,m]of d.entries())p.push(m),g<d.length-1&&p.push(new StringChunk(", "));return p.push(new StringChunk(")")),this.buildQueryFromSourceParams(p,i)}if(is(d,SQL))return this.buildQueryFromSourceParams(d.queryChunks,{...i,inlineParams:u||d.shouldInlineParams});if(is(d,Table)){const p=d[Table.Symbol.Schema],g=d[Table.Symbol.Name];return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Column))return{sql:s(d.table[Table.Symbol.Name])+"."+s(d.name),params:[]};if(is(d,View)){const p=d[ViewBaseConfig].schema,g=d[ViewBaseConfig].name;return{sql:p===void 0?s(g):s(p)+"."+s(g),params:[]}}if(is(d,Param)){const p=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(is(p,SQL))return this.buildQueryFromSourceParams([p],i);if(u)return{sql:this.mapInlineParam(p,i),params:[]};let g;return l!==void 0&&(g=[l(d.encoder)]),{sql:a(f.value++,p),params:[p],typings:g}}return is(d,Placeholder)?{sql:a(f.value++,d),params:[d]}:is(d,SQL.Aliased)&&d.fieldAlias!==void 0?{sql:s(d.fieldAlias),params:[]}:is(d,Subquery)?d[SubqueryConfig].isWith?{sql:s(d[SubqueryConfig].alias),params:[]}:this.buildQueryFromSourceParams([new StringChunk("("),d[SubqueryConfig].sql,new StringChunk(") "),new Name(d[SubqueryConfig].alias)],i):isSQLWrapper(d)?this.buildQueryFromSourceParams([new StringChunk("("),d.getSQL(),new StringChunk(")")],i):is(d,Relation)?this.buildQueryFromSourceParams([d.sourceTable,new StringChunk("."),sql.identifier(d.fieldName)],i):u?{sql:this.mapInlineParam(d,i),params:[]}:{sql:a(f.value++,d),params:[d]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new SQL.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}}class Name{value;static[entityKind]="Name";brand;constructor(e){this.value=e}getSQL(){return new SQL([this])}}const noopDecoder={mapFromDriverValue:n=>n},noopEncoder={mapToDriverValue:n=>n};({...noopDecoder,...noopEncoder});class Param{value;encoder;static[entityKind]="Param";brand;constructor(e,t=noopEncoder){this.value=e,this.encoder=t}getSQL(){return new SQL([this])}}function sql(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new StringChunk(n[0]));for(const[i,s]of e.entries())t.push(s,new StringChunk(n[i+1]));return new SQL(t)}(function(n){function e(){return new SQL([])}n.empty=e;function t(f){return new SQL(f)}n.fromList=t;function i(f){return new SQL([new StringChunk(f)])}n.raw=i;function s(f,d){const p=[];for(const[g,m]of f.entries())g>0&&d!==void 0&&p.push(d),p.push(m);return new SQL(p)}n.join=s;function a(f){return new Name(f)}n.identifier=a;function l(f){return new Placeholder(f)}n.placeholder=l;function u(f,d){return new Param(f,d)}n.param=u})(sql||(sql={}));(function(n){class e{sql;fieldAlias;static[entityKind]="SQL.Aliased";isSelectionField=!1;constructor(i,s){this.sql=i,this.fieldAlias=s}getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}n.Aliased=e})(SQL||(SQL={}));class Placeholder{name;static[entityKind]="Placeholder";constructor(e){this.name=e}getSQL(){return new SQL([this])}}Column.prototype.getSQL=function(){return new SQL([this])};class ColumnAliasProxyHandler{table;static[entityKind]="ColumnAliasProxyHandler";constructor(e){this.table=e}get(e,t){return t==="table"?this.table:e[t]}}class TableAliasProxyHandler{alias;replaceOriginalName;static[entityKind]="TableAliasProxyHandler";constructor(e,t){this.alias=e,this.replaceOriginalName=t}get(e,t){if(t===Table.Symbol.IsAlias)return!0;if(t===Table.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===Table.Symbol.OriginalName)return this.alias;if(t===ViewBaseConfig)return{...e[ViewBaseConfig],name:this.alias,isAlias:!0};if(t===Table.Symbol.Columns){const s=e[Table.Symbol.Columns];if(!s)return s;const a={};return Object.keys(s).map(l=>{a[l]=new Proxy(s[l],new ColumnAliasProxyHandler(new Proxy(e,this)))}),a}const i=e[t];return is(i,Column)?new Proxy(i,new ColumnAliasProxyHandler(new Proxy(e,this))):i}}var _a$b;class ColumnBuilder{constructor(e,t,i={},s,a){this.name=e,this.dataType=t,this.options={...i},this._predicateUri=s,this.elementType=a??null}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){const t=this.options.isArray&&this.elementType?this.elementType:this.dataType;if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(t){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return String(Number(e));case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}parseValue(e,t){return this.parseSingleValue(e,t)}parseSingleValue(e,t){if(!t)return e;if(t.includes("#integer")||t.includes("#int"))return parseInt(e,10);if(t.includes("#decimal")||t.includes("#double"))return parseFloat(e);if(t.includes("#boolean"))return e==="true";if(t.includes("#dateTime"))return new Date(e);if(t.includes("#json"))try{return JSON.parse(e)}catch{return console.warn("Failed to parse JSON value:",e),e}return e.startsWith("http://")||e.startsWith("https://"),e}primaryKey(){return this._predicateUri="@id",this.options={...this.options,primaryKey:!0,required:!0,predicate:"@id"},this}notNull(){return this.options={...this.options,required:!0,notNull:!0},this}predicate(e){const t=resolveTermIri(e);return this._predicateUri=t,this.options={...this.options,predicate:t},this}default(e){return this.options={...this.options,defaultValue:e},this}defaultNow(){return this.options={...this.options,defaultValue:()=>new Date},this}inverse(e=!0){return this.options={...this.options,inverse:e},this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options={...this.options,linkTarget:e}:this.options={...this.options,linkTableName:e}:this.options={...this.options,linkTable:e},this}array(){return new ColumnBuilder(this.name,"array",{...this.options,baseType:this.dataType,isArray:!0},this._predicateUri,this.dataType)}getPredicateUri(){return this._predicateUri}}class PodColumnBase{constructor(e,t,i={},s){this.name=e,this.dataType=t,this.options=i,this.tableName=s}getPredicate(e){if(this.options.predicate)return this.options.predicate;if(e)return`${e.uri}${this.name}`;throw new Error(`Missing predicate for column "${this.name}"; please set namespace or predicate explicitly.`)}isLink(){return!!(this.options.linkTarget||this.options.linkTableName||this.options.linkTable)}getLinkTarget(){return this.options.linkTarget}getLinkTableName(){return this.options.linkTableName}getLinkTable(){return this.options.linkTable}primaryKey(){return this.options.primaryKey=!0,this.options.required=!0,this.options.predicate="@id",this}notNull(){return this.options.required=!0,this}default(e){return this.options.defaultValue=e,this}predicate(e){return this.options.predicate=resolveTermIri(e),this}link(e){return typeof e=="string"?e.startsWith("http://")||e.startsWith("https://")?this.options.linkTarget=e:this.options.linkTableName=e:this.options.linkTable=e,this}inverse(e=!0){return this.options.inverse=e,this}isInverse(){return this.options.inverse===!0}formatValue(e){if(e==null)throw new Error("Cannot format null or undefined value");if(this.options.isArray){if(!Array.isArray(e))throw new Error("Array column requires array value");return e.map(t=>this.formatSingleValue(t))}return this.formatSingleValue(e)}formatSingleValue(e){if(this.options.linkTarget&&typeof e=="string")return`<${e}>`;switch(this.dataType){case"string":return`"${String(e).replace(/"/g,'"')}"`;case"integer":return`"${Number(e)}"^^<http://www.w3.org/2001/XMLSchema#integer>`;case"boolean":return`"${e}"^^<http://www.w3.org/2001/XMLSchema#boolean>`;case"datetime":return`"${(e instanceof Date?e:new Date(e)).toISOString()}"^^<http://www.w3.org/2001/XMLSchema#dateTime>`;case"json":case"object":return`"${JSON.stringify(e).replace(/"/g,'"')}"^^<http://www.w3.org/2001/XMLSchema#json>`;case"uri":if(typeof e!="string"||!e.includes(":"))throw new Error(`URI column requires valid IRI, got: ${e}`);return`<${e}>`;default:return`"${String(e).replace(/"/g,'"')}"`}}}_a$b=entityKind;PodColumnBase[_a$b]="PodColumn";class PodStringColumn extends PodColumnBase{constructor(e,t={}){super(e,"string",t)}}class PodIntegerColumn extends PodColumnBase{constructor(e,t={}){super(e,"integer",t)}}class PodBooleanColumn extends PodColumnBase{constructor(e,t={}){super(e,"boolean",t)}}class PodDateTimeColumn extends PodColumnBase{constructor(e,t={}){super(e,"datetime",t)}}class PodJsonColumn extends PodColumnBase{constructor(e,t={}){super(e,"json",t)}}class PodObjectColumn extends PodColumnBase{constructor(e,t={}){super(e,"object",t)}}class PodUriColumn extends PodColumnBase{constructor(e,t={}){super(e,"uri",t)}}class PodArrayColumn extends PodColumnBase{constructor(e,t,i={}){super(e,"array",i),this.elementType=t}}function boolean$2(n,e={}){return new ColumnBuilder(n,"boolean",e)}function timestamp(n,e={}){return new ColumnBuilder(n,"datetime",e)}function object$1(n,e={}){return new ColumnBuilder(n,"object",e)}function uri(n,e={}){return new ColumnBuilder(n,"uri",e)}function id(n="id",e={}){const t=new PodStringColumn(n,{...e,predicate:"@id",primaryKey:!0,required:!0,...e.defaultValue!==void 0?{defaultValue:e.defaultValue}:{}});return t._virtualId=!0,t}function string$2(n,e={}){return new ColumnBuilder(n,"string",e)}function integer$1(n,e={}){return new ColumnBuilder(n,"integer",e)}function date$3(n,e={}){return new ColumnBuilder(n,"datetime",e)}function text(n,e={}){return new ColumnBuilder(n,"string",e)}function real(n,e={}){return new ColumnBuilder(n,"integer",e)}function validateColumnOverride(n,e,t){const i=n.getPredicateUri?.()??n.options?.predicate,s=e.options?.predicate;if(i&&s&&i!==s)throw new Error(`Schema 继承错误: 不能修改 "${t}" 列的 predicate。父 schema 定义为 "${s}",子 schema 尝试改为 "${i}"。子类只能添加约束(notNull, default),不能更改 predicate。`)}function mergeSchemaColumns(n,e){const t={};for(const[i,s]of Object.entries(n.columns))t[i]=s;for(const[i,s]of Object.entries(e)){const a=n.columns[i];if(a&&!(s instanceof PodColumnBase)){validateColumnOverride(s,a,i);const l=s;!l.getPredicateUri?.()&&!l.options?.predicate&&(l.options={...l.options,predicate:a.options?.predicate})}t[i]=s}return t}function renderDefaultIdTemplate(n,e){if(!/\{[^{}]+\}/.test(n))return n;if(/\{\s*id\s*\}/.test(n))throw new Error("id default template uses {key} for the generated local key; {id} is the final resource id");const t=e.row??{},i=resolveDate(t,e.now),s={yyyy:String(i.getUTCFullYear()),MM:String(i.getUTCMonth()+1).padStart(2,"0"),dd:String(i.getUTCDate()).padStart(2,"0")};return n.replace(/\{([^{}]+)\}/g,(a,l)=>{const u=l.trim();if(u==="key")return e.key;if(u==="yyyy")return s.yyyy;if(u==="MM")return s.MM;if(u==="dd")return s.dd;const f=resolveExpression(u,t,e);return f==null?"":String(f)})}function resolveDate(n,e=new Date){const t=n.createdAt??n.favoredAt??n.indexedAt??e,i=t instanceof Date?t:new Date(typeof t=="number"&&Math.abs(t)<1e11?t*1e3:t);return Number.isFinite(i.getTime())?i:e}function resolveExpression(n,e,t){const i=parseExpression(n);let s=resolveTemplatePath(i.path,e,t);for(const a of i.transforms)s=applyTransform(s,a,i.path,t);return i.selector?applyPathSelector(s,i.selector):s}function parseExpression(n){const e=n.match(/^(.+?)\[(.*)\]$/),t=e?e[1].trim():n,[i,...s]=t.split("|").map(a=>a.trim()).filter(Boolean);return{path:i??n,transforms:s,selector:e?.[2]?.trim()}}function resolveTemplatePath(n,e,t){const i=n.split("."),s=i[0];return i.reduce((a,l,u)=>{if(typeof a=="string")return s?resolveResourceProperty(a,s,l,t):void 0;if(!(!a||typeof a!="object"))return s&&isResourceProperty(l)&&!((l==="id"||l==="key")&&l in a)?resolveResourceProperty(a,s,l,t):u>0&&l==="id"&&readRef(a)?extractResourceId(a,s??"",t):a[l]},e)}function isResourceProperty(n){return n==="id"||n==="key"||n==="doc"||n==="document"||n==="dir"||n==="owner"}function resolveResourceProperty(n,e,t,i){if(t==="id")return extractResourceId(n,e,i);const s=extractResourceId(n,e,i);if(s){if(t==="key"){const a=extractTemplateValuesForField(n,e,i);return a?.key??a?.id??deriveResourceKey(s)}if(t==="doc"||t==="document")return resourceDocument(s);if(t==="dir"||t==="owner")return deriveOwnerDir(s)}}function applyTransform(n,e,t,i){if(e==="slug")return slugifyValue(String(n??""));const s=extractResourceId(n,t,i);if(e==="resource")return s;if(e==="document")return s?resourceDocument(s):"";if(e==="owner")return s?deriveOwnerDir(s):"";const a=extractTemplateValuesForField(n,t,i);return e==="id"?a?.id??a?.key??s??"":a?.[e]??""}function extractResourceId(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return normalizePodDataResourceId$1(i);if(!isCompleteResourceId$1(i))return renderLinkedResourceId(s,i);const a=relativeSubjectFromRef$1(s,i);return normalizePodDataResourceId$1(a??i)}function extractTemplateValuesForField(n,e,t){const i=readRef(n);if(!i)return null;const s=resolveLinkedResource(e,t);if(!s)return null;const a=relativeSubjectFromRef$1(s,i)??(isCompleteResourceId$1(i)?null:renderLinkedResourceId(s,i));if(!a)return null;const l=resourceTemplate(s);return l?extractVarsFromTemplate(normalizePodDataResourceId$1(a),l):{id:normalizePodDataResourceId$1(a)}}function resolveLinkedResource(n,e){const t=e.links?.[n];if(t)return t;const i=e.resource?.columns?.[n];return i?.getLinkTable?.()??i?.options?.linkTable??null}function resourceTemplate(n){const e=n.getSubjectTemplate?.()??n.config?.subjectTemplate;if(e)return e;const t=n.columns?.id?.options?.defaultValue;return typeof t=="string"?t:null}function renderLinkedResourceId(n,e){const t=resourceTemplate(n);if(!t)return e;const i=n.columns?.id?.options?.defaultValue;return typeof i=="function"?String(i(e,{})):t.replace(/\{([^}]+)\}/g,(s,a)=>{const l=parseTemplateField(a);return l==="id"||l==="key"?e:""})}function readRef(n){if(typeof n=="string"&&n.length>0)return n;if(!n||typeof n!="object")return null;const e=n,t=e["@id"]??e.subject??e.id;return typeof t=="string"&&t.length>0?t:null}function resourcePath(n){return normalizeResourcePath$1(n.getResourcePath?.()??n.config?.base??"")}function relativeSubjectFromRef$1(n,e){const t=resourcePath(n);if(!t)return normalizePodDataResourceId$1(e);const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const a=e.indexOf(s);if(a<0)continue;let l=e.slice(a+s.length);return l.startsWith("/")&&(l=l.slice(1)),l.length>0?l:null}return normalizePodDataResourceId$1(e)}function extractVarsFromTemplate(n,e){let t=0;const i=new Map,s=[];let a=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp$1(e.slice(a,u.index)));const f=`var${t++}`;i.set(f,parseTemplateField(u[1]??"")),s.push(`(?<${f}>.+?)`),a=u.index+u[0].length}s.push(escapeRegExp$1(e.slice(a)));const l=s.join("");try{const u=n.match(new RegExp(`^${l}$`));if(!u?.groups)return null;const f={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);!g||p===void 0||(f[g]=decodeURIComponent(p))}return f}catch{return null}}function parseTemplateField(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function escapeRegExp$1(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function applyPathSelector(n,e){const t=splitResourcePath(n);if(!t)return;if(/^-?\d+$/.test(e))return t[normalizeIndex(Number(e),t.length)];const i=e.match(/^(-?\d*)\s*:\s*(-?\d*)$/);if(!i)throw new Error(`Invalid id default path selector [${e}]`);const s=i[1]===""?0:normalizeSliceIndex(Number(i[1]),t.length),a=i[2]===""?t.length:normalizeSliceIndex(Number(i[2]),t.length);return t.slice(s,a).join("/")}function splitResourcePath(n){const e=readRef(n);if(!e)return null;const t=normalizePodDataResourceId$1(e),[i,s]=t.split("#"),a=(i??t).split("/").filter(Boolean);return s&&a.push(s),a}function normalizePodDataResourceId$1(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function normalizeResourcePath$1(n){return n.trim().replace(/^(\.\/)+/,"")}function isCompleteResourceId$1(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function deriveOwnerDir(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#"),i=t>=0?e.slice(0,t):e,s=t>=0?e.slice(t+1):"",a=i.match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/[^/]+\.(?:ttl|jsonld|json)$/i);if(a?.[1])return a[1];if(i==="task/index.ttl"&&s&&s!=="this")return`task/${s}`;const l=i.match(/^(.+)\/index\.(?:ttl|jsonld|json)$/i);if(l?.[1])return l[1];const u=i.match(/^(.+)\.(?:ttl|jsonld|json)$/i);if(u?.[1])return u[1];const f=i.split("/").filter(Boolean);return f.length>1?f.slice(0,-1).join("/"):i}function resourceDocument(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");return t>=0?e.slice(0,t):e}function deriveResourceKey(n){const e=normalizePodDataResourceId$1(n),t=e.indexOf("#");if(t>=0){const u=e.slice(t+1);if(u&&u!=="this"&&u!=="me"&&u!=="it")return u}const i=resourceDocument(e).replace(/\/+$/u,""),s=i.match(/(?:^|\/)([^/]+)\/index\.(?:ttl|jsonld|json)$/iu);if(s?.[1])return s[1];const a=i.match(/(?:^|\/)([^/]+)\.(?:ttl|jsonld|json)$/iu);if(a?.[1])return a[1];const l=i.split("/").filter(Boolean);return l.length>0?l[l.length-1]:e}function slugifyValue(n){return n.normalize("NFKC").toLowerCase().trim().replace(/[\s_]+/g,"-").replace(/[^\p{Letter}\p{Number}.-]+/gu,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function normalizeIndex(n,e){return n<0?e+n:n}function normalizeSliceIndex(n,e){const t=n<0?e+n:n;return Math.max(0,Math.min(e,t))}function parseTemplateVariableField$1(n){const e=n.split("|").map(i=>i.trim()).filter(Boolean)[0]??n,t=e.replace(/\[[^\]]*\]$/u,"").trim();return t.split(".")[0]?.trim()||t||e}function normalizeResourcePath(n){return n.trim().replace(/^(\.\/)+/,"")}function podResourcePath(n){return normalizeResourcePath(n.getResourcePath?.()??n.config?.base??"")}function podResourceSubjectTemplate(n){return n.getSubjectTemplate?.()??n.config?.subjectTemplate}function podResourceIdDefaultTemplate(n){const e=n.columns?.id?.options?.defaultValue;return typeof e=="string"?e:void 0}function resourceRelativePrefix(n){const e=podResourcePath(n),t=normalizeResourcePath(n.getContainerPath?.()??n.config?.containerPath??"");return e?t&&e.startsWith(t)?normalizeResourcePath(e.slice(t.length)):e.split("/").pop()??e:""}function qualifyFragmentResourceId(n,e){if(!e.startsWith("#"))return e;const t=resourceRelativePrefix(n);return t?`${t}${e}`:e}function templateRelativeSubject(n,e){if((podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n))?.startsWith("#")&&!e.startsWith("#")){const i=e.indexOf("#");if(i>=0)return e.slice(i)}return e}function isBaseRelativeSubjectId$1(n){return!n||/^https?:\/\//.test(n)||n.startsWith("/")?!1:n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:#|$)/i.test(n)}function isTemplateCompleteResourceId(n,e){if(!e||/^https?:\/\//.test(e)||e.startsWith("/"))return!1;const t=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n);return t?extractTemplateValues(templateRelativeSubject(n,e),t)!==null:!1}function isResourceRelativeSubjectId(n,e){return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)}function relativeSubjectFromRef(n,e){const t=podResourcePath(n);if(!t)return null;const i=Array.from(new Set([t,t.replace(/^\/+/,""),t.endsWith("/")?t.slice(0,-1):t].filter(Boolean)));for(const s of i){const a=e.indexOf(s);if(a<0)continue;let l=e.slice(a+s.length);if(l.startsWith("/")&&(l=l.slice(1)),l.length>0)return l}return isBaseRelativeSubjectId$1(e)||isTemplateCompleteResourceId(n,e)?normalizeResourcePath(e):null}function extractTemplateValues(n,e){if(!e.includes("{"))return n===e?{}:null;let t=0;const i=new Map,s=[];let a=0;for(const u of e.matchAll(/\{([^}]+)\}/g)){s.push(escapeRegExp(e.slice(a,u.index)));const f=`var${t++}`;i.set(f,parseTemplateVariableField$1(u[1]??"")),s.push(`(?<${f}>.+?)`),a=u.index+u[0].length}s.push(escapeRegExp(e.slice(a)));const l=`^${s.join("")}$`;try{const u=n.match(new RegExp(l));if(!u?.groups)return null;const f={};for(const[d,p]of Object.entries(u.groups)){const g=i.get(d);if(!g||p===void 0)continue;const m=decodeURIComponent(p);if(g in f&&f[g]!==m)return null;f[g]=m}return f}catch{return null}}function escapeRegExp(n){return n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function parsePodResourceRef(n,e){if(!e)return null;const t=relativeSubjectFromRef(n,e);if(!t)return null;const i=qualifyFragmentResourceId(n,t),s=podResourceSubjectTemplate(n)??podResourceIdDefaultTemplate(n),a=s?extractTemplateValues(templateRelativeSubject(n,i),s):{id:decodeURIComponent(i)};return a?{resourceId:decodeURIComponent(i),templateValues:a}:null}function extractPodResourceTemplateValue(n,e,t="id"){return parsePodResourceRef(n,e)?.templateValues[t]??null}function resolvePodBaseUrl(n){const e=n.trim();return e?e.includes("/profile/card#me")?e.replace("/profile/card#me","").replace(/\/+$/u,""):e.replace(/\/+$/u,""):""}function resolvePodBaseUrlFromDatabase(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getDialect=="function"?e.getDialect():null,i=readPodUrl(t);if(i)return resolvePodBaseUrl(i);const s=typeof e.getSession=="function"?e.getSession():e.session,a=readPodUrl(s);if(a)return resolvePodBaseUrl(a);const l=readWebId(s);return l&&l.includes("/profile/card#me")?resolvePodBaseUrl(l):null}function normalizePodDataResourceId(n){const e=n.indexOf("#"),[t,i=""]=e>=0?[n.slice(0,e),n.slice(e)]:[n,""],s=t.indexOf("/.data/");return`${s>=0?t.slice(s+7):t.replace(/^\/?\.data\//u,"").replace(/^\/+/u,"")}${i}`}function resolvePodResourceId(n,e){const t=resolveKnownTargetIri(e);if(t)return parsePodResourceRef(n,t)?.resourceId??normalizePodDataResourceId(t);if(typeof e=="string")return assertCompleteStringResourceId(n,e),normalizePodDataResourceId(e);const i=typeof e.id=="string"&&e.id.trim().length>0?e.id.trim():void 0;if(!i)throw new Error("resolvePodResourceId requires a resource id on target.id or a full target IRI");if(isCompleteResourceId(i)||isTemplateCompleteResourceId(n,i))return normalizePodDataResourceId(i);const s=resolveDefaultResourceId(n,i,e);if(s)return normalizePodDataResourceId(s);const a=podResourceSubjectTemplate(n);return normalizePodDataResourceId(a?renderSubjectTemplateResourceId(a,i,e):i)}function buildPodResourceIri(n,e){const t=resolvePodBaseUrl(n);if(!t||/^https?:\/\//u.test(e))return e;const i=e.startsWith("/")?e:`/.data/${normalizePodDataResourceId(e)}`;return new URL(i.replace(/^\/+/u,""),`${t}/`).toString()}function buildPodResourceIriForResource(n,e,t){const i=resolveKnownTargetIri(t);if(i)return i;const s=resolvePodRootTargetPath(t);if(s)return buildPodResourceIri(n,s);const a=resolvePodResourceId(e,t),l=isResourceRelativeSubjectId(e,a)?`${podResourcePath(e).replace(/\/+$/u,"")}/${normalizeResourcePath(a)}`:e.resolveUri?.(a)??`/.data/${normalizePodDataResourceId(a)}`;return buildPodResourceIri(n,l)}function buildPodResourceIriForDatabase(n,e,t){const i=resolvePodBaseUrlFromDatabase(n);if(!i)throw new Error("buildPodResourceIriForDatabase requires a database with a Pod URL or WebID");return buildPodResourceIriForResource(i,e,t)}function resolvePodResourceIriForDatabase(n,e,t){if(!t)return null;try{return buildPodResourceIriForDatabase(n,e,t)}catch{return null}}function resolveKnownTargetIri(n){if(typeof n=="string")return/^https?:\/\//u.test(n)?n:null;const e=n["@id"]??n.subject;return typeof e=="string"&&/^https?:\/\//u.test(e)?e:null}function resolvePodRootTargetPath(n){if(typeof n=="string")return n.startsWith("/")?n:null;const e=typeof n.id=="string"?n.id.trim():"";return e.startsWith("/")?e:null}function isCompleteResourceId(n){return/^https?:\/\//u.test(n)||n.startsWith("/")||n.startsWith("#")||n.includes("#")||/\.(ttl|jsonld|json)(?:$|[?#])/iu.test(n)}function assertCompleteStringResourceId(n,e){if(isCompleteResourceId(e)||isTemplateCompleteResourceId(n,e))return;const t=n.columns?.id?.options?.defaultValue!==void 0,i=podResourceSubjectTemplate(n);if(t||i)throw new Error("resolvePodResourceId does not accept local keys as string targets. Pass a structured row object with id and required fields, or pass a complete resource id/IRI.")}function resolveDefaultResourceId(n,e,t){const i=n.columns?.id?.options?.defaultValue;if(i===void 0)return null;if(typeof i=="string")return renderDefaultIdTemplate(i,{key:e,row:t,resource:n});if(typeof i!="function")return String(i);const s=i;return s.length===0?String(s()):String(s(e,t))}function renderSubjectTemplateResourceId(n,e,t){const i=n.replace(/\{\s*id\s*\}/gu,"{key}");return renderDefaultIdTemplate(i,{key:encodeURIComponent(e),row:t})}function readPodUrl(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.getPodUrl=="function"?e.getPodUrl():e.info?.podUrl??e.podUrl;return typeof t=="string"&&t.trim().length>0?t:null}function readWebId(n){if(!n||typeof n!="object")return null;const e=n,t=e.info?.webId??e.webId;return typeof t=="string"&&t.trim().length>0?t:null}var _a$a;class PodTable{constructor(e,t,i){this.initialized=!1;const s=i.type;if(!s)throw new Error("podTable requires a type (RDF class) via options.type");const a=i.typeIndex,l=a==="private"||a==="public",u=this.resolveBase(i.base,e);this.resourcePath=u.resourcePath,this.containerPath=u.containerPath;const f=this.resolveSubjectTemplate(i.subjectTemplate,u.resourcePath,u.containerPath,e);this.subjectTemplate=f.template,this.hasCustomSubjectTemplate=f.isCustom,this.resourceMode=i.resourceMode??(i.sparqlEndpoint?"sparql":void 0),this.sparqlEndpoint=i.sparqlEndpoint,this.registerTypeIndexEnabled=l&&i.autoRegister!==!1,this.config={name:e,base:u.resourcePath,type:resolveTermIri(s),namespace:i.namespace,typeIndex:l?a:void 0,saiRegistryPath:i.saiRegistryPath,autoRegister:i.autoRegister,containerPath:u.containerPath,hooks:i.hooks},this.subjectTemplate&&(this.config.subjectTemplate=this.subjectTemplate),this.parentClasses=this.normalizeParents(i.subClassOf??[]),this.parentClasses.length>0&&(this.config.subClassOf=[...this.parentClasses]),this.columns=t,Object.assign(this,t);let d=0;for(const p of Object.values(t))if(p.options.primaryKey&&d++,p.table=this,p.tableName=e,!p.options.predicate&&!p._virtualId&&!i.namespace)throw new Error(`Column "${p.name}" in table "${e}" is missing a predicate.`);if(d!==1)throw new Error(`PodTable "${e}" must have exactly one primary key column. Found ${d}.`);this.$inferSelect={},this.$inferInsert={},this.$inferUpdate={},this._={brand:"Table",config:this.config,name:e,schema:void 0,columns:t,inferSelect:{},inferInsert:{},inferUpdate:{}},this.mapping=this.buildTableMapping()}getContainerPath(){return this.containerPath}getType(){return this.config.type}getRdfClass(){return this.getType()}getNamespace(){return this.config.namespace}getSubjectTemplate(){return this.subjectTemplate}buildId(e){return resolvePodResourceId(this,e)}buildIri(e,t){return buildPodResourceIriForResource(e,this,t)}buildIriForDatabase(e,t){return buildPodResourceIriForDatabase(e,this,t)}resolveIriForDatabase(e,t){return resolvePodResourceIriForDatabase(e,this,t)}parseRef(e){return parsePodResourceRef(this,e)}extractTemplateValue(e,t="id"){return extractPodResourceTemplateValue(this,e,t)}hasCustomTemplate(){return this.hasCustomSubjectTemplate}getSubClassOf(){return[...this.parentClasses]}getMapping(){return this.mapping}get $schema(){return new SolidSchema(this.columns,{type:this.config.type,namespace:this.config.namespace,subjectTemplate:this.subjectTemplate,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0})}resolveUri(e){const t=this.subjectTemplate;if(!t)return/^https?:\/\//.test(e)||e.startsWith("/")?e:`${this.config.base.endsWith("/")?this.config.base:`${this.config.base}/`}${e}`;const i=t.replace(/\{id\}/g,e);return i.startsWith("#")?`${this.resourcePath}${i}`:`${this.containerPath.endsWith("/")?this.containerPath:`${this.containerPath}/`}${i}`}resolveBase(e,t){if(!e||e.trim().length===0)throw new Error(`podTable '${t}' requires a 'base' option.`);const i=this.normalizeBaseInput(e),s=this.normalizeResourcePath(i);if(s.endsWith("/")){const l=this.ensureTrailingSlash(s);return{resourcePath:l,containerPath:l}}const a=this.ensureTrailingSlash(this.deriveContainerPath(s));return{resourcePath:s,containerPath:a}}normalizeBaseInput(e){const t=e.trim(),i=t.match(/^([a-zA-Z][\w+.-]*):\/\/(.*)$/);if(i){const[,s,a]=i,l=s.toLowerCase(),u=a.trim();return l==="http"||l==="https"?`${l}://${u}`:u.startsWith("/")?u:`/${u}`}return t}normalizeResourcePath(e){if(/^[a-zA-Z][\w+.-]*:\/\//.test(e))return e;const i=e.trim().replace(/^(\.\/)+/,"").replace(/\/+/g,"/");return i.startsWith("/")?i:`/${i}`}deriveContainerPath(e){const t=e.endsWith("/")?e.slice(0,-1):e,i=t.lastIndexOf("/");return i===-1?"/":t.slice(0,i+1)}ensureTrailingSlash(e){return e.endsWith("/")?e:`${e}/`}getResourcePath(){return this.resourcePath}getResourceMode(){return this.resourceMode}getSparqlEndpoint(){return this.sparqlEndpoint}shouldRegisterTypeIndex(){return this.registerTypeIndexEnabled}async init(e){await e.registerTable(this)}isInitialized(){return this.initialized}markInitialized(e=!0){this.initialized=e}setBase(e){const t=this.resolveBase(e,this.config.name);this.resourcePath=t.resourcePath,this.containerPath=t.containerPath,this.config.base=t.resourcePath,this.config.containerPath=t.containerPath,this._?.config&&(this._.config.base=this.config.base,this._.config.containerPath=this.config.containerPath),this.hasCustomSubjectTemplate||(this.subjectTemplate=void 0,delete this.config.subjectTemplate,this._?.config&&delete this._.config.subjectTemplate),this.mapping=this.buildTableMapping()}setSubjectTemplate(e){this.subjectTemplate=e,this.hasCustomSubjectTemplate=!0,this.config.subjectTemplate=e,this._?.config&&(this._.config.subjectTemplate=e),this.mapping=this.buildTableMapping()}setSparqlEndpoint(e){this.sparqlEndpoint=e,this.resourceMode||(this.resourceMode="sparql")}getColumns(){return this.columns}getColumn(e){return this.columns[e]}hasColumn(e){return e in this.columns}resolveSubjectTemplate(e,t,i,s){return e&&e.trim().length>0?{template:e.trim(),isCustom:!0}:{template:void 0,isCustom:!1}}buildTableMapping(){const e={};for(const t of Object.values(this.columns))e[t.name]=this.buildColumnMapping(t);return{name:this.config.name,type:this.config.type,subjectTemplate:this.subjectTemplate,namespace:this.config.namespace,subClassOf:this.parentClasses.length>0?[...this.parentClasses]:void 0,columns:e,relations:this.relations}}buildColumnMapping(e){const t=e._virtualId?"@id":e.getPredicate(this.config.namespace);return{column:e.name,predicate:t,kind:e.isLink()?"object":"datatype",datatype:this.inferColumnDatatype(e),linkTarget:e.getLinkTarget(),isArray:e.options.isArray??!1,inverse:e.isInverse()}}inferColumnDatatype(e){switch(e.dataType){case"string":return"http://www.w3.org/2001/XMLSchema#string";case"integer":return"http://www.w3.org/2001/XMLSchema#integer";case"boolean":return"http://www.w3.org/2001/XMLSchema#boolean";case"datetime":return"http://www.w3.org/2001/XMLSchema#dateTime";case"json":case"object":return"http://www.w3.org/2001/XMLSchema#json";default:return}}normalizeParents(e){if(!e)return[];const i=(Array.isArray(e)?e:[e]).map(s=>resolveTermIri(s)).filter(s=>s&&s.length>0);return Array.from(new Set(i))}}_a$a=entityKind;PodTable[_a$a]="PodTable";function podTable(n,e,t){const i={};for(const[s,a]of Object.entries(e)){if(a instanceof PodColumnBase){i[s]=a;continue}let l;switch(a.dataType){case"integer":l=new PodIntegerColumn(a.name,a.options);break;case"datetime":l=new PodDateTimeColumn(a.name,a.options);break;case"boolean":l=new PodBooleanColumn(a.name,a.options);break;case"json":l=new PodJsonColumn(a.name,a.options);break;case"object":l=new PodObjectColumn(a.name,a.options);break;case"array":{const f=a.elementType??a.options.baseType??"string";l=new PodArrayColumn(a.name,f,a.options);break}case"uri":l=new PodUriColumn(a.name,a.options);break;default:l=new PodStringColumn(a.name,a.options);break}const u=a.getPredicateUri?.();u&&l.predicate(u),i[s]=l}return new PodTable(n,i,t)}class SolidSchema{constructor(e,t){this.columns=e,this.options=t,this.$kind="SolidSchema",this.namespace=t.namespace,this.subjectTemplate=t.subjectTemplate,this.subClassOf=t.subClassOf?Array.isArray(t.subClassOf)?t.subClassOf.map(resolveTermIri):[resolveTermIri(t.subClassOf)]:void 0}table(e,t){return new PodTable(e,this.columns,{...this.options,...t})}extend(e,t){const i=mergeSchemaColumns(this,e),s=[this.type];return this.subClassOf&&s.push(...this.subClassOf),solidSchema(i,{...t,subClassOf:s})}get type(){return resolveTermIri(this.options.type)}}function solidSchema(n,e){const t={};for(const[i,s]of Object.entries(n)){if(s instanceof PodColumnBase){t[i]=s;continue}let a;switch(s.dataType){case"integer":a=new PodIntegerColumn(s.name,s.options);break;case"datetime":a=new PodDateTimeColumn(s.name,s.options);break;case"boolean":a=new PodBooleanColumn(s.name,s.options);break;case"json":a=new PodJsonColumn(s.name,s.options);break;case"object":a=new PodObjectColumn(s.name,s.options);break;case"array":{const u=s.elementType??s.options.baseType??"string";a=new PodArrayColumn(s.name,u,s.options);break}case"uri":a=new PodUriColumn(s.name,s.options);break;default:a=new PodStringColumn(s.name,s.options);break}const l=s.getPredicateUri?.();l&&a.predicate(l),t[i]=a}return new SolidSchema(t,e)}function isSolidSchema(n){return n instanceof SolidSchema||n?.$kind==="SolidSchema"}const index=Object.freeze(Object.defineProperty({__proto__:null,ColumnBuilder,PodArrayColumn,PodBooleanColumn,PodColumnBase,PodDateTimeColumn,PodIntegerColumn,PodJsonColumn,PodObjectColumn,PodStringColumn,PodTable,PodUriColumn,SolidSchema,boolean:boolean$2,date:date$3,generateNanoId,hasStringValue:hasStringValue$2,hasTermValue,id,integer:integer$1,isSolidSchema,mergeSchemaColumns,object:object$1,podTable,real,resolveTermIri,solidSchema,string:string$2,text,timestamp,uri,validateColumnOverride},Symbol.toStringTag,{value:"Module"})),XSD$9="http://www.w3.org/2001/XMLSchema#";function getPredicateForColumn(n,e){if(!n)return"http://example.org/unknown";if(typeof e.getMapping=="function"){const s=e.getMapping()?.columns?.[n.name];if(s?.predicate)return s.predicate}if(typeof n.getPredicateUri=="function")return n.getPredicateUri();if(n._predicateUri)return n._predicateUri;if(n.predicate&&typeof n.predicate=="string")return n.predicate;const t=e instanceof SolidSchema?e.options.namespace:e.config.namespace;if(typeof n.getPredicate=="function")try{return n.getPredicate(t)}catch{}return n.options?.predicate?n.options.predicate:t?`${typeof t=="string"?t:t.uri}${n.name}`:(n.name==="id"&&console.log("[DEBUG] getPredicateForColumn 'id' fallback to example.org. Column:",n),`http://example.org/${n.name}`)}function formatValue(n,e,t,i){return Array.isArray(n)?n.map(s=>formatSingleValue(s,e,t,i)):formatSingleValue(n,e,t,i)}function formatSingleValue(n,e,t,i){if(n==null)return'""';if(e?.dataType==="uri"||e?.options?.linkTarget){const s=String(n);if(s.startsWith("<")&&s.endsWith(">")){const a=s.slice(1,-1);return t&&!t.isAbsoluteUri(a)?`<${t.resolveLink(a,e,i)}>`:s}return t?`<${t.resolveLink(s,e,i)}>`:s.startsWith("<")?s:`<${s}>`}return typeof n=="string"?!e&&(n.startsWith("http://")||n.startsWith("https://"))?`<${n}>`:`"${n.replace(/\\/g,"\\\\").replace(/"/g,'"')}"`:typeof n=="number"?Number.isInteger(n)?String(n):`"${n}"^^<${XSD$9}decimal>`:typeof n=="boolean"?`"${n}"^^<${XSD$9}boolean>`:n instanceof Date?`"${n.toISOString()}"^^<${XSD$9}dateTime>`:`"${String(n)}"`}function resolveColumn(n,e){if(n&&typeof n=="object"&&n instanceof PodColumnBase)return n;if(n&&typeof n=="object"&&"name"in n){const t=n.name;if(typeof t=="string"&&e.columns[t])return e.columns[t]}if(typeof n=="string"){const t=e.columns[n];if(t)return t}throw new Error(`Unable to resolve column reference for select field: ${String(n)}`)}function generateSubjectUri(n,e,t){const i=t.resolveSubject(e,n);if(!i)throw new Error("Failed to generate subject URI");return i}const scriptRel="modulepreload",assetsURL=function(n){return"/auth/callback/"+n},seen={},__vitePreload=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let f=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=l?.nonce||l?.getAttribute("nonce");s=f(t.map(d=>{if(d=assetsURL(d),d in seen)return;seen[d]=!0;const p=d.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${g}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":scriptRel,p||(m.as="script"),m.crossOrigin="",m.href=d,u&&m.setAttribute("nonce",u),document.head.appendChild(m),p)return new Promise((v,S)=>{m.addEventListener("load",v),m.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function a(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&a(u.reason);return e().catch(a)})};var _a$9;class SPARQLExpression{constructor(){this[_a$9]="SPARQLExpression"}}_a$9=Symbol.toStringTag;class BinaryExpression extends SPARQLExpression{constructor(e,t,i){super(),this.left=e,this.operator=t,this.right=i,this.type="binary_expr"}}class LogicalExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.expressions=t,this.type="logical_expr"}}class UnaryExpression extends SPARQLExpression{constructor(e,t){super(),this.operator=e,this.value=t,this.type="unary_expr"}}class SelectionAliasExpression extends SPARQLExpression{constructor(e){super(),this.alias=e}}function eq(n,e){return new BinaryExpression(n,"=",e)}function like(n,e){return new BinaryExpression(n,"LIKE",e)}function inArray(n,e){return new BinaryExpression(n,"IN",e)}function and(...n){return new LogicalExpression("AND",n.filter(Boolean))}function or(...n){return new LogicalExpression("OR",n.filter(Boolean))}function parseActivityStreamsMessage(n){const e=JSON.parse(n);return{id:e.id||e["@id"]||"",type:e.type,object:typeof e.object=="string"?e.object:e.object?.id||e.object?.["@id"]||"",published:e.published||new Date().toISOString(),state:e.state}}class BaseChannel{constructor(e){this._connected=!1,this.config=e}get connected(){return this._connected}handleMessage(e){try{const t=parseActivityStreamsMessage(e);this.config.onNotification(t)}catch(t){this.handleError(new Error(`Failed to parse notification: ${t}`))}}handleError(e){this.config.onError?this.config.onError(e):console.error("[NotificationChannel] Error:",e)}handleClose(){this._connected=!1,this.config.onClose&&this.config.onClose()}}class SSEChannel extends BaseChannel{constructor(e){super(e),this.abortController=null,this.reader=null,this.contentType=""}async connect(){if(this._connected)return;this.abortController=new AbortController;const e=this.config.fetch||fetch;try{const t=`notify-sse-${Date.now()}`,i=await e(this.config.receiveFrom,{method:"GET",headers:{Accept:"text/turtle, text/event-stream","X-Request-ID":t},signal:this.abortController.signal});if(!i.ok)throw new Error(`SSE connection failed: ${i.status} ${i.statusText}`);if(!i.body)throw new Error("SSE response has no body");this.contentType=i.headers.get("content-type")||"",this._connected=!0,this.reader=i.body.getReader(),this.readStream()}catch(t){throw t.name!=="AbortError"&&this.handleError(t),t}}disconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader&&(this.reader.cancel().catch(()=>{}),this.reader=null),this._connected=!1,this.handleClose()}async readStream(){if(!this.reader)return;const e=new TextDecoder;let t="";try{for(;this._connected;){const{done:i,value:s}=await this.reader.read();if(i){t.trim()&&this.parseNotification(t.trim()),this.handleClose();break}const a=e.decode(s,{stream:!0});t+=a,this.contentType.includes("text/turtle")?t=this.processTurtleBuffer(t):t=this.processSSEBuffer(t)}}catch(i){i.name!=="AbortError"&&this.handleError(i)}}processTurtleBuffer(e){const t=e.split(`
88
88
  `);let i="";for(let s=0;s<t.length;s++){const a=t[s];i+=a+`
89
89
  `,a.trim().endsWith(".")&&(this.parseTurtleNotification(i.trim()),i="")}return i}processSSEBuffer(e){const t=e.split(`
90
90
 
@@ -120,7 +120,7 @@ LIMIT 50`,prefixes:{}},d=s.kind==="sparql"?await this.dialect.executeOnResource(
120
120
  VALUES ?linkPred { ${u} }
121
121
  ?parent ?linkPred ?child .
122
122
  OPTIONAL { ?child ?pred ?obj . }
123
- }`,prefixes:{}},F=await f.executeQueryWithSource(T,w);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,m=new Map,v=new Map;d.forEach(w=>{const A=this.normalizeInlineIri(w.parent),C=this.normalizeInlineIri(w.linkPred),T=this.normalizeInlineIri(w.child),F=this.normalizeInlineIri(w.pred),P=this.normalizeInlineObjectValue(w.obj);if(!A||!C)return;const M=a.get(C);if(M){const q=m.get(A)??new Map,ee=q.get(M.name)??[];T&&!ee.includes(T)&&ee.push(T),q.set(M.name,ee),m.set(A,q)}if(!T||!F)return;const O=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},Q=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,O);return}const pe=O[Q];pe===void 0?O[Q]=P:Array.isArray(pe)?O[Q]=[...pe,P]:O[Q]=[pe,P],v.set(T,O)});const S=w=>{if(Array.isArray(w))return w.map(C=>this.normalizeInlineIri(C)).filter(C=>!!C);const A=this.normalizeInlineIri(w);return A?[A]:[]},E=(w,A,C)=>{const T=w?m.get(w)?.get(C.name)??[]:[],P=(T.length>0?T:S(A)).map(M=>v.get(M)??{"@id":M,id:this.extractIdFromSubject(M,t)});return C.dataType==="array"?P:P[0]??null};return e.forEach(w=>{const A=this.normalizeInlineIri(w["@id"]??w.subject??w.uri??w.id);s.forEach(C=>{w[C.name]=E(A,w[C.name],C)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const a of this.orderByClauses){const l=this.getOrderByValue(i,a.column),u=this.getOrderByValue(s,a.column),f=this.compareOrderByValues(l,u);if(f!==0)return a.direction==="desc"?-f:f}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const a=this.serializeValueForKey(s);t.has(a)||(t.add(a),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(a=>{const l=this.normalizeInlineIri(a["@id"])??this.normalizeInlineIri(a.subject)??this.normalizeInlineIri(a.uri)??(typeof a.id=="string"?a.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...a});return}if(!t.has(l)){const d={...a};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const m=this.getColumnDefinitionForRowKey(p);(m?.options?.isArray||m?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),f=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(a).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const m=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...m];v.forEach(A=>{const C=f(A);S.some(T=>f(T)===C)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),w=E?.options?.isArray||E?.dataType==="array";!w&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):w?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(a=>t.get(a))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){return e?e.dataType==="object"?!0:e.dataType==="array"?(e.elementType??e.options?.baseType)==="object":!1:!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const w=this.serializeValueForKey(E);u.has(w)||u.set(w,E)}if(u.size===0)return[];const f=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(a.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const w=d(),C=await(conditionTargetsReservedIdentifier(E)?w.applyInternalQueryCondition(E):w.where(E));S.push(...C)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const m=this.buildJoinLookupCondition(p,f);if(m){const S=d(),w=await(conditionTargetsReservedIdentifier(m)?S.applyInternalQueryCondition(m):S.where(m));return this.normalizeJoinRows(e,w)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),f=a.column==="id"&&u.length>0;if(!f&&i.length===1)return;const d=new Map;for(const m of i){const v=m.left.alias===e.alias?m.left:m.right;d.set(v.column,m)}const p=[],g=new Set;for(const m of t){const v=this.getRowValueForColumn(m,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],w=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,M=this.getRowValueForColumn(m,P);if(M==null){if(f&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(Q=>{const pe=d.get(Q);if(!pe)return!0;const ee=(pe.left.alias===e.alias?pe.left:pe.right)===pe.left?pe.right:pe.left,_e=this.getRowValueForColumn(m,ee);return _e==null})));A=!0;break}const O=e.table.getColumn(F.column);if(!O){A=!0;break}E.push(eq(O,M)),w.push(`${F.column}:${this.serializeValueForKey(M)}`)}if(A)continue;if(f&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const O=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,Q=this.getRowValueForColumn(m,O);return Q==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const C=w.join("|");g.has(C)||(g.add(C),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),a=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${a}, join.${a})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const a=this.extractSubjectValue(i);if(a){s.subject=a,s["@id"]=a,s.uri=a,s[`${e.alias}.subject`]=a,s[`${e.alias}.@id`]=a,s[`${e.alias}.uri`]=a;const l=this.extractIdFromSubject(a,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const m of i)p.push({...g,...m});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[a]=s,l=a.left.alias===t.alias?a.left:a.right,u=l===a.left?a.right:a.left,f=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const m=this.serializeValueForKey(g);f.has(m)||f.set(m,[]),f.get(m).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),m=this.serializeValueForKey(g),S=(g!=null?f.get(m)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(a=>{const l=a.left.alias===i?a.left:a.right,u=l===a.left?a.right:a.left,f=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return f==null||d===void 0||d===null?!1:this.serializeValueForKey(f)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,a=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(a.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const a=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return a==null;case"IS NOT NULL":return a!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(a=>this.evaluateCondition(e,a)):i.toUpperCase()==="OR"?s.some(a=>this.evaluateCondition(e,a)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const a=parsePodResourceRef(t,e);if(a)return a.templateValues.id??a.resourceId}if(t){const a=this.session.getDialect?.(),u=(a?.getUriResolver?.()??new UriResolverImpl(a?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const a=e.slice(s+1);if(a.length>0)return a}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(a=>a.id||a["@id"]).filter(a=>typeof a=="string"&&a.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),a=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(a),a}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(a){console.error("[InsertQueryBuilder] afterInsert hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[a,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);for(const[a,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const a=e;return a.length===0?a():a(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):a;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,a])=>Array.isArray(a));return s.length===0?i:i.map(a=>{const l={...a};for(const[u,f]of s)u in l&&(l[u]=[...f]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const a of e)try{await t.afterUpdate(i,a,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):a;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(a){console.error("[DeleteQueryBuilder] afterDelete hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(a=>i.unregisterResourceSubject?.(e.table,a));return}s.forEach(a=>i.registerResourceSubject?.(e.table,a))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const a=this.getKnownRowIri(s);a&&i.add(a)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,a,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,a,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-CMOmp0rf.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),a=new Map;s.headers&&s.headers.forEach((f,d)=>{a.set(d.toLowerCase(),f||"")});const u={...s,headers:{get:f=>{const d=f.toLowerCase();return a.get(d)||null},has:f=>{const d=f.toLowerCase();return a.has(d)},forEach:f=>{a.forEach((d,p)=>f(d,p))},entries:()=>a.entries(),keys:()=>a.keys(),values:()=>a.values(),[Symbol.iterator]:()=>a.entries(),includes:f=>{if(!f)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(f.toLowerCase())||p.toLowerCase().includes(f.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:f=>{if(!f)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(f.toLowerCase())||p.toLowerCase().includes(f.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(f){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(f)),""}},json:async()=>{try{return await s.json()}catch(f){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(f)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(f){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(f)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(a=>{const l=a,u={},f=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>f(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())f(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&f(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let a=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(a=d.headers.get("ETag"),this.logging&&a&&console.log(`[UPDATE] Got ETag for ${s}: ${a}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":a??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),f=await u(l);if(f.ok)i.push({success:!0,source:s,status:f.status}),await this.invalidateCache(t,s);else if(f.status===409||f.status===412){this.logging&&console.log(`[UPDATE] ${f.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(f.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const m={...l,"If-Match":g},v=await u(m);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await f.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${f.status} ${f.statusText}`,details:p})}}else{const d=await f.text();i.push({success:!1,source:s,error:`${f.status} ${f.statusText}`,details:d})}}catch(a){i.push({success:!1,source:s,error:this.formatError(a)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
123
+ }`,prefixes:{}},F=await f.executeQueryWithSource(T,w);d.push(...F)}const g=t.config.namespace?.uri??t.config.namespace,m=new Map,v=new Map;d.forEach(w=>{const A=this.normalizeInlineIri(w.parent),C=this.normalizeInlineIri(w.linkPred),T=this.normalizeInlineIri(w.child),F=this.normalizeInlineIri(w.pred),P=this.normalizeInlineObjectValue(w.obj);if(!A||!C)return;const M=a.get(C);if(M){const q=m.get(A)??new Map,ee=q.get(M.name)??[];T&&!ee.includes(T)&&ee.push(T),q.set(M.name,ee),m.set(A,q)}if(!T||!F)return;const O=v.get(T)??{"@id":T,id:this.extractIdFromSubject(T,t)},Q=this.normalizeInlinePredicateKey(F,g);if(P===void 0){v.set(T,O);return}const pe=O[Q];pe===void 0?O[Q]=P:Array.isArray(pe)?O[Q]=[...pe,P]:O[Q]=[pe,P],v.set(T,O)});const S=w=>{if(Array.isArray(w))return w.map(C=>this.normalizeInlineIri(C)).filter(C=>!!C);const A=this.normalizeInlineIri(w);return A?[A]:[]},E=(w,A,C)=>{const T=w?m.get(w)?.get(C.name)??[]:[],P=(T.length>0?T:S(A)).map(M=>v.get(M)??{"@id":M,id:this.extractIdFromSubject(M,t)});return C.dataType==="array"?P:P[0]??null};return e.forEach(w=>{const A=this.normalizeInlineIri(w["@id"]??w.subject??w.uri??w.id);s.forEach(C=>{w[C.name]=E(A,w[C.name],C)})}),e}normalizeInlinePredicateKey(e,t){if(t&&e.startsWith(t))return e.slice(t.length);const i=e.lastIndexOf("#");if(i!==-1&&i<e.length-1)return e.slice(i+1);const s=e.lastIndexOf("/");return s!==-1&&s<e.length-1?e.slice(s+1):e}normalizeInlineObjectValue(e){if(e!=null)return typeof e=="object"&&"value"in e?e.value??void 0:e}normalizeInlineIri(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&typeof e["@id"]=="string")return e["@id"];if(typeof e=="object"&&typeof e.id=="string"&&e.id.includes("http"))return e.id;if(typeof e=="object"&&typeof e.value=="string")return e.value}}applyDeferredOrderBy(e){if(this.orderByClauses.length===0||e.length<2)return e;const t=[...e];return t.sort((i,s)=>{for(const a of this.orderByClauses){const l=this.getOrderByValue(i,a.column),u=this.getOrderByValue(s,a.column),f=this.compareOrderByValues(l,u);if(f!==0)return a.direction==="desc"?-f:f}return 0}),t}applyDistinctRows(e){if(!this.isDistinct||e.length<2)return e;const t=new Set,i=[];for(const s of e){const a=this.serializeValueForKey(s);t.has(a)||(t.add(a),i.push(s))}return i}applyDeferredOffsetAndLimit(e){const t=this.offsetCount??0,i=t>0?e.slice(t):e;return this.limitCount===void 0?i:i.slice(0,this.limitCount)}getOrderByValue(e,t){if(t in e)return e[t];const i=Object.keys(e).find(s=>s.endsWith(`.${t}`));if(i)return e[i]}compareOrderByValues(e,t){return e===t?0:e==null?1:t==null?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}mergeRowsBySubject(e){const t=new Map,i=[];return e.forEach(a=>{const l=this.normalizeInlineIri(a["@id"])??this.normalizeInlineIri(a.subject)??this.normalizeInlineIri(a.uri)??(typeof a.id=="string"?a.id:void 0);if(typeof process<"u"&&define_process_env_default$2?.DEBUG_INLINE_MERGE==="1"&&console.log("mergeRowsBySubject key",l),!l){i.push(`__anon_${i.length}`),t.set(i[i.length-1],{...a});return}if(!t.has(l)){const d={...a};Object.entries(d).forEach(([p,g])=>{if(g===void 0)return;const m=this.getColumnDefinitionForRowKey(p);(m?.options?.isArray||m?.dataType==="array")&&!Array.isArray(g)&&(d[p]=[g])}),t.set(l,d),i.push(l);return}const u=t.get(l),f=d=>{if(d instanceof Date)return`date:${d.toISOString()}`;if(typeof d=="string")return`str:${d}`;if(typeof d=="number")return`num:${d}`;if(typeof d=="boolean")return`bool:${d}`;if(d==null)return"nil";try{return`obj:${JSON.stringify(d)}`}catch{return`obj:${String(d)}`}};Object.entries(a).forEach(([d,p])=>{if(p===void 0)return;const g=u[d];if(g===void 0){u[d]=p;return}const m=Array.isArray(g)?g:[g],v=Array.isArray(p)?p:[p],S=[...m];v.forEach(A=>{const C=f(A);S.some(T=>f(T)===C)||S.push(A)});const E=this.getColumnDefinitionForRowKey(d),w=E?.options?.isArray||E?.dataType==="array";!w&&S.length>1?(console.warn(`[Data Integrity] Multiple values found for single-value column '${d}' on subject '${l}'. Using first value.`),u[d]=S[0]):w?u[d]=S:u[d]=S.length===1?S[0]:S})}),i.map(a=>t.get(a))}getColumnDefinitionForRowKey(e){if(!e)return;if(!e.includes("."))return this.selectedTable?.columns[e];const[t,i]=e.split(".",2);if(!(!t||!i))return t===this.primaryAlias?this.selectedTable?.columns[i]:this.aliasToTable.get(t)?.columns?.[i]}inferSourceFromChild(e,t){if(!e)return this.session.getDialect().getPodUrl();const i=e.indexOf("#");if(i>0)return e.slice(0,i);const s=t.getResourcePath?.()||t.config.base||t.getContainerPath?.();return s?s.startsWith("http")?s:`${this.session.getDialect().getPodUrl()}${s.replace(/^\//,"")}`:this.session.getDialect().getPodUrl()}isInlineObjectColumn(e){return e?e.dataType==="object"?!0:e.dataType==="array"?(e.elementType??e.options?.baseType)==="object":!1:!1}async applyJoinFallback(e){let t=e;for(const i of this.joins){const s=await this.fetchJoinRows(i,t);t=this.mergeRowsWithJoin(t,i,s)}return t}async fetchJoinRows(e,t){if(e.type==="crossJoin"){const S=await this.session.select().from(e.table);return this.normalizeJoinRows(e,S)}const i=e.resolvedConditions??[];if(i.length===0)return[];const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=new Map;for(const S of t){const E=this.getRowValueForColumn(S,l);if(E==null)continue;const w=this.serializeValueForKey(E);u.has(w)||u.set(w,E)}if(u.size===0)return[];const f=Array.from(u.values()),d=()=>this.session.select().from(e.table),p=e.table.getColumn(a.column),g=this.buildExactJoinLookupConditions(e,t);if(g&&g.length>0){const S=[];for(const E of g){const w=d(),C=await(conditionTargetsReservedIdentifier(E)?w.applyInternalQueryCondition(E):w.where(E));S.push(...C)}return this.mergeRowsBySubject(this.normalizeJoinRows(e,S))}const m=this.buildJoinLookupCondition(p,f);if(m){const S=d(),w=await(conditionTargetsReservedIdentifier(m)?S.applyInternalQueryCondition(m):S.where(m));return this.normalizeJoinRows(e,w)}const v=await d();return this.normalizeJoinRows(e,v)}buildExactJoinLookupConditions(e,t){const i=e.resolvedConditions??[];if(i.length===0)return;const[s]=i,a=s.left.alias===e.alias?s.left:s.right,l=a===s.left?s.right:s.left,u=this.getRequiredSubjectTemplateVariables(e.table),f=a.column==="id"&&u.length>0;if(!f&&i.length===1)return;const d=new Map;for(const m of i){const v=m.left.alias===e.alias?m.left:m.right;d.set(v.column,m)}const p=[],g=new Set;for(const m of t){const v=this.getRowValueForColumn(m,l);if(v==null)continue;const S=typeof v=="string"&&this.isAbsoluteIri(v),E=[],w=[];let A=!1;for(const T of i){const F=T.left.alias===e.alias?T.left:T.right,P=F===T.left?T.right:T.left,M=this.getRowValueForColumn(m,P);if(M==null){if(f&&!S&&u.includes(F.column))throw new Error(this.buildMissingJoinLocatorError(e,u.filter(Q=>{const pe=d.get(Q);if(!pe)return!0;const ee=(pe.left.alias===e.alias?pe.left:pe.right)===pe.left?pe.right:pe.left,_e=this.getRowValueForColumn(m,ee);return _e==null})));A=!0;break}const O=e.table.getColumn(F.column);if(!O){A=!0;break}E.push(eq(O,M)),w.push(`${F.column}:${this.serializeValueForKey(M)}`)}if(A)continue;if(f&&!S){const T=u.filter(F=>{const P=d.get(F);if(!P)return!0;const O=(P.left.alias===e.alias?P.left:P.right)===P.left?P.right:P.left,Q=this.getRowValueForColumn(m,O);return Q==null});if(T.length>0)throw new Error(this.buildMissingJoinLocatorError(e,T))}if(E.length===0)continue;const C=w.join("|");g.has(C)||(g.add(C),p.push(E.length===1?E[0]:and(...E)))}return p.length>0?p:void 0}buildJoinLookupCondition(e,t){if(!(!e||t.length===0))return t.length===1?eq(e,t[0]):inArray(e,t)}getRequiredSubjectTemplateVariables(e){const t=e.getSubjectTemplate?.()??e.config?.subjectTemplate??"";return Array.from(new Set(Array.from(t.matchAll(/\{([^}]+)\}/g)).map(i=>i[1].split("|")[0]?.trim()||i[1]).filter(Boolean))).filter(i=>i!=="id"&&i!=="index"&&i!=="yyyy"&&i!=="MM"&&i!=="dd"&&i!=="HH"&&i!=="mm"&&i!=="ss"&&i!=="timestamp"&&i!=="date")}isAbsoluteIri(e){return/^[a-zA-Z][\w+.-]*:\/\//.test(e)}buildMissingJoinLocatorError(e,t){const i=e.table.getSubjectTemplate?.()??e.table.config?.subjectTemplate??"<exact-id>",s=Array.from(new Set(t)),a=s[0]??"...";return`Cannot join table "${e.table.config.name??"unknown"}" by id with subjectTemplate "${i}" because locator variable(s) [${s.join(", ")}] are missing. Add join conditions for all required template variables (for example eq(base.${a}, join.${a})) or join via full IRI values.`}normalizeJoinRows(e,t){return t.map(i=>{const s={};for(const[l,u]of Object.entries(i))s[`${e.alias}.${l}`]=u;const a=this.extractSubjectValue(i);if(a){s.subject=a,s["@id"]=a,s.uri=a,s[`${e.alias}.subject`]=a,s[`${e.alias}.@id`]=a,s[`${e.alias}.uri`]=a;const l=this.extractIdFromSubject(a,e.table);l!==void 0&&(this.shouldUseSubjectIdentityColumn(e.table,"id")||s[`${e.alias}.id`]===void 0)&&(s[`${e.alias}.id`]=l)}return s})}mergeRowsWithJoin(e,t,i){if(t.type==="crossJoin"){if(e.length===0||i.length===0)return[];const p=[];for(const g of e)for(const m of i)p.push({...g,...m});return p}const s=t.resolvedConditions??[];if(s.length===0)return e;const[a]=s,l=a.left.alias===t.alias?a.left:a.right,u=l===a.left?a.right:a.left,f=new Map;for(const p of i){const g=this.getRowValueForColumn(p,l);if(g==null)continue;const m=this.serializeValueForKey(g);f.has(m)||f.set(m,[]),f.get(m).push(p)}const d=[];for(const p of e){const g=this.getRowValueForColumn(p,u),m=this.serializeValueForKey(g),S=(g!=null?f.get(m)??[]:[]).filter(E=>this.joinRowMatchesAllConditions(p,E,t.alias,s));if(S.length===0){if(t.type==="innerJoin")continue;d.push({...p,...this.createEmptyJoinRow(t)});continue}for(const E of S)d.push({...p,...E})}return d}joinRowMatchesAllConditions(e,t,i,s){return s.every(a=>{const l=a.left.alias===i?a.left:a.right,u=l===a.left?a.right:a.left,f=this.getRowValueForColumn(e,u),d=this.getRowValueForColumn(t,l);return f==null||d===void 0||d===null?!1:this.serializeValueForKey(f)===this.serializeValueForKey(d)})}createEmptyJoinRow(e){const t={};for(const i of Object.keys(e.table.columns))t[`${e.alias}.${i}`]=void 0;return t[`${e.alias}.subject`]=void 0,t[`${e.alias}.id`]=void 0,t}applyJoinFilters(e){return this.joinFilters.length===0?e:e.filter(t=>this.joinFilters.every(i=>this.evaluateCondition(t,i)))}applyHavingFilter(e){return this.havingCondition?e.filter(t=>this.evaluateCondition(t,this.havingCondition)):e}evaluateCondition(e,t){switch(t.type){case"binary_expr":return this.evaluateBinaryCondition(e,t);case"unary_expr":return this.evaluateUnaryCondition(e,t);case"logical_expr":return this.evaluateLogicalCondition(e,t);default:return!0}}evaluateBinaryCondition(e,t){const i=t.left,s=t.right,a=t.operator;if(!i)return!0;const l=this.resolveConditionOperandValue(e,i,this.primaryAlias),u=this.resolveConditionOperandValue(e,s);switch(a.toUpperCase()){case"=":return l===u;case"!=":case"<>":return l!==u;case">":return Number(l)>Number(u);case">=":return Number(l)>=Number(u);case"<":return Number(l)<Number(u);case"<=":return Number(l)<=Number(u);case"IN":return Array.isArray(u)&&u.includes(l);case"NOT IN":return Array.isArray(u)&&!u.includes(l);case"LIKE":return typeof l=="string"&&typeof u=="string"&&this.computeLikeMatch(l,u);default:return!0}}evaluateUnaryCondition(e,t){const i=t.operator,s=t.value;if(i.toUpperCase()==="NOT")return!this.evaluateCondition(e,s);if(!s)return!0;const a=this.resolveConditionOperandValue(e,s,this.primaryAlias);switch(i.toUpperCase()){case"IS NULL":return a==null;case"IS NOT NULL":return a!=null;default:return!0}}evaluateLogicalCondition(e,t){const i=t.operator,s=t.expressions??[];return i.toUpperCase()==="AND"?s.every(a=>this.evaluateCondition(e,a)):i.toUpperCase()==="OR"?s.some(a=>this.evaluateCondition(e,a)):!0}resolveConditionOperandValue(e,t,i){if(t instanceof SelectionAliasExpression)return e[t.alias];const s=this.getConditionColumnReference(t,i);return s?this.getRowValueForColumn(e,s):t}getColumnKeyCandidates(e){const t=[],i=this.primaryAlias;return e.alias===i&&t.push(e.column),t.push(`${e.alias}.${e.column}`),t}getRowValueForColumn(e,t){const i=this.getColumnKeyCandidates(t);for(const s of i)if(s in e)return e[s]}shouldUseSubjectIdentityColumn(e,t){const i=e?.columns?.[t];return!!(i?._virtualId||i?.options?.predicate==="@id")}serializeValueForKey(e){return e===null?"null":typeof e=="object"?JSON.stringify(e):String(e)}extractIdFromSubject(e,t){if(!e)return;if(t){const a=parsePodResourceRef(t,e);if(a)return a.templateValues.id??a.resourceId}if(t){const a=this.session.getDialect?.(),u=(a?.getUriResolver?.()??new UriResolverImpl(a?.getPodUrl?.()??"")).parseSubject(e,t);if(u&&u.id)return u.id}const i=e.indexOf("#");if(i!==-1)return e.slice(i);const s=e.lastIndexOf("/");if(s!==-1){const a=e.slice(s+1);if(a.length>0)return a}}computeLikeMatch(e,t){const i=t.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/%/g,".*").replace(/_/g,".")}$`,"i").test(e)}async selectIdsByCondition(e,t){return(await this.session.select({id:e.getColumn("id")??e.columns.id}).from(e).where(t).columns({"@id":e.columns.id})).map(a=>a.id||a["@id"]).filter(a=>typeof a=="string"&&a.length>0)}then(e,t){return this.execute().then(e,t)}}_a$7=entityKind;SelectQueryBuilder[_a$7]="SelectQueryBuilder";var _a$6;class InsertQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.getRowsWithDefaults();return{table:this.table,rows:i}}}values(e){return e instanceof SQL?this.sql=e:this.insertValues=e,this}returning(e){return this.returningFields=e??!0,this}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const i=this.sql.queryChunks.join(""),s=inferSPARQLQueryType(i);if(!s)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:s,query:i,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);return t.convertInsert(this.toIR())}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL insert in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.insertValues){const e=this.getRowsWithDefaults(),t=this.returningFields?this.getSubjectUris(e):[],i={type:"insert",table:this.table,values:Array.isArray(this.insertValues)?e:e[0],plan:{table:this.table,rows:e}},s=await this.session.execute(i),a=this.returningFields?await this.fetchReturningRowsBySubjects(t):s;return await this.runAfterInsertHooks(a),a}else throw new Error("No values specified for INSERT query")}then(e,t){return this.execute().then(e,t)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e);return projectReturningRows(orderRowsBySubjects(t,e),this.returningFields)}getSubjectUris(e){const t=this.session.getDialect().getUriResolver?.();if(!t)throw new Error("returning() requires dialect URI resolver support");return e.map(i=>generateSubjectUri(i,this.table,t))}async runAfterInsertHooks(e){const t=this.table.config.hooks;if(!t?.afterInsert)return;const i=this.buildHookContext();if(!i){console.warn("[InsertQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterInsert(i,s)}catch(a){console.error("[InsertQueryBuilder] afterInsert hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}getRowsWithDefaults(){const e=this.insertValues;if(!e)throw new Error("No values specified for INSERT query");return(Array.isArray(e)?e:[e]).map(i=>this.applyDefaultValues(i))}applyDefaultValues(e){const t={...e},i=this.table?.columns??{},s=Object.entries(i);for(const[a,l]of s.filter(([,u])=>!this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);for(const[a,l]of s.filter(([,u])=>this.isPrimaryKeyColumn(u)))this.applyDefaultValue(t,a,l);return t}applyDefaultValue(e,t,i){if(e[t]===void 0){const s=i.options?.defaultValue;s!==void 0&&(e[t]=this.resolveDefaultValue(s,i,e))}}resolveDefaultValue(e,t,i){const s=this.isPrimaryKeyColumn(t)?generateNanoId():void 0;if(typeof e=="string"&&s)return renderDefaultIdTemplate(e,{key:s,row:i,resource:this.table});if(typeof e!="function")return e;const a=e;return a.length===0?a():a(s,i)}isPrimaryKeyColumn(e){return e.options?.primaryKey===!0||e.options?.predicate==="@id"}}_a$6=entityKind;InsertQueryBuilder[_a$6]="InsertQueryBuilder";var _a$5;class UpdateQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{if(!this.updateData)throw new Error("No data specified for UPDATE query");const i=this.normalizeWhereConditionsForUpdate();if(!i)throw new Error("UPDATE operation requires where conditions to locate target resources");return{table:this.table,data:this.updateData,where:i}}}set(e){return e instanceof SQL?this.sql=e:this.updateData=e,this}returning(e){return this.returningFields=e??!0,this}where(e){if(e instanceof SQL)this.sql||(this.sql=e);else if(this.isQueryCondition(e)){assertPublicWhereCondition("update",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("update",e),this.whereConditions=e,this.conditionTree=void 0;return this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForUpdate(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertUpdate(i.data,i.where,i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL update in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else if(this.updateData){const e=this.toIR(),i=(this.returningFields?await this.fetchMatchedRows(e.where):[]).map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"update",table:this.table,data:e.data,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?await this.fetchReturningRowsBySubjects(i):a;return await this.runAfterUpdateHooks(l),l}else throw new Error("No data specified for UPDATE query")}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];return!this.conditionTree&&typeof t=="string"?await this.session.select().from(this.table).whereByIri(t):await this.session.select().from(this.table).where(e)}async fetchReturningRowsBySubjects(e){if(e.length===0)return[];const t=await this.session.select().from(this.table).whereByIri(e),i=projectReturningRows(orderRowsBySubjects(t,e),this.returningFields),s=Object.entries(this.updateData??{}).filter(([,a])=>Array.isArray(a));return s.length===0?i:i.map(a=>{const l={...a};for(const[u,f]of s)u in l&&(l[u]=[...f]);return l})}async runAfterUpdateHooks(e){const t=this.table.config.hooks;if(!t?.afterUpdate)return;const i=this.buildHookContext();if(!i){console.warn("[UpdateQueryBuilder] Cannot run hooks: missing session info");return}const s=this.updateData??{};for(const a of e)try{await t.afterUpdate(i,a,s)}catch(l){console.error("[UpdateQueryBuilder] afterUpdate hook failed:",l)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$5=entityKind;UpdateQueryBuilder[_a$5]="UpdateQueryBuilder";var _a$4;class DeleteQueryBuilder{constructor(e,t){this.session=e,this.table=t,this.toIR=()=>{const i=this.normalizeWhereConditionsForDelete();return{table:this.table,where:i}}}where(e){if(e instanceof SQL)this.sql=e;else if(this.isQueryCondition(e)){assertPublicWhereCondition("delete",e),this.conditionTree=e;const t=this.convertQueryConditionToSimple(e);this.whereConditions=Object.keys(t).length>0?t:void 0}else assertPublicWhereObject("delete",e),this.whereConditions=e,this.conditionTree=void 0;return this}returning(e){return this.returningFields=e??!0,this}whereByIri(e){return this.whereConditions={"@id":e},this.conditionTree=void 0,this}isQueryCondition(e){return e&&typeof e=="object"&&"type"in e&&"operator"in e}convertQueryConditionToSimple(e){if(e.type==="binary_expr"){const t=e.left,i=e.right,s=typeof t=="string"?t:t?.name;if(s&&i!==void 0)return{[s]:i}}return{}}normalizeWhereConditionsForDelete(){return this.conditionTree?this.conditionTree:buildConditionTreeFromObject(this.whereConditions)}buildSPARQLQuery(e="toSPARQL()"){if(this.sql){const s=this.sql.queryChunks.join(""),a=inferSPARQLQueryType(s);if(!a)throw new Error(`${e} could not infer SPARQL query type from raw AST input`);return{type:a,query:s,prefixes:{}}}const t=this.session.getDialect().getSPARQLConverter?.();if(!t)throw new Error(`${e} requires dialect SPARQL converter support`);const i=this.toIR();return t.convertDelete(i.where??{},i.table)}toSPARQL(){return this.buildSPARQLQuery("toSPARQL()")}toSparql(){return this.toSPARQL()}async execute(){if(this.sql){if(this.returningFields)throw new Error("returning() is not supported for raw SQL delete in Solid dialect");return await this.session.executeSql(this.sql,this.table)}else{const e=this.toIR(),t=this.returningFields?await this.fetchMatchedRows(e.where):[],i=t.map(u=>resolveRowSubject(u)).filter(u=>typeof u=="string"&&u.length>0),s={type:"delete",table:this.table,where:e.where,plan:e},a=await this.session.execute(s),l=this.returningFields?projectReturningRows(orderRowsBySubjects(t,i),this.returningFields):a;return await this.runAfterDeleteHooks(l),l}}async fetchMatchedRows(e){const t=this.whereConditions?.["@id"];if(!this.conditionTree&&typeof t=="string")return await this.session.select().from(this.table).whereByIri(t);let i=this.session.select().from(this.table);return e&&(i=i.where(e)),await i}async runAfterDeleteHooks(e){const t=this.table.config.hooks;if(!t?.afterDelete)return;const i=this.buildHookContext();if(!i){console.warn("[DeleteQueryBuilder] Cannot run hooks: missing session info");return}for(const s of e)try{await t.afterDelete(i,s)}catch(a){console.error("[DeleteQueryBuilder] afterDelete hook failed:",a)}}buildHookContext(){const e=this.session.getDialect(),t=e.getWebId(),i=e.getAuthenticatedFetch();return!t||!i?null:{session:{info:{isLoggedIn:!0,webId:t},fetch:i},table:this.table,db:this.table._db??null}}then(e,t){return this.execute().then(e,t)}}_a$4=entityKind;DeleteQueryBuilder[_a$4]="DeleteQueryBuilder";var _a$3;class PodAsyncSession{constructor(e,t,i={}){this.dialect=e,this._schema=t,this.options=i}getSchema(){return this._schema}isConnected(){return this.dialect.isConnected()}getDialect(){return this.dialect}getOptions(){return this.options}async ensureInitialized(e){const t=typeof this.dialect.getResourcePreparationMode=="function"?this.dialect.getResourcePreparationMode():"best-effort";if(t==="off"){e&&typeof e.markInitialized=="function"&&e.markInitialized(!0);return}if(e&&typeof e.isInitialized=="function"){if(!e.isInitialized())try{typeof e.init=="function"?await e.init(this.dialect):await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i;e.markInitialized?.(!0)}return}if(e)try{await this.dialect.registerTable(e)}catch(i){if(t!=="best-effort")throw i}}async execute(e){if(this.options.logger&&console.log("Executing operation:",e),!e||!e.type)throw new Error("Invalid operation: missing type");if(!e.table)throw new Error("Invalid operation: missing table");if(!["select","insert","update","delete"].includes(e.type))throw new Error(`Unsupported operation type: ${e.type}`);if(await this.ensureInitialized(e.table),Array.isArray(e.joins))for(const s of e.joins)s?.table&&await this.ensureInitialized(s.table);const i=await this.dialect.query(e);return this.updateSubjectIndex(e,i),i}updateSubjectIndex(e,t){if(e.type==="select")return;const i=this.dialect;if(typeof i.registerResourceSubject!="function"&&typeof i.unregisterResourceSubject!="function")return;const s=this.resolveOperationSubjects(e,t);if(e.type==="delete"){s.forEach(a=>i.unregisterResourceSubject?.(e.table,a));return}s.forEach(a=>i.registerResourceSubject?.(e.table,a))}resolveOperationSubjects(e,t){const i=new Set;for(const s of t){const a=this.getKnownRowIri(s);a&&i.add(a)}if(e.type==="insert"){const s=e.plan;(Array.isArray(s?.rows)?s.rows:[]).forEach(l=>{try{i.add(generateSubjectUri(l,e.table,this.dialect.getUriResolver?.()))}catch{}})}return Array.from(i)}getKnownRowIri(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;for(const i of["@id","subject","uri","source"]){const s=t[i];if(typeof s=="string"&&/^https?:\/\//.test(s))return s}return null}async executeSql(e,t){return this.options.logger&&console.log("Executing SQL AST:",e),await this.ensureInitialized(t),await this.dialect.executeSql(e,t)}select(e){return new SelectQueryBuilder(this,e)}insert(e){return new InsertQueryBuilder(this,e)}update(e){return new UpdateQueryBuilder(this,e)}delete(e){return new DeleteQueryBuilder(this,e)}async transaction(e){return await e(this)}}_a$3=entityKind;PodAsyncSession[_a$3]="PodAsyncSession";const resolveCreateRequire$1=()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(!nodeRequire)return null;const moduleLib=nodeRequire("module");return!moduleLib||typeof moduleLib.createRequire!="function"?null:moduleLib.createRequire}catch{return null}},createRequireFn=resolveCreateRequire$1(),isAbsoluteModuleFilename=n=>n.startsWith("file:")||n.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(n),moduleFilename=typeof __filename=="string"&&isAbsoluteModuleFilename(__filename)?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json",createDefaultRequireModule=()=>{if(!createRequireFn)return null;try{return createRequireFn(moduleFilename)}catch{return null}},defaultRequireModule=createDefaultRequireModule(),patchActionObserverHttp=(n,e)=>{if(!n)return!1;try{const t=n(e);if(t&&t.ActionObserverHttp){if(t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied)return!0;const i=t.ActionObserverHttp.prototype.onRun;return t.ActionObserverHttp.prototype.onRun=function(s,a,l){return(!this.observedActors||!Array.isArray(this.observedActors))&&(this.observedActors=[]),i.call(this,s,a,l)},t.ActionObserverHttp.prototype.__drizzleSolidObservedActorsPatchApplied=!0,!0}return!1}catch{return!1}},applyComunicaPatches=(n=defaultRequireModule)=>n?["@comunica/actor-query-result-serialize-sparql-json","@comunica/actor-query-result-serialize-stats","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-sparql-json","@comunica/query-sparql-solid/node_modules/@comunica/actor-query-result-serialize-stats"].map(t=>patchActionObserverHttp(n,t)).some(Boolean):!1;applyComunicaPatches();let configuredQueryEngineFactory=null;const resolveCreateRequire=async()=>{if(typeof window<"u")return null;try{const nodeRequire=eval("require");if(nodeRequire){const n=nodeRequire("module");if(n&&typeof n.createRequire=="function")return n.createRequire}}catch{}try{const n=await __vitePreload(()=>import("node:module"),[]);if(typeof n.createRequire=="function")return n.createRequire}catch{}return null},buildMissingComunicaError=n=>{const e=n instanceof Error&&n.message?` Original error: ${n.message}`:"";return new Error("A SPARQL query engine is required for this operation. Install `@comunica/query-sparql-solid` in the consuming app, or provide `sparql.createQueryEngine` to `drizzle(...)`, or call `configureSparqlEngine(...)` before executing LDP/SPARQL-client queries."+e)},loadComunicaModuleWithRequire=async n=>{const e=await resolveCreateRequire();if(!e)throw new Error("Node module resolution is not available in this runtime.");const t=e(n);applyComunicaPatches(t);const i=t("@comunica/query-sparql-solid");if(applyComunicaPatches(t),!i||typeof i.QueryEngine!="function")throw new Error("Resolved module does not export QueryEngine.");return i},loadDefaultComunicaModule=async()=>{try{return await loadComunicaModuleWithRequire(typeof __filename=="string"?__filename:typeof process<"u"&&typeof process.cwd=="function"?`${process.cwd().replace(/\/$/,"")}/package.json`:"/package.json")}catch(n){try{applyComunicaPatches();const e=await __vitePreload(()=>import("./index-browser-D8YW6coF.js").then(t=>t.i),[]);if(applyComunicaPatches(),e&&typeof e.QueryEngine=="function")return e}catch(e){throw buildMissingComunicaError(e??n)}throw buildMissingComunicaError(n)}},createDefaultQueryEngine=async()=>{const n=await loadDefaultComunicaModule();return new n.QueryEngine},configureSparqlEngine=n=>{configuredQueryEngineFactory=n?.createQueryEngine??null},getConfiguredSparqlEngineFactory=n=>n??configuredQueryEngineFactory??createDefaultQueryEngine;class ComunicaSPARQLExecutor{constructor(e){this.engine=null,this.sources=[...e.sources],this.fetchFn=this.createSafeFetch(e.fetch||fetch),this.logging=e.logging||!1,this.createQueryEngine=getConfiguredSparqlEngineFactory(e.createQueryEngine)}formatError(e){return e instanceof Error?e.message:String(e)}createSourceRef(e,t="auto"){return t==="sparql"?{type:"sparql",value:e}:e}createSafeFetch(e){return async(t,i)=>{try{const s=await e(t,i),a=new Map;s.headers&&s.headers.forEach((f,d)=>{a.set(d.toLowerCase(),f||"")});const u={...s,headers:{get:f=>{const d=f.toLowerCase();return a.get(d)||null},has:f=>{const d=f.toLowerCase();return a.has(d)},forEach:f=>{a.forEach((d,p)=>f(d,p))},entries:()=>a.entries(),keys:()=>a.keys(),values:()=>a.values(),[Symbol.iterator]:()=>a.entries(),includes:f=>{if(!f)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(f.toLowerCase())||p.toLowerCase().includes(f.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:f=>{if(!f)return!1;for(const[d,p]of Array.from(a.entries()))if(d.toLowerCase().includes(f.toLowerCase())||p.toLowerCase().includes(f.toLowerCase()))return!0;return!1},text:async()=>{try{return await s.text()}catch(f){return this.logging&&console.warn("[SafeFetch] Text parsing failed:",this.formatError(f)),""}},json:async()=>{try{return await s.json()}catch(f){return this.logging&&console.warn("[SafeFetch] JSON parsing failed:",this.formatError(f)),{}}},clone:()=>{try{return this.createSafeFetch(e)(t,i)}catch(f){return this.logging&&console.warn("[SafeFetch] Clone failed:",this.formatError(f)),u}}};return u}catch(s){throw this.logging&&console.error("[SafeFetch] Error:",this.formatError(s)),s}}}async initEngine(){return this.engine||(this.engine=await this.createQueryEngine()),this.engine}async executeQuery(e){try{const t=await this.initEngine();if(this.logging&&console.log(`[Comunica] Executing ${e.type} query:`,e.query),e.type==="SELECT")return await this.executeSelectInternal(e,t);if(e.type==="ASK")return await this.executeAskInternal(e,t);if(["INSERT","UPDATE","DELETE"].includes(e.type))return await this.executeUpdate(e,t);throw new Error(`Unsupported query type: ${e.type}`)}catch(t){throw console.error("SPARQL query execution failed:",this.formatError(t)),t}}async executeSelect(e){try{this.logging&&console.log("[SPARQL] Executing SELECT query with full processing");const t={type:"SELECT",query:e.trim()},i=this.sources[0];if(!i)throw new Error("No data sources configured");return this.logging&&(console.log("[SPARQL] Query object:",t),console.log("[SPARQL] Source URL:",i)),await this.executeQueryWithSource(t,i)}catch(t){throw this.logging&&console.error("[Simple] SELECT query execution failed:",this.formatError(t)),t}}async queryBindings(e,t){return await(await(await this.initEngine()).queryBindings(e,{sources:[t],fetch:this.fetchFn})).toArray()}async executeSelectInternal(e,t){try{if(this.sources.length===0)throw new Error("No sources configured for SPARQL query");return(await(await t.queryBindings(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})).toArray()).map(a=>{const l=a,u={},f=(d,p)=>{const g=this.extractBindingKeyName(d);g&&(u[g]=this.convertComunicaTerm(p))};if(l&&typeof l.forEach=="function")l.forEach((d,p)=>f(p,d));else if(l&&typeof l.entries=="function")for(const[d,p]of l.entries())f(d,p);else for(const d in l)Object.prototype.hasOwnProperty.call(l,d)&&f(d,l[d]);return u})}catch(i){throw console.error("SELECT query failed:",this.formatError(i)),i}}async executeAskInternal(e,t){try{if(this.logging&&console.log("[Comunica] Executing ASK query:",e.query),this.sources.length===0)throw new Error("No sources configured for SPARQL query");return[{result:await t.queryBoolean(e.query,{sources:this.sources,fetch:this.fetchFn,httpTimeout:3e4,httpRetryCount:1,httpRetryDelay:1e3})}]}catch(i){throw console.error("ASK query failed:",this.formatError(i)),i}}async executeUpdate(e,t){try{this.logging&&console.log(`[Simple] Executing ${e.type} query:`,e.query);const i=[];for(const s of this.sources)try{this.logging&&console.log(`[Comunica] Executing UPDATE query on ${s}:`,e.query.substring(0,100)+"...");let a=null;try{const d=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});d.ok&&(a=d.headers.get("ETag"),this.logging&&a&&console.log(`[UPDATE] Got ETag for ${s}: ${a}`))}catch{this.logging&&console.log(`[UPDATE] HEAD request failed for ${s}, continuing without ETag`)}const l={"Content-Type":"application/sparql-update","If-Match":a??"*"},u=async d=>this.fetchFn(s,{method:"PATCH",headers:d,body:e.query}),f=await u(l);if(f.ok)i.push({success:!0,source:s,status:f.status}),await this.invalidateCache(t,s);else if(f.status===409||f.status===412){this.logging&&console.log(`[UPDATE] ${f.status} conflict for ${s}, trying multiple retry strategies`);let d=!1;if(f.status===412)try{const p=await this.fetchFn(s,{method:"HEAD",headers:{Accept:"text/turtle"}});if(p.ok){const g=p.headers.get("ETag");if(g){const m={...l,"If-Match":g},v=await u(m);v.ok&&(i.push({success:!0,source:s,status:v.status,retried:!0,strategy:"refreshed-etag"}),await this.invalidateCache(t,s),d=!0)}}}catch(p){this.logging&&console.log("[UPDATE] Retry with refreshed ETag failed:",p)}if(!d)try{const p=await u({"Content-Type":"application/sparql-update"});p.ok&&(i.push({success:!0,source:s,status:p.status,retried:!0,strategy:"no-etag"}),await this.invalidateCache(t,s),d=!0)}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 1 failed:",p)}if(!d)try{if((await this.fetchFn(s,{method:"GET",headers:{Accept:"text/turtle"}})).ok){const g=await this.fetchFn(s,{method:"PUT",headers:{"Content-Type":"application/sparql-update"},body:e.query});g.ok&&(i.push({success:!0,source:s,status:g.status,retried:!0,strategy:"put-method"}),await this.invalidateCache(t,s),d=!0)}}catch(p){this.logging&&console.log("[UPDATE] Retry strategy 2 failed:",p)}if(!d){const p=await f.text();i.push({success:!1,source:s,error:`All retry strategies failed: ${f.status} ${f.statusText}`,details:p})}}else{const d=await f.text();i.push({success:!1,source:s,error:`${f.status} ${f.statusText}`,details:d})}}catch(a){i.push({success:!1,source:s,error:this.formatError(a)})}return i}catch(i){throw console.error("UPDATE query failed:",this.formatError(i)),i}}async invalidateHttpCache(e){this.engine&&(await this.invalidateCache(this.engine,e),await this.invalidateCache(this.engine,void 0))}async invalidateCache(e,t){const i=e.invalidateHttpCache;if(typeof i=="function")try{await i.call(e,t)}catch(s){this.logging&&console.warn(`[UPDATE] Failed to invalidate cache for ${t}:`,this.formatError(s))}}extractBindingKeyName(e){if(e==null)return null;if(typeof e=="string")return e;if(typeof e=="object"){const t=e;if(t&&typeof t.value=="string"||t&&t.termType==="Variable"&&typeof t.value=="string")return t.value}return typeof e=="symbol"?e.description??e.toString():String(e)}convertComunicaTerm(e){if(!e)return null;const t=e;switch(t.termType){case"NamedNode":return t.value;case"Literal":if(t.datatype&&t.datatype.value){const i=t.datatype.value;if(typeof i=="string"){if(i.includes("#integer")||i.includes("#int"))return parseInt(String(t.value),10);if(i.includes("#decimal")||i.includes("#double"))return parseFloat(String(t.value));if(i.includes("#boolean"))return t.value==="true";if(i.includes("#dateTime"))return new Date(String(t.value));if(i.includes("#json"))try{return JSON.parse(String(t.value))}catch(s){return console.warn("Failed to parse JSON value:",t.value,this.formatError(s)),t.value}else if(i.includes("#jsonArray")||i.includes("solid/terms#jsonArray"))try{const s=JSON.parse(String(t.value));return Array.isArray(s)?s:(console.warn("Expected array but got:",typeof s,s),[s])}catch(s){return console.warn("Failed to parse JSON Array value:",t.value,this.formatError(s)),[t.value]}}}return t.value;case"BlankNode":return`_:${String(t.value)}`;default:return t.value}}async queryContainer(e,t){const i=e&&e.startsWith("http")?e:`${this.sources[0]}${e||""}`;let s;return t?s=t:s={type:"SELECT",query:`
124
124
  SELECT ?subject ?predicate ?object WHERE {
125
125
  ?subject ?predicate ?object .
126
126
  FILTER(STRSTARTS(STR(?subject), "${i}"))
@@ -304,7 +304,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
304
304
  `,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},illegalIriChars=/[\x00-\x20<>\\"\{\}\|\^\`]/,lineModeRegExps={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},invalidRegExp=/$0^/;class N3Lexer{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const t in this)!(t in lineModeRegExps)&&this[t]instanceof RegExp&&(this[t]=invalidRegExp)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let i=this._input,s=i.length;for(;;){let u,f;for(;u=this._newline.exec(i);)this.comments&&(f=this._comment.exec(u[0]))&&a("comment",f[1],"",this._line,u[0].length),i=i.substr(u[0].length,i.length),s=i.length,this._line++;if(!u&&(u=this._whitespace.exec(i))&&(i=i.substr(u[0].length,i.length)),this._endOfFile.test(i))return t&&(this.comments&&(f=this._comment.exec(i))&&a("comment",f[1],"",this._line,i.length),i=null,a("eof","","",this._line,0)),this._input=i;const d=this._line,p=i[0];let g="",m="",v="",S=null,E=0,w=!1;switch(p){case"^":if(i.length<3)break;if(i[1]==="^"){if(this._previousMarker="^^",i=i.substr(2),i[0]!=="<"){w=!0;break}}else{this._n3Mode&&(E=1,g="^");break}case"<":if(S=this._unescapedIri.exec(i))g="IRI",m=S[1];else if(S=this._iri.exec(i)){if(m=this._unescape(S[1]),m===null||illegalIriChars.test(m))return l(this);g="IRI"}else i.length>1&&i[1]==="<"?(g="<<",E=2):this._n3Mode&&i.length>1&&i[1]==="="&&(E=2,this._isImpliedBy?(g="abbreviation",m="<"):(g="inverse",m=">"));break;case">":i.length>1&&i[1]===">"&&(g=">>",E=2);break;case"_":((S=this._blank.exec(i))||t&&(S=this._blank.exec(`${i} `)))&&(g="blank",v="_",m=S[1]);break;case'"':if(S=this._simpleQuotedString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(S=this._simpleApostropheString.exec(i))m=S[1];else if({value:m,matchLength:E}=this._parseLiteral(i),m===null)return l(this);(S!==null||E!==0)&&(g="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(S=this._variable.exec(i))&&(g="var",m=S[0]);break;case"@":this._previousMarker==="literal"&&(S=this._langcode.exec(i))?(g="langcode",m=S[1]):(S=this._keyword.exec(i))&&(g=S[0]);break;case".":if(i.length===1?t:i[1]<"0"||i[1]>"9"){g=".",E=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(S=this._number.exec(i)||t&&(S=this._number.exec(`${i} `)))&&(g="literal",m=S[0],v=typeof S[1]=="string"?xsd$1.double:typeof S[2]=="string"?xsd$1.decimal:xsd$1.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(S=this._sparqlKeyword.exec(i))?g=S[0].toUpperCase():w=!0;break;case"f":case"t":(S=this._boolean.exec(i))?(g="literal",m=S[0],v=xsd$1.boolean):w=!0;break;case"a":(S=this._shortPredicates.exec(i))?(g="abbreviation",m="a"):w=!0;break;case"=":this._n3Mode&&i.length>1&&(g="abbreviation",i[1]!==">"?(E=1,m="="):(E=2,m=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(E=1,g=p);break;case"{":!this._lineMode&&i.length>=2&&(i[1]==="|"?(g="{|",E=2):(g=p,E=1));break;case"|":i.length>=2&&i[1]==="}"&&(g="|}",E=2);break;default:w=!0}if(w&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(S=this._prefix.exec(i))?(g="prefix",m=S[1]||""):((S=this._prefixed.exec(i))||t&&(S=this._prefixed.exec(`${i} `)))&&(g="prefixed",v=S[1]||"",m=this._unescape(S[2]))),this._previousMarker==="^^")switch(g){case"prefixed":g="type";break;case"IRI":g="typeIRI";break;default:g=""}if(!g)return t||!/^'''|^"""/.test(i)&&/\n|\r/.test(i)?l(this):this._input=i;const A=E||S[0].length,C=a(g,m,v,d,A);this.previousToken=C,this._previousMarker=g,i=i.substr(A,i.length)}function a(u,f,d,p,g){const m=i?s-i.length:s,v=m+g,S={type:u,value:f,prefix:d,line:p,start:m,end:v};return e(null,S),S}function l(u){e(u._syntaxError(/^\S*/.exec(i)[0]))}}_unescape(e){let t=!1;const i=e.replace(escapeSequence,(s,a,l,u)=>{if(typeof a=="string")return String.fromCharCode(Number.parseInt(a,16));if(typeof l=="string"){let f=Number.parseInt(l,16);return f<=65535?String.fromCharCode(Number.parseInt(l,16)):String.fromCharCode(55296+((f-=65536)>>10),56320+(f&1023))}return u in escapeReplacements?escapeReplacements[u]:(t=!0,"")});return t?null:i}_parseLiteral(e){if(e.length>=3){const t=e.match(/^(?:"""|"|'''|'|)/)[0],i=t.length;let s=Math.max(this._literalClosingPos,i);for(;(s=e.indexOf(t,s))>0;){let a=0;for(;e[s-a-1]==="\\";)a++;if(a%2===0){const l=e.substring(i,s),u=l.split(/\r\n|\r|\n/).length-1,f=s+i;if(i===1&&u!==0||i===3&&this._lineMode)break;return this._line+=u,{value:this._unescape(l),matchLength:f}}s++}this._literalClosingPos=e.length-i+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{const i=[];let s;if(this._tokenizeToEnd((a,l)=>a?s=a:i.push(l),!0),s)throw s;return i}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",i=>{this._input!==null&&i.length!==0&&(this._pendingBuffer&&(i=bufferExports.Buffer.concat([this._pendingBuffer,i]),this._pendingBuffer=null),i[i.length-1]&128?this._pendingBuffer=i:(typeof this._input>"u"?this._input=this._readStartingBom(typeof i=="string"?i:i.toString()):this._input+=i,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}}const{rdf,xsd}=namespaces;let DEFAULTGRAPH,_blankNodeCounter=0;const DataFactory={namedNode,blankNode,variable,literal,defaultGraph,quad,triple:quad,fromTerm,fromQuad};class Term{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof Term?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class NamedNode extends Term{get termType(){return"NamedNode"}}class Literal extends Term{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let t=e.lastIndexOf('"')+1;return t<e.length&&e[t++]==="@"?e.substr(t).toLowerCase():""}get datatype(){return new NamedNode(this.datatypeString)}get datatypeString(){const e=this.id,t=e.lastIndexOf('"')+1,i=t<e.length?e[t]:"";return i==="^"?e.substr(t+2):i!=="@"?xsd.string:rdf.langString}equals(e){return e instanceof Literal?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class BlankNode extends Term{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Variable extends Term{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}class DefaultGraph extends Term{constructor(){return super(""),DEFAULTGRAPH||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}}DEFAULTGRAPH=new DefaultGraph;class Quad extends Term{constructor(e,t,i,s){super(""),this._subject=e,this._predicate=t,this._object=i,this._graph=s||DEFAULTGRAPH}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function namedNode(n){return new NamedNode(n)}function blankNode(n){return new BlankNode(n||`n3-${_blankNodeCounter++}`)}function literal(n,e){if(typeof e=="string")return new Literal(`"${n}"@${e.toLowerCase()}`);let t=e?e.value:"";return t===""&&(typeof n=="boolean"?t=xsd.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?xsd.integer:xsd.double:(t=xsd.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===xsd.string?new Literal(`"${n}"`):new Literal(`"${n}"^^${t}`)}function variable(n){return new Variable(n)}function defaultGraph(){return DEFAULTGRAPH}function quad(n,e,t,i){return new Quad(n,e,t,i)}function fromTerm(n){if(n instanceof Term)return n;switch(n.termType){case"NamedNode":return namedNode(n.value);case"BlankNode":return blankNode(n.value);case"Variable":return variable(n.value);case"DefaultGraph":return DEFAULTGRAPH;case"Literal":return literal(n.value,n.language||n.datatype);case"Quad":return fromQuad(n);default:throw new Error(`Unexpected termType: ${n.termType}`)}}function fromQuad(n){if(n instanceof Quad)return n;if(n.termType!=="Quad")throw new Error(`Unexpected termType: ${n.termType}`);return quad(fromTerm(n.subject),fromTerm(n.predicate),fromTerm(n.object),fromTerm(n.graph))}let blankNodePrefix=0;class N3Parser{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&initDataFactory(this,e.factory);const t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",i=/turtle/.test(t),s=/trig/.test(t),a=/triple/.test(t),l=/quad/.test(t),u=this._n3Mode=/n3/.test(t),f=a||l;(this._supportsNamedGraphs=!(i||u))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(i||s||a||u),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),f&&(this._resolveRelativeIRI=d=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new N3Lexer({lineMode:f,n3:u,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){blankNodePrefix=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,i,s,a){const l=this._n3Mode;this._contextStack.push({type:e,subject:i,predicate:s,object:a,graph:t,inverse:l?this._inversePredicate:!1,blankPrefix:l?this._prefixes._:"",quantified:l?this._quantified:null}),l&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){const i=this._contextStack.pop();if(!i||i.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=i.subject,this._predicate=i.predicate,this._object=i.object,this._graph=i.graph,this._n3Mode&&(this._inversePredicate=i.inverse,this._prefixes._=i.blankPrefix,this._quantified=i.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let i;switch(e.type){case"IRI":case"typeIRI":const s=this._resolveIRI(e.value);if(s===null)return this._error("Invalid IRI",e);i=this._factory.namedNode(s);break;case"type":case"prefixed":const a=this._prefixes[e.prefix];if(a===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);i=this._factory.namedNode(a+e.value);break;case"blank":i=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":i=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&i.id in this._quantified&&(i=this._quantified[i.id]),i}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,i=null,s=this._readListItem;const a=this._subject,l=this._contextStack,u=l[l.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),s=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,i=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),l.length!==0&&l[l.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(s=this._readPredicate,this._subject===this.RDF_NIL)return s}else if(s=this._getContextEndReader(),this._object===this.RDF_NIL)return s;i=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,s=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),s=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(i===null&&(this._subject=i=this._factory.blankNode()),a===null?u.predicate===null?u.subject=i:u.object=i:this._emit(a,this.RDF_REST,i,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,i,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(i,this.RDF_FIRST,t,this._graph)}return s}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const i=this._readEntity(e);if(i===void 0)return;t=this._factory.literal(this._literalValue,i),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){const i=this._completeLiteral(e);if(i)return this._object=i.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),i.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(i.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,i=this._graph;const s=this._subject,a=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,a&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const l=this._predicate,u=this._object;this._subject=this._factory.quad(s,l,u,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(i=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(s!==null){const l=this._predicate,u=this._object;a?this._emit(u,l,s,i):this._emit(s,l,u,i)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){const t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const t=this._contextStack,i=t.length&&t[t.length-1];if(i&&i.type==="item"){const s=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,s,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,i;const s=this._factory.blankNode();if((i=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=s):(t=this._object,this._object=s),this._emit(t,i,s,this._graph),this._readPath}_readBackwardPath(e){const t=this._factory.blankNode();let i,s;if((i=this._readEntity(e))!==void 0)return this._predicate===null?(s=this._subject,this._subject=t):(s=this._object,this._object=t),this._emit(t,i,s,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,i,s){this._callback(null,this._factory.quad(e,t,i,s||this.DEFAULTGRAPH))}_error(e,t){const i=new Error(`${e} on line ${t.line}.`);i.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(i),this._callback=noop}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const t=e.length;let i="",s=-1,a=-1,l=0,u="/";for(;s<t;){switch(u){case":":if(a<0&&e[++s]==="/"&&e[++s]==="/")for(;(a=s+1)<t&&e[a]!=="/";)s=a;break;case"?":case"#":s=t;break;case"/":if(e[s+1]===".")switch(u=e[++s+1],u){case"/":i+=e.substring(l,s-1),l=s+1;break;case void 0:case"?":case"#":return i+e.substring(l,s)+e.substr(s+1);case".":if(u=e[++s+1],u===void 0||u==="/"||u==="?"||u==="#"){if(i+=e.substring(l,s-2),(l=i.lastIndexOf("/"))>=a&&(i=i.substr(0,l)),u!=="/")return`${i}/${e.substr(s+1)}`;l=s+1}}}u=e[++s]}return i+e.substring(l)}parse(e,t,i){let s,a,l;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(s=t.onQuad,a=t.onPrefix,l=t.onComment):(s=t,a=i),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${blankNodePrefix++}_`,this._prefixCallback=a||noop,this._inversePredicate=!1,this._quantified=Object.create(null),!s){const f=[];let d;if(this._callback=(p,g)=>{p?d=p:g&&f.push(g)},this._lexer.tokenize(e).every(p=>this._readCallback=this._readCallback(p)),d)throw d;return f}let u=(f,d)=>{f!==null?(this._callback(f),this._callback=noop):this._readCallback&&(this._readCallback=this._readCallback(d))};l&&(this._lexer.comments=!0,u=(f,d)=>{f!==null?(this._callback(f),this._callback=noop):this._readCallback&&(d.type==="comment"?l(d.value):this._readCallback=this._readCallback(d))}),this._callback=s,this._lexer.tokenize(e,u)}}function noop(){}function initDataFactory(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(namespaces.rdf.first),n.RDF_REST=e.namedNode(namespaces.rdf.rest),n.RDF_NIL=e.namedNode(namespaces.rdf.nil),n.N3_FORALL=e.namedNode(namespaces.r.forAll),n.N3_FORSOME=e.namedNode(namespaces.r.forSome),n.ABBREVIATIONS={a:e.namedNode(namespaces.rdf.type),"=":e.namedNode(namespaces.owl.sameAs),">":e.namedNode(namespaces.log.implies),"<":e.namedNode(namespaces.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}initDataFactory(N3Parser.prototype,DataFactory);async function resolveSolidProfileIdentityFromWebIdDocument(n,e={}){const t=e.webId??n.info?.webId;if(!t?.trim()||typeof n.fetch!="function")return null;const i=stripHash(t),s=await n.fetch(i,{headers:{Accept:"text/turtle, application/ld+json;q=0.9, text/n3;q=0.8, */*;q=0.1"}});if(!s.ok)throw new Error(`Failed to fetch WebID profile: ${s.status} ${s.statusText}`.trim());const a=s.headers.get("content-type")??"",l=await s.text();if(!l.trim())return buildSolidProfileIdentity(t,null);const u=await parseSolidProfileDocument(l,{contentType:a,profileDocumentUrl:i,webId:t});return buildSolidProfileIdentity(t,u)}async function parseSolidProfileDocument(n,e){return(e.contentType?.toLowerCase()??"").includes("application/ld+json")||n.trimStart().startsWith("{")?parseJsonLdProfileDocument(n,e.webId):await parseTurtleProfileDocument(n,e)}async function parseTurtleProfileDocument(n,e){const t=N3Parser,s=new t({baseIRI:e.profileDocumentUrl}).parse(n);return pickProfileFromQuads(s,e.webId)}function parseJsonLdProfileDocument(n,e){try{const t=JSON.parse(n),i=Array.isArray(t)?t:isRecord$5(t)&&Array.isArray(t["@graph"])?t["@graph"]:[t],s=i.find(l=>isRecord$5(l)&&l["@id"]===e),a=isRecord$5(s)?s:i.find(isRecord$5);return a?normalizeProfileRow({id:e,name:pickJsonLdString(a,VCARD.fn),nick:pickJsonLdString(a,FOAF.nick),avatar:pickJsonLdString(a,VCARD.hasPhoto),note:pickJsonLdString(a,VCARD.note),email:pickJsonLdString(a,VCARD.hasEmail),phone:pickJsonLdString(a,VCARD.hasTelephone),region:pickJsonLdString(a,VCARD.region),gender:pickJsonLdString(a,VCARD.hasGender)}):null}catch{return null}}function pickProfileFromQuads(n,e){const t={id:e};for(const i of n){if(i.subject.value!==e)continue;const s=i.predicate.value,a=i.object.value;!s||!a||(s===VCARD.fn?t.name=a:s===FOAF.nick?t.nick=a:s===VCARD.hasPhoto?t.avatar=a:s===VCARD.note?t.note=a:s===VCARD.hasEmail?t.email=a:s===VCARD.hasTelephone?t.phone=a:s===VCARD.region?t.region=a:s===VCARD.hasGender&&(t.gender=a))}return normalizeProfileRow(t)}function buildSolidProfileIdentity(n,e){return{webId:n,profile:e,displayName:pickSolidProfileDisplayName(e),username:extractProfileUsernameFromWebId(n)}}function normalizeProfileRow(n){const e=Object.fromEntries(Object.entries(n).filter(([,t])=>typeof t=="string"&&t.trim()));return Object.keys(e).length>1?e:null}function pickJsonLdString(n,e){return normalizeJsonLdValue(n[e])}function normalizeJsonLdValue(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(normalizeJsonLdValue).find(Boolean);if(isRecord$5(n))return normalizeJsonLdValue(n["@value"]??n["@id"])}function stripHash(n){const e=n.indexOf("#");return e>=0?n.slice(0,e):n}function isRecord$5(n){return typeof n=="object"&&n!==null}const ContactClass={PERSON:UDFS.PersonContact,AGENT:UDFS.AgentContact,GROUP:UDFS.GroupContact},contactResource=podTable("contact",{id:id("id").default("{key}.ttl"),name:string$2("name").predicate(VCARD.fn).notNull(),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),about:uri("about").predicate(SCHEMA.about).notNull(),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([ContactClass.PERSON]),contactType:string$2("contactType").predicate(UDFS.contactType).notNull(),isPublic:boolean$2("isPublic").predicate(AS.audience).default(!1),externalPlatform:string$2("externalPlatform").predicate(UDFS.externalPlatform),externalId:string$2("externalId").predicate(UDFS.externalId),alias:string$2("alias").predicate(UDFS.alias),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),note:text("note").predicate(VCARD.note),sortKey:string$2("sortKey").predicate(UDFS.sortKey),gender:string$2("gender").predicate(VCARD.hasGender),province:string$2("province").predicate(VCARD.region),city:string$2("city").predicate(VCARD.locality),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt),lastSyncedAt:timestamp("lastSyncedAt").predicate(UDFS.lastSyncedAt)},{base:"/.data/contacts/",sparqlEndpoint:"/.data/contacts/-/sparql",type:VCARD.Individual,namespace:UDFS});definePodRepository({namespace:"contact",resource:contactResource,searchableFields:["name","alias","note"],defaultSort:{field:"name",direction:"asc"}});const ChatStatus={ACTIVE:"active"},chatResource=podTable("chats",{id:id("id").default("{key}/index.ttl#this"),title:string$2("title").predicate(DCTerms.title).notNull(),description:string$2("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(SCHEMA.image),author:uri("author").predicate(DCTerms.creator),status:string$2("status").predicate(UDFS.status).notNull().default(ChatStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),muted:boolean$2("muted").predicate(UDFS.muted).default(!1),unreadCount:integer$1("unreadCount").predicate(UDFS.unreadCount).default(0),contact:uri("contact").predicate(UDFS.hasContact).link(contactResource),participants:uri("participants").array().predicate(WF.participant),metadata:object$1("metadata").predicate(UDFS.metadata),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt),lastMessage:uri("lastMessage").predicate(UDFS.lastMessage),lastMessagePreview:text("lastMessagePreview").predicate(SCHEMA.text),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat/",sparqlEndpoint:"/.data/chat/-/sparql",type:MEETING.LongChat,namespace:UDFS});definePodRepository({namespace:"chat",resource:chatResource,searchableFields:["title","description"],defaultSort:{field:"lastActiveAt",direction:"desc"}});const ProviderAuthMode={apiKey:"apiKey"},credentialResource=podTable("credential",{id:id("id").default("credentials.ttl#{key}"),provider:uri("provider").predicate(UDFS.provider).link("aiProvider"),authMode:string$2("authMode").predicate(UDFS.authMode).default(ProviderAuthMode.apiKey),service:string$2("service").predicate(UDFS.service).notNull().default("ai"),status:string$2("status").predicate(UDFS.status).notNull().default("active"),apiKey:string$2("apiKey").predicate(UDFS.apiKey),storageMode:string$2("storageMode").predicate(UDFS.storageMode),secretPayload:string$2("secretPayload").predicate(UDFS.secretPayload),encryptedSecret:string$2("encryptedSecret").predicate(UDFS.encryptedSecret),wrappedDataKey:string$2("wrappedDataKey").predicate(UDFS.wrappedDataKey),encryptionAlgorithm:string$2("encryptionAlgorithm").predicate(UDFS.encryptionAlgorithm),keyVersion:string$2("keyVersion").predicate(UDFS.keyVersion),scopes:text("scopes").array().predicate(UDFS.scopes),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),accountLabel:string$2("accountLabel").predicate(UDFS.accountLabel),lastRefreshAt:timestamp("lastRefreshAt").predicate(UDFS.lastRefreshAt),reauthRequired:boolean$2("reauthRequired").predicate(UDFS.reauthRequired).default(!1),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),label:string$2("label").predicate(UDFS.label),isDefault:boolean$2("isDefault").predicate(UDFS.isDefault).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).defaultNow(),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),clientCredentialId:string$2("clientCredentialId").predicate(UDFS.clientCredentialId),appliedTo:string$2("appliedTo").predicate(UDFS.appliedTo),appliedOn:string$2("appliedOn").predicate(UDFS.appliedOn),appliedAt:timestamp("appliedAt").predicate(UDFS.appliedAt),failCount:integer$1("failCount").predicate(UDFS.failCount).default(0),rateLimitResetAt:timestamp("rateLimitResetAt").predicate(UDFS.rateLimitResetAt),oauthRefreshToken:string$2("oauthRefreshToken").predicate(UDFS.oauthRefreshToken),oauthAccessToken:string$2("oauthAccessToken").predicate(UDFS.oauthAccessToken),oauthExpiresAt:timestamp("oauthExpiresAt").predicate(UDFS.oauthExpiresAt),projectId:string$2("projectId").predicate(UDFS.projectId),organizationId:string$2("organizationId").predicate(UDFS.organizationId)},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:UDFS.Credential,namespace:UDFS});function resourceKey(n,e){return n&&n.length>0?n:`${e}_${Math.random().toString(36).slice(2,12)}`}function workflowOwnerDir(n){return taskDir(n)??runDir(n)??deliveryDir(n)??issueDir(n)??threadDir(n)??chatDir(n)??aboutDir(n)}function chatDir(n){const e=typeof n?.chat=="string"?n.chat:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^chat\/(.+)\/index\.ttl#this$/);return i?.[1]?`chat/${i[1]}`:null}function threadDir(n){const e=typeof n?.thread=="string"?n.thread:void 0;return e?normalizePodDataResourceId(e).match(/^((?:chat|task)\/.+)\/index\.ttl#[^#/]+$/)?.[1]??null:null}function taskDir(n){const e=typeof n?.task=="string"?n.task:void 0;if(!e)return null;const t=normalizePodDataResourceId(e);if(t==="task/index.ttl#this")return"task";const i=t.match(/^task\/index\.ttl#([^#/]+)$/);if(i?.[1])return`task/${i[1]}`;const s=t.match(/^task\/(.+)\.ttl(?:#[^#/]+)?$/);return s?.[1]?`task/${s[1]}`:null}function issueDir(n){const e=typeof n?.issue=="string"?n.issue:void 0;if(!e)return null;const i=normalizePodDataResourceId(e).match(/^issues\/(.+)\.ttl(?:#[^#/]+)?$/);return i?.[1]?`issues/${i[1]}`:null}function deliveryDir(n){const e=typeof n?.delivery=="string"?n.delivery:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/deliveries\.ttl#[^#/]+$/)?.[1]??null:null}function runDir(n){const e=typeof n?.run=="string"?n.run:void 0;return e?normalizePodDataResourceId(e).match(/^(.+)\/\d{4}\/\d{2}\/\d{2}\/runs\.ttl#[^#/]+$/)?.[1]??null:null}function aboutDir(n){const e=typeof n?.about=="string"?n.about:void 0;return e?runDir({run:e})??deliveryDir({delivery:e})??taskDir({task:e})??issueDir({issue:e})??threadDir({thread:e})??chatDir({chat:e}):null}const ThreadStatus={ACTIVE:"active"},threadResource=podTable("thread",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/index.ttl#{key}",{key:resourceKey(n,"thread"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),title:string$2("title").predicate(DCTerms.title),status:string$2("status").predicate(UDFS.status).notNull().default(ThreadStatus.ACTIVE),starred:boolean$2("starred").predicate(UDFS.favorite).default(!1),workspace:uri("workspace").predicate(UDFS.workspace),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:SIOC.Thread,namespace:UDFS});definePodRepository({namespace:"thread",resource:threadResource,searchableFields:["title"],defaultSort:{field:"updatedAt",direction:"desc"}});const MessageRole={USER:"user"},MessageStatus={COMPLETED:"completed"},messageResource=podTable("chat_message",{id:id("id").default((n,e)=>renderDefaultIdTemplate("{parent.dir}/{yyyy}/{MM}/{dd}/messages.ttl#{key}",{key:resourceKey(n,"msg"),row:e})),parent:uri("parent").predicate(SIOC.has_parent).notNull(),chat:uri("chat").predicate(WF.message).inverse().link(chatResource),thread:uri("thread").predicate(SIOC.has_member).inverse().link(threadResource),maker:uri("maker").predicate(FOAF.maker),role:string$2("role").predicate(UDFS.messageType).notNull().default(MessageRole.USER),content:text("content").predicate(SIOC.content).notNull(),richContent:text("richContent").predicate(SIOC.richContent),status:string$2("status").predicate(UDFS.messageStatus).notNull().default(MessageStatus.COMPLETED),toolName:string$2("toolName").predicate(UDFS.toolName),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),metadata:object$1("metadata").predicate(UDFS.metadata),replacedBy:string$2("replacedBy").predicate(DCTerms.isReplacedBy),deletedAt:timestamp("deletedAt").predicate(SCHEMA.dateDeleted),senderName:string$2("senderName").predicate(UDFS.senderName),senderAvatarUrl:uri("senderAvatarUrl").predicate(UDFS.senderAvatarUrl),mentions:uri("mentions").array().predicate(UDFS.mentions),replyTo:uri("replyTo").predicate(UDFS.replyTo),routedBy:uri("routedBy").predicate(UDFS.routedBy),routeTargetAgent:uri("routeTargetAgent").predicate(UDFS.routeTargetAgent),coordinationId:string$2("coordinationId").predicate(UDFS.coordinationId),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:MEETING.Message,namespace:UDFS}),exactFilterColumns={parent:messageResource.parent,chat:messageResource.chat,thread:messageResource.thread,maker:messageResource.maker,role:messageResource.role,status:messageResource.status,toolName:messageResource.toolName,toolCallId:messageResource.toolCallId,coordinationId:messageResource.coordinationId};function exactFilter$1(n,e){return e===void 0?void 0:eq(exactFilterColumns[n],e)}function messageListFilter(n){if(!n)return;const e=[exactFilter$1("parent",n.parent),exactFilter$1("chat",n.chat),exactFilter$1("thread",n.thread),exactFilter$1("maker",n.maker),exactFilter$1("role",n.role),exactFilter$1("status",n.status),exactFilter$1("toolName",n.toolName),exactFilter$1("toolCallId",n.toolCallId),exactFilter$1("coordinationId",n.coordinationId)].filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}definePodRepository({namespace:"message",resource:messageResource,searchableFields:["content"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>messageListFilter(n)});function chatProjectMemoryResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const chatProjectContextResource=podTable("chatProjectContext",{id:id("id"),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),instructions:text("instructions").predicate(UDFS.systemMessage),memoryEnabled:boolean$2("memoryEnabled").predicate(UDFS.memoryEnabled).notNull().default(!0),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-projects/",sparqlEndpoint:"/.data/chat-projects/-/sparql",type:UDFS.ChatProjectContext,namespace:UDFS}),chatProjectMemoryResource=podTable("chatProjectMemory",{id:id("id").default(n=>n?chatProjectMemoryResourceId(n):""),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),text:text("text").predicate(SCHEMA.text).notNull(),sourceMessage:uri("sourceMessage").predicate(UDFS.sourceMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/chat-project-memories/",sparqlEndpoint:"/.data/chat-project-memories/-/sparql",type:UDFS.ProjectMemory,namespace:UDFS});definePodRepository({namespace:"chat-project-context",resource:chatProjectContextResource,defaultSort:{field:"updatedAt",direction:"desc"},filter:({filters:n})=>n?.workspace?eq(chatProjectContextResource.workspace,n.workspace):void 0});definePodRepository({namespace:"chat-project-memory",resource:chatProjectMemoryResource,searchableFields:["text"],defaultSort:{field:"createdAt",direction:"asc"},filter:({filters:n})=>n?.workspace?eq(chatProjectMemoryResource.workspace,n.workspace):void 0});function conversationShareResourceId(n){return n.endsWith(".ttl")?n:`${encodeURIComponent(n)}.ttl`}const conversationShareResource=podTable("conversationShare",{id:id("id").default(n=>n?conversationShareResourceId(n):""),thread:uri("thread").predicate(UDFS.targetThread).notNull(),resourceUrl:uri("resourceUrl").predicate(SCHEMA.url).notNull(),includeToolDetails:boolean$2("includeToolDetails").predicate(UDFS.includeToolDetails).notNull().default(!1),excludedMessageIds:string$2("excludedMessageIds").array().predicate(UDFS.excludedMessage),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/chat-shares/",sparqlEndpoint:"/.data/chat-shares/-/sparql",type:UDFS.ConversationShare,namespace:UDFS});definePodRepository({namespace:"conversation-share",resource:conversationShareResource,defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>n?.thread?eq(conversationShareResource.thread,n.thread):void 0});const TaskStatus={OPEN:"open"},taskResource=podTable("task",{id:id("id").default("index.ttl#{key}"),title:string$2("title").predicate(DCTerms.title),instruction:text("instruction").predicate(UDFS.instruction).notNull(),prompt:text("prompt").predicate(UDFS.prompt),issue:uri("issue").predicate(UDFS.issue).link("issue"),message:uri("message").predicate(UDFS.message),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(TaskStatus.OPEN),priority:string$2("priority").predicate(UDFS.priority),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),source:uri("source").predicate(DCTerms.source),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/task/",sparqlEndpoint:"/.data/task/-/sparql",type:UDFS.Task,namespace:UDFS}),ScheduleStatus={ACTIVE:"active"},ScheduleKind={ONCE:"once"},scheduleResource=podTable("schedule",{id:id("id"),task:uri("task").predicate(UDFS.task).notNull().link(taskResource),status:string$2("status").predicate(UDFS.status).notNull().default(ScheduleStatus.ACTIVE),scheduleKind:string$2("scheduleKind").predicate(UDFS.scheduleKind).notNull().default(ScheduleKind.ONCE),cron:string$2("cron").predicate(UDFS.cron),intervalSeconds:integer$1("intervalSeconds").predicate(UDFS.intervalSeconds),timezone:string$2("timezone").predicate(UDFS.timezone),startsAt:timestamp("startsAt").predicate(UDFS.startsAt),nextRunAt:timestamp("nextRunAt").predicate(UDFS.nextRunAt),lastRunAt:timestamp("lastRunAt").predicate(UDFS.lastRunAt),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Schedule,namespace:UDFS}),AutomationRuleStatus={ACTIVE:"active"},AutomationRuleKind={EVENT:"event"};podTable("automation_rule",{id:id("id"),title:string$2("title").predicate(DCTerms.title).notNull(),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default(AutomationRuleStatus.ACTIVE),ruleKind:string$2("ruleKind").predicate(UDFS.ruleKind).notNull().default(AutomationRuleKind.EVENT),task:uri("task").predicate(UDFS.task).link(taskResource),schedule:uri("schedule").predicate(UDFS.schedule).link(scheduleResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),condition:object$1("condition").predicate(UDFS.condition),actions:object$1("actions").predicate(UDFS.actions),metadata:object$1("metadata").predicate(UDFS.metadata),lastTriggeredAt:timestamp("lastTriggeredAt").predicate(UDFS.lastTriggeredAt),lastRunStatus:string$2("lastRunStatus").predicate(UDFS.lastRunStatus),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.AutomationRule,namespace:UDFS});const DeliveryStatus={PENDING:"pending"},DeliveryKind={TASK_DISPATCH:"task_dispatch"},deliveryResource=podTable("delivery",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/deliveries.ttl#{key}"),kind:string$2("kind").predicate(UDFS.deliveryKind).notNull().default(DeliveryKind.TASK_DISPATCH),status:string$2("status").predicate(UDFS.status).notNull().default(DeliveryStatus.PENDING),task:uri("task").predicate(UDFS.task).link(taskResource),source:uri("source").predicate(DCTerms.source),target:uri("target").predicate(AS.target),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),targetThread:uri("targetThread").predicate(UDFS.targetThread).link(threadResource),targetSession:uri("targetSession").predicate(UDFS.targetSession),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object),objective:text("objective").predicate(UDFS.objective),payload:object$1("payload").predicate(UDFS.payload),projection:object$1("projection").predicate(UDFS.projection),projectedRole:string$2("projectedRole").predicate(UDFS.projectedRole),metadata:object$1("metadata").predicate(UDFS.metadata),error:text("error").predicate(UDFS.error),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),dispatchedAt:timestamp("dispatchedAt").predicate(UDFS.startedAt),consumedAt:timestamp("consumedAt").predicate(UDFS.consumedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Delivery,namespace:UDFS}),issueResource=podTable("issue",{id:id("id").default("{key}.ttl"),title:string$2("title").predicate(DCTerms.title).notNull(),document:uri("document").predicate(DCTerms.source),description:text("description").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("open"),priority:string$2("priority").predicate(UDFS.priority).default("medium"),labels:text("labels").array().predicate(UDFS.tags),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),parentIssue:uri("parentIssue").predicate(UDFS.parentIssue).link("issue"),tasks:uri("tasks").predicate(UDFS.task).array(),createdBy:uri("createdBy").predicate(DCTerms.creator),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),closedAt:timestamp("closedAt").predicate(UDFS.closedAt),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/.data/issues/",sparqlEndpoint:"/.data/issues/-/sparql",type:UDFS.Issue,namespace:UDFS}),RunStatus={QUEUED:"queued"},runResource=podTable("run",{id:id("id").default("{thread.dir}/{yyyy}/{MM}/{dd}/runs.ttl#{key}"),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),trigger:uri("trigger").predicate(UDFS.trigger),input:uri("input").predicate(UDFS.input),thread:uri("thread").predicate(UDFS.inThread).notNull().link(threadResource),workspace:uri("workspace").predicate(UDFS.workspace).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(RunStatus.QUEUED),runner:string$2("runner").predicate(UDFS.runner).notNull(),prompt:string$2("prompt").predicate(UDFS.prompt),externalRunId:string$2("externalRunId").predicate(UDFS.externalRunId),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),heartbeatAt:timestamp("heartbeatAt").predicate(UDFS.heartbeatAt),cancelRequestedAt:timestamp("cancelRequestedAt").predicate(UDFS.cancelRequestedAt),error:string$2("error").predicate(UDFS.error),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),completedAt:timestamp("completedAt").predicate(UDFS.completedAt),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Run,namespace:UDFS});podTable("run_step",{id:id("id").default("{run.doc}#{key}"),run:uri("run").predicate(UDFS.run).notNull().link(runResource),stepType:string$2("stepType").predicate(UDFS.stepType).notNull(),message:string$2("message").predicate(DCTerms.description),payload:object$1("payload").predicate(UDFS.payload),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.RunStep,namespace:UDFS});const evidenceResource=podTable("evidence",{id:id("id").default("evidence/{yyyy}/{MM}/{dd}.ttl#{key}"),evidenceKind:string$2("evidenceKind").predicate(UDFS.evidenceKind).notNull(),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),summary:text("summary").predicate(DCTerms.abstract),source:uri("source").predicate(DCTerms.source),actor:uri("actor").predicate(DCTerms.creator),outcome:string$2("outcome").predicate(UDFS.outcome),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Evidence,namespace:UDFS}),ReportStatus={DRAFT:"draft"};podTable("report",{id:id("id").default((n,e)=>{const t=resourceKey(n,"report"),i=workflowOwnerDir(e)??"reports";return renderDefaultIdTemplate(`${i}/{yyyy}/{MM}/{dd}/reports.ttl#{key}`,{key:t,row:e})}),reportKind:string$2("reportKind").predicate(UDFS.reportKind).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default(ReportStatus.DRAFT),outcome:string$2("outcome").predicate(UDFS.outcome),about:uri("about").predicate(SCHEMA.about).notNull(),issue:uri("issue").predicate(UDFS.issue).link(issueResource),task:uri("task").predicate(UDFS.task).link(taskResource),delivery:uri("delivery").predicate(UDFS.delivery).link(deliveryResource),run:uri("run").predicate(UDFS.run).link(runResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),evidence:uri("evidence").predicate(UDFS.evidence).array().link(evidenceResource),summary:text("summary").predicate(DCTerms.abstract).notNull(),reviewer:uri("reviewer").predicate(SCHEMA.reviewedBy),actor:uri("actor").predicate(DCTerms.creator),source:uri("source").predicate(DCTerms.source),metricFacts:object$1("metricFacts").predicate(UDFS.metricFacts),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),publishedAt:timestamp("publishedAt").predicate(DCTerms.issued),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/",sparqlEndpoint:"/.data/-/sparql",type:UDFS.Report,namespace:UDFS});podTable("idea",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),summary:string$2("summary").predicate(DCTerms.abstract).notNull(),document:uri("document").predicate(DCTerms.source),input:text("input").predicate(DCTerms.description),status:string$2("status").predicate(UDFS.status).notNull().default("captured"),commitment:string$2("commitment").predicate(UDFS.commitment).notNull().default("thought"),affectedArea:string$2("affectedArea").predicate(UDFS.affectedArea),currentUnderstanding:text("currentUnderstanding").predicate(UDFS.currentUnderstanding),openQuestions:text("openQuestions").array().predicate(UDFS.openQuestions),related:uri("related").array().predicate(DCTerms.relation),conflicts:text("conflicts").array().predicate(UDFS.conflicts),nextStep:text("nextStep").predicate(UDFS.nextStep),promotedTo:uri("promotedTo").predicate(UDFS.promotedTo),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),sourceMessages:uri("sourceMessages").array().predicate(DCTerms.source),createdBy:uri("createdBy").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/ideas/",sparqlEndpoint:"/.data/ideas/-/sparql",type:UDFS.Idea,namespace:UDFS});definePodRepository({namespace:"issue",resource:issueResource,searchableFields:["title","description"],defaultSort:{field:"updatedAt",direction:"desc"}});var MessageBlockType;(function(n){n.UNKNOWN="unknown",n.MAIN_TEXT="main_text",n.THINKING="thinking",n.IMAGE="image",n.CODE="code",n.TOOL="tool",n.TOOL_APPROVAL="tool_approval",n.TASK_PROGRESS="task_progress",n.FILE="file",n.ERROR="error",n.CITATION="citation"})(MessageBlockType||(MessageBlockType={}));var MessageBlockStatus;(function(n){n.PENDING="pending",n.PROCESSING="processing",n.STREAMING="streaming",n.SUCCESS="success",n.ERROR="error",n.PAUSED="paused"})(MessageBlockStatus||(MessageBlockStatus={}));const fixtureToolCallBlock={type:"tool",toolCallId:"toolcall-1",toolName:"write_file",arguments:{path:"README.md",content:"hello"},status:"waiting_approval",duration:123},fixtureToolApprovalBlock={type:"tool_approval",toolCallId:"toolcall-1",toolName:"write_file",toolDescription:"Write a file in the workspace",arguments:{path:"README.md",content:"hello"},risk:"medium",status:"pending",decisionRole:"human"},fixtureTaskProgressBlock={type:"task_progress",task:"https://pod.example/.data/task/index.ttl#task-1",title:"CP0 contract baseline",steps:[{id:"s1",label:"Freeze contracts",status:"done",duration:10},{id:"s2",label:"Add namespaces",status:"running"}],currentStep:2,totalSteps:2};JSON.stringify({blocks:[fixtureToolCallBlock,fixtureToolApprovalBlock,fixtureTaskProgressBlock]});const favoriteResource=podTable("favorite",{id:id("id"),targetType:uri("targetType").predicate(RDF$1.type).notNull(),target:uri("target").predicate(UDFS.favoriteTarget).notNull(),title:string$2("title").predicate(DCTerms.title).notNull(),snapshotContent:text("snapshotContent").predicate(SCHEMA.text),snapshotAuthor:string$2("snapshotAuthor").predicate(SCHEMA.author),sourceModule:string$2("sourceModule").predicate(UDFS.sourceModule),searchText:text("searchText").predicate(UDFS.searchText),snapshotMeta:text("snapshotMeta").predicate(UDFS.snapshotMeta),favoredAt:timestamp("favoredAt").predicate(UDFS.favoredAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified)},{base:"/.data/favorites/",sparqlEndpoint:"/.data/favorites/-/sparql",type:SCHEMA.CreativeWork,namespace:UDFS});async function createFavorite(n,e,t){const{rdfType:i,sourceModule:s,extractor:a}=e,l=t["@id"]||t.id;if(!l){console.warn("[StarredSync] Cannot create favorite: missing target URI");return}const u=a.getTitle(t),f={id:crypto.randomUUID(),targetType:i,target:l,title:u,snapshotContent:a.getContent?.(t),snapshotAuthor:a.getAuthor?.(t),sourceModule:s,searchText:a.getSearchText?.(t)??u,snapshotMeta:a.getSnapshotMeta?.(t),favoredAt:new Date,updatedAt:new Date};try{getDbInstance()||console.warn("[StarredSync] No db instance registered")}catch(d){console.error("[StarredSync] Failed to create favorite:",d)}}async function deleteFavorite(n,e){if(e)try{const t=getDbInstance()}catch(t){console.error("[StarredSync] Failed to delete favorite:",t)}}function createStarredSyncHook(n){return{afterUpdate:async(e,t,i)=>{if(!("starred"in i))return;const s=t.starred,a=t["@id"]||t.id;s?await createFavorite(e,n,t):await deleteFavorite(e,a)}}}let dbInstance=null;function getDbInstance(){return dbInstance}const chatSnapshotExtractor={getTitle:n=>n.title||"未命名对话",getContent:n=>n.lastMessagePreview},threadSnapshotExtractor={getTitle:n=>n.title||"未命名话题"};createStarredSyncHook({rdfType:MEETING.LongChat,sourceModule:"chat",extractor:chatSnapshotExtractor});createStarredSyncHook({rdfType:SIOC.Thread,sourceModule:"thread",extractor:threadSnapshotExtractor});const approvalResource=podTable("approval",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId).notNull(),toolName:string$2("toolName").predicate(UDFS.toolName).notNull(),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),risk:string$2("risk").predicate(UDFS.risk).notNull(),status:string$2("status").predicate(UDFS.status).notNull().default("pending"),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),context:text("context").predicate(UDFS.context),approvalOptions:text("approvalOptions").predicate(UDFS.approvalOptions),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/approvals/",sparqlEndpoint:"/.data/approvals/-/sparql",type:UDFS.ApprovalRequest,namespace:UDFS}),InputRequestStatus={PENDING:"pending"},inputRequestResource=podTable("input_request",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),session:uri("session").predicate(UDFS.session).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),run:uri("run").predicate(UDFS.run).link(runResource),task:uri("task").predicate(UDFS.task).link(taskResource),requester:uri("requester").predicate(UDFS.requester),requestKind:string$2("requestKind").predicate(UDFS.requestKind).notNull().default("user-input"),prompt:text("prompt").predicate(UDFS.prompt).notNull(),context:text("context").predicate(UDFS.context),inputOptions:text("inputOptions").predicate(UDFS.inputOptions),status:string$2("status").predicate(UDFS.status).notNull().default(InputRequestStatus.PENDING),leaseOwner:string$2("leaseOwner").predicate(UDFS.leaseOwner),leaseExpiresAt:timestamp("leaseExpiresAt").predicate(UDFS.leaseExpiresAt),assignedTo:uri("assignedTo").predicate(UDFS.assignedTo),response:text("response").predicate(UDFS.response),answeredBy:uri("answeredBy").predicate(UDFS.answeredBy),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),reason:text("reason").predicate(UDFS.reason),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),resolvedAt:timestamp("resolvedAt").predicate(UDFS.resolvedAt)},{base:"/.data/input-requests/",sparqlEndpoint:"/.data/input-requests/-/sparql",type:UDFS.InputRequest,namespace:UDFS}),CaptureCandidateStatus={CANDIDATE:"candidate"},captureCandidateResource=podTable("capture_candidate",{id:id("id").default("candidates/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),summary:text("summary").predicate(DCTerms.abstract).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence).notNull().default("medium"),reason:text("reason").predicate(UDFS.reason),status:string$2("status").predicate(UDFS.status).notNull().default(CaptureCandidateStatus.CANDIDATE),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureCandidate,namespace:UDFS}),captureEventResource=podTable("capture_event",{id:id("id").default("events/{yyyy}/{MM}/{dd}.ttl#{key}"),source:uri("source").predicate(DCTerms.source).notNull(),captureCandidate:uri("captureCandidate").predicate(UDFS.captureCandidate).link(captureCandidateResource),targetResource:uri("targetResource").predicate(UDFS.targetResource),decision:string$2("decision").predicate(UDFS.captureDecision).notNull(),suggestedType:uri("suggestedType").predicate(UDFS.suggestedType),suggestedTarget:uri("suggestedTarget").predicate(UDFS.suggestedTarget),confidence:string$2("confidence").predicate(UDFS.confidence),reason:text("reason").predicate(UDFS.reason),userCorrection:text("userCorrection").predicate(UDFS.userCorrection),approval:uri("approval").predicate(UDFS.approval).link(approvalResource),inputRequest:uri("inputRequest").predicate(UDFS.inputRequest).link(inputRequestResource),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),task:uri("task").predicate(UDFS.task).link(taskResource),run:uri("run").predicate(UDFS.run).link(runResource),actor:uri("actor").predicate(DCTerms.creator),about:uri("about").predicate(SCHEMA.about),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/capture/",sparqlEndpoint:"/.data/capture/-/sparql",type:UDFS.CaptureEvent,namespace:UDFS}),candidateExactFilterColumns={source:captureCandidateResource.source,suggestedType:captureCandidateResource.suggestedType,suggestedTarget:captureCandidateResource.suggestedTarget,status:captureCandidateResource.status,chat:captureCandidateResource.chat,thread:captureCandidateResource.thread,task:captureCandidateResource.task,run:captureCandidateResource.run},eventExactFilterColumns={source:captureEventResource.source,captureCandidate:captureEventResource.captureCandidate,targetResource:captureEventResource.targetResource,decision:captureEventResource.decision,approval:captureEventResource.approval,inputRequest:captureEventResource.inputRequest,chat:captureEventResource.chat,thread:captureEventResource.thread,task:captureEventResource.task,run:captureEventResource.run};function exactFilter(n,e,t){return t===void 0?void 0:eq(n[e],t)}function combineFilters(n){const e=n.filter(t=>!!t);if(e.length!==0)return e.length===1?e[0]:and(...e)}function captureCandidateListFilter(n){if(n)return combineFilters([exactFilter(candidateExactFilterColumns,"source",n.source),exactFilter(candidateExactFilterColumns,"suggestedType",n.suggestedType),exactFilter(candidateExactFilterColumns,"suggestedTarget",n.suggestedTarget),exactFilter(candidateExactFilterColumns,"status",n.status),exactFilter(candidateExactFilterColumns,"chat",n.chat),exactFilter(candidateExactFilterColumns,"thread",n.thread),exactFilter(candidateExactFilterColumns,"task",n.task),exactFilter(candidateExactFilterColumns,"run",n.run)])}function captureEventListFilter(n){if(n)return combineFilters([exactFilter(eventExactFilterColumns,"source",n.source),exactFilter(eventExactFilterColumns,"captureCandidate",n.captureCandidate),exactFilter(eventExactFilterColumns,"targetResource",n.targetResource),exactFilter(eventExactFilterColumns,"decision",n.decision),exactFilter(eventExactFilterColumns,"approval",n.approval),exactFilter(eventExactFilterColumns,"inputRequest",n.inputRequest),exactFilter(eventExactFilterColumns,"chat",n.chat),exactFilter(eventExactFilterColumns,"thread",n.thread),exactFilter(eventExactFilterColumns,"task",n.task),exactFilter(eventExactFilterColumns,"run",n.run)])}definePodRepository({namespace:"capture-candidate",resource:captureCandidateResource,searchableFields:["summary","reason"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureCandidateListFilter(n)});definePodRepository({namespace:"capture-event",resource:captureEventResource,searchableFields:["reason","userCorrection"],defaultSort:{field:"createdAt",direction:"desc"},filter:({filters:n})=>captureEventListFilter(n)});podTable("settings",{id:id("id").default((n,e)=>{const t=typeof e?.key=="string"?e.key:n;return t?`${encodeURIComponent(t)}.ttl`:""}),key:string$2("key").predicate(UDFS.settingKey).notNull(),value:text("value").predicate(UDFS.settingValue).notNull(),valueType:string$2("valueType").predicate(UDFS.settingType).notNull().default("string"),category:string$2("category").predicate(DCTerms.type).notNull(),label:string$2("label").predicate(DCTerms.title),description:text("description").predicate(DCTerms.description),owner:string$2("owner").predicate(DCTerms.creator).notNull(),isSensitive:boolean$2("isSensitive").predicate(UDFS.status).default(!1),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),modifiedAt:timestamp("modifiedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/settings/",sparqlEndpoint:"/settings/-/sparql",type:SCHEMA.PropertyValue,namespace:UDFS});const agentResource=podTable("agent",{id:id("id").default("{key}/"),name:string$2("name").predicate(FOAF.name).notNull(),description:text("description").predicate(DCTerms.description),avatarUrl:uri("avatarUrl").predicate(VCARD.hasPhoto),root:uri("root").predicate(UDFS.root),identity:uri("identity").predicate(UDFS.webId),hasSkill:uri("hasSkill").array().predicate(UDFS.hasSkill),instructions:text("instructions").predicate(UDFS.systemMessage),provider:string$2("provider").predicate(UDFS.provider),model:string$2("model").predicate(UDFS.model),backend:string$2("backend").predicate(UDFS.backend),runtime:string$2("runtime").predicate(UDFS.runtime),transport:string$2("transport").predicate(UDFS.transport),endpoint:uri("endpoint").predicate(UDFS.endpoint),credentialSource:string$2("credentialSource").predicate(UDFS.credentialSource),temperature:real("temperature").predicate(UDFS.temperature).default(.7),tools:text("tools").array().predicate(UDFS.tools),contextRound:integer$1("contextRound").predicate(UDFS.contextRound).default(4),authorityPolicy:object$1("authorityPolicy").predicate(UDFS.authorityPolicy),toolPolicy:object$1("toolPolicy").predicate(UDFS.toolPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),ttsModel:string$2("ttsModel").predicate(UDFS.ttsModel),videoModel:string$2("videoModel").predicate(UDFS.videoModel),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),deletedAt:timestamp("deletedAt").predicate(UDFS.deletedAt)},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:FOAF.Agent,namespace:UDFS});definePodRepository({namespace:"agent",resource:agentResource,searchableFields:["name","description","instructions"]});podTable("skill",{id:id("id").default("{agent.key}/skills/{key}/"),agent:uri("agent").predicate(UDFS.agent).notNull().link(agentResource),root:uri("root").predicate(UDFS.root),name:string$2("name").predicate(UDFS.name).notNull(),displayName:string$2("displayName").predicate(UDFS.displayName),enabled:boolean$2("enabled").predicate(UDFS.enabled).default(!0),version:string$2("version").predicate(UDFS.version),source:string$2("source").predicate(UDFS.source),checksum:string$2("checksum").predicate(UDFS.checksum),loadPolicy:string$2("loadPolicy").predicate(UDFS.loadPolicy),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow()},{base:"/agents/",sparqlEndpoint:"/agents/-/sparql",type:UDFS.Skill,namespace:UDFS});const sessionResource=podTable("session",{id:id("id").default("{yyyy}/{MM}/{dd}/{key}.ttl"),owner:uri("owner").predicate(UDFS.actor).notNull(),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),status:string$2("status").predicate(UDFS.sessionStatus).notNull().default("active"),tool:string$2("tool").predicate(UDFS.sessionTool),tokenUsage:integer$1("tokenUsage").predicate(UDFS.tokenUsage).default(0),messages:uri("messages").predicate(UDFS.message).array(),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),metadata:object$1("metadata").predicate(UDFS.metadata),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(DCTerms.modified).notNull().defaultNow(),archivedAt:timestamp("archivedAt").predicate(UDFS.archivedAt)},{base:"/.data/sessions/",sparqlEndpoint:"/.data/sessions/-/sparql",type:UDFS.term("Session"),namespace:UDFS});definePodRepository({namespace:"session",resource:sessionResource,searchableFields:["chat","thread","status","tool"],defaultSort:{field:"updatedAt",direction:"desc"}});podTable("audit",{id:id("id").default("{yyyy}/{MM}/{dd}.ttl#{key}"),action:string$2("action").predicate(UDFS.action).notNull(),actor:uri("actor").predicate(UDFS.actor).notNull(),actorRole:string$2("actorRole").predicate(UDFS.actorRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),session:uri("session").predicate(UDFS.session),chat:uri("chat").predicate(UDFS.conversation).link(chatResource),thread:uri("thread").predicate(UDFS.inThread).link(threadResource),entry:uri("entry").predicate(UDFS.entry),toolCallId:string$2("toolCallId").predicate(UDFS.toolCallId),toolName:string$2("toolName").predicate(UDFS.toolName),approval:uri("approval").predicate(UDFS.approval),policy:uri("policy").predicate(UDFS.policy),policyVersion:string$2("policyVersion").predicate(UDFS.policyVersion),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/.data/audits/",sparqlEndpoint:"/.data/audits/-/sparql",type:UDFS.AuditEntry,namespace:UDFS});podTable("grant",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AutonomyGrant]),target:uri("target").predicate(ODRL.target).notNull(),action:uri("action").predicate(ODRL.action).notNull(),title:string$2("title").predicate(DCTerms.title),summary:text("summary").predicate(DCTerms.abstract),description:text("description").predicate(DCTerms.description),schema:uri("schema").predicate(DCTerms.conformsTo),pageKind:string$2("pageKind").predicate(UDFS.pageKind),wikiStatus:string$2("wikiStatus").predicate(UDFS.status),tags:text("tags").predicate(UDFS.tags),source:string$2("source").predicate(UDFS.sourceKind),sourceHash:string$2("sourceHash").predicate(UDFS.sourceHash),compiledAt:timestamp("compiledAt").predicate(UDFS.compiledAt),compiledFrom:uri("compiledFrom").array().predicate(UDFS.compiledFrom),related:uri("related").array().predicate(DCTerms.relation),effect:string$2("effect").predicate(UDFS.effect).notNull(),riskCeiling:string$2("riskCeiling").predicate(UDFS.riskCeiling),policy:text("policy").predicate(UDFS.policy),context:text("context").predicate(UDFS.context),decisionBy:uri("decisionBy").predicate(UDFS.decisionBy).notNull(),decisionRole:string$2("decisionRole").predicate(UDFS.decisionRole).notNull(),onBehalfOf:uri("onBehalfOf").predicate(UDFS.onBehalfOf),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow(),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/settings/autonomy/grants/",sparqlEndpoint:"/settings/autonomy/grants/-/sparql",type:ODRL.Policy,namespace:ODRL});podTable("inbox_notification",{id:id("id").default("{key}.ttl"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([AS.Announce]),actor:uri("actor").predicate(AS.actor),object:uri("object").predicate(AS.object).notNull(),createdAt:timestamp("createdAt").predicate(DCTerms.created).notNull().defaultNow()},{base:"/inbox/",sparqlEndpoint:"/inbox/-/sparql",type:AS.Activity,namespace:AS});var util;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const a={};for(const l of s)a[l]=l;return a},n.getValidEnumValues=s=>{const a=n.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of a)l[u]=s[u];return n.objectValues(l)},n.objectValues=s=>n.objectKeys(s).map(function(a){return s[a]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&a.push(l);return a},n.find=(s,a)=>{for(const l of s)if(a(l))return l},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function i(s,a=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(a)}n.joinValues=i,n.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(util||(util={}));var objectUtil;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=n=>{switch(typeof n){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(n)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(n)?ZodParsedType.array:n===null?ZodParsedType.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&n instanceof Map?ZodParsedType.map:typeof Set<"u"&&n instanceof Set?ZodParsedType.set:typeof Date<"u"&&n instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},i={_errors:[]},s=a=>{for(const l of a.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let u=i,f=0;for(;f<l.path.length;){const d=l.path[f];f===l.path.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(l))):u[d]=u[d]||{_errors:[]},u=u[d],f++}}};return s(this),i}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=n=>new ZodError(n);const errorMap=(n,e)=>{let t;switch(n.code){case ZodIssueCode.invalid_type:n.received===ZodParsedType.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${util.joinValues(n.keys,", ")}`;break;case ZodIssueCode.invalid_union:t="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${util.joinValues(n.options)}`;break;case ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${util.joinValues(n.options)}, received '${n.received}'`;break;case ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case ZodIssueCode.invalid_date:t="Invalid date";break;case ZodIssueCode.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:util.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case ZodIssueCode.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case ZodIssueCode.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case ZodIssueCode.custom:t="Invalid input";break;case ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case ZodIssueCode.not_finite:t="Number must be finite";break;default:t=e.defaultError,util.assertNever(n)}return{message:t}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,a=[...t,...s.path||[]],l={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let u="";const f=i.filter(d=>!!d).slice().reverse();for(const d of f)u=d(l,{data:e,defaultError:u}).message;return{...s,path:a,message:u}};function addIssueToContext(n,e){const t=getErrorMap(),i=makeIssue({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===errorMap?void 0:errorMap].filter(s=>!!s)});n.common.issues.push(i)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return INVALID;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const a=await s.key,l=await s.value;i.push({key:a,value:l})}return ParseStatus.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:a,value:l}=s;if(a.status==="aborted"||l.status==="aborted")return INVALID;a.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(i[a.value]=l.value)}return{status:e.value,value:i}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=n=>({status:"dirty",value:n}),OK=n=>({status:"valid",value:n}),isAborted=n=>n.status==="aborted",isDirty=n=>n.status==="dirty",isValid=n=>n.status==="valid",isAsync=n=>typeof Promise<"u"&&n instanceof Promise;var errorUtil;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(n,e)=>{if(isValid(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(n.common.issues);return this._error=t,this._error}}};function processCreateParams(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{const{message:f}=n;return l.code==="invalid_enum_value"?{message:f??u.defaultError}:typeof u.data>"u"?{message:f??i??u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:f??t??u.defaultError}},description:s}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parseSync({data:e,path:i.path,parent:i});return handleResult(i,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return isValid(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>isValid(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},s=this._parse({data:e,path:i.path,parent:i}),a=await(isAsync(s)?s:Promise.resolve(s));return handleResult(i,a)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{const l=e(s),u=()=>a.addIssue({code:ZodIssueCode.custom,...i(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(f=>f?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function timeRegex(n){return new RegExp(`^${timeRegexSource(n)}$`)}function datetimeRegex(n){let e=`${dateRegexSource}T${timeRegexSource(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function isValidIP(n,e){return!!((e==="v4"||!e)&&ipv4Regex.test(n)||(e==="v6"||!e)&&ipv6Regex.test(n))}function isValidJWT(n,e){if(!jwtRegex.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function isValidCidr(n,e){return!!((e==="v4"||!e)&&ipv4CidrRegex.test(n)||(e==="v6"||!e)&&ipv6CidrRegex.test(n))}class ZodString extends ZodType{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ZodParsedType.string){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:a.parsedType}),INVALID}const i=new ParseStatus;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),i.dirty());else if(a.kind==="length"){const l=e.data.length>a.value,u=e.data.length<a.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?addIssueToContext(s,{code:ZodIssueCode.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):u&&addIssueToContext(s,{code:ZodIssueCode.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),i.dirty())}else if(a.kind==="email")emailRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"email",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"emoji",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="uuid")uuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"uuid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="nanoid")nanoidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid")cuidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="cuid2")cuid2Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="ulid")ulidRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ulid",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"url",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"regex",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),i.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{startsWith:a.value},message:a.message}),i.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:{endsWith:a.value},message:a.message}),i.dirty()):a.kind==="datetime"?datetimeRegex(a).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"datetime",message:a.message}),i.dirty()):a.kind==="date"?dateRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"date",message:a.message}),i.dirty()):a.kind==="time"?timeRegex(a).test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.invalid_string,validation:"time",message:a.message}),i.dirty()):a.kind==="duration"?durationRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"duration",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="ip"?isValidIP(e.data,a.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"ip",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="jwt"?isValidJWT(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"jwt",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="cidr"?isValidCidr(e.data,a.version)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"cidr",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="base64"?base64Regex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):a.kind==="base64url"?base64urlRegex.test(e.data)||(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{validation:"base64url",code:ZodIssueCode.invalid_string,message:a.message}),i.dirty()):util.assertNever(a);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(i)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...errorUtil.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...errorUtil.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodString.create=n=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:n?.coerce??!1,...processCreateParams(n)});function floatSafeRemainder(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,a=Number.parseInt(n.toFixed(s).replace(".","")),l=Number.parseInt(e.toFixed(s).replace(".",""));return a%l/10**s}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ZodParsedType.number){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:a.parsedType}),INVALID}let i;const s=new ParseStatus;for(const a of this._def.checks)a.kind==="int"?util.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?floatSafeRemainder(e.data,a.value)!==0&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_finite,message:a.message}),s.dirty()):util.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&util.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=n=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let i;const s=new ParseStatus;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),addIssueToContext(i,{code:ZodIssueCode.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):util.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,i,s){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:errorUtil.toString(s)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=n=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:n?.coerce??!1,...processCreateParams(n)});class ZodBoolean extends ZodType{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ZodParsedType.boolean){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:i.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=n=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:n?.coerce||!1,...processCreateParams(n)});class ZodDate extends ZodType{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ZodParsedType.date){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:a.parsedType}),INVALID}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return addIssueToContext(a,{code:ZodIssueCode.invalid_date}),INVALID}const i=new ParseStatus;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),i.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),addIssueToContext(s,{code:ZodIssueCode.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),i.dirty()):util.assertNever(a);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ZodDate.create=n=>new ZodDate({checks:[],coerce:n?.coerce||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(n)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:i.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=n=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(n)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:i.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=n=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(n)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:i.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=n=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(n)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=n=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(n)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=n=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(n)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=n=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(n)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:i.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=n=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(n)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(s.exactLength!==null){const l=t.data.length>s.exactLength.value,u=t.data.length<s.exactLength.value;(l||u)&&(addIssueToContext(t,{code:l?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,u)=>s.type._parseAsync(new ParseInputLazyPath(t,l,t.path,u)))).then(l=>ParseStatus.mergeArray(i,l));const a=[...t.data].map((l,u)=>s.type._parseSync(new ParseInputLazyPath(t,l,t.path,u)));return ParseStatus.mergeArray(i,a)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}ZodArray.create=(n,e)=>new ZodArray({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(e)});function deepPartialify(n){if(n instanceof ZodObject){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=ZodOptional.create(deepPartialify(i))}return new ZodObject({...n._def,shape:()=>e})}else return n instanceof ZodArray?new ZodArray({...n._def,type:deepPartialify(n.element)}):n instanceof ZodOptional?ZodOptional.create(deepPartialify(n.unwrap())):n instanceof ZodNullable?ZodNullable.create(deepPartialify(n.unwrap())):n instanceof ZodTuple?ZodTuple.create(n.items.map(e=>deepPartialify(e))):n}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ZodParsedType.object){const d=this._getOrReturnCtx(e);return addIssueToContext(d,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:d.parsedType}),INVALID}const{status:i,ctx:s}=this._processInputParams(e),{shape:a,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const d in s.data)l.includes(d)||u.push(d);const f=[];for(const d of l){const p=a[d],g=s.data[d];f.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)f.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];f.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 f){const g=await p.key,m=await p.value;d.push({key:g,value:m,alwaysSet:p.alwaysSet})}return d}).then(d=>ParseStatus.mergeObjectSync(i,d)):ParseStatus.mergeObjectSync(i,f)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const s=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:errorUtil.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};for(const i of util.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const i of util.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const i of util.objectKeys(this.shape)){const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const i of util.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let a=this.shape[i];for(;a instanceof ZodOptional;)a=a._def.innerType;t[i]=a}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.strictCreate=(n,e)=>new ZodObject({shape:()=>n,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});ZodObject.lazycreate=(n,e)=>new ZodObject({shape:n,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(e)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(a){for(const u of a)if(u.result.status==="valid")return u.result;for(const u of a)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;const l=a.map(u=>new ZodError(u.ctx.common.issues));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:l}),INVALID}if(t.common.async)return Promise.all(i.map(async a=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(s);{let a;const l=[];for(const f of i){const d={...t,common:{...t.common,issues:[]},parent:null},p=f._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:d}),d.common.issues.length&&l.push(d.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const u=l.map(f=>new ZodError(f));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:u}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(n,e)=>new ZodUnion({options:n,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(e)});function mergeValues(n,e){const t=getParsedType(n),i=getParsedType(e);if(n===e)return{valid:!0,data:n};if(t===ZodParsedType.object&&i===ZodParsedType.object){const s=util.objectKeys(e),a=util.objectKeys(n).filter(u=>s.indexOf(u)!==-1),l={...n,...e};for(const u of a){const f=mergeValues(n[u],e[u]);if(!f.valid)return{valid:!1};l[u]=f.data}return{valid:!0,data:l}}else if(t===ZodParsedType.array&&i===ZodParsedType.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<n.length;a++){const l=n[a],u=e[a],f=mergeValues(l,u);if(!f.valid)return{valid:!1};s.push(f.data)}return{valid:!0,data:s}}else return t===ZodParsedType.date&&i===ZodParsedType.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(a,l)=>{if(isAborted(a)||isAborted(l))return INVALID;const u=mergeValues(a.value,l.value);return u.valid?((isDirty(a)||isDirty(l))&&t.dirty(),{status:t.value,value:u.data}):(addIssueToContext(i,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([a,l])=>s(a,l)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ZodIntersection.create=(n,e,t)=>new ZodIntersection({left:n,right:e,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(t)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.array)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:i.parsedType}),INVALID;if(i.data.length<this._def.items.length)return addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&i.data.length>this._def.items.length&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...i.data].map((l,u)=>{const f=this._def.items[u]||this._def.rest;return f?f._parse(new ParseInputLazyPath(i,l,i.path,u)):null}).filter(l=>!!l);return i.common.async?Promise.all(a).then(l=>ParseStatus.mergeArray(t,l)):ParseStatus.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:n,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(e)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.object)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:i.parsedType}),INVALID;const s=[],a=this._def.keyType,l=this._def.valueType;for(const u in i.data)s.push({key:a._parse(new ParseInputLazyPath(i,u,i.path,u)),value:l._parse(new ParseInputLazyPath(i,i.data[u],i.path,u)),alwaysSet:u in i.data});return i.common.async?ParseStatus.mergeObjectAsync(t,s):ParseStatus.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof ZodType?new ZodRecord({keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(i)}):new ZodRecord({keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.map)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:i.parsedType}),INVALID;const s=this._def.keyType,a=this._def.valueType,l=[...i.data.entries()].map(([u,f],d)=>({key:s._parse(new ParseInputLazyPath(i,u,i.path,[d,"key"])),value:a._parse(new ParseInputLazyPath(i,f,i.path,[d,"value"]))}));if(i.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const f of l){const d=await f.key,p=await f.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 f of l){const d=f.key,p=f.value;if(d.status==="aborted"||p.status==="aborted")return INVALID;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),u.set(d.value,p.value)}return{status:t.value,value:u}}}}ZodMap.create=(n,e,t)=>new ZodMap({valueType:e,keyType:n,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(t)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==ZodParsedType.set)return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:i.parsedType}),INVALID;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(addIssueToContext(i,{code:ZodIssueCode.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function l(f){const d=new Set;for(const p of f){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((f,d)=>a._parse(new ParseInputLazyPath(i,f,i.path,d)));return i.common.async?Promise.all(u).then(f=>l(f)):l(u)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(n,e)=>new ZodSet({valueType:n,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(e)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(n,e)=>new ZodLazy({getter:n,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(e)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}ZodLiteral.create=(n,e)=>new ZodLiteral({value:n,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(e)});function createZodEnum(n,e){return new ZodEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(e)})}class ZodEnum extends ZodType{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{expected:util.joinValues(i),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:i}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==ZodParsedType.string&&i.parsedType!==ZodParsedType.number){const s=util.objectValues(t);return addIssueToContext(i,{expected:util.joinValues(s),received:i.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=util.objectValues(t);return addIssueToContext(i,{received:i.data,code:ZodIssueCode.invalid_enum_value,options:s}),INVALID}return OK(e.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(n,e)=>new ZodNativeEnum({values:n,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(e)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&t.common.async===!1)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const i=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ZodPromise.create=(n,e)=>new ZodPromise({type:n,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(e)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:l=>{addIssueToContext(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const l=s.transform(i.data,a);if(i.common.async)return Promise.resolve(l).then(async u=>{if(t.value==="aborted")return INVALID;const f=await this._def.schema._parseAsync({data:u,path:i.path,parent:i});return f.status==="aborted"?INVALID:f.status==="dirty"||t.value==="dirty"?DIRTY(f.value):f});{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 f=s.refinement(u,a);if(i.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(i.common.async===!1){const u=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(u=>u.status==="aborted"?INVALID:(u.status==="dirty"&&t.dirty(),l(u.value).then(()=>({status:t.value,value:u.value}))))}if(s.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!isValid(l))return INVALID;const u=s.transform(l.value,a);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>isValid(l)?Promise.resolve(s.transform(l.value,a)).then(u=>({status:t.value,value:u})):INVALID);util.assertNever(s)}}ZodEffects.create=(n,e,t)=>new ZodEffects({schema:n,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:e,...processCreateParams(t)});ZodEffects.createWithPreprocess=(n,e,t)=>new ZodEffects({schema:e,effect:{type:"preprocess",transform:n},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(t)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(n,e)=>new ZodOptional({innerType:n,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(e)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(n,e)=>new ZodNullable({innerType:n,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(e)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===ZodParsedType.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(n,e)=>new ZodDefault({innerType:n,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...processCreateParams(e)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return isAsync(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ZodError(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(n,e)=>new ZodCatch({innerType:n,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...processCreateParams(e)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const i=this._getOrReturnCtx(e);return addIssueToContext(i,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:i.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=n=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(n)});class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?INVALID:a.status==="dirty"?(t.dirty(),DIRTY(a.value)):this._def.out._parseAsync({data:a.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?INVALID:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),i=s=>(isValid(s)&&(s.value=Object.freeze(s.value)),s);return isAsync(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}ZodReadonly.create=(n,e)=>new ZodReadonly({innerType:n,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(e)});var ZodFirstPartyTypeKind;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const RiskLevelSchema=enumType(["low","medium","high"]),DecisionRoleSchema=enumType(["human","secretary","system"]),ToolCallStatusSchema=enumType(["calling","waiting_approval","approved","rejected","running","done","error"]),IsoDatetimeSchema=stringType().datetime(),ApprovalOptionSchema=objectType({optionId:stringType(),label:stringType(),kind:stringType().optional(),description:stringType().optional()}).strict(),ToolCallEventV1Schema=objectType({type:literalType("tool.call"),version:literalType(1).optional(),sessionId:stringType(),toolCallId:stringType(),toolName:stringType(),risk:RiskLevelSchema.optional(),status:ToolCallStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),expiresAt:IsoDatetimeSchema.optional(),target:stringType().optional(),action:stringType().optional(),arguments:recordType(unknownType()).optional(),result:unknownType().optional(),error:stringType().optional(),duration:numberType().int().nonnegative().optional(),inboxItemId:stringType().optional(),decisionBy:stringType().optional(),decisionRole:DecisionRoleSchema.optional(),onBehalfOf:stringType().optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolCallEventSchema=ToolCallEventV1Schema,SessionToolSchema=enumType(["claude-code","cursor","windsurf"]),SessionStatusSchema=enumType(["active","paused","completed","error"]),SessionStateEventV1Schema=objectType({type:literalType("session.state"),version:literalType(1).optional(),sessionId:stringType(),chat:stringType(),policy:stringType().optional(),policyVersion:stringType().optional(),status:SessionStatusSchema,previousStatus:stringType(),tool:SessionToolSchema,tokenUsage:numberType().int().nonnegative(),timestamp:IsoDatetimeSchema}).strict(),SessionStateEventSchema=SessionStateEventV1Schema,ToolControlCommandNameSchema=enumType(["approve","reject","pause","resume","stop","inject_message","approve_pattern"]),ToolControlCommandV1Schema=objectType({commandId:stringType().optional(),type:literalType("tool.control"),version:literalType(1).optional(),command:ToolControlCommandNameSchema,sessionId:stringType(),toolCallId:stringType().optional(),message:stringType().optional(),pattern:stringType().optional(),inboxItemId:stringType().optional(),actor:objectType({actorWebId:stringType(),actorRole:DecisionRoleSchema,onBehalfOf:stringType().optional()}).optional(),policyVersion:stringType().optional(),timestamp:IsoDatetimeSchema}).strict(),ToolControlCommandSchema=ToolControlCommandV1Schema,InboxApprovalStatusSchema=enumType(["pending","approved","rejected","expired"]),InboxApprovalEventV1Schema=objectType({type:literalType("inbox.approval"),version:literalType(1).optional(),inboxItemId:stringType(),sessionId:stringType(),toolCallId:stringType(),target:stringType().optional(),action:stringType().optional(),policy:stringType().optional(),policyVersion:stringType().optional(),risk:RiskLevelSchema,status:InboxApprovalStatusSchema,approvalOptions:arrayType(ApprovalOptionSchema).optional(),assignedTo:stringType().optional(),createdAt:IsoDatetimeSchema,expiresAt:IsoDatetimeSchema.optional(),resolvedAt:IsoDatetimeSchema.optional()}).strict(),InboxApprovalEventSchema=InboxApprovalEventV1Schema;unionType([ToolCallEventSchema,SessionStateEventSchema,ToolControlCommandSchema,InboxApprovalEventSchema]);const aiProviderResource=podTable("aiProvider",{id:id("id").default("{key}.ttl"),displayName:string$2("displayName").predicate(UDFS.displayName),baseUrl:string$2("baseUrl").predicate(UDFS.baseUrl),proxyUrl:string$2("proxyUrl").predicate(UDFS.proxyUrl),homepage:string$2("homepage").predicate(UDFS.homepage),apiKeyUrl:string$2("apiKeyUrl").predicate(UDFS.apiKeyUrl),connectMode:string$2("connectMode").predicate(UDFS.connectMode),hasModel:uri("hasModel").predicate(UDFS.hasModel).array().link("aiModel"),defaultModel:uri("defaultModel").predicate(UDFS.defaultModel).link("aiModel"),supportsBackend:string$2("supportsBackend").predicate(UDFS.supportsBackend),capabilities:string$2("capabilities").array().predicate(UDFS.capability),rotationPolicy:string$2("rotationPolicy").predicate(UDFS.rotationPolicy)},{base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql",type:UDFS.Provider,namespace:UDFS}),MODEL_STORAGE={base:"/settings/providers/",sparqlEndpoint:"/settings/providers/-/sparql"},aiModelSchema=solidSchema({id:id("id").default("{isProvidedBy.doc}#{key}"),rdfType:uri("rdfType").array().predicate(RDF$1.type).notNull().default([UDFS.AIModel]),displayName:string$2("displayName").predicate(UDFS.displayName),isProvidedBy:uri("isProvidedBy").predicate(UDFS.isProvidedBy).link(aiProviderResource),inputModalities:text("inputModalities").array().predicate(UDFS.inputModality),outputModalities:text("outputModalities").array().predicate(UDFS.outputModality),runtimeCapabilities:string$2("runtimeCapabilities").array().predicate(UDFS.capability),capabilities:uri("capabilities").array().predicate(UDFS.hasCapability),pricingInput:real("pricingInput").predicate(UDFS.pricingInput),pricingOutput:real("pricingOutput").predicate(UDFS.pricingOutput),status:string$2("status").predicate(UDFS.status).default("active"),createdAt:timestamp("createdAt").predicate(UDFS.createdAt).notNull().defaultNow(),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt).notNull().defaultNow()},{type:UDFS.AIModel,subClassOf:UDFS.Model,namespace:UDFS}),chatModelSchema=aiModelSchema.extend({contextLength:integer$1("contextLength").predicate(UDFS.contextLength),maxOutputTokens:integer$1("maxOutputTokens").predicate(UDFS.maxOutputTokens)},{type:UDFS.ChatModel,namespace:UDFS}),embeddingModelSchema=aiModelSchema.extend({dimension:integer$1("dimension").predicate(UDFS.dimension)},{type:UDFS.EmbeddingModel,namespace:UDFS}),documentUnderstandingModelSchema=aiModelSchema.extend({},{type:UDFS.DocumentUnderstandingModel,namespace:UDFS}),rerankingModelSchema=aiModelSchema.extend({},{type:UDFS.RerankingModel,namespace:UDFS}),imageGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.ImageGenerationModel,namespace:UDFS}),speechRecognitionModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechRecognitionModel,namespace:UDFS}),speechSynthesisModelSchema=aiModelSchema.extend({},{type:UDFS.SpeechSynthesisModel,namespace:UDFS}),videoGenerationModelSchema=aiModelSchema.extend({},{type:UDFS.VideoGenerationModel,namespace:UDFS}),aiModelResource=aiModelSchema.table("aiModel",MODEL_STORAGE);chatModelSchema.table("chatModel",MODEL_STORAGE);embeddingModelSchema.table("embeddingModel",MODEL_STORAGE);documentUnderstandingModelSchema.table("documentUnderstandingModel",MODEL_STORAGE);rerankingModelSchema.table("rerankingModel",MODEL_STORAGE);imageGenerationModelSchema.table("imageGenerationModel",MODEL_STORAGE);speechRecognitionModelSchema.table("speechRecognitionModel",MODEL_STORAGE);speechSynthesisModelSchema.table("speechSynthesisModel",MODEL_STORAGE);videoGenerationModelSchema.table("videoGenerationModel",MODEL_STORAGE);const AI_MODEL_MODALITIES=["text","image","audio","video","pdf"],AI_MODEL_CAPABILITIES=["chat","embedding","reranking","tool_call","reasoning","web","vision","ocr","document_understanding","structured_output","indexing","image_generation","speech_recognition","speech_synthesis","video_generation"],AI_MODEL_CAPABILITY={chat:UDFS.ChatCapability,embedding:UDFS.EmbeddingCapability,reranking:UDFS.RerankingCapability,tool_call:UDFS.ToolCallCapability,reasoning:UDFS.ReasoningCapability,web:UDFS.WebCapability,vision:UDFS.VisionCapability,ocr:UDFS.OCRCapability,document_understanding:UDFS.DocumentUnderstandingCapability,structured_output:UDFS.StructuredOutputCapability,indexing:UDFS.IndexingCapability,image_generation:UDFS.ImageGenerationCapability,speech_recognition:UDFS.SpeechRecognitionCapability,speech_synthesis:UDFS.SpeechSynthesisCapability,video_generation:UDFS.VideoGenerationCapability},AI_MODEL_CLASS={chat:UDFS.ChatModel,embedding:UDFS.EmbeddingModel,document_understanding:UDFS.DocumentUnderstandingModel,reranking:UDFS.RerankingModel,image_generation:UDFS.ImageGenerationModel,speech_recognition:UDFS.SpeechRecognitionModel,speech_synthesis:UDFS.SpeechSynthesisModel,video_generation:UDFS.VideoGenerationModel};new Set(AI_MODEL_MODALITIES);new Set(AI_MODEL_CAPABILITIES);new Set(Object.values(AI_MODEL_CAPABILITY));new Map(Object.entries(AI_MODEL_CAPABILITY).map(([n,e])=>[e,n]));new Map(Object.entries(AI_MODEL_CLASS).map(([n,e])=>[e,n]));podTable("aiConfig",{id:id("id").default("config.ttl#{key}"),chatModel:uri("chatModel").predicate(UDFS.chatModel).link(aiModelResource),ocrModel:uri("ocrModel").predicate(UDFS.ocrModel).link(aiModelResource),readerModel:uri("readerModel").predicate(UDFS.readerModel).link(aiModelResource),embeddingModel:uri("embeddingModel").predicate(UDFS.embeddingModel).link(aiModelResource),indexerModel:uri("indexerModel").predicate(UDFS.indexerModel).link(aiModelResource),rerankerModel:uri("rerankerModel").predicate(UDFS.rerankerModel).link(aiModelResource),ocrEnabled:boolean$2("ocrEnabled").predicate(UDFS.ocrEnabled).default(!0),automaticOcr:boolean$2("automaticOcr").predicate(UDFS.automaticOcr).default(!0),imageRecognition:boolean$2("imageRecognition").predicate(UDFS.imageRecognition).default(!0),pdfRecognition:boolean$2("pdfRecognition").predicate(UDFS.pdfRecognition).default(!0),tableRecognition:boolean$2("tableRecognition").predicate(UDFS.tableRecognition).default(!1),processingMode:string$2("processingMode").predicate(UDFS.processingMode).default("auto"),readerPolicy:string$2("readerPolicy").predicate(UDFS.readerPolicy).default("auto"),readerPriority:string$2("readerPriority").predicate(UDFS.readerPriority).default("structure-first"),maxFileSizeMb:integer$1("maxFileSizeMb").predicate(UDFS.maxFileSizeMb).default(64),maxPages:integer$1("maxPages").predicate(UDFS.maxPages).default(500),updatedAt:timestamp("updatedAt").predicate(UDFS.updatedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AIConfig,namespace:UDFS});podTable("vectorStore",{id:id("id").default("vector-stores.ttl#{key}"),name:string$2("name").predicate(UDFS.name),container:uri("container").predicate(UDFS.container),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),lastActiveAt:timestamp("lastActiveAt").predicate(UDFS.lastActiveAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.VectorStore,namespace:UDFS});podTable("indexedFile",{id:id("id").default("indexed-files.ttl#{key}"),fileUrl:uri("fileUrl").predicate(UDFS.fileUrl),vectorId:integer$1("vectorId").predicate(UDFS.vectorId),chunkingStrategy:string$2("chunkingStrategy").predicate(UDFS.chunkingStrategy),status:string$2("status").predicate(UDFS.status),usageBytes:integer$1("usageBytes").predicate(UDFS.usageBytes),lastError:string$2("lastError").predicate(UDFS.lastError),indexedAt:timestamp("indexedAt").predicate(UDFS.indexedAt)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.IndexedFile,namespace:UDFS});podTable("agentStatus",{id:id("id").default("agent-status.ttl#{key}"),agent:uri("agent").predicate(UDFS.agent).link(agentResource),status:string$2("status").predicate(UDFS.status),startedAt:timestamp("startedAt").predicate(UDFS.startedAt),lastActivityAt:timestamp("lastActivityAt").predicate(UDFS.lastActivityAt),currentTask:uri("currentTask").predicate(UDFS.task).link(taskResource),errorMessage:string$2("errorMessage").predicate(UDFS.errorMessage)},{base:"/settings/ai/",sparqlEndpoint:"/settings/ai/-/sparql",type:UDFS.AgentStatus,namespace:UDFS});const GatewayAccessKeyDeployment={local:"local",cloud:"cloud"},QuotaSnapshotStatus={available:"available",unsupported:"unsupported",error:"error"},gatewayAccessKeyResource=podTable("gatewayAccessKey",{id:id("id").default("ai/gateway/access-keys.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),secretHash:string$2("secretHash").predicate(UDFS.secretHash),name:string$2("name").predicate(UDFS.name),deployment:string$2("deployment").predicate(UDFS.deployment),scopes:text("scopes").array().predicate(UDFS.scopes),createdAt:timestamp("createdAt").predicate(UDFS.createdAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),lastUsedAt:timestamp("lastUsedAt").predicate(UDFS.lastUsedAt),disabledAt:timestamp("disabledAt").predicate(UDFS.disabledAt),revokedAt:timestamp("revokedAt").predicate(UDFS.revokedAt)},{base:"/.data/",type:UDFS.GatewayAccessKey,namespace:UDFS}),quotaSnapshotResource=podTable("quotaSnapshot",{id:id("id").default("ai/gateway/quota.ttl#{key}"),owner:uri("owner").predicate(UDFS.owner),deployment:string$2("deployment").predicate(UDFS.deployment),provider:string$2("provider").predicate(UDFS.provider),credential:uri("credential").predicate(UDFS.credential).link(credentialResource),status:string$2("status").predicate(UDFS.status),balance:integer$1("balance").predicate(UDFS.balance),windows:text("windows").predicate(UDFS.windows),observedAt:timestamp("observedAt").predicate(UDFS.observedAt),expiresAt:timestamp("expiresAt").predicate(UDFS.expiresAt),source:string$2("source").predicate(UDFS.source)},{base:"/.data/",type:UDFS.QuotaSnapshot,namespace:UDFS});ensureResourceIntrospectionColumns(gatewayAccessKeyResource);ensureResourceIntrospectionColumns(quotaSnapshotResource);function ensureResourceIntrospectionColumns(n){const e=n;e._&&e.columns&&e._.columns!==e.columns&&(e._.columns=e.columns);const t=e.columns;for(const i of Object.values(t??{}))typeof i.options?.predicate=="string"&&(i.getPredicate=()=>i.options?.predicate)}new Set(Object.values(GatewayAccessKeyDeployment));new Set(Object.values(QuotaSnapshotStatus));const AIConfigRuntimeCapability={chatCompletions:"chat_completions",responses:"responses",responsesWebSearch:"responses_web_search",imageInput:"image_input",imageGeneration:"image_generation",imageEditing:"image_editing",toolCalls:"tool_calls"};new Set(Object.values(AIConfigRuntimeCapability));const AI_CONFIG_PROVIDER_CATALOG=[{id:"dashscope",displayName:"DashScope",aliases:["qwen","alibaba","dashscope-cn"],defaultBaseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",defaultModels:["text-embedding-v4"],defaultModelType:"embedding"},{id:"openai",displayName:"OpenAI",aliases:["codex"],defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",displayName:"Anthropic",aliases:["claude"],defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",displayName:"Google",defaultBaseUrl:"https://generativelanguage.googleapis.com/v1beta"},{id:"deepseek",displayName:"DeepSeek",defaultBaseUrl:"https://api.deepseek.com/v1"},{id:"ollama",displayName:"Ollama",defaultBaseUrl:"http://localhost:11434/v1"},{id:"x-ai",displayName:"xAI",aliases:["xai"],defaultBaseUrl:"https://api.x.ai/v1"},{id:"openrouter",displayName:"OpenRouter",defaultBaseUrl:"https://openrouter.ai/api/v1"},{id:"minimax",displayName:"MiniMax",defaultBaseUrl:"https://api.minimax.chat/v1"},{id:"mistral",displayName:"Mistral",defaultBaseUrl:"https://api.mistral.ai/v1"},{id:"groq",displayName:"Groq",defaultBaseUrl:"https://api.groq.com/openai/v1"},{id:"moonshot",displayName:"Moonshot",defaultBaseUrl:"https://api.moonshot.cn/v1"},{id:"zhipu",displayName:"ZhiPu",defaultBaseUrl:"https://open.bigmodel.cn/api/paas/v4"},{id:"codebuddy",displayName:"CodeBuddy",defaultBaseUrl:"https://api.codebuddy.ai/v1"},{id:"paddleocr",displayName:"PaddleOCR",aliases:["paddle"],defaultBaseUrl:"https://paddleocr.aistudio-app.com/api/v2/ocr/jobs",defaultModels:["PP-OCRv6"],defaultModelType:"document_understanding"}];new Map(AI_CONFIG_PROVIDER_CATALOG.map(n=>[n.id,n]));const ABSOLUTE_IRI=/^[a-zA-Z][a-zA-Z\d+.-]*:/;function normalizeText(n){return n.trim().toLowerCase()}function normalizeAIConfigResourceId(n){if(!n)return"";const e=n.trim();if(!e)return"";if(e.includes("#"))return e.split("#").pop()||e;if(!ABSOLUTE_IRI.test(e)&&!e.endsWith(".ttl"))return e;const t=e.replace(/\/$/,""),i=t.split("/").pop()||t;return i.endsWith(".ttl")?i.slice(0,-4):i}function aiConfigResourceRefToModelId(n,e){return normalizeAIConfigModelId(n,e)}function normalizeAIConfigModelId(n,e){const t=normalizeAIConfigResourceId(n);if(!t.includes("/"))return t;const[i,...s]=t.split("/");return s.length===0||!e?t:normalizeAIConfigProviderId(i)===normalizeAIConfigProviderId(e)?s.join("/"):t}function normalizeAIConfigProviderId(n){const e=normalizeText(normalizeAIConfigResourceId(n));if(!e)return"";for(const t of AI_CONFIG_PROVIDER_CATALOG)if(t.id===e||(t.aliases??[]).includes(e))return t.id;return e}function normalizeAIConfigModelStorageId(n,e){return aiConfigResourceRefToModelId(n,e)}function buildAIConfigModelStorageId(n,e){return aiModelResource.buildId({id:e,isProvidedBy:aiConfigProviderRef(n)})}function aiConfigProviderRef(n){const e=normalizeAIConfigProviderId(n);return e&&`settings/providers/${aiProviderResource.buildId({id:e})}`}function aiConfigModelRef(n,e){if(e===void 0)return normalizeAIConfigResourceId(n);const t=normalizeAIConfigProviderId(n),i=normalizeAIConfigModelStorageId(e,t);return t&&i?`settings/providers/${buildAIConfigModelStorageId(t,i)}`:i}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."},disabledAt:{type:"timestamp",predicate:UDFS.disabledAt,description:"Temporary disable timestamp. Clear it to enable the key again."},revokedAt:{type:"timestamp",predicate:UDFS.revokedAt,description:"Revocation timestamp. Presence means the key is no longer valid."}},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,a)=>a.score-s.score||s.uri.localeCompare(a.uri)).slice(0,Math.max(1,t.limit??10))},predicates(t={}){return e(t).flatMap(i=>Object.entries(i.fields).filter(([s])=>!t.field||s===t.field).map(([s,a])=>({schemaUri:i.uri,field:s,predicate:a.predicate,type:a.type,required:!!a.required,secret:!!a.secret,array:!!a.array,description:a.description})))}}}function normalizeSearchTerms(n){return n.toLowerCase().split(/[\s,;:/#._-]+/u).map(e=>e.trim()).filter(Boolean)}function scoreDescriptorSearch(n,e){const t=new Set;let i=0;const s=(a,l,u)=>{if(!l)return;const f=l.toLowerCase();for(const d of e)f.includes(d)&&(t.add(a),i+=u)};s("uri",n.uri,10),s("class",n.class,10),s("namespace",n.namespace,4),s("resourceKind",n.resourceKind,8),s("description",n.description,4),s("storage",`${n.storage.base}${n.storage.resourceIdPattern}`,3);for(const[a,l]of Object.entries(n.fields))s(`field:${a}`,a,6),s(`predicate:${a}`,l.predicate,6),s(`description:${a}`,l.description,3);for(const a of n.examples){s("example",a.request,3);for(const[l,u]of Object.entries(a.match))s(`example:${l}`,String(u),3)}return i<=0?null:{uri:n.uri,resourceKind:n.resourceKind,class:n.class,namespace:n.namespace,source:n.source,trustLevel:n.trustLevel,description:n.description,score:i,matchedFields:[...t].sort()}}const CLOUD_PROVISIONING_UNAVAILABLE="Cloud storage is not ready. Please wait for Xpod to reconnect and try again.",localProvisionResolvers=new WeakMap;function isManagedLocalProvisionHost(){return typeof window<"u"&&localProvisionResolvers.has(window)}function unregisterLocalProvisionResolver(){typeof window<"u"&&localProvisionResolvers.delete(window)}function registerLocalProvisionResolver(n){typeof window<"u"&&localProvisionResolvers.set(window,n)}function readStoredProvisionCodeRaw(){try{const n=sessionStorage.getItem("provisionCode")?.trim();return n||void 0}catch{return}}function isProvisionCodeCurrent(n){const e=n.split(".")[0];if(!e)return!0;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return!0;const s=JSON.parse(globalThis.atob(i));return typeof s.exp=="number"?s.exp>Math.floor(Date.now()/1e3):!0}catch{return!0}}function normalizeProvisionCode(n){const e=n?.trim();if(e)return isProvisionCodeCurrent(e)?e:void 0}function getStoredProvisionCode(){return normalizeProvisionCode(readStoredProvisionCodeRaw())}function setStoredProvisionCode(n){try{sessionStorage.setItem("provisionCode",n)}catch{}}function clearStoredProvisionCode(){try{sessionStorage.removeItem("provisionCode")}catch{}}function buildPodCreatePayload(n,e=getStoredProvisionCode(),t){const i={name:n.trim()};return e&&(i.settings={provisionCode:e,...t?{provisionReceipt:t}:{}}),i}async function resolveProvisionCodeForCurrentScope(n){const e=await resolveCurrentProvisionTargetState(n);if(e.activeProvisionCode)return e.activeProvisionCode;if(e.hasProvisionOperation)throw new Error(CLOUD_PROVISIONING_UNAVAILABLE)}async function resolveCurrentProvisionTarget(n){const{hasProvisionOperation:e,...t}=await resolveCurrentProvisionTargetState(n);return t}async function resolveCurrentProvisionTargetState(n){const e=typeof window<"u"?window.__XPOD__:void 0;if(e?.authenticating===!0){const l=typeof e.provisionCode=="string"?e.provisionCode.trim():void 0,u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):(clearStoredProvisionCode(),l?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}:{hasProvisionOperation:!1})}const t=n?.trim()||(typeof e?.provisionCode=="string"?e.provisionCode.trim():void 0),i=typeof window<"u"?localProvisionResolvers.get(window):void 0;if(!t&&i){const l=await i(),u=normalizeProvisionCode(l);return u?(setStoredProvisionCode(u),{activeProvisionCode:u,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(u)?.storageRoot}):{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(l)?.storageRoot}}const s=t||readStoredProvisionCodeRaw(),a=normalizeProvisionCode(s);return a?{activeProvisionCode:a,hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(a)?.storageRoot}:s?{hasProvisionOperation:!0,storageRoot:resolveProvisionStorageTarget(s)?.storageRoot}:{hasProvisionOperation:!1}}async function resolveProvisionCodeForPodCreate(n){return resolveProvisionCodeForCurrentScope(n)}function decodeProvisionScopePayload(n){const e=parseProvisionScopePayload(n);if(!e)return;const t=typeof e.serviceAccessToken=="string"?e.serviceAccessToken:typeof e.serviceToken=="string"?e.serviceToken:void 0;if(!(typeof e.spUrl!="string"||!t)&&!(typeof e.exp=="number"&&e.exp<Math.floor(Date.now()/1e3))&&!(typeof e.serviceAccessTokenExp=="number"&&e.serviceAccessTokenExp<Math.floor(Date.now()/1e3)))return{spUrl:ensureTrailingSlash(e.spUrl),serviceToken:t,serviceAccessToken:typeof e.serviceAccessToken=="string"?e.serviceAccessToken:void 0,serviceAccessTokenExp:typeof e.serviceAccessTokenExp=="number"?e.serviceAccessTokenExp:void 0,spDomain:typeof e.spDomain=="string"?e.spDomain:void 0,exp:typeof e.exp=="number"?e.exp:void 0}}function parseProvisionScopePayload(n){if(!n)return;const e=n.split(".")[0];if(e)try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=t.padEnd(Math.ceil(t.length/4)*4,"=");if(typeof globalThis.atob!="function")return;const s=Uint8Array.from(globalThis.atob(i),a=>a.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch{return}}function resolveProvisionScope(n){const e=decodeProvisionScopePayload(n);if(!e)return;const t=e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl);return{lookupUrl:t,storageRoot:t,serviceToken:e.serviceToken}}function resolveProvisionStorageTarget(n){const e=parseProvisionScopePayload(n);if(typeof e?.spUrl=="string")return{storageRoot:e.spDomain?ensureTrailingSlash(`https://${e.spDomain}`):ensureTrailingSlash(e.spUrl)}}async function prepareProvisionedPod(n,e,t){const i=resolveProvisionScope(t);if(!i||!t)return t?{provisionCode:t}:void 0;const s=await n(new URL("/provision/pods",resolveProvisionApiBaseUrl(i)).toString(),{method:"POST",headers:{Authorization:`Bearer ${i.serviceToken}`,"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({podName:e})});if(!s.ok)throw new Error(await readResponseMessage$1(s)??"Failed to prepare Local Pod");const a=await s.json().catch(()=>{}),l=typeof a?.provisionReceipt=="string"?a.provisionReceipt:void 0;if(!l)throw new Error("Local Pod preparation did not return a provision receipt");return{provisionCode:t,provisionReceipt:l}}async function lookupProvisionScopedWebIds(n,e,t){const i=resolveProvisionScope(t);return i?(await queryProvisionScopedWebIds(n,e,i)).map(a=>({webId:a.webId,podUrl:typeof a.podUrl=="string"?ensureTrailingSlash(a.podUrl):void 0,storageUrl:ensureTrailingSlash(a.storageUrl)})):void 0}async function queryProvisionScopedWebIds(n,e,t){const i=Array.from(new Set(e.filter(f=>typeof f=="string"&&f.length>0)));if(i.length===0)return[];const s=resolveProvisionApiBaseUrl(t),a=await n(new URL("/provision/webids",s).toString(),{method:"POST",headers:{Authorization:`Bearer ${t.serviceToken}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({webIds:i})});if(!a.ok)throw new Error(`Local storage bindings request failed (${a.status})`);const l=await a.json().catch(()=>{});if(!Array.isArray(l?.entries)||l.entries.some(f=>!f||typeof f.webId!="string"||!f.webId||typeof f.storageUrl!="string"||!f.storageUrl))throw new Error("Local storage bindings response is malformed");const u=new Set(i);return l.entries.filter(f=>f&&typeof f.webId=="string"&&u.has(f.webId)).filter(f=>typeof f.storageUrl=="string"&&f.storageUrl.length>0).filter(f=>storageUrlBelongsToRoot(f.storageUrl,t.storageRoot))}function resolveProvisionApiBaseUrl(n){return(isManagedLocalProvisionHost()?currentLoopbackLookupUrl():void 0)??n.lookupUrl}function currentLoopbackLookupUrl(){if(!(typeof window>"u"))try{const n=new URL(window.location.href);return isLoopbackHostname$3(n.hostname)?ensureTrailingSlash(n.origin):void 0}catch{return}}function isLoopbackHostname$3(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}async function readResponseMessage$1(n){const e=await n.text?.().catch(()=>{});if(e)try{const t=JSON.parse(e);return typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:e}catch{return e}}async function filterWebIdsByStorageRoot(n,e,t){const i=normalizeStorageRoot(t);if(!i)return[];const s=Array.from(new Set(e.filter(l=>typeof l=="string"&&l.length>0)));return(await Promise.all(s.map(async l=>{const f=(await fetchProfileStorageUrls(n,l)).find(d=>storageUrlBelongsToRoot(d,i));return f?{webId:l,storageUrl:ensureTrailingSlash(f)}:void 0}))).filter(l=>!!l)}function storageUrlBelongsToRoot(n,e){const t=normalizeStorageUrl$2(n),i=normalizeStorageRoot(e);return!!(t&&i&&t.startsWith(i))}function normalizeStorageRoot(n){if(n)try{return ensureTrailingSlash(new URL(n).toString())}catch{return}}const SOLID_STORAGE_KEYS=new Set(["solid:storage","http://www.w3.org/ns/solid/terms#storage","pim:storage","http://www.w3.org/ns/pim/space#storage"]);async function fetchProfileStorageUrls(n,e){const t=await n(e,{headers:{Accept:"text/turtle, application/ld+json, application/json"},credentials:"include"}).catch(()=>{});if(!t?.ok)return[];const i=t.headers?.get?.("content-type")??"",s=await t.text().catch(()=>"");if(!s)return[];if(i.includes("json"))try{return uniqueNormalizedStorageUrls(extractStorageUrlsFromJson(JSON.parse(s)))}catch{return[]}return uniqueNormalizedStorageUrls(extractStorageUrlsFromTurtle(s))}function extractStorageUrlsFromTurtle(n){return Array.from(n.matchAll(/(?:solid:storage|pim:storage|<http:\/\/www\.w3\.org\/ns\/solid\/terms#storage>|<http:\/\/www\.w3\.org\/ns\/pim\/space#storage>)\s+<([^>]+)>/giu)).map(e=>e[1]).filter(e=>typeof e=="string"&&e.length>0)}function extractStorageUrlsFromJson(n){const e=new Set,t=new WeakSet,i=(s,a=!1)=>{if(typeof s=="string"){a&&e.add(s);return}if(!(!s||typeof s!="object")&&!t.has(s)){if(t.add(s),Array.isArray(s)){for(const l of s)i(l,a);return}for(const[l,u]of Object.entries(s)){const f=SOLID_STORAGE_KEYS.has(l);if(a&&l==="@id"){i(u,!0);continue}i(u,a||f)}}};return i(n),Array.from(e)}function normalizeStorageUrl$2(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$2(t);i&&e.add(i)}return Array.from(e)}function ensureTrailingSlash(n){return n.replace(/\/+$/u,"")+"/"}const XPOD_LAST_OIDC_ISSUER_STORAGE_KEY="xpod.solid.lastOidcIssuer",XPOD_SOLID_SESSION_ID_STORAGE_KEY="xpod.solid.sessionId",XPOD_INRUPT_STORAGE_KEY_PREFIX="xpod.inrupt.",XpodSolidRuntimeContext=reactExports.createContext(null);function snapshotToState(n,e,t){return n.status==="initializing"?{status:"loading",issuer:t}:n.status==="anonymous"?{status:"anonymous",issuer:t}:n.status==="expired"?{status:"expired",webId:n.webId,issuer:t}:n.status==="error"?{status:"error",webId:n.webId,error:n.error,podUrl:e?.podUrl,issuer:t}:{status:"authenticated",webId:n.webId,podUrl:e?.podUrl,issuer:t}}async function discoverPodUrlFromWebId({webId:n,fetch:e}){const t=await fetchProfileStorageUrls(e,n);if(t.length!==1)throw new Error(t.length===0?"WebID profile does not declare a Solid storage URL":"WebID profile declares multiple Solid storage URLs; choose an explicit storage");return ensureTrailingSlash(new URL(t.at(0)).toString())}function createXpodSolidRuntimeValue(n={}){const e=createXpodSolidRuntimeStoragePolicy(n.storage);let t=[];const i=createSolidLocalRouteFetch({fetch:globalThis.fetch,routes:()=>t}),s=n.sessionFactory?.({fetch:i})??createInruptSession(e.oidcSession,i);let a=readStoredOidcIssuer(e.issuer);const l=createSolidSessionRuntime({session:s}),u=createPodRuntime({adapter:{discoverPod:discoverPodUrlFromWebId,openDatabase:({podUrl:f,fetch:d})=>drizzle({get info(){return s.info},fetch:d},{podUrl:f,schema:{aiProvider:aiProviderResource,credential:credentialResource},resourcePreparation:"off"}),hydrateCollections:()=>{}}});return{session:l,pod:u,storage:e,getIssuer:()=>readIssuerFromSessionInfo(s.info)??a??readStoredOidcIssuer(e.issuer),getExpectedIssuer:()=>a??expectedSameOriginIssuer(readIssuerFromSessionInfo(s.info)),setIssuer:f=>{const d=normalizeXpodOidcIssuer(f);a=d,d&&writeStoredOidcIssuer(d,e.issuer)},setLocalPodRoute:f=>{t=f?[f,...["/api/","/v1/"].map(d=>({canonicalBaseUrl:new URL(d,f.canonicalBaseUrl).href,localBaseUrl:new URL(d,f.localBaseUrl).href}))]:[]}}}function createInruptSession(n=getOptionalPersistentStorage(),e=globalThis.fetch){return new Session({fetch:e,...n?{secureStorage:new InMemoryStorage,insecureStorage:toInruptStorage(n,"insecure")}:{}})}function toInruptStorage(n,e){const t=i=>inruptStorageKey(e,i);return{get:async i=>n.getItem(t(i))??void 0,set:async(i,s)=>{n.setItem(t(i),s)},delete:async i=>{n.removeItem(t(i))}}}function inruptStorageKey(n,e){return`${XPOD_INRUPT_STORAGE_KEY_PREFIX}${n}:${e}`}let defaultRuntime;function getXpodSolidRuntimeValue(){return defaultRuntime??=createXpodSolidRuntimeValue(),defaultRuntime}function withXpodProvisionScope(n,e){const t=new URL(n);return e?.trim()&&t.searchParams.set("provisionCode",e.trim()),t.toString()}async function resolveXpodLoginContext(n,e){const t=await e("/provision/status",{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{oidcIssuer:normalizeXpodOidcIssuer(n)};const i=t?.ok?await t.json().catch(()=>{}):void 0,s=normalizeXpodOidcIssuer(i?.oidcIssuer);if(i?.managed===!1)return{oidcIssuer:s??normalizeXpodOidcIssuer(n)};const a=typeof i?.provisionCode=="string"&&i.provisionCode.trim()?i.provisionCode.trim():void 0;if(!s||i?.managed===!0&&!a)throw new Error("暂时无法确认本机登录信息,请稍后重试。");return{oidcIssuer:s,provisionCode:a}}function safeAuthError(n){return n.message==="Solid session expired"?n:new Error("Solid login failed. Please reconnect your Pod.")}function normalizeXpodLoginTransaction(n,e=typeof window>"u"?"http://localhost":window.location.origin){if(!n||typeof n!="object")throw new TypeError("Xpod login requires a validated WebID transaction");const t=normalizeWebIdLoginTransaction(n),i=assertXpodLoginRoute(t.route,e),s=normalizeXpodReturnTo(t.returnTo);return{...t,route:i,authorizationSurface:"redirect",discovery:"strict",...s===void 0?{}:{returnTo:s}}}function useXpodSolidRuntimeContext(){const n=reactExports.useContext(XpodSolidRuntimeContext);if(!n)throw new Error("useXpodSolidRuntime must be used within XpodSolidRuntimeProvider");return n}function readIssuerFromSessionInfo(n){const e=n.issuer??n.oidcIssuer;return normalizeXpodOidcIssuer(e)}function normalizeXpodOidcIssuer(n){if(!(typeof n!="string"||!n.trim()))try{const e=new URL(n.trim());return e.protocol!=="https:"&&e.protocol!=="http:"||e.username||e.password||e.search||e.hash?void 0:e.toString()}catch{return}}function isCurrentXpodSessionSnapshot(n,e,t){if(n.status!=="authenticated")return!0;const i=normalizeXpodOidcIssuer(e),s=normalizeXpodOidcIssuer(t);return!i||!s||i!==s?!1:isHttpResourceUrl(n.webId)}function expectedSameOriginIssuer(n,e=typeof window>"u"?"http://localhost":window.location.origin){const t=normalizeXpodOidcIssuer(n);return t&&hasOrigin(t,e)?t:void 0}function hasOrigin(n,e){try{return new URL(n).origin===new URL(e).origin}catch{return!1}}function isHttpResourceUrl(n){try{const e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!e.username&&!e.password}catch{return!1}}function readStoredOidcIssuer(n=getOptionalPersistentStorage()){try{return normalizeXpodOidcIssuer(n?.getItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY))}catch{return}}function clearStoredXpodOidcIssuer(n){try{n?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalPersistentStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY),getOptionalSessionStorage()?.removeItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY)}catch{}}function writeStoredOidcIssuer(n,e=getOptionalPersistentStorage()){try{e?.setItem(XPOD_LAST_OIDC_ISSUER_STORAGE_KEY,n)}catch{}}function createXpodSolidRuntimeStoragePolicy(n={}){const e=getOptionalPersistentStorage();return{oidcSession:n.oidcSession??e,issuer:n.issuer??e,selectedStorage:n.selectedStorage??e}}function getOptionalPersistentStorage(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function getOptionalSessionStorage(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}async function currentHostLocalPodRoute(n,e){if(typeof window>"u")return;const t=desktopLocalPodRoute(n);if(t)return t;if(storageUrlUsesCurrentOrigin(n))return;const i=await fetchCurrentProvisionRouteStatus(e);return currentProvisionLocalPodRoute(n,i)}function currentProvisionLocalPodRoute(n,e){if(!(typeof window>"u")&&!(e.managed!==!0||typeof e.storageRoot!="string")&&managedPublicRouteCoversStorage(n,e.storageRoot))return podScopedLocalRoute(n)}function currentProvisionLocalOriginRoute(n){if(!(typeof window>"u")&&!(n.managed!==!0||typeof n.storageRoot!="string")&&isLoopbackHostname$2(window.location.hostname))try{const e=new URL(n.storageRoot);return!["http:","https:"].includes(e.protocol)||e.username||e.password||e.origin===window.location.origin?void 0:{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:new URL(e.pathname,window.location.origin).href}}catch{return}}function isLoopbackHostname$2(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}function desktopLocalPodRoute(n){if(!(typeof window>"u"||!window.xpodDesktop))return podScopedLocalRoute(n)}async function fetchCurrentProvisionRouteStatus(n){let e;try{e=await n(new URL("/provision/status",window.location.origin).href,{credentials:"include",headers:{accept:"application/json"}})}catch{return{}}if(!e.ok||!e.headers.get("content-type")?.includes("application/json"))return await e.arrayBuffer().catch(()=>{}),{};const t=await e.json().catch(()=>{});return{managed:t?.managed===!0,storageRoot:typeof t?.publicUrl=="string"?t.publicUrl:void 0}}function podScopedLocalRoute(n){try{const e=new URL(n),t=new URL(e.pathname,window.location.origin);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:(e.search="",e.hash="",t.search="",t.hash="",{canonicalBaseUrl:e.href.endsWith("/")?e.href:`${e.href}/`,localBaseUrl:t.href.endsWith("/")?t.href:`${t.href}/`})}catch{return}}function managedPublicRouteCoversStorage(n,e){try{const t=new URL(e),i=new URL(t.pathname,window.location.origin);return resolveSolidLocalRouteUrl(n,[{canonicalBaseUrl:t.href,localBaseUrl:i.href}])!==void 0}catch{return!1}}function storageUrlUsesCurrentOrigin(n){try{return new URL(n).origin===window.location.origin}catch{return!1}}const CALLBACK_IDENTITY_PREFIX="xpod.auth.callback.identity.v1.",RETRYABLE_STORAGE_FAILURE_CODES=new Set(["provision-status-unavailable","profile-read-failed","pod-open-failed"]),CALLBACK_COMPLETION_PREFIX="xpod.auth.callback.completed.v1.",CALLBACK_COMPLETION_TTL_MS=600*1e3,INRUPT_CURRENT_URL_KEY="solidClientAuthn:currentUrl",callbackRuns=new Map,AUTO_RESET_FAILURE_CODES=new Set(["webid-mismatch","binding-mismatch"]),FAILURE_MESSAGES={"missing-transaction":{title:"登录请求已失效",message:"这次登录请求已经失效,请重新登录。",action:"重新登录"},"replayed-transaction":{title:"登录请求已使用",message:"这次登录请求已经完成,不能再次使用。请重新登录。",action:"重新登录"},"expired-transaction":{title:"登录请求已过期",message:"登录等待时间过长,请重新登录。",action:"重新登录"},"malformed-transaction":{title:"登录请求无效",message:"登录信息不完整或已被修改,请重新登录。",action:"重新登录"},"oidc-state-invalid":{title:"登录验证已失效",message:"登录页面与当前会话不再匹配,请重新登录。",action:"重新登录"},"oidc-provider-error":{title:"授权未完成",message:"身份服务未能完成此次授权,请重新登录。",action:"重新登录"},unauthenticated:{title:"登录没有完成",message:"Xpod 没有收到有效的 WebID,请重新登录。",action:"重新登录"},"unsafe-route":{title:"登录请求不安全",message:"Xpod 已阻止异常的登录来源,请从应用内重新登录。",action:"重新登录"},"unsafe-return-to":{title:"登录请求不安全",message:"Xpod 已阻止异常的返回地址,请从应用内重新登录。",action:"重新登录"},"missing-storage":{title:"没有可用的 Pod",message:"当前账号还没有可用于本次登录的 Pod,请返回后重试。",action:"返回并重试"},"provision-status-unavailable":{title:"暂时无法确认本机 Pod",message:"Xpod 暂时无法读取存储服务状态,请稍后重试。",action:"重试连接"},"local-binding-missing":{title:"本机绑定尚未完成",message:"当前账号还没有绑定到这台 Xpod。请先修复本机初始化,再重新登录。",action:"修复本机绑定"},"webid-mismatch":{title:"身份与 Pod 不匹配",message:"本次登录身份与所选 Pod 不一致,请重新登录。",action:"重新登录"},"binding-mismatch":{title:"身份与 Pod 不匹配",message:"Xpod 无法确认当前身份拥有所选 Pod,请重新登录。",action:"重新登录"},"profile-read-failed":{title:"暂时无法读取身份资料",message:"未能读取你的 WebID 资料,暂时无法确认 Pod 地址。请稍后重试,不需要重新创建 Pod。",action:"重试连接"},"pod-open-failed":{title:"暂时无法打开 Pod",message:"Xpod 无法连接到你的 Pod,请检查服务状态后重试。",action:"重试连接"},"storage-unavailable":{title:"无法保存登录状态",message:"当前环境无法保存本次登录状态,请重新打开 Xpod 后重试。",action:"重新登录"},"redirect-failed":{title:"登录已完成",message:"身份验证已经完成,但目标页面没有正常打开。",action:"返回概览"}};async function completeXpodOidcCallback(n){const e=new URL(n.href),t=e.origin,i=captureRecoveryPointers(),s=findCompletedCallbackDestination(e,n.storage,n.now);if(s)return n.locationReplace?.(s),{status:"redirected",destination:s};let a=e.searchParams.get("transaction");const l=e.searchParams.has("code")||e.searchParams.has("state")||e.searchParams.has("error"),u=l?readInruptCurrentDestination(e):void 0;let f,d,p;try{f=n.transactionStore??createXpodLoginTransactionStore({storage:n.storage,origin:t});const M=f.readSinglePending();!a&&M&&(a=M.id),a?!M||M.id!==a?(f.consume(a),p=failure("missing-transaction")):d=M:p=failure("missing-transaction")}catch(M){p=failure(transactionFailureCode(M))}const g=a?readCompletedDestination(e,a,n.storage,n.now):void 0;if(g){if(l&&u&&!d){const M=await handleIncomingRedirect(n.runtime,n.href);if(M.status==="failure"){const O=await recoverFailedOidcCallback({callbackUrl:e,destination:u,recoveryPointers:i,storage:n.storage,locationReplace:n.locationReplace});return O||M}return n.locationReplace?.(u),{status:"redirected",destination:u}}return n.locationReplace?.(g),{status:"redirected",destination:g}}if(!d){if(u){const M=await handleIncomingRedirect(n.runtime,n.href);if(M.status==="failure"){const O=await recoverFailedOidcCallback({callbackUrl:e,destination:u,recoveryPointers:i,storage:n.storage,locationReplace:n.locationReplace});return O||M}return n.locationReplace?.(u),{status:"redirected",destination:u}}return p??failure("missing-transaction")}if(!f||!a)return failure("missing-transaction");const m=await resumeOrCompleteIdentity(n,d);if(m.status==="failure"){const M=await recoverFailedOidcCallback({callbackUrl:e,destination:productDestinationForTransaction(d,t),recoveryPointers:i,transactionStore:f,transactionId:a,storage:n.storage,locationReplace:n.locationReplace});return M||m}const v=m.webId;try{assertXpodLoginRoute(d.route,t)}catch{return failure("unsafe-route")}let S;try{S=normalizeXpodReturnTo(d.returnTo)}catch{return failure("unsafe-return-to")}const E=d.selectedStorage&&new URL(d.selectedStorage.storageUrl).origin===t?{storageRoot:t,available:!0}:await resolveCurrentXpodProvisionStatus(n.fetch??fetch,t);if(!E.available)return failure("provision-status-unavailable");const w=E.storageRoot,A=currentProvisionLocalOriginRoute(E);A&&n.runtime.setLocalPodRoute(A);let C;try{C=d.selectedStorage??await discoverCurrentXpodStorage(n.runtime.session.fetch,v,w)}catch{return failure("profile-read-failed")}if(C&&!isSafeSelectedStorage(C,t,w))return failure("binding-mismatch");if(C&&C.webId!==v)return failure("webid-mismatch");if(!C)return E.managed?failure("local-binding-missing",E.provisionUrl):failure("missing-storage");let T;try{n.runtime.setLocalPodRoute(currentProvisionLocalPodRoute(C.storageUrl,E)),T=await n.runtime.pod.open({webId:v,podUrl:C.storageUrl,fetch:n.runtime.session.fetch})}catch{return{...failure("pod-open-failed")}}const F=C;if(!isSafeSelectedStorage(F,t,w)||T.webId!==F.webId||!sameUrl$3(T.podUrl,F.storageUrl))return failure("binding-mismatch");try{rememberXpodSelectedStorage(F,{storage:n.storage,origin:t,storageRoot:w,now:n.now})}catch{return failure("storage-unavailable")}const P=new URL(S??XPOD_DEFAULT_RETURN_PATH,t).href;try{f.consume(a),rememberCompletedDestination(a,P,e,n.storage,n.now),(n.storage??window.sessionStorage).removeItem(`${CALLBACK_IDENTITY_PREFIX}${a}`),n.locationReplace?.(P)}catch{return clearXpodSelectedStorage({storage:n.storage}),failure("redirect-failed")}return{status:"redirected",destination:P,transaction:d,selectedStorage:F,pod:T}}async function resumeOrCompleteIdentity(n,e){const t=new URL(n.href),i=n.storage??window.sessionStorage,s=`${CALLBACK_IDENTITY_PREFIX}${e.id}`,a=callbackIdentity(t),l=n.now??Date.now;try{const f=i.getItem(s);if(f){const d=JSON.parse(f);if(!isRecord$4(d)||d.callback!==a||typeof d.webId!="string"||typeof d.completedAt!="number"||!Number.isFinite(d.completedAt))return failure("oidc-state-invalid");if(l()<d.completedAt||l()-d.completedAt>CALLBACK_COMPLETION_TTL_MS)return failure("expired-transaction");const p=n.runtime.session.getSnapshot();return p.status!=="authenticated"?failure("unauthenticated"):p.webId!==d.webId?failure("webid-mismatch"):{status:"success",webId:p.webId}}}catch{return failure("storage-unavailable")}const u=await handleIncomingRedirect(n.runtime,n.href);if(u.status==="failure")return u;try{i.setItem(s,JSON.stringify({callback:a,webId:u.webId,completedAt:l()}))}catch{return failure("storage-unavailable")}return u}function completeXpodOidcCallbackOnce(n){const e=new URL(n.href);if(findCompletedCallbackDestination(e,n.storage,n.now))return completeXpodOidcCallback(n);const t=callbackRunKey(e,n.transactionStore),i=callbackRuns.get(t);if(i)return i;const s=completeXpodOidcCallback(n);return callbackRuns.set(t,s),s}function callbackRunKey(n,e){let t=n.searchParams.get("transaction");if(!t)try{t=e?.readSinglePending()?.id??createXpodLoginTransactionStore({origin:n.origin}).readSinglePending()?.id??(readInruptCurrentDestination(n)?"<silent>":"<missing>")}catch{t=readInruptCurrentDestination(n)?"<silent>":"<missing>"}return`${n.origin}:${t}`}function callbackIdentity(n){return`${n.origin}${n.pathname}?state=${encodeURIComponent(n.searchParams.get("state")??"")}`}function findCompletedCallbackDestination(n,e,t){if(n.searchParams.get("state"))try{const i=e??window.sessionStorage,s=n.searchParams.get("transaction");for(let a=0;a<i.length;a+=1){const l=i.key(a);if(!l?.startsWith(CALLBACK_COMPLETION_PREFIX))continue;const u=l.slice(CALLBACK_COMPLETION_PREFIX.length);if(s&&s!==u)continue;const f=i.getItem(l);if(!f)continue;const d=JSON.parse(f);if(isRecord$4(d)&&d.callback===callbackIdentity(n))return readCompletedDestination(n,u,i,t)}}catch{}}function readCompletedDestination(n,e,t,i=()=>Date.now()){try{const s=t??window.sessionStorage,a=`${CALLBACK_COMPLETION_PREFIX}${e}`,l=s.getItem(a);if(!l)return;const u=JSON.parse(l);if(u.callback!==void 0&&u.callback!==callbackIdentity(n)||typeof u.destination!="string"||typeof u.completedAt!="number"||!Number.isFinite(u.completedAt))return;if(i()<u.completedAt||i()-u.completedAt>CALLBACK_COMPLETION_TTL_MS){s.removeItem(a);return}const f=new URL(u.destination);if(f.origin!==n.origin||f.username||f.password)return;const d=normalizeXpodReturnTo(`${f.pathname}${f.search}${f.hash}`);return d?new URL(d,n.origin).href:void 0}catch{return}}function readInruptCurrentDestination(n){try{const e=window.localStorage.getItem(INRUPT_CURRENT_URL_KEY);if(!e)return;const t=new URL(e,n.origin);if(t.origin!==n.origin)return;const i=`${t.pathname}${t.search}`,s=normalizeXpodReturnTo(i);return s===void 0?void 0:new URL(s,n.origin).href}catch{return}}function rememberCompletedDestination(n,e,t,i,s=()=>Date.now()){(i??window.sessionStorage).setItem(`${CALLBACK_COMPLETION_PREFIX}${n}`,JSON.stringify({destination:e,callback:callbackIdentity(t),completedAt:s()}))}function XpodOidcCallbackApp({runtime:n,transactionStore:e,href:t=typeof window>"u"?"http://localhost/auth/callback":window.location.href,location:i=typeof window>"u"?void 0:window.location,restartSignIn:s,renderRedirected:a}){const[l]=reactExports.useState(()=>n?void 0:createCallbackRuntime()),u=n??l,[f,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),m=reactExports.useRef(void 0),v=reactExports.useRef(!1),[S]=reactExports.useState(()=>{const A=new URL(t);return readRestartTransaction(A,e)?.id??A.searchParams.get("transaction")}),E=reactExports.useMemo(()=>resolveXpodCallbackRestartDestination({href:t,transactionStore:e}),[t,e]);if(reactExports.useEffect(()=>{m.current||(m.current=completeXpodOidcCallbackOnce({href:t,runtime:u,transactionStore:e,locationReplace:i?.replace.bind(i)}),m.current.then(d))},[u,t,i,e]),reactExports.useEffect(()=>{typeof document>"u"||f?.status==="redirected"&&a||(document.title=f?.status==="failure"?`Xpod - ${FAILURE_MESSAGES[f.code].title}`:f?.status==="redirected"?"Xpod - 登录完成":"Xpod - 正在登录")},[a,f]),reactExports.useEffect(()=>{!f||f.status!=="failure"||AUTO_RESET_FAILURE_CODES.has(f.code)&&(v.current||(v.current=!0,queueMicrotask(()=>{g(!0),resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S}).finally(()=>{(s??(C=>window.location.replace(C)))(E)})})))},[u,S,t,E,s,f,e]),!f)return jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"正在完成登录",message:"请稍候,不要关闭这个窗口。"});if(f.status==="redirected")return a?.(f)??jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"登录完成",message:"正在打开 Xpod。"});if(AUTO_RESET_FAILURE_CODES.has(f.code))return jsxRuntimeExports.jsx(XpodCallbackStatus,{title:"正在重新登录",message:"Xpod 正在清理不匹配的登录状态。"});const w=FAILURE_MESSAGES[f.code];return jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"modal",title:w.title,lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}),closeOnEscape:!1,children:jsxRuntimeExports.jsxs("div",{className:"flex min-h-0 flex-1 flex-col px-5 pb-5",children:[jsxRuntimeExports.jsx("div",{className:"flex min-h-0 flex-1 flex-col justify-center py-5",children:jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 text-destructive"}),jsxRuntimeExports.jsx("h2",{className:"text-[15px] font-semibold leading-6 text-foreground",children:w.title})]}),jsxRuntimeExports.jsx("p",{role:"alert",className:"mt-2 text-xs leading-5 text-muted-foreground",children:w.message}),jsxRuntimeExports.jsxs("details",{className:"group mt-3 text-[11px] leading-4 text-muted-foreground",children:[jsxRuntimeExports.jsxs("summary",{className:"-ml-1 inline-flex min-h-8 cursor-pointer list-none items-center gap-1 rounded-md px-1 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":"true",className:"h-3 w-3 shrink-0 group-open:rotate-90"}),"技术详情"]}),jsxRuntimeExports.jsxs("div",{className:"mt-1 max-h-24 overflow-y-auto overscroll-contain",children:[jsxRuntimeExports.jsx("code",{className:"block break-all text-left",children:f.code}),!1]})]})]})}),jsxRuntimeExports.jsx(Button,{type:"button",className:"w-full shrink-0 rounded-xl",disabled:p,"aria-busy":p,onClick:()=>{if(!p){if(RETRYABLE_STORAGE_FAILURE_CODES.has(f.code)){callbackRuns.delete(callbackRunKey(new URL(t),e)),d(void 0),m.current=completeXpodOidcCallbackOnce({href:t,runtime:u,transactionStore:e,locationReplace:i?.replace.bind(i)}),m.current.then(d);return}g(!0),(f.code==="redirect-failed"?Promise.resolve():resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S})).finally(()=>{if(f.actionUrl){(s??(T=>window.location.replace(T)))(f.actionUrl);return}(s??(C=>window.location.replace(C)))(E)})}},children:p?"正在重置…":w.action}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",disabled:p,onClick:()=>{p||(g(!0),setXpodLoginCancelled(!0),resetXpodOidcCallback({href:t,runtime:u,transactionStore:e,associatedTransactionId:S,preserveSession:!0}).finally(()=>{(s??(C=>window.location.replace(C)))(E)}))},children:"返回应用"})]})})}function resolveXpodCallbackRestartDestination({href:n,transactionStore:e,basePath:t="/auth/callback/"}){const i=new URL(n),a=readRestartTransaction(i,e)?.returnTo;if(a)try{const u=normalizeXpodReturnTo(a);if(u)return u}catch{}const l=readInruptCurrentDestination(i);if(l)try{const u=new URL(l);if(u.origin===i.origin)return`${u.pathname}${u.search}${u.hash}`}catch{}return callbackProductEntryPath(t,i.pathname)}function readRestartTransaction(n,e){try{const t=e?e.readSinglePending():createXpodLoginTransactionStore({origin:n.origin}).readSinglePending(),i=n.searchParams.get("transaction");return i&&t?.id!==i?void 0:t}catch{return}}function callbackProductEntryPath(n,e){return normalizeBasePath(n)==="/settings/"||e==="/settings/auth-callback.html"||e.startsWith("/settings/")?"/settings/":XPOD_DEFAULT_RETURN_PATH}function normalizeBasePath(n){if(n)try{const e=new URL(n,"https://xpod.local");return e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`}catch{return}}function XpodCallbackStatus({title:n,message:e}){return jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"modal",title:n,lead:jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0}),closeOnEscape:!1,children:jsxRuntimeExports.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-[15px] font-semibold text-foreground",children:n}),jsxRuntimeExports.jsx("p",{role:"status","aria-live":"polite",className:"mt-2 max-w-[13rem] text-xs leading-5 text-muted-foreground",children:e})]})})}async function resetXpodOidcCallback({href:n,runtime:e,transactionStore:t,storage:i,preserveSession:s=!1,associatedTransactionId:a}){const l=new URL(n);let u=a===void 0?l.searchParams.get("transaction"):a;try{const f=t??createXpodLoginTransactionStore({storage:i,origin:l.origin}),d=f.readSinglePending();a===void 0&&!u&&d&&(u=d.id),d&&d.id===u&&f.cancel(d.id)}catch{}try{const f=i??window.sessionStorage;u&&(f.removeItem(`${CALLBACK_COMPLETION_PREFIX}${u}`),f.removeItem(`${CALLBACK_IDENTITY_PREFIX}${u}`)),window.localStorage.removeItem(INRUPT_CURRENT_URL_KEY)}catch{}try{s||await e.session.logout()}catch{}callbackRuns.delete(`${l.origin}:${u??"<missing>"}`),callbackRuns.delete(`${l.origin}:<silent>`),callbackRuns.delete(`${l.origin}:<missing>`)}async function handleIncomingRedirect(n,e){let t="oidc-state-invalid";try{if(new URL(e).searchParams.has("error")&&(t="oidc-provider-error"),!n.session.handleIncomingRedirect)return failure("oidc-state-invalid");const i=await n.session.handleIncomingRedirect(e);if(t==="oidc-provider-error")return failure(t);const s=isRecord$4(i)?i:void 0;if(s?.status==="error"||s?.status==="expired")return failure("oidc-state-invalid");const a=s?.status==="authenticated"||s?.isLoggedIn===!0?readString(s.webId):void 0,l=n.session.getSnapshot();if(l.status==="error"||l.status==="expired")return failure("oidc-state-invalid");const u=a??(l.status==="authenticated"?l.webId:void 0);return u?{status:"success",webId:u}:failure("unauthenticated")}catch{return failure(t)}}function isRecord$4(n){return typeof n=="object"&&n!==null}async function recoverFailedOidcCallback({callbackUrl:n,destination:e,recoveryPointers:t,transactionStore:i,transactionId:s,storage:a,locationReplace:l}){const u=n.searchParams.get("error");if(isRecoverableSilentRestoreError(u)){clearRecoverableCallbackState({transactionStore:i,transactionId:s,storage:a});for(const{storage:f,key:d,value:p}of t)try{f.getItem(d)===p&&f.removeItem(d)}catch{}return l?.(e),{status:"redirected",destination:e}}}function isRecoverableSilentRestoreError(n){return n==="login_required"||n==="interaction_required"||n==="consent_required"||n==="account_selection_required"}function clearRecoverableCallbackState({transactionStore:n,transactionId:e,storage:t}){try{const i=n?.readSinglePending(),s=e;s&&i?.id===s&&n?.cancel(s),s&&i?.id===s&&((t??window.sessionStorage).removeItem(`${CALLBACK_COMPLETION_PREFIX}${s}`),(t??window.sessionStorage).removeItem(`${CALLBACK_IDENTITY_PREFIX}${s}`))}catch{}clearXpodSelectedStorage({storage:t})}function captureRecoveryPointers(){const n=[];for(const e of["localStorage","sessionStorage"])try{const t=window[e];for(const i of[INRUPT_CURRENT_URL_KEY,"solidClientAuthn:currentSession",XPOD_SOLID_SESSION_ID_STORAGE_KEY,XPOD_LAST_OIDC_ISSUER_STORAGE_KEY]){const s=t.getItem(i);s!==null&&n.push({storage:t,key:i,value:s})}}catch{}return n}function productDestinationForTransaction(n,e){try{const t=normalizeXpodReturnTo(n.returnTo);return new URL(t??XPOD_DEFAULT_RETURN_PATH,e).href}catch{return new URL(XPOD_DEFAULT_RETURN_PATH,e).href}}function readString(n){return typeof n=="string"&&n?n:void 0}function isSafeSelectedStorage(n,e,t){try{const i=new URL(n.storageUrl),s=new URL(n.webId);return(i.origin===e||storageUrlBelongsToRoot(i.href,t))&&["http:","https:"].includes(i.protocol)&&["http:","https:"].includes(s.protocol)&&!i.username&&!i.password&&!i.hash&&!s.username&&!s.password}catch{return!1}}async function resolveCurrentXpodProvisionStatus(n,e){const t=await n(new URL("/provision/status",e),{headers:{Accept:"application/json"},credentials:"include"}).catch(()=>{});if(t?.status===404)return{storageRoot:e,available:!0};if(!t?.ok)return{storageRoot:e,available:!1};const i=await t.json().catch(()=>{});return!i||typeof i.managed!="boolean"&&typeof i.publicUrl!="string"?{storageRoot:e,available:!1}:{available:!0,storageRoot:typeof i?.publicUrl=="string"&&i.publicUrl?i.publicUrl:e,managed:i?.managed===!0,provisionUrl:safeProvisionUrl(i?.provisionUrl)}}function safeProvisionUrl(n){if(!(typeof n!="string"||!n))try{const e=new URL(n);return e.protocol==="https:"&&!e.username&&!e.password?e.href:void 0}catch{return}}async function discoverCurrentXpodStorage(n,e,t){let i=!1;const a=await filterWebIdsByStorageRoot(async(l,u)=>{const f=await n(l,u).catch(d=>{throw String(l)===e&&(i=!0),d});return String(l)===e&&!f.ok&&(i=!0),f},[e],t);if(i)throw new Error("Unable to read WebID profile storage bindings");if(a.length===1)return a[0]}function transactionFailureCode(n){switch(n?.code){case"consumed":return"replayed-transaction";case"expired":return"expired-transaction";case"malformed":return"malformed-transaction";default:return"missing-transaction"}}function failure(n,e){return{status:"failure",code:n,message:FAILURE_MESSAGES[n].message,...e?{actionUrl:e}:{}}}function sameUrl$3(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function createCallbackRuntime(){return createXpodSolidRuntimeValue()}var ABSOLUTE_URL_REGEX=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,PROTOCOL_RELATIVE_URL_REGEX=/^[\\/]{2}/;function normalizeProtocolRelativeUrl(n,e){return e+n.replace(/\\/g,"/")}var PopStateEventType="popstate";function isLocation(n){return typeof n=="object"&&n!=null&&"pathname"in n&&"search"in n&&"hash"in n&&"state"in n&&"key"in n}function createBrowserHistory(n={}){function e(i,s){let a=s.state?.masked,{pathname:l,search:u,hash:f}=a||i.location;return createLocation("",{pathname:l,search:u,hash:f},s.state&&s.state.usr||null,s.state&&s.state.key||"default",a?{pathname:i.location.pathname,search:i.location.search,hash:i.location.hash}:void 0)}function t(i,s){return typeof s=="string"?s:createPath(s)}return getUrlBasedHistory(e,t,null,n)}function invariant(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function warning(n,e){if(!n){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function createKey(){return Math.random().toString(36).substring(2,10)}function getHistoryState(n,e){return{usr:n.state,key:n.key,idx:e,masked:n.mask?{pathname:n.pathname,search:n.search,hash:n.hash}:void 0}}function createLocation(n,e,t=null,i,s){return{pathname:typeof n=="string"?n:n.pathname,search:"",hash:"",...typeof e=="string"?parsePath(e):e,state:t,key:e&&e.key||i||createKey(),mask:s}}function createPath({pathname:n="/",search:e="",hash:t=""}){return e&&e!=="?"&&(n+=e.charAt(0)==="?"?e:"?"+e),t&&t!=="#"&&(n+=t.charAt(0)==="#"?t:"#"+t),n}function parsePath(n){let e={};if(n){let t=n.indexOf("#");t>=0&&(e.hash=n.substring(t),n=n.substring(0,t));let i=n.indexOf("?");i>=0&&(e.search=n.substring(i),n=n.substring(0,i)),n&&(e.pathname=n)}return e}function getUrlBasedHistory(n,e,t,i={}){let{window:s=document.defaultView,v5Compat:a=!1}=i,l=s.history,u="POP",f=null,d=p();d==null&&(d=0,l.replaceState({...l.state,idx:d},""));function p(){return(l.state||{idx:null}).idx}function g(){u="POP";let w=p(),A=w==null?null:w-d;d=w,f&&f({action:u,location:E.location,delta:A})}function m(w,A){u="PUSH";let C=isLocation(w)?w:createLocation(E.location,w,A);d=p()+1;let T=getHistoryState(C,d),F=E.createHref(C.mask||C);try{l.pushState(T,"",F)}catch(P){if(P instanceof DOMException&&P.name==="DataCloneError")throw P;s.location.assign(F)}a&&f&&f({action:u,location:E.location,delta:1})}function v(w,A){u="REPLACE";let C=isLocation(w)?w:createLocation(E.location,w,A);d=p();let T=getHistoryState(C,d),F=E.createHref(C.mask||C);l.replaceState(T,"",F),a&&f&&f({action:u,location:E.location,delta:0})}function S(w){return createBrowserURLImpl(s,w)}let E={get action(){return u},get location(){return n(s,l)},listen(w){if(f)throw new Error("A history only accepts one active listener");return s.addEventListener(PopStateEventType,g),f=w,()=>{s.removeEventListener(PopStateEventType,g),f=null}},createHref(w){return e(s,w)},createURL:S,encodeLocation(w){let A=S(w);return{pathname:A.pathname,search:A.search,hash:A.hash}},push:m,replace:v,go(w){return l.go(w)}};return E}function createBrowserURLImpl(n,e,t=!1){let i="http://localhost";n&&(i=n.location.origin!=="null"?n.location.origin:n.location.href),invariant(i,"No window.location.(origin|href) available to create URL");let s=typeof e=="string"?e:createPath(e);return s=s.replace(/ $/,"%20"),!t&&PROTOCOL_RELATIVE_URL_REGEX.test(s)&&(s=i+s),new URL(s,i)}function matchRoutes(n,e,t="/"){return matchRoutesImpl(n,e,t,!1)}function matchRoutesImpl(n,e,t,i,s){let a=typeof e=="string"?parsePath(e):e,l=stripBasename(a.pathname||"/",t);if(l==null)return null;let u=flattenAndRankRoutes(n),f=null,d=decodePath(l);for(let p=0;f==null&&p<u.length;++p)f=matchRouteBranch(u[p],d,i);return f}function flattenAndRankRoutes(n){let e=flattenRoutes(n);return rankRouteBranches(e),e}function flattenRoutes(n,e=[],t=[],i="",s=!1){let a=(l,u,f=s,d)=>{let p={relativePath:d===void 0?l.path||"":d,caseSensitive:l.caseSensitive===!0,childrenIndex:u,route:l};if(p.relativePath.startsWith("/")){if(!p.relativePath.startsWith(i)&&f)return;invariant(p.relativePath.startsWith(i),`Absolute route path "${p.relativePath}" nested under path "${i}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),p.relativePath=p.relativePath.slice(i.length)}let g=joinPaths([i,p.relativePath]),m=t.concat(p);l.children&&l.children.length>0&&(invariant(l.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${g}".`),flattenRoutes(l.children,e,m,g,f)),!(l.path==null&&!l.index)&&e.push({path:g,score:computeScore(g,l.index),routesMeta:m.map((v,S)=>{let[E,w]=compilePath(v.relativePath,v.caseSensitive,S===m.length-1);return{...v,matcher:E,compiledParams:w}})})};return n.forEach((l,u)=>{if(l.path===""||!l.path?.includes("?"))a(l,u);else for(let f of explodeOptionalSegments(l.path))a(l,u,!0,f)}),e}function explodeOptionalSegments(n){let e=n.split("/");if(e.length===0)return[];let[t,...i]=e,s=t.endsWith("?"),a=t.replace(/\?$/,"");if(i.length===0)return s?[a,""]:[a];let l=explodeOptionalSegments(i.join("/")),u=[];return u.push(...l.map(f=>f===""?a:[a,f].join("/"))),s&&u.push(...l),u.map(f=>n.startsWith("/")&&f===""?"/":f)}function rankRouteBranches(n){n.sort((e,t)=>e.score!==t.score?t.score-e.score:compareIndexes(e.routesMeta.map(i=>i.childrenIndex),t.routesMeta.map(i=>i.childrenIndex)))}var paramRe=/^:[\w-]+$/,dynamicSegmentValue=3,indexRouteValue=2,emptySegmentValue=1,staticSegmentValue=10,splatPenalty=-2,isSplat=n=>n==="*";function computeScore(n,e){let t=n.split("/"),i=t.length;return t.some(isSplat)&&(i+=splatPenalty),e&&(i+=indexRouteValue),t.filter(s=>!isSplat(s)).reduce((s,a)=>s+(paramRe.test(a)?dynamicSegmentValue:a===""?emptySegmentValue:staticSegmentValue),i)}function compareIndexes(n,e){return n.length===e.length&&n.slice(0,-1).every((i,s)=>i===e[s])?n[n.length-1]-e[e.length-1]:0}function matchRouteBranch(n,e,t=!1){let{routesMeta:i}=n,s={},a="/",l=[];for(let u=0;u<i.length;++u){let f=i[u],d=u===i.length-1,p=a==="/"?e:e.slice(a.length)||"/",g={path:f.relativePath,caseSensitive:f.caseSensitive,end:d},m=f.matcher&&f.compiledParams?matchPathImpl(g,p,f.matcher,f.compiledParams):matchPath(g,p),v=f.route;if(!m&&d&&t&&!i[i.length-1].route.index&&(m=matchPath({path:f.relativePath,caseSensitive:f.caseSensitive,end:!1},p)),!m)return null;Object.assign(s,m.params),l.push({params:s,pathname:joinPaths([a,m.pathname]),pathnameBase:normalizePathname(joinPaths([a,m.pathnameBase])),route:v}),m.pathnameBase!=="/"&&(a=joinPaths([a,m.pathnameBase]))}return l}function matchPath(n,e){typeof n=="string"&&(n={path:n,caseSensitive:!1,end:!0});let[t,i]=compilePath(n.path,n.caseSensitive,n.end);return matchPathImpl(n,e,t,i)}function matchPathImpl(n,e,t,i){let s=e.match(t);if(!s)return null;let a=s[0],l=a.replace(/(.)\/+$/,"$1"),u=s.slice(1);return{params:i.reduce((d,{paramName:p,isOptional:g},m)=>{if(p==="*"){let S=u[m]||"";l=a.slice(0,a.length-S.length).replace(/(.)\/+$/,"$1")}const v=u[m];return g&&!v?d[p]=void 0:d[p]=(v||"").replace(/%2F/g,"/"),d},{}),pathname:a,pathnameBase:l,pattern:n}}function compilePath(n,e=!1,t=!0){warning(n==="*"||!n.endsWith("*")||n.endsWith("/*"),`Route path "${n}" will be treated as if it were "${n.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/,"/*")}".`);let i=[],s="^"+n.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,u,f,d,p)=>{if(i.push({paramName:u,isOptional:f!=null}),f){let g=p.charAt(d+l.length);return g&&g!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return n.endsWith("*")?(i.push({paramName:"*"}),s+=n==="*"||n==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):t?s+="\\/*$":n!==""&&n!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,e?void 0:"i"),i]}function decodePath(n){try{return n.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return warning(!1,`The URL path "${n}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${e}).`),n}}function stripBasename(n,e){if(e==="/")return n;if(!n.toLowerCase().startsWith(e.toLowerCase()))return null;let t=e.endsWith("/")?e.length-1:e.length,i=n.charAt(t);return i&&i!=="/"?null:n.slice(t)||"/"}function resolvePath(n,e="/"){let{pathname:t,search:i="",hash:s=""}=typeof n=="string"?parsePath(n):n,a;return t?(t=removeDoubleSlashes(t),t.startsWith("/")?a=resolvePathname(t.substring(1),"/"):a=resolvePathname(t,e)):a=e,{pathname:a,search:normalizeSearch(i),hash:normalizeHash(s)}}function resolvePathname(n,e){let t=removeTrailingSlash(e).split("/");return n.split("/").forEach(s=>{s===".."?t.length>1&&t.pop():s!=="."&&t.push(s)}),t.length>1?t.join("/"):"/"}function getInvalidPathError(n,e,t,i){return`Cannot include a '${n}' character in a manually specified \`to.${e}\` field [${JSON.stringify(i)}]. Please separate it out to the \`to.${t}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function getPathContributingMatches(n){return n.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function getResolveToMatches(n){let e=getPathContributingMatches(n);return e.map((t,i)=>i===e.length-1?t.pathname:t.pathnameBase)}function resolveTo(n,e,t,i=!1){let s;typeof n=="string"?s=parsePath(n):(s={...n},invariant(!s.pathname||!s.pathname.includes("?"),getInvalidPathError("?","pathname","search",s)),invariant(!s.pathname||!s.pathname.includes("#"),getInvalidPathError("#","pathname","hash",s)),invariant(!s.search||!s.search.includes("#"),getInvalidPathError("#","search","hash",s)));let a=n===""||s.pathname==="",l=a?"/":s.pathname,u;if(l==null)u=t;else{let g=e.length-1;if(!i&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),g-=1;s.pathname=m.join("/")}u=g>=0?e[g]:"/"}let f=resolvePath(s,u),d=l&&l!=="/"&&l.endsWith("/"),p=(a||l===".")&&t.endsWith("/");return!f.pathname.endsWith("/")&&(d||p)&&(f.pathname+="/"),f}var removeDoubleSlashes=n=>n.replace(/[\\/]{2,}/g,"/"),joinPaths=n=>removeDoubleSlashes(n.join("/")),removeTrailingSlash=n=>n.replace(/\/+$/,""),normalizePathname=n=>removeTrailingSlash(n).replace(/^\/*/,"/"),normalizeSearch=n=>!n||n==="?"?"":n.startsWith("?")?n:"?"+n,normalizeHash=n=>!n||n==="#"?"":n.startsWith("#")?n:"#"+n,ErrorResponseImpl=class{constructor(n,e,t,i=!1){this.status=n,this.statusText=e||"",this.internal=i,t instanceof Error?(this.data=t.toString(),this.error=t):this.data=t}};function isRouteErrorResponse(n){return n!=null&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.internal=="boolean"&&"data"in n}function getRoutePattern(n){let e=n.map(t=>t.route.path).filter(Boolean);return joinPaths(e)||"/"}var isBrowser$1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function parseToInfo(n,e){let t=n;if(typeof t!="string"||!ABSOLUTE_URL_REGEX.test(t))return{absoluteURL:void 0,isExternal:!1,to:t};let i=t,s=!1;if(isBrowser$1)try{let a=new URL(window.location.href),l=PROTOCOL_RELATIVE_URL_REGEX.test(t)?new URL(normalizeProtocolRelativeUrl(t,a.protocol)):new URL(t),u=stripBasename(l.pathname,e);l.origin===a.origin&&u!=null?t=u+l.search+l.hash:s=!0}catch{warning(!1,`<Link to="${t}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:i,isExternal:s,to:t}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var validMutationMethodsArr=["POST","PUT","PATCH","DELETE"];new Set(validMutationMethodsArr);var validRequestMethodsArr=["GET",...validMutationMethodsArr];new Set(validRequestMethodsArr);var invalidProtocols=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function hasInvalidProtocol(n){try{return invalidProtocols.includes(new URL(n).protocol)}catch{return!1}}var DataRouterContext=reactExports.createContext(null);DataRouterContext.displayName="DataRouter";var DataRouterStateContext=reactExports.createContext(null);DataRouterStateContext.displayName="DataRouterState";var RSCRouterContext=reactExports.createContext(!1);function useIsRSCRouterContext(){return reactExports.useContext(RSCRouterContext)}var ViewTransitionContext=reactExports.createContext({isTransitioning:!1});ViewTransitionContext.displayName="ViewTransition";var FetchersContext=reactExports.createContext(new Map);FetchersContext.displayName="Fetchers";var AwaitContext=reactExports.createContext(null);AwaitContext.displayName="Await";var NavigationContext=reactExports.createContext(null);NavigationContext.displayName="Navigation";var LocationContext=reactExports.createContext(null);LocationContext.displayName="Location";var RouteContext=reactExports.createContext({outlet:null,matches:[],isDataRoute:!1});RouteContext.displayName="Route";var RouteErrorContext=reactExports.createContext(null);RouteErrorContext.displayName="RouteError";var ERROR_DIGEST_BASE="REACT_ROUTER_ERROR",ERROR_DIGEST_REDIRECT="REDIRECT",ERROR_DIGEST_ROUTE_ERROR_RESPONSE="ROUTE_ERROR_RESPONSE";function decodeRedirectErrorDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_REDIRECT}:{`))try{let e=JSON.parse(n.slice(28));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.location=="string"&&typeof e.reloadDocument=="boolean"&&typeof e.replace=="boolean")return e}catch{}}function decodeRouteErrorResponseDigest(n){if(n.startsWith(`${ERROR_DIGEST_BASE}:${ERROR_DIGEST_ROUTE_ERROR_RESPONSE}:{`))try{let e=JSON.parse(n.slice(40));if(typeof e=="object"&&e&&typeof e.status=="number"&&typeof e.statusText=="string")return new ErrorResponseImpl(e.status,e.statusText,e.data)}catch{}}function useHref(n,{relative:e}={}){invariant(useInRouterContext(),"useHref() may be used only in the context of a <Router> component.");let{basename:t,navigator:i}=reactExports.useContext(NavigationContext),{hash:s,pathname:a,search:l}=useResolvedPath(n,{relative:e}),u=a;return t!=="/"&&(u=a==="/"?t:joinPaths([t,a])),i.createHref({pathname:u,search:l,hash:s})}function useInRouterContext(){return reactExports.useContext(LocationContext)!=null}function useLocation(){return invariant(useInRouterContext(),"useLocation() may be used only in the context of a <Router> component."),reactExports.useContext(LocationContext).location}var navigateEffectWarning="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function useIsomorphicLayoutEffect(n){reactExports.useContext(NavigationContext).static||reactExports.useLayoutEffect(n)}function useNavigate(){let{isDataRoute:n}=reactExports.useContext(RouteContext);return n?useNavigateStable():useNavigateUnstable()}function useNavigateUnstable(){invariant(useInRouterContext(),"useNavigate() may be used only in the context of a <Router> component.");let n=reactExports.useContext(DataRouterContext),{basename:e,navigator:t}=reactExports.useContext(NavigationContext),{matches:i}=reactExports.useContext(RouteContext),{pathname:s}=useLocation(),a=JSON.stringify(getResolveToMatches(i)),l=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{l.current=!0}),reactExports.useCallback((f,d={})=>{if(warning(l.current,navigateEffectWarning),!l.current)return;if(typeof f=="number"){t.go(f);return}let p=resolveTo(f,JSON.parse(a),s,d.relative==="path");n==null&&e!=="/"&&(p.pathname=p.pathname==="/"?e:joinPaths([e,p.pathname])),(d.replace?t.replace:t.push)(p,d.state,d)},[e,t,a,s,n])}var OutletContext=reactExports.createContext(null);function useOutlet(n){let e=reactExports.useContext(RouteContext).outlet;return reactExports.useMemo(()=>e&&reactExports.createElement(OutletContext.Provider,{value:n},e),[e,n])}function useResolvedPath(n,{relative:e}={}){let{matches:t}=reactExports.useContext(RouteContext),{pathname:i}=useLocation(),s=JSON.stringify(getResolveToMatches(t));return reactExports.useMemo(()=>resolveTo(n,JSON.parse(s),i,e==="path"),[n,s,i,e])}function useRoutes(n,e){return useRoutesImpl(n)}function useRoutesImpl(n,e,t){invariant(useInRouterContext(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:i}=reactExports.useContext(NavigationContext),{matches:s}=reactExports.useContext(RouteContext),a=s[s.length-1],l=a?a.params:{},u=a?a.pathname:"/",f=a?a.pathnameBase:"/",d=a&&a.route;{let w=d&&d.path||"";warningOnce(u,!d||w.endsWith("*")||w.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${u}" (under <Route path="${w}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
305
305
 
306
306
  Please change the parent <Route path="${w}"> to <Route path="${w==="/"?"*":`${w}/*`}">.`)}let p=useLocation(),g;g=p;let m=g.pathname||"/",v=m;if(f!=="/"){let w=f.replace(/^\//,"").split("/");v="/"+m.replace(/^\//,"").split("/").slice(w.length).join("/")}let S=t&&t.state.matches.length?t.state.matches.map(w=>Object.assign(w,{route:t.manifest[w.route.id]||w.route})):matchRoutes(n,{pathname:v});return warning(d||S!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),warning(S==null||S[S.length-1].route.element!==void 0||S[S.length-1].route.Component!==void 0||S[S.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`),_renderMatches(S&&S.map(w=>Object.assign({},w,{params:Object.assign({},l,w.params),pathname:joinPaths([f,i.encodeLocation?i.encodeLocation(w.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?f:joinPaths([f,i.encodeLocation?i.encodeLocation(w.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:w.pathnameBase])})),s,t)}function DefaultErrorComponent(){let n=useRouteError(),e=isRouteErrorResponse(n)?`${n.status} ${n.statusText}`:n instanceof Error?n.message:JSON.stringify(n),t=n instanceof Error?n.stack:null,i="rgba(200,200,200, 0.5)",s={padding:"0.5rem",backgroundColor:i},a={padding:"2px 4px",backgroundColor:i},l=null;return console.error("Error handled by React Router default ErrorBoundary:",n),l=reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("p",null,"💿 Hey developer 👋"),reactExports.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",reactExports.createElement("code",{style:a},"ErrorBoundary")," or"," ",reactExports.createElement("code",{style:a},"errorElement")," prop on your route.")),reactExports.createElement(reactExports.Fragment,null,reactExports.createElement("h2",null,"Unexpected Application Error!"),reactExports.createElement("h3",{style:{fontStyle:"italic"}},e),t?reactExports.createElement("pre",{style:s},t):null,l)}var defaultErrorElement=reactExports.createElement(DefaultErrorComponent,null),RenderErrorBoundary=class extends reactExports.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,e){return e.location!==n.location||e.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:e.error,location:e.location,revalidation:n.revalidation||e.revalidation}}componentDidCatch(n,e){this.props.onError?this.props.onError(n,e):console.error("React Router caught the following error during render",n)}render(){let n=this.state.error;if(this.context&&typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){const t=decodeRouteErrorResponseDigest(n.digest);t&&(n=t)}let e=n!==void 0?reactExports.createElement(RouteContext.Provider,{value:this.props.routeContext},reactExports.createElement(RouteErrorContext.Provider,{value:n,children:this.props.component})):this.props.children;return this.context?reactExports.createElement(RSCErrorHandler,{error:n},e):e}};RenderErrorBoundary.contextType=RSCRouterContext;var errorRedirectHandledMap=new WeakMap;function RSCErrorHandler({children:n,error:e}){let{basename:t}=reactExports.useContext(NavigationContext);if(typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){let i=decodeRedirectErrorDigest(e.digest);if(i){let s=errorRedirectHandledMap.get(e);if(s)throw s;let a=parseToInfo(i.location,t),l=a.absoluteURL||a.to;if(hasInvalidProtocol(l))throw new Error("Invalid redirect location");if(isBrowser$1&&!errorRedirectHandledMap.get(e))if(a.isExternal||i.reloadDocument)window.location.href=l;else{const u=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:i.replace}));throw errorRedirectHandledMap.set(e,u),u}return reactExports.createElement("meta",{httpEquiv:"refresh",content:`0;url=${l}`})}}return n}function RenderedRoute({routeContext:n,match:e,children:t}){let i=reactExports.useContext(DataRouterContext);return i&&i.static&&i.staticContext&&(e.route.errorElement||e.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=e.route.id),reactExports.createElement(RouteContext.Provider,{value:n},t)}function _renderMatches(n,e=[],t){let i=t?.state;if(n==null){if(!i)return null;if(i.errors)n=i.matches;else if(e.length===0&&!i.initialized&&i.matches.length>0)n=i.matches;else return null}let s=n,a=i?.errors;if(a!=null){let p=s.findIndex(g=>g.route.id&&a?.[g.route.id]!==void 0);invariant(p>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(",")}`),s=s.slice(0,Math.min(s.length,p+1))}let l=!1,u=-1;if(t&&i){l=i.renderFallback;for(let p=0;p<s.length;p++){let g=s[p];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(u=p),g.route.id){let{loaderData:m,errors:v}=i,S=g.route.loader&&!m.hasOwnProperty(g.route.id)&&(!v||v[g.route.id]===void 0);if(g.route.lazy||S){t.isStatic&&(l=!0),u>=0?s=s.slice(0,u+1):s=[s[0]];break}}}}let f=t?.onError,d=i&&f?(p,g)=>{f(p,{location:i.location,params:i.matches?.[0]?.params??{},pattern:getRoutePattern(i.matches),errorInfo:g})}:void 0;return s.reduceRight((p,g,m)=>{let v,S=!1,E=null,w=null;i&&(v=a&&g.route.id?a[g.route.id]:void 0,E=g.route.errorElement||defaultErrorElement,l&&(u<0&&m===0?(warningOnce("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,w=null):u===m&&(S=!0,w=g.route.hydrateFallbackElement||null)));let A=e.concat(s.slice(0,m+1)),C=()=>{let T;return v?T=E:S?T=w:g.route.Component?T=reactExports.createElement(g.route.Component,null):g.route.element?T=g.route.element:T=p,reactExports.createElement(RenderedRoute,{match:g,routeContext:{outlet:p,matches:A,isDataRoute:i!=null},children:T})};return i&&(g.route.ErrorBoundary||g.route.errorElement||m===0)?reactExports.createElement(RenderErrorBoundary,{location:i.location,revalidation:i.revalidation,component:E,error:v,children:C(),routeContext:{outlet:null,matches:A,isDataRoute:!0},onError:d}):C()},null)}function getDataRouterConsoleError(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError(n)),e}function useDataRouterState(n){let e=reactExports.useContext(DataRouterStateContext);return invariant(e,getDataRouterConsoleError(n)),e}function useRouteContext(n){let e=reactExports.useContext(RouteContext);return invariant(e,getDataRouterConsoleError(n)),e}function useCurrentRouteId(n){let e=useRouteContext(n),t=e.matches[e.matches.length-1];return invariant(t.route.id,`${n} can only be used on routes that contain a unique "id"`),t.route.id}function useRouteId(){return useCurrentRouteId("useRouteId")}function useRouteError(){let n=reactExports.useContext(RouteErrorContext),e=useDataRouterState("useRouteError"),t=useCurrentRouteId("useRouteError");return n!==void 0?n:e.errors?.[t]}function useNavigateStable(){let{router:n}=useDataRouterContext("useNavigate"),e=useCurrentRouteId("useNavigate"),t=reactExports.useRef(!1);return useIsomorphicLayoutEffect(()=>{t.current=!0}),reactExports.useCallback(async(s,a={})=>{warning(t.current,navigateEffectWarning),t.current&&(typeof s=="number"?await n.navigate(s):await n.navigate(s,{fromRouteId:e,...a}))},[n,e])}var alreadyWarned={};function warningOnce(n,e,t){!e&&!alreadyWarned[n]&&(alreadyWarned[n]=!0,warning(!1,t))}reactExports.memo(DataRoutes2);function DataRoutes2({routes:n,manifest:e,future:t,state:i,isStatic:s,onError:a}){return useRoutesImpl(n,void 0,{manifest:e,state:i,isStatic:s,onError:a})}function Navigate({to:n,replace:e,state:t,relative:i}){invariant(useInRouterContext(),"<Navigate> may be used only in the context of a <Router> component.");let{static:s}=reactExports.useContext(NavigationContext);warning(!s,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:a}=reactExports.useContext(RouteContext),{pathname:l}=useLocation(),u=useNavigate(),f=resolveTo(n,getResolveToMatches(a),l,i==="path"),d=JSON.stringify(f);return reactExports.useEffect(()=>{u(JSON.parse(d),{replace:e,state:t,relative:i})},[u,d,i,e,t]),null}function Outlet(n){return useOutlet(n.context)}function Router({basename:n="/",children:e=null,location:t,navigationType:i="POP",navigator:s,static:a=!1,useTransitions:l}){invariant(!useInRouterContext(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let u=n.replace(/^\/*/,"/"),f=reactExports.useMemo(()=>({basename:u,navigator:s,static:a,useTransitions:l,future:{}}),[u,s,a,l]);typeof t=="string"&&(t=parsePath(t));let{pathname:d="/",search:p="",hash:g="",state:m=null,key:v="default",mask:S}=t,E=reactExports.useMemo(()=>{let w=stripBasename(d,u);return w==null?null:{location:{pathname:w,search:p,hash:g,state:m,key:v,mask:S},navigationType:i}},[u,d,p,g,m,v,i,S]);return warning(E!=null,`<Router basename="${u}"> is not able to match the URL "${d}${p}${g}" because it does not start with the basename, so the <Router> won't render anything.`),E==null?null:reactExports.createElement(NavigationContext.Provider,{value:f},reactExports.createElement(LocationContext.Provider,{children:e,value:E}))}var defaultMethod="get",defaultEncType="application/x-www-form-urlencoded";function isHtmlElement(n){return typeof HTMLElement<"u"&&n instanceof HTMLElement}function isButtonElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="button"}function isFormElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="form"}function isInputElement(n){return isHtmlElement(n)&&n.tagName.toLowerCase()==="input"}function isModifiedEvent(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function shouldProcessLinkClick(n,e){return n.button===0&&(!e||e==="_self")&&!isModifiedEvent(n)}var _formDataSupportsSubmitter=null;function isFormDataSubmitterSupported(){if(_formDataSupportsSubmitter===null)try{new FormData(document.createElement("form"),0),_formDataSupportsSubmitter=!1}catch{_formDataSupportsSubmitter=!0}return _formDataSupportsSubmitter}var supportedFormEncTypes=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function getFormEncType(n){return n!=null&&!supportedFormEncTypes.has(n)?(warning(!1,`"${n}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${defaultEncType}"`),null):n}function getFormSubmissionInfo(n,e){let t,i,s,a,l;if(isFormElement(n)){let u=n.getAttribute("action");i=u?stripBasename(u,e):null,t=n.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("enctype"))||defaultEncType,a=new FormData(n)}else if(isButtonElement(n)||isInputElement(n)&&(n.type==="submit"||n.type==="image")){let u=n.form;if(u==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let f=n.getAttribute("formaction")||u.getAttribute("action");if(i=f?stripBasename(f,e):null,t=n.getAttribute("formmethod")||u.getAttribute("method")||defaultMethod,s=getFormEncType(n.getAttribute("formenctype"))||getFormEncType(u.getAttribute("enctype"))||defaultEncType,a=new FormData(u,n),!isFormDataSubmitterSupported()){let{name:d,type:p,value:g}=n;if(p==="image"){let m=d?`${d}.`:"";a.append(`${m}x`,"0"),a.append(`${m}y`,"0")}else d&&a.append(d,g)}}else{if(isHtmlElement(n))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');t=defaultMethod,i=null,s=defaultEncType,l=n}return a&&s==="text/plain"&&(l=a,a=void 0),{action:i,method:t.toLowerCase(),encType:s,formData:a,body:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function invariant2(n,e){if(n===!1||n===null||typeof n>"u")throw new Error(e)}function singleFetchUrl(n,e,t,i){let s=typeof n=="string"?new URL(n,typeof window>"u"?"server://singlefetch/":window.location.origin):n;return t?s.pathname.endsWith("/")?s.pathname=`${s.pathname}_.${i}`:s.pathname=`${s.pathname}.${i}`:s.pathname==="/"?s.pathname=`_root.${i}`:e&&stripBasename(s.pathname,e)==="/"?s.pathname=`${removeTrailingSlash(e)}/_root.${i}`:s.pathname=`${removeTrailingSlash(s.pathname)}.${i}`,s}async function loadRouteModule(n,e){if(n.id in e)return e[n.id];try{let t=await import(n.module);return e[n.id]=t,t}catch(t){return console.error(`Error loading route module \`${n.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function isHtmlLinkDescriptor(n){return n==null?!1:n.href==null?n.rel==="preload"&&typeof n.imageSrcSet=="string"&&typeof n.imageSizes=="string":typeof n.rel=="string"&&typeof n.href=="string"}async function getKeyedPrefetchLinks(n,e,t){let i=await Promise.all(n.map(async s=>{let a=e.routes[s.route.id];if(a){let l=await loadRouteModule(a,t);return l.links?l.links():[]}return[]}));return dedupeLinkDescriptors(i.flat(1).filter(isHtmlLinkDescriptor).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function getNewMatchesForLinks(n,e,t,i,s,a){let l=(f,d)=>t[d]?f.route.id!==t[d].route.id:!0,u=(f,d)=>t[d].pathname!==f.pathname||t[d].route.path?.endsWith("*")&&t[d].params["*"]!==f.params["*"];return a==="assets"?e.filter((f,d)=>l(f,d)||u(f,d)):a==="data"?e.filter((f,d)=>{let p=i.routes[f.route.id];if(!p||!p.hasLoader)return!1;if(l(f,d)||u(f,d))return!0;if(f.route.shouldRevalidate){let g=f.route.shouldRevalidate({currentUrl:new URL(s.pathname+s.search+s.hash,window.origin),currentParams:t[0]?.params||{},nextUrl:new URL(n,window.origin),nextParams:f.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function getModuleLinkHrefs(n,e,{includeHydrateFallback:t}={}){return dedupeHrefs(n.map(i=>{let s=e.routes[i.route.id];if(!s)return[];let a=[s.module];return s.clientActionModule&&(a=a.concat(s.clientActionModule)),s.clientLoaderModule&&(a=a.concat(s.clientLoaderModule)),t&&s.hydrateFallbackModule&&(a=a.concat(s.hydrateFallbackModule)),s.imports&&(a=a.concat(s.imports)),a}).flat(1))}function dedupeHrefs(n){return[...new Set(n)]}function sortKeys(n){let e={},t=Object.keys(n).sort();for(let i of t)e[i]=n[i];return e}function dedupeLinkDescriptors(n,e){let t=new Set;return new Set(e),n.reduce((i,s)=>{let a=JSON.stringify(sortKeys(s));return t.has(a)||(t.add(a),i.push({key:a,link:s})),i},[])}function useDataRouterContext2(){let n=reactExports.useContext(DataRouterContext);return invariant2(n,"You must render this element inside a <DataRouterContext.Provider> element"),n}function useDataRouterStateContext(){let n=reactExports.useContext(DataRouterStateContext);return invariant2(n,"You must render this element inside a <DataRouterStateContext.Provider> element"),n}var FrameworkContext=reactExports.createContext(void 0);FrameworkContext.displayName="FrameworkContext";function useFrameworkContext(){let n=reactExports.useContext(FrameworkContext);return invariant2(n,"You must render this element inside a <HydratedRouter> element"),n}function usePrefetchBehavior(n,e){let t=reactExports.useContext(FrameworkContext),[i,s]=reactExports.useState(!1),[a,l]=reactExports.useState(!1),{onFocus:u,onBlur:f,onMouseEnter:d,onMouseLeave:p,onTouchStart:g}=e,m=reactExports.useRef(null);reactExports.useEffect(()=>{if(n==="render"&&l(!0),n==="viewport"){let E=A=>{A.forEach(C=>{l(C.isIntersecting)})},w=new IntersectionObserver(E,{threshold:.5});return m.current&&w.observe(m.current),()=>{w.disconnect()}}},[n]),reactExports.useEffect(()=>{if(i){let E=setTimeout(()=>{l(!0)},100);return()=>{clearTimeout(E)}}},[i]);let v=()=>{s(!0)},S=()=>{s(!1),l(!1)};return t?n!=="intent"?[a,m,{}]:[a,m,{onFocus:composeEventHandlers(u,v),onBlur:composeEventHandlers(f,S),onMouseEnter:composeEventHandlers(d,v),onMouseLeave:composeEventHandlers(p,S),onTouchStart:composeEventHandlers(g,v)}]:[!1,m,{}]}function composeEventHandlers(n,e){return t=>{n&&n(t),t.defaultPrevented||e(t)}}function PrefetchPageLinks({page:n,...e}){let t=useIsRSCRouterContext(),{nonce:i}=useFrameworkContext(),{router:s}=useDataRouterContext2(),a=reactExports.useMemo(()=>matchRoutes(s.routes,n,s.basename),[s.routes,n,s.basename]);return a?(e.nonce==null&&i&&(e={...e,nonce:i}),t?reactExports.createElement(RSCPrefetchPageLinksImpl,{page:n,matches:a,...e}):reactExports.createElement(PrefetchPageLinksImpl,{page:n,matches:a,...e})):null}function useKeyedPrefetchLinks(n){let{manifest:e,routeModules:t}=useFrameworkContext(),[i,s]=reactExports.useState([]);return reactExports.useEffect(()=>{let a=!1;return getKeyedPrefetchLinks(n,e,t).then(l=>{a||s(l)}),()=>{a=!0}},[n,e,t]),i}function RSCPrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s}=useFrameworkContext(),{basename:a}=useDataRouterContext2(),l=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let u=singleFetchUrl(n,a,s.v8_trailingSlashAwareDataRequests,"rsc"),f=!1,d=[];for(let p of e)typeof p.route.shouldRevalidate=="function"?f=!0:d.push(p.route.id);return f&&d.length>0&&u.searchParams.set("_routes",d.join(",")),[u.pathname+u.search]},[a,s.v8_trailingSlashAwareDataRequests,n,i,e]);return reactExports.createElement(reactExports.Fragment,null,l.map(u=>reactExports.createElement("link",{key:u,rel:"prefetch",as:"fetch",href:u,...t})))}function PrefetchPageLinksImpl({page:n,matches:e,...t}){let i=useLocation(),{future:s,manifest:a,routeModules:l}=useFrameworkContext(),{basename:u}=useDataRouterContext2(),{loaderData:f,matches:d}=useDataRouterStateContext(),p=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"data"),[n,e,d,a,i]),g=reactExports.useMemo(()=>getNewMatchesForLinks(n,e,d,a,i,"assets"),[n,e,d,a,i]),m=reactExports.useMemo(()=>{if(n===i.pathname+i.search+i.hash)return[];let E=new Set,w=!1;if(e.forEach(C=>{let T=a.routes[C.route.id];!T||!T.hasLoader||(!p.some(F=>F.route.id===C.route.id)&&C.route.id in f&&l[C.route.id]?.shouldRevalidate||T.hasClientLoader?w=!0:E.add(C.route.id))}),E.size===0)return[];let A=singleFetchUrl(n,u,s.v8_trailingSlashAwareDataRequests,"data");return w&&E.size>0&&A.searchParams.set("_routes",e.filter(C=>E.has(C.route.id)).map(C=>C.route.id).join(",")),[A.pathname+A.search]},[u,s.v8_trailingSlashAwareDataRequests,f,i,a,p,e,n,l]),v=reactExports.useMemo(()=>getModuleLinkHrefs(g,a),[g,a]),S=useKeyedPrefetchLinks(g);return reactExports.createElement(reactExports.Fragment,null,m.map(E=>reactExports.createElement("link",{key:E,rel:"prefetch",as:"fetch",href:E,...t})),v.map(E=>reactExports.createElement("link",{key:E,rel:"modulepreload",href:E,...t})),S.map(({key:E,link:w})=>reactExports.createElement("link",{key:E,nonce:t.nonce,...w,crossOrigin:w.crossOrigin??t.crossOrigin})))}function mergeRefs(...n){return e=>{n.forEach(t=>{typeof t=="function"?t(e):t!=null&&(t.current=e)})}}var isBrowser2=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{isBrowser2&&(window.__reactRouterVersion="7.18.2")}catch(n){}function BrowserRouter({basename:n,children:e,useTransitions:t,window:i}){let s=reactExports.useRef();s.current==null&&(s.current=createBrowserHistory({window:i,v5Compat:!0}));let a=s.current,[l,u]=reactExports.useState({action:a.action,location:a.location}),f=reactExports.useCallback(d=>{t===!1?u(d):reactExports.startTransition(()=>u(d))},[t]);return reactExports.useLayoutEffect(()=>a.listen(f),[a,f]),reactExports.createElement(Router,{basename:n,children:e,location:l.location,navigationType:l.action,navigator:a,useTransitions:t})}var Link=reactExports.forwardRef(function n({onClick:e,discover:t="render",prefetch:i="none",relative:s,reloadDocument:a,replace:l,mask:u,state:f,target:d,to:p,preventScrollReset:g,viewTransition:m,defaultShouldRevalidate:v,...S},E){let{basename:w,navigator:A,useTransitions:C}=reactExports.useContext(NavigationContext),T=typeof p=="string"&&ABSOLUTE_URL_REGEX.test(p),F=parseToInfo(p,w);p=F.to;let P=useHref(p,{relative:s}),M=useLocation(),O=null;if(u){let De=resolveTo(u,[],M.mask?M.mask.pathname:"/",!0);w!=="/"&&(De.pathname=De.pathname==="/"?w:joinPaths([w,De.pathname])),O=A.createHref(De)}let[Q,pe,q]=usePrefetchBehavior(i,S),ee=useLinkClickHandler(p,{replace:l,mask:u,state:f,target:d,preventScrollReset:g,relative:s,viewTransition:m,defaultShouldRevalidate:v,useTransitions:C});function _e(De){e&&e(De),De.defaultPrevented||ee(De)}let te=!(F.isExternal||a),Ie=reactExports.createElement("a",{...S,...q,href:(te?O:void 0)||F.absoluteURL||P,onClick:te?_e:e,ref:mergeRefs(E,pe),target:d,"data-discover":!T&&t==="render"?"true":void 0});return Q&&!T?reactExports.createElement(reactExports.Fragment,null,Ie,reactExports.createElement(PrefetchPageLinks,{page:P})):Ie});Link.displayName="Link";var NavLink=reactExports.forwardRef(function n({"aria-current":e="page",caseSensitive:t=!1,className:i="",end:s=!1,style:a,to:l,viewTransition:u,children:f,...d},p){let g=useResolvedPath(l,{relative:d.relative}),m=useLocation(),v=reactExports.useContext(DataRouterStateContext),{navigator:S,basename:E}=reactExports.useContext(NavigationContext),w=v!=null&&useViewTransitionState(g)&&u===!0,A=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,C=m.pathname,T=v&&v.navigation&&v.navigation.location?v.navigation.location.pathname:null;t||(C=C.toLowerCase(),T=T?T.toLowerCase():null,A=A.toLowerCase()),T&&E&&(T=stripBasename(T,E)||T);const F=A!=="/"&&A.endsWith("/")?A.length-1:A.length;let P=C===A||!s&&C.startsWith(A)&&C.charAt(F)==="/",M=T!=null&&(T===A||!s&&T.startsWith(A)&&T.charAt(A.length)==="/"),O={isActive:P,isPending:M,isTransitioning:w},Q=P?e:void 0,pe;typeof i=="function"?pe=i(O):pe=[i,P?"active":null,M?"pending":null,w?"transitioning":null].filter(Boolean).join(" ");let q=typeof a=="function"?a(O):a;return reactExports.createElement(Link,{...d,"aria-current":Q,className:pe,ref:p,style:q,to:l,viewTransition:u},typeof f=="function"?f(O):f)});NavLink.displayName="NavLink";var Form=reactExports.forwardRef(({discover:n="render",fetcherKey:e,navigate:t,reloadDocument:i,replace:s,state:a,method:l=defaultMethod,action:u,onSubmit:f,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m,...v},S)=>{let{useTransitions:E}=reactExports.useContext(NavigationContext),w=useSubmit(),A=useFormAction(u,{relative:d}),C=l.toLowerCase()==="get"?"get":"post",T=typeof u=="string"&&ABSOLUTE_URL_REGEX.test(u),F=P=>{if(f&&f(P),P.defaultPrevented)return;P.preventDefault();let M=P.nativeEvent.submitter,O=M?.getAttribute("formmethod")||l,Q=()=>w(M||P.currentTarget,{fetcherKey:e,method:O,navigate:t,replace:s,state:a,relative:d,preventScrollReset:p,viewTransition:g,defaultShouldRevalidate:m});E&&t!==!1?reactExports.startTransition(()=>Q()):Q()};return reactExports.createElement("form",{ref:S,method:C,action:A,onSubmit:i?f:F,...v,"data-discover":!T&&n==="render"?"true":void 0})});Form.displayName="Form";function getDataRouterConsoleError2(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function useDataRouterContext3(n){let e=reactExports.useContext(DataRouterContext);return invariant(e,getDataRouterConsoleError2(n)),e}function useLinkClickHandler(n,{target:e,replace:t,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:f,useTransitions:d}={}){let p=useNavigate(),g=useLocation(),m=useResolvedPath(n,{relative:l});return reactExports.useCallback(v=>{if(shouldProcessLinkClick(v,e)){v.preventDefault();let S=t!==void 0?t:createPath(g)===createPath(m),E=()=>p(n,{replace:S,mask:i,state:s,preventScrollReset:a,relative:l,viewTransition:u,defaultShouldRevalidate:f});d?reactExports.startTransition(()=>E()):E()}},[g,p,m,t,i,s,e,n,a,l,u,f,d])}var fetcherId=0,getUniqueFetcherId=()=>`__${String(++fetcherId)}__`;function useSubmit(){let{router:n}=useDataRouterContext3("useSubmit"),{basename:e}=reactExports.useContext(NavigationContext),t=useRouteId(),i=n.fetch,s=n.navigate;return reactExports.useCallback(async(a,l={})=>{let{action:u,method:f,encType:d,formData:p,body:g}=getFormSubmissionInfo(a,e);if(l.navigate===!1){let m=l.fetcherKey||getUniqueFetcherId();await i(m,t,l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||f,formEncType:l.encType||d,flushSync:l.flushSync})}else await s(l.action||u,{defaultShouldRevalidate:l.defaultShouldRevalidate,preventScrollReset:l.preventScrollReset,formData:p,body:g,formMethod:l.method||f,formEncType:l.encType||d,replace:l.replace,state:l.state,fromRouteId:t,flushSync:l.flushSync,viewTransition:l.viewTransition})},[i,s,e,t])}function useFormAction(n,{relative:e}={}){let{basename:t}=reactExports.useContext(NavigationContext),i=reactExports.useContext(RouteContext);invariant(i,"useFormAction must be used inside a RouteContext");let[s]=i.matches.slice(-1),a={...useResolvedPath(n||".",{relative:e})},l=useLocation();if(n==null){a.search=l.search;let u=new URLSearchParams(a.search),f=u.getAll("index");if(f.some(p=>p==="")){u.delete("index"),f.filter(g=>g).forEach(g=>u.append("index",g));let p=u.toString();a.search=p?`?${p}`:""}}return(!n||n===".")&&s.route.index&&(a.search=a.search?a.search.replace(/^\?/,"?index&"):"?index"),t!=="/"&&(a.pathname=a.pathname==="/"?t:joinPaths([t,a.pathname])),createPath(a)}function useViewTransitionState(n,{relative:e}={}){let t=reactExports.useContext(ViewTransitionContext);invariant(t!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:i}=useDataRouterContext3("useViewTransitionState"),s=useResolvedPath(n,{relative:e});if(!t.isTransitioning)return!1;let a=stripBasename(t.currentLocation.pathname,i)||t.currentLocation.pathname,l=stripBasename(t.nextLocation.pathname,i)||t.nextLocation.pathname;return matchPath(s.pathname,l)!=null||matchPath(s.pathname,a)!=null}function WebAccountRestoringView({label:n="正在恢复登录状态…",accountName:e}){return jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex min-h-44 flex-col items-center justify-center gap-3 px-5 py-8 text-center",children:[jsxRuntimeExports.jsx(LoaderCircle,{"aria-hidden":"true",className:"h-6 w-6 animate-spin text-primary"}),e?jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-foreground",children:e}):null,jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:n})]})}function WebAccountFailureView({title:n="操作未完成",description:e,primaryLabel:t="重试",onPrimary:i,secondaryLabel:s="返回",onSecondary:a,pending:l=!1}){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-44 flex-col items-center justify-center gap-4 px-5 py-8 text-center",children:[jsxRuntimeExports.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10",children:jsxRuntimeExports.jsx(CircleAlert,{"aria-hidden":"true",className:"h-5 w-5 text-destructive"})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-base font-semibold text-foreground",children:n}),e?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm leading-6 text-muted-foreground",children:e}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xs",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:i,className:"h-10 rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",children:t}),a?jsxRuntimeExports.jsx("button",{type:"button",disabled:l,onClick:a,className:"h-9 rounded-lg border border-border bg-background px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus:outline-none focus-visible:border-ring",children:s}):null]})]})}let automaticLoginBlocked=!1,logoutState={status:"idle"},operation,inFlight;const logoutListeners=new Set,isXpodAutomaticLoginBlocked=()=>automaticLoginBlocked,getXpodProductLogoutState=()=>logoutState;function subscribeXpodProductLogout(n){return logoutListeners.add(n),()=>{logoutListeners.delete(n)}}function publish(n){logoutState=n,logoutListeners.forEach(e=>e())}function logoutXpodProduct(n,e,t={}){return inFlight||(automaticLoginBlocked=!0,operation={account:n,runtime:e,solidCleared:!1,onComplete:t.onComplete},retryXpodProductLogout())}function retryXpodProductLogout(){if(inFlight)return inFlight;if(!operation)return Promise.resolve();const n=operation;return inFlight=(async()=>{let t=n.solidCleared?"account":"solid";publish({status:"running",step:t});try{if(n.solidCleared||(await n.runtime?.logout(),n.solidCleared=!0),t="account",publish({status:"running",step:t}),await n.account.logout(),n.account.isAnonymous&&!n.account.isAnonymous())throw new Error("Account sign-out did not complete")}catch(i){throw publish({status:"error",step:t}),i}operation=void 0,publish({status:"idle"}),n.onComplete?.()})().finally(()=>{inFlight=void 0}),inFlight}const LogoutRecoveryOwner=reactExports.createContext(!1);function XpodProductLogoutBoundary({children:n}){const e=reactExports.useContext(LogoutRecoveryOwner),t=reactExports.useSyncExternalStore(subscribeXpodProductLogout,getXpodProductLogoutState,getXpodProductLogoutState);if(e)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});const i=t.status!=="idle";return jsxRuntimeExports.jsxs(LogoutRecoveryOwner.Provider,{value:!0,children:[i&&jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"退出 Xpod",children:t.status==="running"?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在退出…"}):jsxRuntimeExports.jsx(WebAccountFailureView,{title:"退出未完成",description:t.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{retryXpodProductLogout().catch(()=>{})}})}),jsxRuntimeExports.jsx("div",{className:i?"hidden":"contents","aria-hidden":i||void 0,inert:i||void 0,children:n})]})}const AuthContext=reactExports.createContext(null);function useAuth(){const n=reactExports.useContext(AuthContext);if(!n)throw new Error("useAuth must be used within AuthProvider");return n}function useXpodProfileCardIdentity({accountIdentity:n,runtime:e}){const t=e?.state.status,i=t==="authenticated"&&e?e.webId??e.state.webId:n?.webId,s=t==="authenticated"&&i?void 0:n,a=s?.displayName,l=s?.username,u=s?.id,f=s?.webId,d=e?.fetch,p=reactExports.useMemo(()=>accountProfileFallback({displayName:a,username:l,id:u},i),[a,u,l,f,i]),g=`${i??""}\0${p.displayName}\0${p.username??""}`,[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1);reactExports.useEffect(()=>{const A=d;if(t!=="authenticated"||!A||!i)return;let C=!1,T;async function F(P,M){E(!0);try{const O=await resolveSolidProfileIdentityFromWebIdDocument({info:{webId:M},fetch:P});if(C||!O)return;const Q=normalizedHttpUrl(O.profile?.avatar);let pe=Q;if(Q&&(pe=await resolveAuthenticatedAvatarUrl(P,Q),T=pe?.startsWith("blob:")?pe:void 0),C){T&&URL.revokeObjectURL(T);return}v({key:g,value:{displayName:O.displayName??O.username??p.displayName,username:O.username||p.username,avatarUrl:pe??p.avatarUrl,avatarSourceUrl:Q,note:O.profile?.note||p.note,region:O.profile?.region||p.region,webId:O.webId||p.webId,loading:!1,source:"webid-profile"}})}catch{C||v(void 0)}finally{C||E(!1)}}return F(A,i),()=>{C=!0,T&&URL.revokeObjectURL(T)}},[d,p,g,t,i]);const w=t==="authenticated"?S:!1;return t==="authenticated"&&m?.key===g?{...m.value,loading:w}:{...p,loading:w}}function accountProfileFallback(n,e){const t=n?.username||usernameFromWebId$1(e)||n?.id;return{displayName:n?.displayName||t||n?.id||"Xpod account",username:t,webId:e,loading:!1,source:"account"}}async function resolveAuthenticatedAvatarUrl(n,e){try{const t=await n(e);if(!t.ok)return e;const i=await t.blob();return URL.createObjectURL(i)}catch{return e}}function normalizedHttpUrl(n){if(n)try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"?e.href:void 0}catch{return}}function usernameFromWebId$1(n){if(n)try{const e=new URL(n);return e.pathname.split("/").filter(Boolean).at(0)||e.hostname}catch{return}}const useXpodSolidRuntime=useXpodSolidRuntimeContext,XPOD_REMEMBERED_LOGIN_KEY="xpod.remembered-login.v1",XPOD_PENDING_ACCOUNT_EMAIL_KEY="xpod.pending-account-email.v1",XPOD_PENDING_ACCOUNT_ISSUER_KEY="xpod.pending-account-issuer.v1";function optionalPersistentStorage(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function readRememberedXpodLogin(n={}){const e=n.storage??optionalPersistentStorage();if(e)try{const t=e.getItem(XPOD_REMEMBERED_LOGIN_KEY);if(!t)return;const i=normalizeRememberedXpodLogin(JSON.parse(t),n.origin??currentOrigin());return i||e.removeItem(XPOD_REMEMBERED_LOGIN_KEY),i}catch{try{e.removeItem(XPOD_REMEMBERED_LOGIN_KEY)}catch{}return}}function rememberXpodLogin(n,e={}){const t=e.storage??optionalPersistentStorage();if(!t)return;const i=normalizeRememberedXpodLogin(n,e.origin??currentOrigin());if(i)try{return t.setItem(XPOD_REMEMBERED_LOGIN_KEY,JSON.stringify(i)),t.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function clearRememberedXpodLogin(n=optionalPersistentStorage()){try{n?.removeItem(XPOD_REMEMBERED_LOGIN_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n?.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY)}catch{}}function rememberedXpodLoginMatchesActive(n,e){if(!n||!e.webId||!e.selectedStorage)return!1;const t=validatedWebId(n.webId),i=validatedWebId(n.storageBinding.webId),s=normalizedUrl(n.storageBinding.storageUrl,!0),a=validatedWebId(e.webId),l=validatedWebId(e.selectedStorage.webId),u=normalizedUrl(e.selectedStorage.storageUrl,!0);return!t||!i||!s||!a||!l||!u||t!==i||a!==l||t!==a||s!==u?!1:rememberedXpodAccountMatchesActive(n,e)}function rememberedXpodAccountMatchesActive(n,e){return n?matchingOptionalEmail(n.account.email,e.accountEmail):!1}function rememberPendingXpodAccountEmail(n,e=optionalPersistentStorage(),t){const i=normalizedEmail(n);if(!(!e||!i))try{return e.setItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY,i),t?e.setItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY,normalizedIssuer(t)):e.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY),i}catch{return}}function readPendingXpodAccountEmail(n=optionalPersistentStorage(),e){if(n)try{const t=normalizedEmail(n.getItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY));if(e){const i=n.getItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);if(!i||i!==normalizedIssuer(e)){n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),n.removeItem(XPOD_PENDING_ACCOUNT_ISSUER_KEY);return}}return t||n.removeItem(XPOD_PENDING_ACCOUNT_EMAIL_KEY),t}catch{return}}function normalizedIssuer(n){try{const e=currentOrigin();return e?new URL(n,e).origin:new URL(n).origin}catch{return n.trim()}}function normalizeRememberedXpodLogin(n,e){if(!n||typeof n!="object")return;const t=n;if(t.routeId!==XPOD_LOGIN_ROUTE_ID||!t.account||typeof t.account!="object"||!t.storageBinding||typeof t.storageBinding!="object")return;const i=t.account,s=t.storageBinding,a=normalizedEmail(i.email),l=validatedWebId(t.webId),u=validatedWebId(s.webId),f=normalizedUrl(s.storageUrl,!0);if(i.email!==void 0&&!a||!l||!u||!f||l!==u)return;const d=normalizedAvatarUrl(i.avatarUrl,[l,f,e]);return{account:{...a?{email:a}:{},...normalizedText(i.id)?{id:normalizedText(i.id)}:{},...normalizedText(i.username)?{username:normalizedText(i.username)}:{},...normalizedText(i.displayName)?{displayName:normalizedText(i.displayName)}:{},...d?{avatarUrl:d}:{}},webId:l,storageBinding:{webId:l,storageUrl:f},routeId:XPOD_LOGIN_ROUTE_ID}}function normalizedEmail(n){if(typeof n!="string")return;const e=n.trim();return e&&e.length<=320&&e.includes("@")?e:void 0}function normalizedText(n){if(typeof n!="string")return;const e=n.replace(/\s+/g," ").trim();return e?Array.from(e).slice(0,160).join(""):void 0}function validatedWebId(n){return typeof n=="string"&&!hasInvalidWebIdWhitespace(n)&&normalizedUrl(n)?n:void 0}function normalizedUrl(n,e=!1){if(!(typeof n!="string"||n.length>2048))try{const t=new URL(n);return t.username||t.password||t.protocol!=="http:"&&t.protocol!=="https:"?void 0:(e&&(t.hash="",t.pathname.endsWith("/")||(t.pathname+="/")),t.href)}catch{return}}function normalizedAvatarUrl(n,e){const t=normalizedUrl(n);if(!t)return;const i=new URL(t).origin;return e.some(s=>{const a=normalizedUrl(s);return a&&new URL(a).origin===i})?t:void 0}function matchingOptionalEmail(n,e){const t=normalizedEmail(n)?.toLowerCase(),i=normalizedEmail(e)?.toLowerCase();return!t||!i||t===i}function currentOrigin(){return typeof window>"u"?void 0:window.location.origin}function XpodRememberedLoginBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.selectedStorage,i=useXpodProfileCardIdentity({accountIdentity:n.identity,runtime:e}),s=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,a=readRememberedXpodLogin(),l=readPendingXpodAccountEmail(),u=l??a?.account.email;return reactExports.useEffect(()=>{!s||!t||!e.currentPod||t.webId===s&&(e.currentPod.webId!==s||e.currentPod.podUrl!==t.storageUrl||a&&!rememberedXpodLoginMatchesActive(a,{accountIdentity:n.identity,accountEmail:l,webId:s,selectedStorage:t})||rememberXpodLogin({account:{...u?{email:u}:{},...n.identity??{},displayName:i.displayName,...i.username?{username:i.username}:{},...i.avatarSourceUrl??a?.account.avatarUrl?{avatarUrl:i.avatarSourceUrl??a?.account.avatarUrl}:{}},webId:s,storageBinding:t,routeId:XPOD_LOGIN_ROUTE_ID}))},[n.identity,u,l,i.displayName,i.avatarSourceUrl,i.username,a,e.currentPod,t,s]),null}const CSS_ACCOUNT_COOKIE_NAME="css-account",CSS_ACCOUNT_TOKEN_STORAGE_KEY="xpod.cssAccountToken",CSS_ACCOUNT_AUTHORITY_STORAGE_KEY="xpod.cssAccountAuthority",CSS_ACCOUNT_AUTH_SCHEME="CSS-Account-Token";function isBrowser(){return typeof window<"u"&&typeof document<"u"}function readCssAccountCookie(){if(!isBrowser())return;const n=document.cookie.split(";");for(const e of n){const[t,...i]=e.trim().split("=");if(t===CSS_ACCOUNT_COOKIE_NAME){const s=i.join("=");try{return s?decodeURIComponent(s):void 0}catch{return}}}}function writeCssAccountCookie(n){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=${encodeURIComponent(n)}; Path=/; SameSite=Lax`)}function clearCssAccountCookie(){isBrowser()&&(document.cookie=`${CSS_ACCOUNT_COOKIE_NAME}=; Path=/; SameSite=Lax; Max-Age=0`)}function clearLegacyStoredToken(){if(!(typeof window>"u")){try{window.localStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}try{window.sessionStorage.removeItem(CSS_ACCOUNT_TOKEN_STORAGE_KEY)}catch{}}}function bindAccountSessionAuthority(n){if(!isBrowser())return!1;const e=normalizeAccountAuthority(n),t=window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY),i=t!==null?t!==e:new URL(e).origin!==window.location.origin;return window.localStorage.setItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY,e),i&&clearAccountSessionToken(),i}function normalizeAccountAuthority(n){const e=new URL(n,window.location.origin);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.pathname!=="/.account/"||e.search||e.hash)throw new Error("Invalid Account authority");return e.href}function storeAccountSessionToken(n){!n||readCssAccountCookie()===n||writeCssAccountCookie(n)}function clearAccountSessionToken(){clearLegacyStoredToken(),clearCssAccountCookie()}function getAccountSessionToken(){return readCssAccountCookie()}function accountTokenHeaders(n,e={Accept:"application/json"}){const t={...e};return n&&!hasHeader(t,"Authorization")&&(t.Authorization=`${CSS_ACCOUNT_AUTH_SCHEME} ${n}`),t}function storedAccountTokenHeaders(n={Accept:"application/json"},e){if(e)try{if(window.localStorage.getItem(CSS_ACCOUNT_AUTHORITY_STORAGE_KEY)!==normalizeAccountAuthority(e))return{...n}}catch{return{...n}}return accountTokenHeaders(getAccountSessionToken(),n)}function hasHeader(n,e){const t=e.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===t)}let cachedRoute,cachedRouteOrigin;function resolveSameOriginAccountControlUrl(n){if(typeof window>"u"||typeof n!="string"||!n.trim())return;const e=n.trim();try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin||!["http:","https:"].includes(t.protocol)||t.username||t.password?void 0:scopeAccountUrl(t)}catch{return}}async function resolveHostedAccountControlUrl(n,e=fetch,t){if(typeof window>"u"||typeof n!="string"||!n.trim())return;if(t)try{const d=new URL(t,window.location.origin),p=new URL(n.trim(),d);if(p.origin===d.origin&&d.pathname.startsWith("/.account/")&&p.pathname.startsWith("/.account/")&&["http:","https:"].includes(p.protocol)&&!p.username&&!p.password)return scopeAccountUrl(p)}catch{}const i=resolveSameOriginAccountControlUrl(n);if(i)return i;let s;try{s=new URL(n)}catch{return}if(!["http:","https:"].includes(s.protocol)||s.username||s.password||!s.pathname.startsWith("/.account/"))return;if(cachedRoute&&cachedRouteOrigin===window.location.origin){const d=resolveSolidLocalRouteUrl(s,[cachedRoute]);if(d)return scopeAccountUrl(d)}const a={localBaseUrl:`${window.location.origin}/`,statusUrl:new URL("/provision/status",window.location.origin).href},l=await Promise.resolve(e.call(globalThis,a.statusUrl,{credentials:"include",headers:{accept:"application/json"}})).catch(()=>{}),u=l?await discoverSolidLocalRoute({...a,fetch:async()=>l.clone()}):void 0;u&&(cachedRoute=u,cachedRouteOrigin=window.location.origin);const f=u?resolveSolidLocalRouteUrl(s,[u]):void 0;return f?scopeAccountUrl(f):void 0}const LOCAL_ACCOUNT_INDEX$1="/.account/";function isProvisionStatusResponse(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}async function resolveXpodAccountIndex(n=fetch){if(typeof window>"u")return LOCAL_ACCOUNT_INDEX$1;if(!isLoopbackHostname$1(window.location.hostname)){const i=window.__XPOD__?.idpIndex;if(i!==void 0){try{const s=new URL(i,window.location.origin);if(typeof i=="string"&&i.trim()&&["http:","https:"].includes(s.protocol)&&s.pathname===LOCAL_ACCOUNT_INDEX$1&&!s.username&&!s.password&&!s.search&&!s.hash)return unregisterLocalProvisionResolver(),s.href}catch{}throw new Error("Server bootstrap did not expose a valid Account index")}}const e=await n(new URL("/provision/status",window.location.origin),{credentials:"include",headers:{accept:"application/json"}});if(e.status===404)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(!e.ok)throw new Error(`Local provisioning status request failed (${e.status})`);let t;try{t=await e.json()}catch{throw new Error("Local provisioning status response was not valid JSON")}if(!isProvisionStatusResponse(t)||typeof t.managed!="boolean")throw new Error("Local provisioning status response was not valid");if(t.managed===!1)return unregisterLocalProvisionResolver(),new URL(LOCAL_ACCOUNT_INDEX$1,window.location.origin).href;if(typeof t.oidcIssuer=="string")try{const i=new URL(t.oidcIssuer);if(["http:","https:"].includes(i.protocol)&&!i.username&&!i.password)return installLocalProvisionResolver(n),typeof t.provisionCode=="string"&&setStoredProvisionCode(t.provisionCode),new URL(LOCAL_ACCOUNT_INDEX$1,i).href}catch{}throw new Error("Local provisioning status did not expose a valid OIDC issuer")}function installLocalProvisionResolver(n){const e=new URL("/provision/status",window.location.origin);registerLocalProvisionResolver(async()=>{const t=await n(e,{credentials:"include",headers:{accept:"application/json"}}),i=t.ok?await t.json().catch(()=>{}):void 0;if(i?.managed!==!0||i?.registered!==!0||typeof i?.provisionCode!="string")throw new Error(CLOUD_PROVISIONING_UNAVAILABLE);return i.provisionCode})}function isLoopbackHostname$1(n){return n==="localhost"||n==="::1"||n==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(n)}const LOCAL_ACCOUNT_INDEX="/.account/",ACCOUNT_ERROR_MESSAGE="Xpod 登录服务暂时不可用,请稍后重试。",ACCOUNT_CONTROLS_RETRY_DELAYS_MS=[250,750,1500],ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS=300,OIDC_PENDING_PROBE_TIMEOUT_MS=3e3;function isAccountSpaPath(){if(typeof window>"u")return!1;const n=window.location.pathname;return n==="/.account"||n.startsWith("/.account/")}function accountIdentityFromControls(n){const e=n?.account;if(!e)return;const t={...typeof e.id=="string"?{id:e.id}:{},...typeof e.username=="string"?{username:e.username}:{},...typeof e.displayName=="string"?{displayName:e.displayName}:{}};return Object.keys(t).length>0?t:void 0}function accountStateForControls(n){return n?.account?.logout?{status:"authenticated"}:{status:"anonymous",mode:"login"}}function isTransientAccountControlsStatus(n){return n===502||n===503||n===504}function transientAccountState(n){return n?{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}:{status:"initializing"}}function wait(n){return new Promise(e=>setTimeout(e,n))}function AuthProvider({children:n}){const[e,t]=reactExports.useState(),[i,s]=reactExports.useState(null),[a,l]=reactExports.useState(!0),[u,f]=reactExports.useState(null),[d,p]=reactExports.useState(!1),[g,m]=reactExports.useState({status:"initializing"}),v=reactExports.useRef(0),S=reactExports.useRef(!0),E=reactExports.useRef(0),w=reactExports.useRef(void 0),A=reactExports.useRef(null),C=g.status==="authenticated",T=a||g.status==="submitting",F=reactExports.useRef(!1),P=reactExports.useCallback(De=>{(bindAccountSessionAuthority(De)||w.current&&w.current!==De)&&(E.current+=1,v.current+=1,F.current=!1,A.current=null,s(null),p(!1),m({status:"initializing"})),w.current=De,t(De)},[]),M=reactExports.useCallback(async()=>{l(!0),f(null),m(De=>De.status==="authenticated"?De:{status:"initializing"});try{const De=await resolveXpodAccountIndex();return S.current?(P(De),De):void 0}catch{if(!S.current)return;A.current=null,s(null),p(!1),f(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1);return}},[P]);reactExports.useEffect(()=>{let De=!0;return resolveXpodAccountIndex().then(de=>{De&&S.current&&P(de)}).catch(()=>{!De||!S.current||(A.current=null,s(null),p(!1),f(ACCOUNT_ERROR_MESSAGE),m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}),l(!1))}),()=>{De=!1}},[P]),reactExports.useEffect(()=>(S.current=!0,()=>{S.current=!1,E.current+=1}),[]);const O=reactExports.useCallback(De=>S.current&&De===E.current,[]),Q=reactExports.useCallback(async()=>{const De=new AbortController,de=setTimeout(()=>De.abort(),OIDC_PENDING_PROBE_TIMEOUT_MS);try{const Oe=w.current;if(!Oe)return!1;const le=await fetch(scopeAccountUrl(new URL("oidc/consent/",Oe)),{headers:storedAccountTokenHeaders(void 0,Oe),credentials:"include",signal:De.signal});return le.ok?!!(await le.json()).client:!1}catch{return!1}finally{clearTimeout(de)}},[]),pe=reactExports.useCallback(async({exposeTransientError:De,generation:de,confirmUnauthenticated:Oe})=>{const le=w.current;if(!le)return"stale";try{const Ae=await fetch(scopeAccountUrl(le),{headers:storedAccountTokenHeaders(void 0,le),credentials:"include"});if(!O(de))return"stale";if(Ae.ok){const $=await Ae.json();if(!O(de))return"stale";if(!$?.controls||typeof $.controls!="object"||Array.isArray($.controls))throw new Error("Invalid CSS Account controls response");const H=$.controls,fe=++v.current;p(!1),A.current=H,s(H),f(null);const ae=accountStateForControls(H);return F.current=ae.status==="anonymous",m(ae),H.account?.logout&&isAccountSpaPath()&&Q().then(Pe=>{O(de)&&fe===v.current&&p(Pe)}),"ok"}else{if(Ae.status===401||Ae.status===403)return Oe?(v.current+=1,clearAccountSessionToken(),F.current=!0,p(!1),A.current={},s({}),m({status:"anonymous",mode:"login"}),f(null),"ok"):"unauthenticated";if(v.current+=1,p(!1),isTransientAccountControlsStatus(Ae.status))return f(null),m(H=>H.status==="authenticated"?H:transientAccountState(De)),"transient-error";const $=`Failed to load account controls (Status: ${Ae.status})`;return f($),m({status:"error",mode:"login",message:$}),"terminal-error"}}catch{return O(de)?(v.current+=1,p(!1),f(null),m(Ae=>Ae.status==="authenticated"?Ae:transientAccountState(De)),"transient-error"):"stale"}},[Q,O]),q=reactExports.useCallback(async()=>{const De=++E.current;for(let de=0;de<=ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length;de+=1){const Oe=de===ACCOUNT_CONTROLS_RETRY_DELAYS_MS.length,le=await pe({exposeTransientError:Oe,generation:De});if(le==="unauthenticated")return!O(De)||(await wait(ACCOUNT_UNAUTHENTICATED_CONFIRM_DELAY_MS),!O(De))?"stale":pe({exposeTransientError:!0,generation:De,confirmUnauthenticated:!0});if(le!=="transient-error")return le;if(!O(De)||!Oe&&(m(Ae=>Ae.status==="authenticated"?Ae:{status:"initializing"}),await wait(ACCOUNT_CONTROLS_RETRY_DELAYS_MS[de]),!O(De)))return"stale"}return"transient-error"},[pe,O]);reactExports.useEffect(()=>{if(!e)return;let De=!0;return(async()=>(await q(),De&&S.current&&l(!1)))(),()=>{De=!1}},[q,e]);const ee=reactExports.useCallback(async()=>{const De=await M();if(De&&De===e){const de=await q();if(S.current&&l(!1),de==="ok")return accountStateForControls(A.current)}return{status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE}},[q,e,M]),_e=reactExports.useCallback(async()=>{await ee()},[ee]),te=reactExports.useCallback(async()=>{E.current+=1,v.current+=1,A.current?.account?.logout||(F.current=!1,(w.current??await M())&&await q());const De=w.current,de=A.current?.account?.logout,Oe=await resolveHostedAccountControlUrl(de,fetch,De);let le=!Oe&&(!!de||!F.current);if(Oe)try{const Ae=await fetch(scopeAccountUrl(Oe),{method:"POST",headers:storedAccountTokenHeaders(void 0,De),credentials:"include"});le=!Ae.ok&&Ae.status!==401&&Ae.status!==403}catch{le=!0}if(le){m({status:"error",mode:"login",message:ACCOUNT_ERROR_MESSAGE});return}E.current+=1,v.current+=1,F.current=!0,l(!1),clearAccountSessionToken(),p(!1),A.current={},s({}),f(null),m({status:"anonymous",mode:"login"})},[q,M]),Ie=reactExports.useMemo(()=>accountIdentityFromControls(i),[i]);return jsxRuntimeExports.jsx(AuthContext.Provider,{value:{controls:i,isInitializing:a,initError:u,idpIndex:e??LOCAL_ACCOUNT_INDEX,isLoggedIn:C,isAnonymous:()=>F.current,authenticating:T,hasOidcPending:d,refetchControls:ee,retry:_e,logout:te,accountState:g,identity:Ie},children:n})}const MAX_LABEL_CODE_POINTS=80,MAX_IDENTITY_URL_LENGTH=2048;function XpodDesktopIdentityBridge(){const n=useAuth(),e=useXpodSolidRuntime(),t=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=e.state.status==="authenticated"?e.currentPod?.podUrl??e.podUrl??e.state.podUrl:void 0,s=reactExports.useMemo(()=>projectDesktopIdentity({isLoggedIn:n.isLoggedIn,displayName:n.identity?.displayName,username:n.identity?.username,webId:t,podUrl:i}),[n.identity?.displayName,n.identity?.username,n.isLoggedIn,i,t]);return reactExports.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(s)},[s]),reactExports.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function projectDesktopIdentity({isLoggedIn:n,displayName:e,username:t,webId:i,podUrl:s}){if(!n)return null;const a=sanitizeLabel(e)??sanitizeLabel(t)??"Xpod Account",l=sanitizeCurrentXpodUrl(i),u=sanitizeCurrentXpodUrl(s);return{label:a,...l?{webId:l}:{},...u?{podUrl:u}:{}}}function sanitizeLabel(n){if(!n)return;const t=Array.from(n,i=>{const s=i.codePointAt(0);return isUnsafeLabelCodePoint(s)?" ":i}).join("").replace(/\s+/g," ").trim();if(t)return Array.from(t).slice(0,MAX_LABEL_CODE_POINTS).join("").trim()}function isUnsafeLabelCodePoint(n){return n<32||n>=127&&n<=159||n>=8234&&n<=8238||n>=8294&&n<=8297}function sanitizeCurrentXpodUrl(n){if(!(!n||n.length>MAX_IDENTITY_URL_LENGTH))try{const e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password||!isCurrentXpodOrigin(e)?void 0:e.toString()}catch{return}}function isCurrentXpodOrigin(n){const e=globalThis.window?.location;return e?n.origin===e.origin?!0:n.protocol===e.protocol&&n.port===e.port&&isLoopbackHostname(n.hostname)&&isLoopbackHostname(e.hostname):!1}function isLoopbackHostname(n){const e=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function XpodServiceAvailability({children:n}){const[e,t]=reactExports.useState(!1),i=reactExports.useRef(()=>{}),s=reactExports.useRef(null);return reactExports.useEffect(()=>{if(!e)return;const a=document.activeElement;return s.current?.focus(),()=>{a instanceof HTMLElement&&a.isConnected&&a.focus()}},[e]),reactExports.useEffect(()=>{let a=!1,l,u,f=0;async function d(){if(a||l)return;clearTimeout(u);const g=new AbortController;l=g;const m=setTimeout(()=>g.abort(),5e3);let v=!0;try{const S=await fetch("/service/status",{cache:"no-store",signal:g.signal});if(v=S.status<500,S.ok){const E=await S.json().catch(()=>null);Array.isArray(E)&&(v=!E.some(w=>w&&["css","api"].includes(w.name)&&typeof w.status=="string"&&w.status!=="running")),g.signal.aborted&&(v=!1)}else await S.body?.cancel()}catch{v=!1}finally{clearTimeout(m),l=void 0}a||(f=v?0:f+1,t(!v),u=setTimeout(()=>{document.visibilityState!=="hidden"&&d()},v?1e4:Math.min(2e3*2**Math.min(f-1,4),3e4)))}const p=()=>{document.visibilityState!=="hidden"&&d()};return i.current=()=>{d()},window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",p),d(),()=>{a=!0,clearTimeout(u),l?.abort(),i.current=()=>{},window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",p)}},[]),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{style:{display:"contents"},inert:e||void 0,children:n}),e&&jsxRuntimeExports.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-background/70 p-6 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("section",{role:"alertdialog","aria-modal":"true","aria-labelledby":"xpod-connection-title","aria-describedby":"xpod-connection-description",className:"w-full max-w-sm rounded-2xl border bg-background p-6 shadow-lg",children:[jsxRuntimeExports.jsx("h2",{id:"xpod-connection-title",className:"text-lg font-semibold",children:"Xpod 连接中断"}),jsxRuntimeExports.jsx("p",{id:"xpod-connection-description",className:"mt-3 text-sm text-muted-foreground",children:"暂时无法连接 Xpod,正在自动重连。登录状态和当前页面已保留,恢复后即可继续。"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"刚才未完成的操作不会自动重试,请在连接恢复后确认结果。"}),jsxRuntimeExports.jsx("button",{ref:s,type:"button",onKeyDown:a=>{a.key==="Tab"&&a.preventDefault()},onClick:()=>i.current(),className:"mt-5 w-full rounded-lg bg-primary px-4 py-2 text-primary-foreground",children:"立即重试"})]})})]})}function XpodDesktopNavigationBridge(){const n=useNavigate();return reactExports.useEffect(()=>globalThis.xpodDesktop?.onNavigate?.(e=>{const t=new URL(e,window.location.origin);t.origin===window.location.origin&&n(`${t.pathname}${t.search}${t.hash}`)}),[n]),null}const client_id="https://id.undefineds.co/app/xpod-desktop-client.json",desktopClient={client_id};function XpodSolidRuntimeProvider({children:n,value:e}){const t=e??getXpodSolidRuntimeValue(),i=reactExports.useMemo(()=>t.storage??{},[t]),s=reactExports.useMemo(()=>currentProviderSession(t),[t]),[a,l]=reactExports.useState(s.snapshot),[u,f]=reactExports.useState(s.issuer),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),[v,S]=reactExports.useState(),[E,w]=reactExports.useState(0),[A,C]=reactExports.useState(),T=reactExports.useRef(a),F=reactExports.useRef(s.rejected),P=reactExports.useRef(void 0),M=reactExports.useCallback(async(_e,te)=>F.current?Promise.reject(REJECTED_SESSION_FETCH_ERROR):te===void 0?t.session.fetch(_e):t.session.fetch(_e,te),[t.session]),O=reactExports.useCallback(()=>{if(P.current)return P.current;const _e=(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),f(void 0),p(void 0),m(void 0),S(void 0),C(void 0)}})().finally(()=>{P.current===_e&&(P.current=void 0)});return P.current=_e,_e},[t,i.issuer,i.selectedStorage]),Q=reactExports.useMemo(()=>({...t.session,fetch:M,getSnapshot:()=>T.current}),[M,t.session]);reactExports.useEffect(()=>{const _e=Ie=>{const De=t.getIssuer();if(!isCurrentXpodSessionSnapshot(Ie,De,t.getExpectedIssuer?.()??window.location.origin)){F.current=!0,O();return}Ie.status==="authenticated"&&(F.current=!1);const de=T.current;T.current=Ie,l(Ie),f(De),Ie.status!=="authenticated"?(t.setLocalPodRoute?.(void 0),p(void 0),Ie.status!=="expired"&&m(void 0),S(void 0),C(void 0),t.pod.clear()):(de.status!=="authenticated"||Ie.webId!==de.webId)&&(p(void 0),m(void 0),S(void 0),C(void 0),t.pod.clear(de.status==="authenticated"?{webId:de.webId}:void 0))},te=t.session.subscribe(_e);return _e(t.session.getSnapshot()),te},[O,t,i]),reactExports.useEffect(()=>{F.current&&O()},[O]),reactExports.useEffect(()=>{if(a.status!=="authenticated")return;let _e=!1;const te=readXpodSelectedStorage({storage:i.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:a.webId}),Ie={webId:a.webId,...te?{podUrl:te.storageUrl}:{},fetch:M};return(async()=>{try{const De=await t.pod.open(Ie),de=await currentHostLocalPodRoute(De.podUrl,fetch);if(_e)return;if(t.setLocalPodRoute?.(de),!_e){if(te&&(De.webId!==te.webId||!sameUrl$2(De.podUrl,te.storageUrl))){clearXpodSelectedStorage({storage:i.selectedStorage}),p(void 0),m(void 0),S({webId:a.webId,error:new Error("Selected Pod binding mismatch")});return}p(De),m(te??{webId:De.webId,storageUrl:De.podUrl}),S(void 0)}}catch(De){_e||S({webId:a.webId,error:De instanceof Error?De:new Error(String(De))})}})(),()=>{_e=!0}},[M,E,t,i.selectedStorage,a]);const pe=reactExports.useCallback(()=>{S(void 0),w(_e=>_e+1)},[]),q=a.status==="authenticated"?a.webId:void 0;reactExports.useEffect(()=>{if(!q)return;let _e=!1;return discoverAiClientConfigurationCapability(M).then(te=>{!_e&&t.session.getSnapshot().status==="authenticated"&&t.session.getSnapshot().webId===q&&C(te)}),()=>{_e=!0}},[q,M,t]);const ee=reactExports.useMemo(()=>{const _e=u??t.getIssuer(),te=a.status==="authenticated"&&v?.webId===a.webId?v:void 0,Ie=snapshotToState(a,d,_e);return{session:Q,pod:t.pod,fetch:M,state:Ie.status==="error"?{...Ie,error:safeAuthError(Ie.error)}:Ie,webId:Ie.webId,podUrl:Ie.podUrl,issuer:Ie.issuer,currentPod:d,selectedStorage:g,...te?{podError:te}:{},retryPodOpen:pe,aiClientConfiguration:A,login:async De=>{const de=normalizeXpodLoginTransaction(De),Oe=await resolveXpodLoginContext(de.route.identityProvider.url,fetch),le=Oe.oidcIssuer;if(!le)throw new TypeError("Xpod login route has no valid issuer");const Ae=new URL("/auth/callback",window.location.origin),$=globalThis.xpodDesktop?desktopClient.client_id:void 0;try{await t.session.login({...$?{clientId:$}:{},oidcIssuer:le,redirectUrl:Ae.toString(),handleRedirect:H=>{t.setIssuer(le),f(le);const fe=new URL(H);de.prompt?fe.searchParams.set("prompt",de.prompt):$&&fe.searchParams.get("prompt")==="consent"&&fe.searchParams.delete("prompt"),window.location.assign(Oe.provisionCode?withXpodProvisionScope(fe.href,Oe.provisionCode):fe.href)}}),t.setIssuer(le),f(le)}catch(H){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",H,H instanceof Error?H.cause:void 0),H}},logout:async()=>{await t.session.logout(),t.pod.clear(),clearXpodSelectedStorage({storage:i.selectedStorage}),clearStoredXpodOidcIssuer(i.issuer),p(void 0),m(void 0),C(void 0)}}},[A,d,M,Q,u,v,pe,t,i,g,a]);return jsxRuntimeExports.jsx(SolidRuntimeProvider,{value:{session:Q,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$3(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$3(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}const XPOD_THEME_STORAGE_KEY="xpod.theme",XPOD_THEME_MEDIA_QUERY="(prefers-color-scheme: dark)";function readXpodThemePreference(n=optionalLocalStorage()){try{const e=n?.getItem(XPOD_THEME_STORAGE_KEY);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function resolveXpodTheme(n,e=systemThemeMedia()){return n!=="system"?n:e?.matches?"dark":"light"}function applyXpodTheme(n,e=typeof document>"u"?void 0:document.documentElement){e&&(e.classList.toggle("light",n==="light"),e.classList.toggle("dark",n==="dark"),e.dataset.theme=n,e.style.colorScheme=n)}function initializeXpodTheme(){const n=readXpodThemePreference(),e=resolveXpodTheme(n);return applyXpodTheme(e),{preference:n,resolvedTheme:e}}function systemThemeMedia(){return typeof window>"u"||typeof window.matchMedia!="function"?void 0:window.matchMedia(XPOD_THEME_MEDIA_QUERY)}function optionalLocalStorage(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}const XpodThemeContext=reactExports.createContext(null);function XpodThemeProvider({children:n}){const[e,t]=reactExports.useState(()=>readXpodThemePreference()),[i,s]=reactExports.useState(()=>resolveXpodTheme("system")),a=e==="system"?i:e;reactExports.useEffect(()=>{const u=systemThemeMedia();if(!u)return;const f=d=>{s(d.matches?"dark":"light")};return typeof u.addEventListener=="function"?(u.addEventListener("change",f),()=>u.removeEventListener("change",f)):(u.addListener?.(f),()=>u.removeListener?.(f))},[]),reactExports.useEffect(()=>{applyXpodTheme(a)},[a]);const l=reactExports.useMemo(()=>({preference:e,resolvedTheme:a,setPreference(u){t(u);try{u==="system"?optionalLocalStorage()?.removeItem(XPOD_THEME_STORAGE_KEY):optionalLocalStorage()?.setItem(XPOD_THEME_STORAGE_KEY,u)}catch{}}}),[e,a]);return jsxRuntimeExports.jsx(XpodThemeContext.Provider,{value:l,children:n})}function XpodThemeRoot({children:n}){return reactExports.useContext(XpodThemeContext)?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(XpodThemeProvider,{children:n})}function DesktopLoginReturnAction(){const[n,e]=reactExports.useState(!1),[t,i]=reactExports.useState(!1),s=reactExports.useRef(!1);if(!window.xpodDesktop?.cancelLogin)return null;const a=async()=>{const l=window.xpodDesktop;if(!(s.current||!l?.cancelLogin)){s.current=!0,e(!0),i(!1);try{await l.cancelLogin()}catch{i(!0)}finally{s.current=!1,e(!1)}}};return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[t&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"返回应用未完成,请重试。"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",className:"w-full",disabled:n,"aria-busy":n,onClick:()=>{a()},children:n?"正在返回…":"返回应用"})]})}const xpodAccountCredentialsCopy={productName:"Xpod 账号",loginTitle:"登录",registerTitle:"创建账号",usernameLabel:"Pod 名称",usernamePlaceholder:"选择 Pod 名称",emailLabel:"邮箱",emailPlaceholder:"you@example.com",passwordLabel:"密码",passwordPlaceholder:"输入密码",confirmationLabel:"确认密码",confirmationPlaceholder:"再次输入密码",loginAction:"登录",registerAction:"创建账号",switchToRegister:"切换用户",switchToLogin:"返回登录",usernameChecking:"正在检查 Pod 名称…",usernameAvailable:"Pod 名称可用",usernameUnavailable:"Pod 名称不可用",suggestionsLabel:"可用建议",mismatchError:"两次输入的密码不一致"},xpodAccountPageCopy={forgotPassword:"忘记密码?"},xpodFirstPodCopy={surfaceTitle:"准备存储空间",restoring:"正在检查存储空间…",creating:"正在准备存储空间…",unavailableTitle:"存储空间未准备好",waitingMessage:"正在等待 WebID 与存储空间绑定。",retryLabel:"重试"},xpodRegistrationCopy={usernameRequired:"请填写 Pod 名称",usernameLength:"Pod 名称需为 3-63 个字符",usernameCharset:"Pod 名称只能包含小写字母、数字和连字符",usernameHyphen:"Pod 名称不能以连字符开头或结尾",emailAlreadyRegisteredPasswordMismatch:"该邮箱已注册,但密码不正确,请登录或重置密码。",choosePodName:"请填写 Pod 名称。",podNameTaken:"Pod 名称已被占用,请换一个。"};function safeXpodLoginMessage(n){return n===401||n===403?"邮箱或密码不正确。":n===429?"尝试次数过多,请稍后再试。":"登录失败,请重试。"}const xpodConsentErrors={bindingsFailed:"无法加载 WebID 绑定,请重试。"},xpodFirstPodErrors={checkFailed:"无法检查存储空间状态,请重试。",accountIdentityMissing:"当前账号信息不完整,无法自动准备本机存储空间。",createEndpointMissing:"找不到创建 Pod 的接口,请刷新后重试。",cloudRouteUnavailable:"本机 Xpod 还没有和 Cloud 打通,暂时不能准备存储空间。请保持 Xpod 运行,稍后重试。",storageCreateFailed:"无法创建存储空间,请重试。"};class AccountStorageBindingsError extends Error{code;constructor(e,t){super(t),this.name="AccountStorageBindingsError",this.code=e}}async function fetchAccountStorageBindings(n){const e=resolveOrigin(n.origin),t=n.controls?.account?.bindings;if(typeof t!="string"||t.trim()==="")throw new AccountStorageBindingsError("missing-control","Account storage bindings control is unavailable");const i=n.fetchImpl??fetch,s=parseControlUrl(t,e),a=s.origin===e?s.href:await resolveHostedAccountControlUrl(s.href,i,n.trustedAccountIndex);if(!a)throw new AccountStorageBindingsError("cross-origin","Account storage bindings control is not hosted by this Xpod");const l=storedAccountTokenHeaders({Accept:"application/json",...n.headers});let u;try{u=await i(a,{headers:l,credentials:"include"})}catch(d){throw new AccountStorageBindingsError("request-failed",d instanceof Error?d.message:"Failed to load Account storage bindings")}if(u.status===401||u.status===403)throw new AccountStorageBindingsError("forbidden","Account storage bindings require an authenticated Account");if(!u.ok)throw new AccountStorageBindingsError("request-failed",`Account storage bindings request failed (${u.status})`);let f;try{f=await u.json()}catch{throw new AccountStorageBindingsError("invalid-response","Account storage bindings response is not valid JSON")}return parseAccountStorageBindings(f,s.origin,isTrustedAccountControl(s,n.trustedAccountIndex,e))}function parseAccountStorageBindings(n,e,t=!1){if(!isRecord$2(n)||!Array.isArray(n.bindings))throw new AccountStorageBindingsError("invalid-response","Account storage bindings response is malformed");const i=[],s=new Set;for(const a of n.bindings){if(!isRecord$2(a)||typeof a.webId!="string"||typeof a.storageUrl!="string")throw new AccountStorageBindingsError("invalid-response","Account storage binding row is malformed");const l=normalizeWebId(a.webId),u=normalizeStorageUrl$1(a.storageUrl,t?void 0:e);if(!l||!u)throw new AccountStorageBindingsError("cross-origin","Account storage binding is outside the trusted storage scope");const f={webId:l,storageUrl:u,...typeof a.label=="string"?{label:a.label}:{}},d=`${f.webId}
307
- ${f.storageUrl}`;s.has(d)||(s.add(d),i.push(f))}return i}function resolveOrigin(n){try{return new URL(n??(typeof window>"u"?"http://localhost":window.location.origin)).origin}catch{throw new AccountStorageBindingsError("cross-origin","Current Xpod origin is invalid")}}function parseControlUrl(n,e){try{const t=new URL(n,e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.hash)throw new Error("unsafe control URL");return t}catch{throw new AccountStorageBindingsError("cross-origin","Account storage bindings control is not a valid URL")}}function normalizeWebId(n){if(!hasInvalidWebIdWhitespace(n))try{const e=new URL(n);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:n}catch{return}}function normalizeStorageUrl$1(n,e){try{const t=new URL(n.trim());return e!==void 0&&t.origin!==e||!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash?void 0:(t.pathname=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,t.href)}catch{return}}function isTrustedAccountControl(n,e,t){if(!e)return!1;try{const i=new URL(e,t);return i.pathname.startsWith("/.account/")&&n.origin===i.origin&&n.pathname.startsWith("/.account/")}catch{return!1}}function isRecord$2(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function isRecord$1(n){return typeof n=="object"&&n!==null}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(scopeAccountUrl(n.loginUrl),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const a=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(a||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,onAuthenticated:e,initialEmail:t}){const{controls:i,idpIndex:s,refetchControls:a}=useAuth(),[l,u]=reactExports.useState({email:t!==void 0?t:readPendingXpodAccountEmail(void 0,s)??"",password:""}),[f,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),[m,v]=reactExports.useState(!0),S=reactExports.useRef(!1),E=async C=>{if(!S.current){S.current=!0,g(!0),d(void 0);try{const T=await resolveHostedAccountControlUrl(i?.password?.login,fetch,s)??scopeAccountUrl("/.account/login/password/"),F=await loginAccountPassword({email:C.email?.trim()??"",password:C.password,loginUrl:T,remember:m,fetchImpl:async(M,O)=>{const Q=await fetch(typeof M=="string"||M instanceof URL?scopeAccountUrl(M):M,O);if(!Q.ok)throw new PasswordLoginStatusError(Q.status);return Q}});storeAccountSessionToken(F.accountToken),rememberPendingXpodAccountEmail(C.email?.trim()??"",void 0,s);const P=await a();if(P?.status!=="authenticated"){P?.status==="anonymous"&&clearAccountSessionToken(),d("登录失败,请重试。");return}await e?.()}catch(T){d(T instanceof PasswordLoginStatusError?safeXpodLoginMessage(T.status):safeXpodLoginMessage(500))}finally{S.current=!1,g(!1)}}},w=C=>{u(C),f&&d(void 0)},A={surface:"page",surfaceTitle:"登录 Xpod",copy:xpodAccountCredentialsCopy,footer:n==="embedded"?void 0:jsxRuntimeExports.jsx(AccountEntryLinks,{}),mode:"login",values:l,onChange:w,onSubmit:E,pending:p,rememberAccount:m,onRememberAccountChange:v,errors:f?{form:f}:void 0};return n==="embedded"?jsxRuntimeExports.jsx(AccountCredentialsView,{...A,presentation:"compact",frame:"bare",showHeader:!1}):jsxRuntimeExports.jsx(XpodBlockingAccountCredentialsSurface,{...A})}function AccountEntryLinks(){let n="";try{const e=normalizeXpodReturnTo(`${window.location.pathname}${window.location.search}`);e&&(n=`?${new URLSearchParams({returnTo:e})}`)}catch{}return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-center gap-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/register/${n}`),children:"创建账号"})}),jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"text-border",children:"·"}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/forgot/${n}`),children:xpodAccountPageCopy.forgotPassword})})]})}function AccountWorkspaceBoundary({children:n}){return useXpodSolidRuntimeContext().state.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(AccountAuthBoundary,{children:n})}function AccountAuthBoundary({children:n,accountState:e,retry:t,surface:i="page"}){const s=useAuth(),a=e??s.accountState,l=t??s.retry;return a.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):a.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):a.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):a.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:a.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{l()},children:"重试"}),jsxRuntimeExports.jsx(DesktopLoginReturnAction,{})]})}):i==="embedded"?jsxRuntimeExports.jsxs(LoginSurface,{surface:i,children:[jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"embedded"}),jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:jsxRuntimeExports.jsx(AccountEntryLinks,{})})]}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"page"})}function LoginSurface({children:n,surface:e}){return e==="embedded"?jsxRuntimeExports.jsx(WebAccountLayout,{title:"登录 Xpod",presentation:"compact",children:n}):jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:"登录 Xpod",presentation:"compact",children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const f=Math.max(72,t-n.top+12);return{left:8,bottom:f,width:u,maxHeight:Math.max(240,t-f-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",i=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),s=t||i,[a,l]=reactExports.useState(accountCardRequestedByUrl(s)),[u,f]=reactExports.useState(),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),v=reactExports.useRef(null),S=reactExports.useRef(null),E=reactExports.useRef(void 0),w=reactExports.useId(),A=n.identity,C=readPendingXpodAccountEmail(),T=readRememberedXpodLogin()?.account,F=t?accountCardIdentityFallback(A,C,T):void 0,P=useXpodProfileCardIdentity({accountIdentity:F,runtime:i?e:void 0}),M=P.displayName,O=initialsFor(P.displayName),Q=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),pe=accountHandle(P.username,i?void 0:F?.id,Q),q=e?.selectedStorage?.storageUrl??e?.podUrl,ee=e?.selectedStorage,_e=e?.currentPod,te=reactExports.useMemo(()=>q?podNameFromUrl(q):void 0,[q]),Ie=e?.state.status==="authenticated"&&!!(Q&&q&&ee&&_e)&&ee?.webId===Q&&sameUrl$1(ee?.storageUrl??"",q??"")&&_e?.webId===Q&&sameUrl$1(_e?.podUrl??"",q??""),De=s,de=a&&De,Oe=reactExports.useCallback(H=>{l(H),H||(m(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!de)return;const H=()=>{const fe=S.current;fe&&m(accountCardPosition(fe.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return H(),window.addEventListener("resize",H),window.addEventListener("scroll",H,!0),window.visualViewport?.addEventListener("resize",H),()=>{window.removeEventListener("resize",H),window.removeEventListener("scroll",H,!0),window.visualViewport?.removeEventListener("resize",H)}},[de]),reactExports.useEffect(()=>{if(!De){clearAccountCardRequest();return}if(!de)return;const H=ae=>{const Pe=ae.target;Pe instanceof Node&&(v.current?.contains(Pe)||S.current?.contains(Pe)||Oe(!1))},fe=ae=>{ae.key==="Escape"&&(Oe(!1),S.current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",fe),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",fe)}},[De,de,Oe]),reactExports.useEffect(()=>{!de||!g||v.current?.focus({preventScroll:!0})},[de,g]),reactExports.useEffect(()=>()=>{E.current!==void 0&&window.clearTimeout(E.current)},[]);const le=async()=>{f("logout"),Oe(!1);try{await logoutXpodProduct(n,e),(n.isAnonymous?.()??!0)&&Oe(!1)}catch{}finally{f(void 0)}},Ae=async()=>{f("switch"),Oe(!1);try{await logoutXpodProduct(n,e,{onComplete:()=>{clearRememberedXpodLogin();const H=new URL(XPOD_DEFAULT_RETURN_PATH,window.location.origin);H.searchParams.set("xpod-login","switch"),window.location.assign(H)}}),Oe(!1)}catch{}finally{f(void 0)}},$=async()=>{const H=P.webId??pe;try{await navigator.clipboard.writeText(H),p("Copied")}catch{p("Copy failed")}E.current!==void 0&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>p(void 0),1800)};return De?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:S,type:"button","aria-label":s?`Open account menu for ${M}`:"Open account menu","aria-expanded":de,"aria-controls":de?w:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":Ie?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Oe(!de),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:O})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s?M:"Not signed in"})]}),de&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:v,id:w,role:"region",tabIndex:-1,"aria-label":s?M:"Xpod account","data-avatar-card":"true","data-selected-pod-url":q,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:O})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:M}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:pe}),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:()=>{$()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),d?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:d}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Ie?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:Ie?"Pod connected":i?"WebID connected":"Account connected"})]})]})]}),P.note||P.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[P.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:P.note}):null,P.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:P.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(te)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(q)]})]}),Ie?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:()=>{Ae()},disabled:u!==void 0,children:[u==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{le()},disabled:u!==void 0,children:[u==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const a=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(a,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-Drnlv8Gw.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-Drnlv8Gw.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-Drnlv8Gw.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-W890Vczu.js"),__vite__mapDeps([7,8,9,2,10,3,11,12,5]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-BO7YcO6a.js"),__vite__mapDeps([13,2,9,8,10]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-DT1Aw7YO.js"),__vite__mapDeps([14,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-ybKkidfS.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:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}async function waitForCurrentAccountStorageBindings(n){const e=Math.max(1,n.maxAttempts??20);for(let t=0;t<e;t+=1){const i=(await fetchAccountStorageBindings(n)).filter(s=>storageUrlBelongsToRoot(s.storageUrl,n.storageRoot));if(i.length>0)return i;t+1<e&&await new Promise(s=>setTimeout(s,Math.max(0,n.pollIntervalMs??500)))}throw new Error("Current Local storage binding is not committed yet")}const REGISTRATION_USERNAME_MIN_LENGTH=3,REGISTRATION_USERNAME_MAX_LENGTH=63,REGISTRATION_USERNAME_PATTERN=/^[a-z0-9-]+$/;function normalizeRegistrationUsername(n){return n.trim().toLowerCase()}function getRegistrationUsernameError(n){const e=normalizeRegistrationUsername(n);if(!e)return xpodRegistrationCopy.usernameRequired;if(e.length<REGISTRATION_USERNAME_MIN_LENGTH||e.length>REGISTRATION_USERNAME_MAX_LENGTH)return xpodRegistrationCopy.usernameLength;if(!REGISTRATION_USERNAME_PATTERN.test(e))return xpodRegistrationCopy.usernameCharset;if(e.startsWith("-")||e.endsWith("-"))return xpodRegistrationCopy.usernameHyphen}function deriveFirstPodNameCandidate(n){for(const e of n){if(!e)continue;const t=derivePodSegment(e);if(!t)continue;const i=normalizeRegistrationUsername(t).replace(/[^a-z0-9-]/gu,"-").replace(/-+/gu,"-").replace(/^-+|-+$/gu,"");if(i&&!getRegistrationUsernameError(i))return i}return""}async function createFirstPodAndWaitForBinding(n){const e=n.fetchImpl??fetch,t=normalizeRegistrationUsername(n.username),i=getRegistrationUsernameError(t);if(i)throw new Error(i);const s=await resolveProvisionCodeForPodCreate(n.provisionCode),a=await resolveHostedAccountControlUrl(n.createPodUrl,e,n.trustedAccountIndex);if(!a)throw new Error("Pod creation control is not hosted by this Xpod");const l=await prepareFirstPodProvision(e,t,s),u=await e(scopeAccountUrl(a),{method:"POST",headers:{...n.headers,Accept:"application/json","Content-Type":"application/json"},credentials:"include",body:JSON.stringify(buildPodCreatePayload(t,l?.provisionCode??s,l?.provisionReceipt))});if(!u.ok){const g=await readResponseMessage(u);throw u.status===409||isPodNameConflict(g)?new Error(xpodRegistrationCopy.podNameTaken):new Error(g||"Failed to create Pod")}const f=await u.json().catch(()=>{}),d=extractCreatedBindings(f);if(!n.pickWebIdUrl)return d;const p=await waitForConsentBindings({fetchImpl:e,headers:n.headers,maxAttempts:n.maxAttempts,pickWebIdUrl:n.pickWebIdUrl,pollIntervalMs:n.pollIntervalMs});return p.length>0?p:d}async function waitForConsentBindings(n){const e=n.fetchImpl??fetch,t=Math.max(1,n.maxAttempts??30),i=Math.max(0,n.pollIntervalMs??500);for(let s=0;s<t;s+=1){const a=await fetchConsentBindings(e,n.pickWebIdUrl,n.headers);if(a.length>0)return a;s<t-1&&i>0&&await new Promise(l=>setTimeout(l,i))}return[]}async function fetchConsentBindings(n,e,t){const i=await n(scopeAccountUrl(e),{headers:t,credentials:"include"}).catch(()=>{});if(!i?.ok)return[];const s=await i.json().catch(()=>{});if(!Array.isArray(s?.entries))return[];const a=new Set,l=[];for(const u of s.entries){if(!isRecord(u)||typeof u.webId!="string"||typeof u.storageUrl!="string")continue;const f=normalizeBinding(u.webId,u.storageUrl);if(!f)continue;const d=`${f.webId}
308
- ${f.storageUrl}`;a.has(d)||(a.add(d),l.push(f))}return l}async function readResponseMessage(n){const e=await n.text?.().catch(()=>{});if(e)try{const t=JSON.parse(e);return typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:e}catch{return e}}function isPodNameConflict(n){return n?/already (?:is )?(?:a )?resource/iu.test(n)||/already taken/iu.test(n)||/already exists/iu.test(n):!1}async function prepareFirstPodProvision(n,e,t){try{return await prepareProvisionedPod(n,e,t)}catch(i){const s=i instanceof Error?i.message:String(i);throw isPodNameConflict(s)?new Error(xpodRegistrationCopy.podNameTaken):i}}function extractCreatedBindings(n){if(typeof n?.podUrl!="string")return[];const e=normalizeStorageUrl(n.podUrl);if(!e)return[];const t=new Set;if(typeof n.webId=="string"&&n.webId.length>0&&t.add(n.webId),Array.isArray(n.webIds))for(const i of n.webIds)typeof i=="string"&&i.length>0&&t.add(i);return Array.from(t).map(i=>normalizeBinding(i,e)).filter(i=>!!i)}function derivePodSegment(n){try{return new URL(n).pathname.split("/").filter(Boolean)[0]}catch{return n.includes("@")?n.split("@",1)[0]:n}}function normalizeBinding(n,e){try{const t=new URL(n),i=new URL(e);return!["http:","https:"].includes(t.protocol)||!["http:","https:"].includes(i.protocol)?void 0:(i.pathname=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`,{webId:t.href,storageUrl:i.href})}catch{return}}function normalizeStorageUrl(n){try{const e=new URL(n);return!["http:","https:"].includes(e.protocol)||e.username||e.password||e.hash||e.search?void 0:(e.pathname=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`,e.href)}catch{return}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function resolveConsentStorageBindings(n,e=[]){if(!Array.isArray(n))return[];const t=[];for(const i of n){if(!isRecord$1(i)||typeof i.webId!="string"||typeof i.storageUrl!="string")continue;const s=normalizeConsentBinding(i.webId,i.storageUrl,typeof i.label=="string"?i.label:void 0);if(!s)continue;const a=`${s.webId}
307
+ ${f.storageUrl}`;s.has(d)||(s.add(d),i.push(f))}return i}function resolveOrigin(n){try{return new URL(n??(typeof window>"u"?"http://localhost":window.location.origin)).origin}catch{throw new AccountStorageBindingsError("cross-origin","Current Xpod origin is invalid")}}function parseControlUrl(n,e){try{const t=new URL(n,e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.hash)throw new Error("unsafe control URL");return t}catch{throw new AccountStorageBindingsError("cross-origin","Account storage bindings control is not a valid URL")}}function normalizeWebId(n){if(!hasInvalidWebIdWhitespace(n))try{const e=new URL(n);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:n}catch{return}}function normalizeStorageUrl$1(n,e){try{const t=new URL(n.trim());return e!==void 0&&t.origin!==e||!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash?void 0:(t.pathname=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,t.href)}catch{return}}function isTrustedAccountControl(n,e,t){if(!e)return!1;try{const i=new URL(e,t);return i.pathname.startsWith("/.account/")&&n.origin===i.origin&&n.pathname.startsWith("/.account/")}catch{return!1}}function isRecord$2(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function isRecord$1(n){return typeof n=="object"&&n!==null}class RegistrationError extends Error{code;constructor(e,t){super(e),this.name="RegistrationError",this.code=t}}async function readErrorMessage(n){const e=await n.json().catch(()=>{});return e?.message||e?.error}async function loginAccountPassword(n){const t=await(n.fetchImpl??fetch)(scopeAccountUrl(n.loginUrl),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({email:n.email,password:n.password,...n.remember===void 0?{}:{remember:n.remember}})});if(!t.ok){const a=await readErrorMessage(t);throw n.duplicateEmailRecovery?new RegistrationError(xpodRegistrationCopy.emailAlreadyRegisteredPasswordMismatch,"EMAIL_ALREADY_REGISTERED"):new Error(a||"Auto-login failed")}const i=await t.json().catch(()=>({})),s=typeof i.authorization=="string"?i.authorization:"";if(!s)throw new Error("Account token not returned after login");return{accountToken:s}}class PasswordLoginStatusError extends Error{status;constructor(e){super(`Password login failed with status ${e}`),this.name="PasswordLoginStatusError",this.status=e}}function XpodAccountCredentials({surface:n,onAuthenticated:e,initialEmail:t}){const{controls:i,idpIndex:s,refetchControls:a}=useAuth(),[l,u]=reactExports.useState({email:t!==void 0?t:readPendingXpodAccountEmail(void 0,s)??"",password:""}),[f,d]=reactExports.useState(),[p,g]=reactExports.useState(!1),[m,v]=reactExports.useState(!0),S=reactExports.useRef(!1),E=async C=>{if(!S.current){S.current=!0,g(!0),d(void 0);try{const T=await resolveHostedAccountControlUrl(i?.password?.login,fetch,s)??scopeAccountUrl("/.account/login/password/"),F=await loginAccountPassword({email:C.email?.trim()??"",password:C.password,loginUrl:T,remember:m,fetchImpl:async(M,O)=>{const Q=await fetch(typeof M=="string"||M instanceof URL?scopeAccountUrl(M):M,O);if(!Q.ok)throw new PasswordLoginStatusError(Q.status);return Q}});storeAccountSessionToken(F.accountToken),rememberPendingXpodAccountEmail(C.email?.trim()??"",void 0,s);const P=await a();if(P?.status!=="authenticated"){P?.status==="anonymous"&&clearAccountSessionToken(),d("登录失败,请重试。");return}await e?.()}catch(T){d(T instanceof PasswordLoginStatusError?safeXpodLoginMessage(T.status):safeXpodLoginMessage(500))}finally{S.current=!1,g(!1)}}},w=C=>{u(C),f&&d(void 0)},A={surface:"page",surfaceTitle:"登录 Xpod",copy:xpodAccountCredentialsCopy,footer:n==="embedded"?void 0:jsxRuntimeExports.jsx(AccountEntryLinks,{}),mode:"login",values:l,onChange:w,onSubmit:E,pending:p,rememberAccount:m,onRememberAccountChange:v,errors:f?{form:f}:void 0};return n==="embedded"?jsxRuntimeExports.jsx(AccountCredentialsView,{...A,presentation:"compact",frame:"bare",showHeader:!1}):jsxRuntimeExports.jsx(XpodBlockingAccountCredentialsSurface,{...A})}function AccountEntryLinks(){let n="";try{const e=normalizeXpodReturnTo(`${window.location.pathname}${window.location.search}`);e&&(n=`?${new URLSearchParams({returnTo:e})}`)}catch{}return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-center gap-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/register/${n}`),children:"创建账号"})}),jsxRuntimeExports.jsx("span",{"aria-hidden":"true",className:"text-border",children:"·"}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto px-2 py-1 text-xs font-normal text-muted-foreground hover:text-foreground",children:jsxRuntimeExports.jsx("a",{href:scopeAccountUrl(`/.account/login/password/forgot/${n}`),children:xpodAccountPageCopy.forgotPassword})})]})}function AccountWorkspaceBoundary({children:n}){return useXpodSolidRuntimeContext().state.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):jsxRuntimeExports.jsx(AccountAuthBoundary,{children:n})}function AccountAuthBoundary({children:n,accountState:e,retry:t,surface:i="page"}){const s=useAuth(),a=e??s.accountState,l=t??s.retry;return a.status==="authenticated"?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n}):a.status==="submitting"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在登录…"]})}):a.status==="initializing"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{role:"status","aria-live":"polite",className:"flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"正在加载账号"]})}):a.status==="error"?jsxRuntimeExports.jsx(LoginSurface,{surface:i,children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:a.message}),jsxRuntimeExports.jsx(Button,{className:"w-full",type:"button",onClick:()=>{l()},children:"重试"}),jsxRuntimeExports.jsx(DesktopLoginReturnAction,{})]})}):i==="embedded"?jsxRuntimeExports.jsxs(LoginSurface,{surface:i,children:[jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"embedded"}),jsxRuntimeExports.jsx("div",{className:"mt-6 space-y-3 border-t pt-5",children:jsxRuntimeExports.jsx(AccountEntryLinks,{})})]}):jsxRuntimeExports.jsx(XpodAccountCredentials,{surface:"page"})}function LoginSurface({children:n,surface:e}){return e==="embedded"?jsxRuntimeExports.jsx(WebAccountLayout,{title:"登录 Xpod",presentation:"compact",children:n}):jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:"登录 Xpod",presentation:"compact",children:n})}function AppLayout({navigation:n,children:e,className:t}){return jsxRuntimeExports.jsxs("section",{className:cn("grid h-screen min-h-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_64px] bg-background sm:grid-cols-[60px_minmax(0,1fr)] sm:grid-rows-[minmax(0,1fr)]",t),"data-app-layout":"workspace",children:[jsxRuntimeExports.jsx("aside",{className:"row-start-2 min-h-0 overflow-x-auto overflow-y-hidden border-t border-border/50 bg-layout-sidebar sm:col-start-1 sm:row-start-1 sm:overflow-hidden sm:border-r sm:border-t-0","data-app-layout-navigation":!0,children:n}),jsxRuntimeExports.jsx("div",{className:"col-start-1 row-start-1 min-h-0 min-w-0 overflow-hidden bg-layout-content sm:col-start-2","data-app-layout-content":!0,children:e})]})}const globalNavigationItems=[{id:"ai-connections",label:"AI Connections",href:canonicalRoutes.aiConnections,activePaths:["/ai-connections"],placement:"primary",icon:Sparkles},{id:"ai-config",label:"AI Config",href:canonicalRoutes.aiConfig,activePaths:["/ai-config"],placement:"primary",icon:BrainCircuit},{id:"network",label:"Network",href:canonicalRoutes.network,activePaths:["/network"],placement:"bottom",icon:Globe},{id:"status",label:"Status",href:canonicalRoutes.status,activePaths:["/status"],placement:"bottom",icon:Gauge},{id:"settings",label:"Settings",href:canonicalRoutes.settings,activePaths:["/settings"],placement:"bottom",icon:Settings}];function isGlobalNavigationItemActive(n,e){const t=e.replace(/\/+$/,"")||"/";return n.activePaths.some(i=>t===i||t.startsWith(`${i}/`))}function accountCardPosition(n,e,t){const l=e>=640,u=Math.min(360,e-16);if(l){const d=Math.max(8,Math.min(n.top,t-240-8));return{left:Math.max(8,Math.min(n.right+12,e-u-8)),top:d,width:u,maxHeight:Math.max(240,t-d-8)}}const f=Math.max(72,t-n.top+12);return{left:8,bottom:f,width:u,maxHeight:Math.max(240,t-f-8)}}function XpodUserCard(){const n=useAuth(),e=reactExports.useContext(XpodSolidRuntimeContext),t=n.isLoggedIn&&n.accountState.status==="authenticated",i=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),s=t||i,[a,l]=reactExports.useState(accountCardRequestedByUrl(s)),[u,f]=reactExports.useState(),[d,p]=reactExports.useState(),[g,m]=reactExports.useState(),v=reactExports.useRef(null),S=reactExports.useRef(null),E=reactExports.useRef(void 0),w=reactExports.useId(),A=n.identity,C=readPendingXpodAccountEmail(),T=readRememberedXpodLogin()?.account,F=t?accountCardIdentityFallback(A,C,T):void 0,P=useXpodProfileCardIdentity({accountIdentity:F,runtime:i?e:void 0}),M=P.displayName,O=initialsFor(P.displayName),Q=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),pe=accountHandle(P.username,i?void 0:F?.id,Q),q=e?.selectedStorage?.storageUrl??e?.podUrl,ee=e?.selectedStorage,_e=e?.currentPod,te=reactExports.useMemo(()=>q?podNameFromUrl(q):void 0,[q]),Ie=e?.state.status==="authenticated"&&!!(Q&&q&&ee&&_e)&&ee?.webId===Q&&sameUrl$1(ee?.storageUrl??"",q??"")&&_e?.webId===Q&&sameUrl$1(_e?.podUrl??"",q??""),De=s,de=a&&De,Oe=reactExports.useCallback(H=>{l(H),H||(m(void 0),clearAccountCardRequest())},[]);reactExports.useLayoutEffect(()=>{if(!de)return;const H=()=>{const fe=S.current;fe&&m(accountCardPosition(fe.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return H(),window.addEventListener("resize",H),window.addEventListener("scroll",H,!0),window.visualViewport?.addEventListener("resize",H),()=>{window.removeEventListener("resize",H),window.removeEventListener("scroll",H,!0),window.visualViewport?.removeEventListener("resize",H)}},[de]),reactExports.useEffect(()=>{if(!De){clearAccountCardRequest();return}if(!de)return;const H=ae=>{const Pe=ae.target;Pe instanceof Node&&(v.current?.contains(Pe)||S.current?.contains(Pe)||Oe(!1))},fe=ae=>{ae.key==="Escape"&&(Oe(!1),S.current?.focus())};return document.addEventListener("pointerdown",H),document.addEventListener("keydown",fe),()=>{document.removeEventListener("pointerdown",H),document.removeEventListener("keydown",fe)}},[De,de,Oe]),reactExports.useEffect(()=>{!de||!g||v.current?.focus({preventScroll:!0})},[de,g]),reactExports.useEffect(()=>()=>{E.current!==void 0&&window.clearTimeout(E.current)},[]);const le=async()=>{f("logout"),Oe(!1);try{await logoutXpodProduct(n,e),(n.isAnonymous?.()??!0)&&Oe(!1)}catch{}finally{f(void 0)}},Ae=async()=>{f("switch"),Oe(!1);try{await logoutXpodProduct(n,e,{onComplete:()=>{clearRememberedXpodLogin();const H=new URL(XPOD_DEFAULT_RETURN_PATH,window.location.origin);H.searchParams.set("xpod-login","switch"),window.location.assign(H)}}),Oe(!1)}catch{}finally{f(void 0)}},$=async()=>{const H=P.webId??pe;try{await navigator.clipboard.writeText(H),p("Copied")}catch{p("Copy failed")}E.current!==void 0&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>p(void 0),1800)};return De?jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("button",{ref:S,type:"button","aria-label":s?`Open account menu for ${M}`:"Open account menu","aria-expanded":de,"aria-controls":de?w:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":Ie?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>Oe(!de),children:[jsxRuntimeExports.jsxs(Avatar,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:O})]}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s?M:"Not signed in"})]}),de&&typeof document<"u"?reactDomExports.createPortal(jsxRuntimeExports.jsx("section",{ref:v,id:w,role:"region",tabIndex:-1,"aria-label":s?M:"Xpod account","data-avatar-card":"true","data-selected-pod-url":q,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[jsxRuntimeExports.jsxs(Avatar,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[P.avatarUrl?jsxRuntimeExports.jsx(AvatarImage,{src:P.avatarUrl,alt:M}):null,jsxRuntimeExports.jsx(AvatarFallback,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:O})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[jsxRuntimeExports.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:M}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"shrink-0 opacity-70",children:"Xpod ID"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono font-medium",children:pe}),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:()=>{$()},children:jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3","aria-hidden":"true"})}),d?jsxRuntimeExports.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:d}):null]}),jsxRuntimeExports.jsxs("div",{className:"mt-2.5 inline-flex items-center gap-1.5 rounded-full bg-emerald-500/10 px-2 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300",children:[jsxRuntimeExports.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Ie?"bg-emerald-500":"bg-muted-foreground/50"}`,"aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{children:Ie?"Pod connected":i?"WebID connected":"Account connected"})]})]})]}),P.note||P.region?jsxRuntimeExports.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[P.note?jsxRuntimeExports.jsx("p",{className:"line-clamp-2 text-foreground/85",children:P.note}):null,P.region?jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:P.region}):null]}):null,jsxRuntimeExports.jsx("div",{className:"border-t border-border/40 p-2",children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:jsxRuntimeExports.jsxs("a",{href:"/settings/pod","aria-label":"Pod settings",children:[jsxRuntimeExports.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:jsxRuntimeExports.jsx(Database,{className:"h-4 w-4","aria-hidden":"true"})}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[jsxRuntimeExports.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:podDisplayName(te)}),jsxRuntimeExports.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:["Personal Pod · ",podHost(q)]})]}),Ie?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:()=>{Ae()},disabled:u!==void 0,children:[u==="switch"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Switch account"]}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{le()},disabled:u!==void 0,children:[u==="logout"?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sign out"]})]})]})}),document.body):null]}):null}function accountCardIdentityFallback(n,e,t){if(n?.displayName||n?.username||n?.id||n?.webId)return n;const i=e||(t&&"email"in t&&typeof t.email=="string"?t.email:void 0);if(!i&&!t)return n;const s=t?.username||usernameFromEmail(i);return{...t??{},...s?{username:s}:{},...t?.displayName?{displayName:t.displayName}:{displayName:s||i||"Xpod account"}}}function usernameFromEmail(n){if(n)return n.split("@")[0]?.trim()||void 0}function accountHandle(n,e,t){const i=n||e||usernameFromWebId(t);return i?i.startsWith("@")?i:`@${i}`:"Xpod member"}function initialsFor(n){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():n.slice(0,2).toUpperCase()||"XP"}function podNameFromUrl(n){try{return new URL(n).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function podDisplayName(n){return n?`${n} Pod`:"My Pod"}function podHost(n){if(!n)return"No Pod connected";try{return new URL(n).host}catch{return"Pod storage"}}function usernameFromWebId(n){if(n)try{return new URL(n).pathname.split("/").filter(Boolean).at(0)}catch{return}}function sameUrl$1(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function accountCardRequestedByUrl(n){return n?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function clearAccountCardRequest(){if(typeof window>"u")return;const n=new URL(window.location.href);n.searchParams.get("account")==="open"&&(n.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${n.pathname}${n.search}${n.hash}`))}function handleListNavigationKeyDown(n){if(!["ArrowDown","ArrowUp","Home","End"].includes(n.key))return;const e=n.currentTarget.closest("[data-list-navigation]")??n.currentTarget.closest("nav");if(!e)return;const t=[...e.querySelectorAll('a[href]:not([aria-disabled="true"])')],i=t.indexOf(n.currentTarget);if(i<0||t.length===0)return;n.preventDefault();const s=n.key==="Home"?0:n.key==="End"?t.length-1:n.key==="ArrowDown"?(i+1)%t.length:(i-1+t.length)%t.length;t[s]?.focus()}const navItemBaseClass="rounded-lg transition-colors",navItemInteractiveClass="text-foreground hover:bg-accent/60",navItemFocusClass="focus:outline-none focus:ring-0 focus-visible:bg-accent/70";function getRailNavItemClass(n){return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":`text-foreground ${navItemInteractiveClass}`,"h-9 w-9 rounded-lg p-0",n?"":"mx-2","flex items-center justify-center"].join(" ")}function getListNavItemClass(n,e){const t=e?.compact===!0;return[navItemBaseClass,navItemFocusClass,n?"bg-accent text-accent-foreground":"",t?"rounded-lg px-2 py-2":"rounded-lg px-3 py-2.5","mx-2 flex items-center gap-3 text-sm transition-colors",n?"font-medium":`${navItemInteractiveClass} text-foreground`].join(" ")}function ProductNavLinks({items:n,label:e}){const i=useLocation().pathname;return jsxRuntimeExports.jsx("nav",{"aria-label":e,className:"flex flex-row items-center gap-3 sm:flex-col sm:gap-4",children:n.map(s=>{const a=s.icon,l=s.href??s.path??"/",u=s.activePaths?isGlobalNavigationItemActive(s,i):i===s.path||i.startsWith(`${s.path}/`);return jsxRuntimeExports.jsxs(Link,{to:l,"aria-label":s.label,"aria-current":u?"page":void 0,"data-list-item":"true",title:s.label,onKeyDown:handleListNavigationKeyDown,className:clsx(getRailNavItemClass(u),"text-sm"),children:[jsxRuntimeExports.jsx(a,{className:"h-6 w-6","aria-hidden":"true"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:s.label})]},s.id)})})}function XpodProductLayout({product:n}){const e=globalNavigationItems.filter(i=>i.placement==="primary"),t=globalNavigationItems.filter(i=>i.placement==="bottom");return jsxRuntimeExports.jsx(AppLayout,{className:`xpod-${n}-shell`,navigation:jsxRuntimeExports.jsxs("div",{className:"flex h-full w-full flex-row items-center px-2 sm:min-h-full sm:flex-col sm:px-0 sm:py-4","data-list-navigation":!0,children:[jsxRuntimeExports.jsx("div",{className:"mr-1 shrink-0 sm:mr-0 sm:ml-2 sm:mb-2",children:jsxRuntimeExports.jsx(XpodUserCard,{})}),jsxRuntimeExports.jsx("div",{className:"flex min-w-0 flex-1 flex-row items-center justify-center sm:mt-5 sm:flex-none sm:flex-col sm:justify-start",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:e,label:"Primary Xpod workspaces"})}),jsxRuntimeExports.jsx("div",{className:"flex shrink-0 flex-row items-center gap-3 sm:mt-auto sm:flex-col sm:gap-0",children:jsxRuntimeExports.jsx(ProductNavLinks,{items:t,label:"Xpod settings"})})]}),children:jsxRuntimeExports.jsx("div",{className:"flex h-full min-h-0 flex-col bg-background",children:jsxRuntimeExports.jsx(Outlet,{})})})}function XpodDashboardLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"dashboard"})}function RouteLoadingBoundary({children:n}){return jsxRuntimeExports.jsx(RouteChunkErrorBoundary,{children:jsxRuntimeExports.jsx(reactExports.Suspense,{fallback:jsxRuntimeExports.jsx("div",{className:"p-6 text-sm text-muted-foreground",children:"正在打开…"}),children:n})})}class RouteChunkErrorBoundary extends reactExports.Component{state={};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error("Route module failed to load",e,t.componentStack)}render(){if(!this.state.error)return this.props.children;const e=/Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk .* failed/i.test(this.state.error.message);return jsxRuntimeExports.jsxs("div",{className:"mx-auto flex min-h-64 max-w-md flex-col items-start justify-center gap-3 p-6",children:[jsxRuntimeExports.jsx("div",{className:"text-base font-medium",children:e?"页面已更新":"页面暂时无法打开"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:e?"当前窗口仍在使用旧版页面资源,请重新载入。":"页面加载遇到了问题,请重试。这不表示登录已失效。"}),!1,jsxRuntimeExports.jsx("button",{type:"button",className:"rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground",onClick:()=>window.location.reload(),children:"重新载入"})]})}}const LogsPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-kju2k4Dp.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.LogsPage}))),RdfPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-kju2k4Dp.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.RdfPage}))),StatusPage=reactExports.lazy(()=>__vitePreload(()=>import("./index-kju2k4Dp.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(n=>({default:n.StatusPage}))),NetworkPage=reactExports.lazy(()=>__vitePreload(()=>import("./NetworkPage-DkVgxtNj.js"),__vite__mapDeps([7,8,9,2,10,3,11,12,5]))),StatusWorkspace=reactExports.lazy(()=>__vitePreload(()=>import("./StatusWorkspace-DGcTbHT5.js"),__vite__mapDeps([13,2,9,8,10]))),ServiceStatusPanel=reactExports.lazy(()=>__vitePreload(()=>import("./StatusSubjectPanel-DNsW76aC.js"),__vite__mapDeps([14,1,3])).then(n=>({default:n.ServiceStatusPanel}))),IndexSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexSubjectPanel-CDwT4Yx1.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:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},statusWorkspaceRoute(statusContentRoutes),{path:"runtime",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"rdf",element:jsxRuntimeExports.jsx(Navigate,{to:"index/rdf",replace:!0})},{path:"network/*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"status",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"../overview",replace:!0})}]}]}],statusSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{element:jsxRuntimeExports.jsx(AccountAuthBoundary,{surface:"embedded",children:jsxRuntimeExports.jsx(Outlet,{})}),children:[statusWorkspaceRoute([{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})},...statusContentRoutes,{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:"overview",replace:!0})}])]}]}],networkSurfaceRoutes=[{element:jsxRuntimeExports.jsx(XpodDashboardLayout,{}),children:[{index:!0,element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))},{path:"*",element:lazyRoute$1(jsxRuntimeExports.jsx(NetworkPage,{}))}]}];function XpodSettingsLayout(){return jsxRuntimeExports.jsx(XpodProductLayout,{product:"settings"})}async function waitForCurrentAccountStorageBindings(n){const e=Math.max(1,n.maxAttempts??20);for(let t=0;t<e;t+=1){const i=(await fetchAccountStorageBindings(n)).filter(s=>storageUrlBelongsToRoot(s.storageUrl,n.storageRoot));if(i.length>0)return i;t+1<e&&await new Promise(s=>setTimeout(s,Math.max(0,n.pollIntervalMs??500)))}throw new Error("Current Local storage binding is not committed yet")}const REGISTRATION_USERNAME_MIN_LENGTH=3,REGISTRATION_USERNAME_MAX_LENGTH=63,REGISTRATION_USERNAME_PATTERN=/^[a-z0-9-]+$/;function normalizeRegistrationUsername(n){return n.trim().toLowerCase()}function getRegistrationUsernameError(n){const e=normalizeRegistrationUsername(n);if(!e)return xpodRegistrationCopy.usernameRequired;if(e.length<REGISTRATION_USERNAME_MIN_LENGTH||e.length>REGISTRATION_USERNAME_MAX_LENGTH)return xpodRegistrationCopy.usernameLength;if(!REGISTRATION_USERNAME_PATTERN.test(e))return xpodRegistrationCopy.usernameCharset;if(e.startsWith("-")||e.endsWith("-"))return xpodRegistrationCopy.usernameHyphen}function deriveFirstPodNameCandidate(n){for(const e of n){if(!e)continue;const t=derivePodSegment(e);if(!t)continue;const i=normalizeRegistrationUsername(t).replace(/[^a-z0-9-]/gu,"-").replace(/-+/gu,"-").replace(/^-+|-+$/gu,"");if(i&&!getRegistrationUsernameError(i))return i}return""}async function createFirstPodAndWaitForBinding(n){const e=n.fetchImpl??fetch,t=normalizeRegistrationUsername(n.username),i=getRegistrationUsernameError(t);if(i)throw new Error(i);const s=await resolveProvisionCodeForPodCreate(n.provisionCode),a=await resolveHostedAccountControlUrl(n.createPodUrl,e,n.trustedAccountIndex);if(!a)throw new Error("Pod creation control is not hosted by this Xpod");const l=await prepareFirstPodProvision(e,t,s),u=await e(scopeAccountUrl(a),{method:"POST",headers:{...n.headers,Accept:"application/json","Content-Type":"application/json"},credentials:"include",body:JSON.stringify(buildPodCreatePayload(t,l?.provisionCode??s,l?.provisionReceipt))});if(!u.ok){const g=await readResponseMessage(u);throw u.status===409||isPodNameConflict(g)?new Error(xpodRegistrationCopy.podNameTaken):new Error(g||"Failed to create Pod")}const f=await u.json().catch(()=>{}),d=extractCreatedBindings(f);if(!n.pickWebIdUrl)return d;const p=await waitForConsentBindings({fetchImpl:e,headers:n.headers,maxAttempts:n.maxAttempts,pickWebIdUrl:n.pickWebIdUrl,pollIntervalMs:n.pollIntervalMs});return p.length>0?p:d}async function waitForConsentBindings(n){const e=n.fetchImpl??fetch,t=Math.max(1,n.maxAttempts??30),i=Math.max(0,n.pollIntervalMs??500);for(let s=0;s<t;s+=1){const a=await fetchConsentBindings(e,n.pickWebIdUrl,n.headers);if(a.length>0)return a;s<t-1&&i>0&&await new Promise(l=>setTimeout(l,i))}return[]}async function fetchConsentBindings(n,e,t){const i=await n(scopeAccountUrl(e),{headers:t,credentials:"include"}).catch(()=>{});if(!i?.ok)return[];const s=await i.json().catch(()=>{});if(!Array.isArray(s?.entries))return[];const a=new Set,l=[];for(const u of s.entries){if(!isRecord(u)||typeof u.webId!="string"||typeof u.storageUrl!="string")continue;const f=normalizeBinding(u.webId,u.storageUrl);if(!f)continue;const d=`${f.webId}
308
+ ${f.storageUrl}`;a.has(d)||(a.add(d),l.push(f))}return l}async function readResponseMessage(n){const e=await n.text?.().catch(()=>{});if(e)try{const t=JSON.parse(e);return typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:e}catch{return e}}function isPodNameConflict(n){return n?/already (?:is )?(?:a )?resource/iu.test(n)||/already taken/iu.test(n)||/already exists/iu.test(n):!1}async function prepareFirstPodProvision(n,e,t){try{return await prepareProvisionedPod(n,e,t)}catch(i){const s=i instanceof Error?i.message:String(i);throw isPodNameConflict(s)?new Error(xpodRegistrationCopy.podNameTaken):i}}function extractCreatedBindings(n){if(typeof n?.podUrl!="string")return[];const e=normalizeStorageUrl(n.podUrl);if(!e)return[];const t=new Set;if(typeof n.webId=="string"&&n.webId.length>0&&t.add(n.webId),Array.isArray(n.webIds))for(const i of n.webIds)typeof i=="string"&&i.length>0&&t.add(i);return Array.from(t).map(i=>normalizeBinding(i,e)).filter(i=>!!i)}function derivePodSegment(n){try{return new URL(n).pathname.split("/").filter(Boolean)[0]}catch{return n.includes("@")?n.split("@",1)[0]:n}}function normalizeBinding(n,e){if(!hasInvalidWebIdWhitespace(n))try{const t=new URL(n),i=new URL(e);return!["http:","https:"].includes(t.protocol)||!["http:","https:"].includes(i.protocol)?void 0:(i.pathname=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`,{webId:n,storageUrl:i.href})}catch{return}}function normalizeStorageUrl(n){try{const e=new URL(n);return!["http:","https:"].includes(e.protocol)||e.username||e.password||e.hash||e.search?void 0:(e.pathname=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`,e.href)}catch{return}}function isRecord(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function resolveConsentStorageBindings(n,e=[]){if(!Array.isArray(n))return[];const t=[];for(const i of n){if(!isRecord$1(i)||typeof i.webId!="string"||typeof i.storageUrl!="string")continue;const s=normalizeConsentBinding(i.webId,i.storageUrl,typeof i.label=="string"?i.label:void 0);if(!s)continue;const a=`${s.webId}
309
309
  ${s.storageUrl}`,l=t.find(u=>`${u.webId}
310
- ${u.storageUrl}`===a);l?l.label!==void 0&&s.label!==void 0&&l.label!==s.label&&t.push(s):t.push(s)}return t}function normalizeConsentBinding(n,e,t){if(!hasInvalidWebIdWhitespace(n))try{const i=new URL(n),s=new URL(e.trim());return!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol)||i.username||i.password||s.username||s.password||s.search||s.hash?void 0:(s.pathname=s.pathname.endsWith("/")?s.pathname:`${s.pathname}/`,{webId:n,storageUrl:s.href,...t?{label:t}:{}})}catch{return}}function safeStorageError(n,e){const t=n instanceof Error?n.message:"";return t==="fetch failed"||t.includes("Failed to fetch")||t.includes("Cloud storage is not ready")||t.includes("provision_refresh_failed")||t.includes("provision_refresh_unavailable")||t===xpodFirstPodErrors.cloudRouteUnavailable?xpodFirstPodErrors.cloudRouteUnavailable:t.startsWith("Pod name is already taken.")||t===xpodRegistrationCopy.choosePodName||t===xpodRegistrationCopy.podNameTaken?t:e}function markFirstPodStage(n){}function FirstPodPage({onReady:n}={}){const{controls:e,hasOidcPending:t,idpIndex:i,identity:s,refetchControls:a}=useAuth(),l=useNavigate(),[u,f]=reactExports.useState({status:"checking"}),[d,p]=reactExports.useState(0),g=!n&&t?new URL("oidc/pick-webid/",i).href:void 0;return reactExports.useEffect(()=>{let m=!1;return(async()=>{try{const v=g?await loadPendingOidcStorageBindings(g):void 0;if(m)return;if(v?.bindings.length){l(scopeAccountUrl("/.account/oidc/consent/"),{replace:!0});return}const S=await resolveCurrentProvisionTarget();if(m)return;const E=v?{allWebIds:v.webIds,currentStorageWebIds:[],currentBindings:[],durable:!1}:await loadCurrentStorageWebIds({accountBindingsUrl:e?.account?.bindings,accountWebIdUrl:e?.account?.webId,idpIndex:i,provisionCode:S.activeProvisionCode,provisionStorageRoot:S.storageRoot});if(m)return;if(!v&&E.currentStorageWebIds.length>0&&(!n||E.durable)){if(n){if(!S.storageRoot)throw new Error(xpodFirstPodErrors.cloudRouteUnavailable);await waitForCurrentAccountStorageBindings({controls:{account:{bindings:e?.account?.bindings}},trustedAccountIndex:i,storageRoot:S.storageRoot}),m||n()}else l(scopeAccountUrl("/.account/account/"),{replace:!0});return}if(S.storageRoot&&!S.activeProvisionCode)throw new Error(xpodFirstPodErrors.cloudRouteUnavailable);const w=await resolveProvisionCodeForCurrentScope(S.activeProvisionCode);if(m)return;const C=(n&&E.currentBindings.length>0?existingScopedPodName(E.currentBindings,S.storageRoot):void 0)??(deriveFirstPodNameCandidate([e?.account?.username,s?.username,s?.displayName,s?.webId,...E.allWebIds,readPendingXpodAccountEmail(void 0,i)])||e?.account?.username),T=e?.account?.pod;if(!C)throw new Error(xpodFirstPodErrors.accountIdentityMissing);if(!T)throw new Error(xpodFirstPodErrors.createEndpointMissing);f({status:"creating"});const F=await createFirstPodAndWaitForBinding({createPodUrl:T,headers:storedAccountTokenHeaders(),pickWebIdUrl:g,provisionCode:w,trustedAccountIndex:i,username:C});if(m)return;if(!n&&t&&F.length===0){f({status:"waiting"});return}if(n){if(!S.storageRoot)throw new Error(xpodFirstPodErrors.cloudRouteUnavailable);f({status:"waiting"}),await waitForCurrentAccountStorageBindings({controls:{account:{bindings:e?.account?.bindings}},trustedAccountIndex:i,storageRoot:S.storageRoot}),m||n();return}if(await a(),m)return;l(scopeAccountUrl(t?"/.account/oidc/consent/":"/.account/account/"),{replace:!0})}catch(v){if(!m){const S=safeStorageError(v,xpodFirstPodErrors.checkFailed);f({status:"error",message:S})}}})(),()=>{m=!0}},[e?.account?.bindings,e?.account?.pod,e?.account?.username,e?.account?.webId,t,s?.displayName,s?.username,s?.webId,i,l,n,g,a,d]),jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:xpodFirstPodCopy.surfaceTitle,children:jsxRuntimeExports.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:u.status==="checking"?jsxRuntimeExports.jsx(WebAccountRestoringView,{label:xpodFirstPodCopy.restoring}):u.status==="creating"||u.status==="waiting"?jsxRuntimeExports.jsx(WebAccountRestoringView,{label:u.status==="creating"?xpodFirstPodCopy.creating:xpodFirstPodCopy.waitingMessage}):u.status==="error"?jsxRuntimeExports.jsx(WebAccountFailureView,{title:xpodFirstPodCopy.unavailableTitle,description:u.message,primaryLabel:xpodFirstPodCopy.retryLabel,onPrimary:()=>{f({status:"checking"}),p(m=>m+1)}}):null})})}async function loadPendingOidcStorageBindings(n){const e=await fetch(scopeAccountUrl(n),{headers:storedAccountTokenHeaders(),credentials:"include"});if(!e.ok)throw new Error(xpodConsentErrors.bindingsFailed);const t=await e.json().catch(()=>{});if(!t||!Array.isArray(t.entries))throw new Error(xpodConsentErrors.bindingsFailed);if(t.entries.length>0){for(const s of t.entries)if(resolveConsentStorageBindings([s]).length!==1)throw new Error(xpodConsentErrors.bindingsFailed)}const i=Array.isArray(t.webIds)?t.webIds.filter(s=>typeof s=="string"&&s.length>0):[];return{bindings:resolveConsentStorageBindings(t.entries,i),webIds:i}}async function loadCurrentStorageWebIds(n){let e;n.accountBindingsUrl&&(e=await fetchAccountStorageBindings({controls:{account:{bindings:n.accountBindingsUrl}},origin:window.location.origin,trustedAccountIndex:n.idpIndex}));const t=n.provisionStorageRoot&&e&&e.length>0?e.filter(f=>storageUrlBelongsToRoot(f.storageUrl,n.provisionStorageRoot)).map(f=>f.webId):[];if(t.length>0)return{allWebIds:Array.from(new Set(e.map(f=>f.webId))),currentStorageWebIds:Array.from(new Set(t)),currentBindings:e.filter(f=>storageUrlBelongsToRoot(f.storageUrl,n.provisionStorageRoot)),durable:!0};const i=e&&e.length>0?[]:await fetchAccountWebIds(n.accountWebIdUrl,n.idpIndex),s=Array.from(new Set([...e?.map(f=>f.webId)??[],...i]));if(n.provisionStorageRoot&&!n.provisionCode)return{allWebIds:s,currentStorageWebIds:[],currentBindings:[],durable:!1};if(!resolveProvisionScope(n.provisionCode))return{allWebIds:s,currentStorageWebIds:s,currentBindings:e??[],durable:!!e?.length};const l=await lookupProvisionScopedWebIds(fetch,s,n.provisionCode),u=Array.from(new Set((l??[]).map(f=>f.webId)));return{allWebIds:s,currentStorageWebIds:u,currentBindings:l??[],durable:!1}}async function fetchAccountWebIds(n,e){const t=await resolveHostedAccountControlUrl(n,fetch,e);if(!t)throw new Error(xpodFirstPodErrors.checkFailed);const i=await fetch(scopeAccountUrl(t),{headers:storedAccountTokenHeaders({Accept:"application/json"}),credentials:"include"}).catch(()=>{});if(!i?.ok)throw new Error(xpodFirstPodErrors.checkFailed);const s=await i.json().catch(()=>{});if(!s?.webIdLinks||typeof s.webIdLinks!="object"||Array.isArray(s.webIdLinks))throw new Error(xpodFirstPodErrors.checkFailed);return Object.keys(s.webIdLinks).filter(a=>{try{const l=new URL(a);return["http:","https:"].includes(l.protocol)&&!l.username&&!l.password}catch{return!1}})}function existingScopedPodName(n,e){const t=[...new Set(n.map(l=>l.storageUrl))];if(!e||t.length!==1)throw new Error(xpodFirstPodErrors.checkFailed);const i=t[0];if(!storageUrlBelongsToRoot(i,e))throw new Error(xpodFirstPodErrors.checkFailed);const s=new URL(e).pathname.replace(/\/?$/u,"/"),a=new URL(i).pathname.slice(s.length).split("/").filter(Boolean);if(a.length!==1)throw new Error(xpodFirstPodErrors.checkFailed);return decodeURIComponent(a[0])}function XpodLocalLoginPreflight({onReady:n}){const e=reactExports.useContext(AuthContext),t=reactExports.useRef(!1),i=e?.isInitializing===!0,s=isManagedLocalProvisionHost()&&e?.isLoggedIn===!0;return reactExports.useEffect(()=>{!i&&!s&&!t.current&&(t.current=!0,n())},[i,s,n]),i||!s?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在准备登录…"}):jsxRuntimeExports.jsx(FirstPodPage,{onReady:n})}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),a=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),m=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(m)}catch{return}};let u=!1;const f=p=>{try{return a.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const m=a.readSinglePending();m&&a.cancel(m.id)}catch{}return a.begin(p)}},d=async(p,g,m)=>{const v=l(p),S={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...m?{prompt:m}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},E=f(S);u=!0;try{await n.runtime.login(E)}catch(w){try{a.cancel(E.id)}catch{}throw w}finally{u=!1}return E};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=a.readSinglePending();p&&a.cancel(p.id)},readPending:()=>a.readSinglePending(),callbackUrl(){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary(n){return jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(WebIdAuthBoundaryContent,{...n})})}function WebIdAuthBoundaryContent({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useContext(AuthContext),s=reactExports.useSyncExternalStore(subscribeXpodProductLogout,isXpodAutomaticLoginBlocked,()=>!1),a=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),[l]=reactExports.useState(readXpodAccountSwitch),[u,f]=reactExports.useState(()=>l||readXpodLoginCancelled());reactExports.useLayoutEffect(()=>{l&&consumeXpodAccountSwitch()},[l]),reactExports.useEffect(()=>{if(u)try{a.cancelLogin()}catch{}},[u,a]);const d=runtimeState(t.state),p=storageSelectionState(t,d),g=d.status==="authenticated"&&p?.status==="ready",[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1),[w,A]=reactExports.useState(l?{prompt:"login"}:void 0),C=reactExports.useRef(0),[T,F]=reactExports.useState(!1),P=reactExports.useRef(!1),M=reactExports.useRef(!1),O=reactExports.useCallback($=>{console.error("[WebIdAuthBoundary] authentication action failed",$),v(actionFailureMessage)},[]),Q=reactExports.useCallback($=>{const H=++C.current;v(void 0),E(!0),$().catch(fe=>{H===C.current&&O(fe)}).finally(()=>{H===C.current&&E(!1)})},[O]),pe=reactExports.useCallback(()=>{setXpodLoginCancelled(!1),f(!1),v(void 0),A({})},[]),q=reactExports.useCallback(()=>{if(!w)return;const $=w.prompt;setXpodLoginCancelled(!1),f(!1),A(void 0),Q(async()=>{l&&await t.session.initialize({restorePreviousSession:!1}),await a.startLogin(void 0,void 0,$)})},[a,w,Q,t.session,l]),ee=()=>{if(T){te();return}d.status==="authenticated"?t.retryPodOpen?.():pe()},_e=()=>{if(!T){try{a.cancelLogin()}catch{}setXpodLoginCancelled(!0),f(!0),A(void 0),C.current+=1,E(!1),v(void 0)}},te=()=>Q(async()=>{F(!0);const $=()=>{setXpodLoginCancelled(!1),f(!1),clearRememberedXpodLogin(),v(void 0),A({prompt:"login"}),F(!1)};i?await logoutXpodProduct(i,t,{onComplete:$}):(await t.logout(),$())});if(reactExports.useEffect(()=>{t.state.status!=="loading"||P.current||(P.current=!0,t.session.initialize({restorePreviousSession:!u}).catch(O))},[u,O,t.session,t.state.status]),reactExports.useEffect(()=>{u||w||s||S||T||!e||M.current||d.status!=="anonymous"||(M.current=!0,pe())},[u,s,e,S,w,pe,d.status,T]),g&&!S&&!m)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});if(w)return jsxRuntimeExports.jsx(XpodLocalLoginPreflight,{onReady:q});const Ie="remembered"in d?d.remembered:void 0,De=d.status==="restoring",de=S||e&&!u&&!s&&d.status==="anonymous"&&!m,Oe=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let le,Ae;return m?le=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:m,primaryLabel:"重试",onPrimary:ee,secondaryLabel:T?void 0:"返回登录",onSecondary:T?void 0:_e}):De?(Ae=Ie?void 0:Oe,le=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:Ie?.displayName,avatarUrl:Ie?.avatarUrl,label:rememberedCopy.restoringLabel})):de?le=T?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在切换账号…"}):jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:_e}):d.status==="authenticated"?le=p?.status==="conflict"||p?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:p.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:p.message,primaryLabel:"重试",onPrimary:ee,secondaryLabel:"切换账号",onSecondary:te}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):Ie&&!u?le=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[d.status==="error"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"mb-3 text-center text-xs text-muted-foreground",children:d.message}),jsxRuntimeExports.jsx(LoginAccountView,{name:Ie.displayName,avatarUrl:Ie.avatarUrl,bindingLabel:"Xpod",expired:d.status==="expired"||d.status==="error",expiredTitle:d.status==="error"?"会话恢复未完成":rememberedCopy.expiredTitle,enterLabel:d.status==="expired"||d.status==="error"?rememberedCopy.reauthenticateLabel(Ie.displayName):rememberedCopy.continueLabel(Ie.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:pe,onReauthenticate:ee,onSwitchAccount:te})]}):!u&&(d.status==="error"||d.status==="expired")?le=jsxRuntimeExports.jsx(LoginFailureView,{title:d.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:d.status==="error"?d.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:ee,secondaryLabel:"返回登录",onSecondary:_e}):le=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:Oe,onStart:pe}),jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"登录 Xpod",lead:Ae,children:le})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":{const e=rememberedWebIdLogin(n.webId);return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-B-G4YfTv.js"),__vite__mapDeps([17,18,10,4,11,19]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-aidVtDAU.js"),__vite__mapDeps([20,8,21,18,10]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-DmxLA1Da.js").then(n=>n.M),__vite__mapDeps([22,21,18])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-C-lnRpEy.js"),__vite__mapDeps([23,22,21,18])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-DTyOKrU1.js"),__vite__mapDeps([24,22,21,18])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-8oscxWj2.js"),__vite__mapDeps([25,22,21,18])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-DfU_qHHq.js"),__vite__mapDeps([26,6,1,8,10]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-nfcG67Tx.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})}])],xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodDesktopNavigationBridge,{}),jsxRuntimeExports.jsx(XpodServiceAvailability,{children:jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(XpodShellRoutes,{})})}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??XPOD_DEFAULT_RETURN_PATH)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}function createCallbackNavigation({location:n,history:e}){return{origin:n.origin,replace(t){const i=new URL(t,n.origin);if(i.origin===n.origin&&isProductPath(i.pathname)){e.replaceState({},"",`${i.pathname}${i.search}${i.hash}`);return}n.replace(i.href)}}}function resolveCallbackProductDestination(n,e){try{const t=new URL(n,e);if(t.origin!==e)return;const i=productAppForPathname(t.pathname);return i?{app:i,pathname:t.pathname,target:`${t.pathname}${t.search}${t.hash}`}:void 0}catch{return}}function isProductPath(n){return productAppForPathname(n)!==void 0}function productAppForPathname(n){return productSurfaceRoots.find(({basename:e})=>n===e||n.startsWith(`${e}/`))?.app}initializeXpodTheme();const runtime=getXpodSolidRuntimeValue(),callbackLocation=createCallbackNavigation({location:window.location,history:window.history});function renderRedirected(n){const e=resolveCallbackProductDestination(n.destination,window.location.origin);return e?(`${window.location.pathname}${window.location.search}${window.location.hash}`!==e.target&&window.history.replaceState({},"",e.target),jsxRuntimeExports.jsx(XpodShellApp,{runtime,initialPathname:e.pathname},e.target)):jsxRuntimeExports.jsx("main",{role:"status","aria-live":"polite",children:"Sign-in complete. Opening Xpod…"})}clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodOidcCallbackApp,{runtime,location:callbackLocation,renderRedirected})}));export{setIri as $,getDefaultExportFromCjs as A,Button as B,Card as C,Database as D,createLucideIcon$1 as E,createSlottable as F,Gauge as G,getLinkedResourceUrlAll as H,acp as I,internal_cloneResource as J,getSolidDataset as K,Link as L,freeze as M,NavLink as N,Outlet as O,Primitive as P,getSourceUrl as Q,RefreshCw as R,Sparkles as S,getResourceInfo as T,getSourceIri as U,getThingAll as V,getIriAll as W,X,rdf$3 as Y,acl as Z,setThing as _,CardHeader as a,removeIri as a0,removeAll as a1,createThing as a2,addIri as a3,removeThing as a4,subjectToRdfJsQuads as a5,DataFactory$1 as a6,getIri as a7,saveSolidDatasetAt as a8,createSolidDataset as a9,requireBrowser$2 as aA,requireSparql as aB,requireEvents as aC,requireBrowser$3 as aD,requireString_decoder as aE,bufferExports as aF,commonjsGlobal as aG,foaf as aa,getThing as ab,getUrlAll as ac,buildThing as ad,Avatar as ae,AvatarImage as af,AvatarFallback as ag,LoaderCircle$1 as ah,Input as ai,LoginFailureView as aj,LoginConnectingView as ak,Label as al,dismissToast as am,controlFocusClass as an,Toaster as ao,resolveHostedAccountControlUrl as ap,storedAccountTokenHeaders as aq,credentialResource as ar,aiProviderResource as as,aiModelResource as at,configureSparqlEngine as au,AuthContext as av,createXpodLoginController as aw,requireBuffer as ax,requireLink as ay,getAugmentedNamespace 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};
310
+ ${u.storageUrl}`===a);l?l.label!==void 0&&s.label!==void 0&&l.label!==s.label&&t.push(s):t.push(s)}return t}function normalizeConsentBinding(n,e,t){if(!hasInvalidWebIdWhitespace(n))try{const i=new URL(n),s=new URL(e.trim());return!["http:","https:"].includes(i.protocol)||!["http:","https:"].includes(s.protocol)||i.username||i.password||s.username||s.password||s.search||s.hash?void 0:(s.pathname=s.pathname.endsWith("/")?s.pathname:`${s.pathname}/`,{webId:n,storageUrl:s.href,...t?{label:t}:{}})}catch{return}}function safeStorageError(n,e){const t=n instanceof Error?n.message:"";return t==="fetch failed"||t.includes("Failed to fetch")||t.includes("Cloud storage is not ready")||t.includes("provision_refresh_failed")||t.includes("provision_refresh_unavailable")||t===xpodFirstPodErrors.cloudRouteUnavailable?xpodFirstPodErrors.cloudRouteUnavailable:t.startsWith("Pod name is already taken.")||t===xpodRegistrationCopy.choosePodName||t===xpodRegistrationCopy.podNameTaken?t:e}function markFirstPodStage(n){}function FirstPodPage({onReady:n}={}){const{controls:e,hasOidcPending:t,idpIndex:i,identity:s,refetchControls:a}=useAuth(),l=useNavigate(),[u,f]=reactExports.useState({status:"checking"}),[d,p]=reactExports.useState(0),g=!n&&t?new URL("oidc/pick-webid/",i).href:void 0;return reactExports.useEffect(()=>{let m=!1;return(async()=>{try{const v=g?await loadPendingOidcStorageBindings(g):void 0;if(m)return;if(v?.bindings.length){l(scopeAccountUrl("/.account/oidc/consent/"),{replace:!0});return}const S=await resolveCurrentProvisionTarget();if(m)return;const E=v?{allWebIds:v.webIds,currentStorageWebIds:[],currentBindings:[],durable:!1}:await loadCurrentStorageWebIds({accountBindingsUrl:e?.account?.bindings,accountWebIdUrl:e?.account?.webId,idpIndex:i,provisionCode:S.activeProvisionCode,provisionStorageRoot:S.storageRoot});if(m)return;if(!v&&E.currentStorageWebIds.length>0&&(!n||E.durable)){if(n){if(!S.storageRoot)throw new Error(xpodFirstPodErrors.cloudRouteUnavailable);await waitForCurrentAccountStorageBindings({controls:{account:{bindings:e?.account?.bindings}},trustedAccountIndex:i,storageRoot:S.storageRoot}),m||n()}else l(scopeAccountUrl("/.account/account/"),{replace:!0});return}if(S.storageRoot&&!S.activeProvisionCode)throw new Error(xpodFirstPodErrors.cloudRouteUnavailable);const w=await resolveProvisionCodeForCurrentScope(S.activeProvisionCode);if(m)return;const C=(n&&E.currentBindings.length>0?existingScopedPodName(E.currentBindings,S.storageRoot):void 0)??(deriveFirstPodNameCandidate([e?.account?.username,s?.username,s?.displayName,s?.webId,...E.allWebIds,readPendingXpodAccountEmail(void 0,i)])||e?.account?.username),T=e?.account?.pod;if(!C)throw new Error(xpodFirstPodErrors.accountIdentityMissing);if(!T)throw new Error(xpodFirstPodErrors.createEndpointMissing);f({status:"creating"});const F=await createFirstPodAndWaitForBinding({createPodUrl:T,headers:storedAccountTokenHeaders(),pickWebIdUrl:g,provisionCode:w,trustedAccountIndex:i,username:C});if(m)return;if(!n&&t&&F.length===0){f({status:"waiting"});return}if(n){if(!S.storageRoot)throw new Error(xpodFirstPodErrors.cloudRouteUnavailable);f({status:"waiting"}),await waitForCurrentAccountStorageBindings({controls:{account:{bindings:e?.account?.bindings}},trustedAccountIndex:i,storageRoot:S.storageRoot}),m||n();return}if(await a(),m)return;l(scopeAccountUrl(t?"/.account/oidc/consent/":"/.account/account/"),{replace:!0})}catch(v){if(!m){const S=safeStorageError(v,xpodFirstPodErrors.checkFailed);f({status:"error",message:S})}}})(),()=>{m=!0}},[e?.account?.bindings,e?.account?.pod,e?.account?.username,e?.account?.webId,t,s?.displayName,s?.username,s?.webId,i,l,n,g,a,d]),jsxRuntimeExports.jsx(XpodAccountPageSurface,{title:xpodFirstPodCopy.surfaceTitle,children:jsxRuntimeExports.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:u.status==="checking"?jsxRuntimeExports.jsx(WebAccountRestoringView,{label:xpodFirstPodCopy.restoring}):u.status==="creating"||u.status==="waiting"?jsxRuntimeExports.jsx(WebAccountRestoringView,{label:u.status==="creating"?xpodFirstPodCopy.creating:xpodFirstPodCopy.waitingMessage}):u.status==="error"?jsxRuntimeExports.jsx(WebAccountFailureView,{title:xpodFirstPodCopy.unavailableTitle,description:u.message,primaryLabel:xpodFirstPodCopy.retryLabel,onPrimary:()=>{f({status:"checking"}),p(m=>m+1)}}):null})})}async function loadPendingOidcStorageBindings(n){const e=await fetch(scopeAccountUrl(n),{headers:storedAccountTokenHeaders(),credentials:"include"});if(!e.ok)throw new Error(xpodConsentErrors.bindingsFailed);const t=await e.json().catch(()=>{});if(!t||!Array.isArray(t.entries))throw new Error(xpodConsentErrors.bindingsFailed);if(t.entries.length>0){for(const s of t.entries)if(resolveConsentStorageBindings([s]).length!==1)throw new Error(xpodConsentErrors.bindingsFailed)}const i=Array.isArray(t.webIds)?t.webIds.filter(s=>typeof s=="string"&&s.length>0):[];return{bindings:resolveConsentStorageBindings(t.entries,i),webIds:i}}async function loadCurrentStorageWebIds(n){let e;n.accountBindingsUrl&&(e=await fetchAccountStorageBindings({controls:{account:{bindings:n.accountBindingsUrl}},origin:window.location.origin,trustedAccountIndex:n.idpIndex}));const t=n.provisionStorageRoot&&e&&e.length>0?e.filter(f=>storageUrlBelongsToRoot(f.storageUrl,n.provisionStorageRoot)).map(f=>f.webId):[];if(t.length>0)return{allWebIds:Array.from(new Set(e.map(f=>f.webId))),currentStorageWebIds:Array.from(new Set(t)),currentBindings:e.filter(f=>storageUrlBelongsToRoot(f.storageUrl,n.provisionStorageRoot)),durable:!0};const i=e&&e.length>0?[]:await fetchAccountWebIds(n.accountWebIdUrl,n.idpIndex),s=Array.from(new Set([...e?.map(f=>f.webId)??[],...i]));if(n.provisionStorageRoot&&!n.provisionCode)return{allWebIds:s,currentStorageWebIds:[],currentBindings:[],durable:!1};if(!resolveProvisionScope(n.provisionCode))return{allWebIds:s,currentStorageWebIds:s,currentBindings:e??[],durable:!!e?.length};const l=await lookupProvisionScopedWebIds(fetch,s,n.provisionCode),u=Array.from(new Set((l??[]).map(f=>f.webId)));return{allWebIds:s,currentStorageWebIds:u,currentBindings:l??[],durable:!1}}async function fetchAccountWebIds(n,e){const t=await resolveHostedAccountControlUrl(n,fetch,e);if(!t)throw new Error(xpodFirstPodErrors.checkFailed);const i=await fetch(scopeAccountUrl(t),{headers:storedAccountTokenHeaders({Accept:"application/json"}),credentials:"include"}).catch(()=>{});if(!i?.ok)throw new Error(xpodFirstPodErrors.checkFailed);const s=await i.json().catch(()=>{});if(!s?.webIdLinks||typeof s.webIdLinks!="object"||Array.isArray(s.webIdLinks))throw new Error(xpodFirstPodErrors.checkFailed);return Object.keys(s.webIdLinks).filter(a=>{try{const l=new URL(a);return["http:","https:"].includes(l.protocol)&&!l.username&&!l.password}catch{return!1}})}function existingScopedPodName(n,e){const t=[...new Set(n.map(l=>l.storageUrl))];if(!e||t.length!==1)throw new Error(xpodFirstPodErrors.checkFailed);const i=t[0];if(!storageUrlBelongsToRoot(i,e))throw new Error(xpodFirstPodErrors.checkFailed);const s=new URL(e).pathname.replace(/\/?$/u,"/"),a=new URL(i).pathname.slice(s.length).split("/").filter(Boolean);if(a.length!==1)throw new Error(xpodFirstPodErrors.checkFailed);return decodeURIComponent(a[0])}function XpodLocalLoginPreflight({onReady:n}){const e=reactExports.useContext(AuthContext),t=reactExports.useRef(!1),i=e?.isInitializing===!0,s=isManagedLocalProvisionHost()&&e?.isLoggedIn===!0;return reactExports.useEffect(()=>{!i&&!s&&!t.current&&(t.current=!0,n())},[i,s,n]),i||!s?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在准备登录…"}):jsxRuntimeExports.jsx(FirstPodPage,{onReady:n})}function createXpodLoginController(n){const e=n.location??(typeof window>"u"?"http://localhost/":window.location),i=[createXpodLoginRoute(e)],s=toOrigin(e),a=n.transactionStore??createXpodLoginTransactionStore({origin:s}),l=p=>{if(p!==void 0)return normalizeXpodReturnTo(p);const g=new URL(toHref(e)),m=`${g.pathname}${g.search}`;try{return normalizeXpodReturnTo(m)}catch{return}};let u=!1;const f=p=>{try{return a.begin(p)}catch(g){if(u||!(g instanceof XpodLoginTransactionError)||g.code!=="already_active")throw g;try{const m=a.readSinglePending();m&&a.cancel(m.id)}catch{}return a.begin(p)}},d=async(p,g,m)=>{const v=l(p),S={id:createOpaqueTransactionId(),route:i[0],authorizationSurface:"redirect",discovery:"strict",...m?{prompt:m}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},E=f(S);u=!0;try{await n.runtime.login(E)}catch(w){try{a.cancel(E.id)}catch{}throw w}finally{u=!1}return E};return{routes:i,startLogin:d,retryLogin:d,cancelLogin(){const p=a.readSinglePending();p&&a.cancel(p.id)},readPending:()=>a.readSinglePending(),callbackUrl(){return`${s}/auth/callback`}}}function toOrigin(n){return new URL(toHref(n)).origin}function toHref(n){return typeof n=="string"?n:n.href}const rememberedCopy={restoringLabel:"正在恢复 Xpod 会话…",continueLabel:n=>`使用 ${n} 登录`,reauthenticateLabel:n=>`重新登录 ${n}`,switchAccountLabel:"切换账号",expiredTitle:"会话已过期",connectingTitle:"正在登录…",connectingDetail:"请在授权页面完成登录。",cancelLabel:"取消"},podFailureMessage="无法打开选中的 Pod,请重试。",actionFailureMessage="操作未完成,请重试。";function WebIdAuthBoundary(n){return jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(WebIdAuthBoundaryContent,{...n})})}function WebIdAuthBoundaryContent({children:n,autoStart:e=!1}){const t=useXpodSolidRuntime(),i=reactExports.useContext(AuthContext),s=reactExports.useSyncExternalStore(subscribeXpodProductLogout,isXpodAutomaticLoginBlocked,()=>!1),a=reactExports.useMemo(()=>createXpodLoginController({runtime:t}),[t]),[l]=reactExports.useState(readXpodAccountSwitch),[u,f]=reactExports.useState(()=>l||readXpodLoginCancelled());reactExports.useLayoutEffect(()=>{l&&consumeXpodAccountSwitch()},[l]),reactExports.useEffect(()=>{if(u)try{a.cancelLogin()}catch{}},[u,a]);const d=runtimeState(t.state),p=storageSelectionState(t,d),g=d.status==="authenticated"&&p?.status==="ready",[m,v]=reactExports.useState(),[S,E]=reactExports.useState(!1),[w,A]=reactExports.useState(l?{prompt:"login"}:void 0),C=reactExports.useRef(0),[T,F]=reactExports.useState(!1),P=reactExports.useRef(!1),M=reactExports.useRef(!1),O=reactExports.useCallback($=>{console.error("[WebIdAuthBoundary] authentication action failed",$),v(actionFailureMessage)},[]),Q=reactExports.useCallback($=>{const H=++C.current;v(void 0),E(!0),$().catch(fe=>{H===C.current&&O(fe)}).finally(()=>{H===C.current&&E(!1)})},[O]),pe=reactExports.useCallback(()=>{setXpodLoginCancelled(!1),f(!1),v(void 0),A({})},[]),q=reactExports.useCallback(()=>{if(!w)return;const $=w.prompt;setXpodLoginCancelled(!1),f(!1),A(void 0),Q(async()=>{l&&await t.session.initialize({restorePreviousSession:!1}),await a.startLogin(void 0,void 0,$)})},[a,w,Q,t.session,l]),ee=()=>{if(T){te();return}d.status==="authenticated"?t.retryPodOpen?.():pe()},_e=()=>{if(!T){try{a.cancelLogin()}catch{}setXpodLoginCancelled(!0),f(!0),A(void 0),C.current+=1,E(!1),v(void 0)}},te=()=>Q(async()=>{F(!0);const $=()=>{setXpodLoginCancelled(!1),f(!1),clearRememberedXpodLogin(),v(void 0),A({prompt:"login"}),F(!1)};i?await logoutXpodProduct(i,t,{onComplete:$}):(await t.logout(),$())});if(reactExports.useEffect(()=>{t.state.status!=="loading"||P.current||(P.current=!0,t.session.initialize({restorePreviousSession:!u}).catch(O))},[u,O,t.session,t.state.status]),reactExports.useEffect(()=>{u||w||s||S||T||!e||M.current||d.status!=="anonymous"||(M.current=!0,pe())},[u,s,e,S,w,pe,d.status,T]),g&&!S&&!m)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:n});if(w)return jsxRuntimeExports.jsx(XpodLocalLoginPreflight,{onReady:q});const Ie="remembered"in d?d.remembered:void 0,De=d.status==="restoring",de=S||e&&!u&&!s&&d.status==="anonymous"&&!m,Oe=jsxRuntimeExports.jsx(XpodLoginBrand,{compact:!0,showSubtitle:!0});let le,Ae;return m?le=jsxRuntimeExports.jsx(LoginFailureView,{title:"登录未完成",description:m,primaryLabel:"重试",onPrimary:ee,secondaryLabel:T?void 0:"返回登录",onSecondary:T?void 0:_e}):De?(Ae=Ie?void 0:Oe,le=jsxRuntimeExports.jsx(LoginRestoringView,{accountName:Ie?.displayName,avatarUrl:Ie?.avatarUrl,label:rememberedCopy.restoringLabel})):de?le=T?jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在切换账号…"}):jsxRuntimeExports.jsx(LoginConnectingView,{title:rememberedCopy.connectingTitle,detail:rememberedCopy.connectingDetail,cancelLabel:rememberedCopy.cancelLabel,onCancel:_e}):d.status==="authenticated"?le=p?.status==="conflict"||p?.status==="error"?jsxRuntimeExports.jsx(LoginFailureView,{title:p.status==="conflict"?"存储绑定冲突":"暂时无法打开 Pod",description:p.message,primaryLabel:"重试",onPrimary:ee,secondaryLabel:"切换账号",onSecondary:te}):jsxRuntimeExports.jsx(LoginRestoringView,{label:"正在打开选中的 Pod。"}):Ie&&!u?le=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[d.status==="error"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"mb-3 text-center text-xs text-muted-foreground",children:d.message}),jsxRuntimeExports.jsx(LoginAccountView,{name:Ie.displayName,avatarUrl:Ie.avatarUrl,bindingLabel:"Xpod",expired:d.status==="expired"||d.status==="error",expiredTitle:d.status==="error"?"会话恢复未完成":rememberedCopy.expiredTitle,enterLabel:d.status==="expired"||d.status==="error"?rememberedCopy.reauthenticateLabel(Ie.displayName):rememberedCopy.continueLabel(Ie.displayName),switchLabel:rememberedCopy.switchAccountLabel,onEnter:pe,onReauthenticate:ee,onSwitchAccount:te})]}):!u&&(d.status==="error"||d.status==="expired")?le=jsxRuntimeExports.jsx(LoginFailureView,{title:d.status==="expired"?rememberedCopy.expiredTitle:"无法登录 Xpod",description:d.status==="error"?d.message:"请重新登录后继续。",primaryLabel:"重试",onPrimary:ee,secondaryLabel:"返回登录",onSecondary:_e}):le=jsxRuntimeExports.jsx(WebIdLoginEntryView,{copy:{title:"",startLabel:"登录",pendingLabel:rememberedCopy.connectingTitle},logo:Oe,onStart:pe}),jsxRuntimeExports.jsx(XpodAuthSurface,{mode:"page",title:"登录 Xpod",lead:Ae,children:le})}function storageSelectionState(n,e){if(e.status!=="authenticated")return;if(n.podError?.webId===e.webId)return{status:"error",message:podFailureMessage};if(n.currentPod===void 0)return{status:"waiting_for_binding"};const t=n.selectedStorage??{webId:n.currentPod.webId,storageUrl:n.currentPod.podUrl},i=n.state.status==="authenticated"?n.state.podUrl:void 0;return n.currentPod.webId===e.webId&&t.webId===n.currentPod.webId&&sameUrl(t.storageUrl,n.currentPod.podUrl)&&(i===void 0||sameUrl(n.currentPod.podUrl,i))?{status:"ready",selected:t}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function sameUrl(n,e){try{return new URL(n).href===new URL(e).href}catch{return n===e}}function rememberedWebIdLogin(n){const e=readRememberedXpodLogin();if(e&&!(n&&n!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function withRemembered(n,e){const t=rememberedWebIdLogin(e);return t?{...n,remembered:t}:n}function runtimeState(n){switch(n.status){case"loading":return withRemembered({status:"restoring"});case"anonymous":return withRemembered({status:"anonymous"});case"expired":return withRemembered({status:"expired"},n.webId);case"authenticated":return{status:"authenticated",webId:n.webId};case"error":{const e=rememberedWebIdLogin(n.webId);return{status:"error",message:n.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const ModelsPage=reactExports.lazy(()=>__vitePreload(()=>import("./ModelsPage-DapY2Dwf.js"),__vite__mapDeps([17,18,10,4,11,19]))),AiConfigPage=reactExports.lazy(()=>__vitePreload(()=>import("./AiConfigPage-DgGmHb18.js"),__vite__mapDeps([20,8,21,18,10]))),ModelAssignmentsPanel=reactExports.lazy(()=>__vitePreload(()=>import("./ModelAssignmentsPanel-CwM3k8w7.js").then(n=>n.M),__vite__mapDeps([22,21,18])).then(n=>({default:n.ModelAssignmentsPanel}))),DocumentProcessingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./DocumentProcessingPanel-CJmxu8x1.js"),__vite__mapDeps([23,22,21,18])).then(n=>({default:n.DocumentProcessingPanel}))),SearchIndexingPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SearchIndexingPanel-mbppDZFE.js"),__vite__mapDeps([24,22,21,18])).then(n=>({default:n.SearchIndexingPanel}))),IndexLifecyclePanel=reactExports.lazy(()=>__vitePreload(()=>import("./IndexLifecyclePanel-byCa7h7L.js"),__vite__mapDeps([25,22,21,18])).then(n=>({default:n.IndexLifecyclePanel}))),SystemSettingsPage=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsPage-C6qklJ9k.js"),__vite__mapDeps([26,6,1,8,10]))),PodSettingsSubjectPanel=reactExports.lazy(()=>__vitePreload(()=>import("./SystemSettingsSubjectPanel-B4VV9xkG.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})}])],xpodShellRoutes=[{path:"status",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:statusSurfaceRoutes},{path:"network",children:networkSurfaceRoutes},{path:"ai-connections",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConnectionsSurfaceRoutes},{path:"ai-config",element:jsxRuntimeExports.jsx(WebIdAuthBoundary,{autoStart:!0,children:jsxRuntimeExports.jsx(Outlet,{})}),children:aiConfigSurfaceRoutes},{path:"settings",children:systemSettingsSurfaceRoutes},{path:"dashboard",element:jsxRuntimeExports.jsx(AccountWorkspaceBoundary,{children:jsxRuntimeExports.jsx(Outlet,{})}),children:dashboardRoutes},{index:!0,element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})},{path:"*",element:jsxRuntimeExports.jsx(Navigate,{to:XPOD_DEFAULT_RETURN_PATH,replace:!0})}];function XpodShellRoutes(){const n=useLocation(),e=useRoutes(xpodShellRoutes);return reactExports.useEffect(()=>{document.title=n.pathname.startsWith("/status")?"Xpod Dashboard":"Xpod Settings"},[n.pathname]),e}function XpodShellApp({runtime:n,initialPathname:e}={}){const[t]=reactExports.useState(()=>initializeProductLocation(e));return jsxRuntimeExports.jsx(XpodThemeRoot,{children:jsxRuntimeExports.jsx(AuthProvider,{children:jsxRuntimeExports.jsxs(XpodSolidRuntimeProvider,{value:n,children:[jsxRuntimeExports.jsx(XpodDesktopIdentityBridge,{}),jsxRuntimeExports.jsx(XpodRememberedLoginBridge,{}),jsxRuntimeExports.jsxs(BrowserRouter,{children:[jsxRuntimeExports.jsx(XpodDesktopNavigationBridge,{}),jsxRuntimeExports.jsx(XpodServiceAvailability,{children:jsxRuntimeExports.jsx(XpodProductLogoutBoundary,{children:jsxRuntimeExports.jsx(XpodShellRoutes,{})})}),jsxRuntimeExports.jsx(Toaster,{})]},t)]})})})}function initializeProductLocation(n){const t=`${canonicalProductPathname(n??globalThis.location?.pathname??XPOD_DEFAULT_RETURN_PATH)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==t&&globalThis.history?.replaceState(null,"",t),t}function createCallbackNavigation({location:n,history:e}){return{origin:n.origin,replace(t){const i=new URL(t,n.origin);if(i.origin===n.origin&&isProductPath(i.pathname)){e.replaceState({},"",`${i.pathname}${i.search}${i.hash}`);return}n.replace(i.href)}}}function resolveCallbackProductDestination(n,e){try{const t=new URL(n,e);if(t.origin!==e)return;const i=productAppForPathname(t.pathname);return i?{app:i,pathname:t.pathname,target:`${t.pathname}${t.search}${t.hash}`}:void 0}catch{return}}function isProductPath(n){return productAppForPathname(n)!==void 0}function productAppForPathname(n){return productSurfaceRoots.find(({basename:e})=>n===e||n.startsWith(`${e}/`))?.app}initializeXpodTheme();const runtime=getXpodSolidRuntimeValue(),callbackLocation=createCallbackNavigation({location:window.location,history:window.history});function renderRedirected(n){const e=resolveCallbackProductDestination(n.destination,window.location.origin);return e?(`${window.location.pathname}${window.location.search}${window.location.hash}`!==e.target&&window.history.replaceState({},"",e.target),jsxRuntimeExports.jsx(XpodShellApp,{runtime,initialPathname:e.pathname},e.target)):jsxRuntimeExports.jsx("main",{role:"status","aria-live":"polite",children:"Sign-in complete. Opening Xpod…"})}clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(XpodThemeProvider,{children:jsxRuntimeExports.jsx(XpodOidcCallbackApp,{runtime,location:callbackLocation,renderRedirected})}));export{setIri as $,getDefaultExportFromCjs as A,Button as B,Card as C,Database as D,createLucideIcon$1 as E,createSlottable as F,Gauge as G,getLinkedResourceUrlAll as H,acp as I,internal_cloneResource as J,getSolidDataset as K,Link as L,freeze as M,NavLink as N,Outlet as O,Primitive as P,getSourceUrl as Q,RefreshCw as R,Sparkles as S,getResourceInfo as T,getSourceIri as U,getThingAll as V,getIriAll as W,X,rdf$3 as Y,acl as Z,setThing as _,CardHeader as a,removeIri as a0,removeAll as a1,createThing as a2,addIri as a3,removeThing as a4,subjectToRdfJsQuads as a5,DataFactory$1 as a6,getIri as a7,saveSolidDatasetAt as a8,createSolidDataset as a9,requireBrowser$2 as aA,requireSparql as aB,requireEvents as aC,requireBrowser$3 as aD,requireString_decoder as aE,bufferExports as aF,commonjsGlobal as aG,foaf as aa,getThing as ab,getUrlAll as ac,buildThing as ad,Avatar as ae,AvatarImage as af,AvatarFallback as ag,LoaderCircle$1 as ah,Input as ai,LoginFailureView as aj,LoginConnectingView as ak,Label as al,dismissToast as am,controlFocusClass as an,Toaster as ao,resolveHostedAccountControlUrl as ap,storedAccountTokenHeaders as aq,credentialResource as ar,aiProviderResource as as,aiModelResource as at,configureSparqlEngine as au,AuthContext as av,createXpodLoginController as aw,requireBuffer as ax,requireLink as ay,getAugmentedNamespace 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};