@object-ui/console 3.3.1 → 3.4.0

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 (80) hide show
  1. package/dist/assets/AppManagementPage-CLr3paaF.js +1 -0
  2. package/dist/assets/ConsoleFloatingChatbot-C_ClJ2NU.js +1 -0
  3. package/dist/assets/DashboardView-CODdYLuL.js +1 -0
  4. package/dist/assets/MetadataDetailPage-C1sWJhl2.js +1 -0
  5. package/dist/assets/MetadataFormDialog-Cje6P_Wf.js +1 -0
  6. package/dist/assets/MetadataManagerPage-DobP393N.js +1 -0
  7. package/dist/assets/PageView-DZHuurne.js +2 -0
  8. package/dist/assets/ProfilePage-6u6k00rh.js +1 -0
  9. package/dist/assets/RecordDetailView-cFSCvmx3.js +1 -0
  10. package/dist/assets/ReportView-oYVEbfYq.js +2 -0
  11. package/dist/assets/SearchResultsPage-BjAVc5rm.js +1 -0
  12. package/dist/assets/SystemHubPage-D08IDX3M.js +1 -0
  13. package/dist/assets/data-adapter-CleWpyQH.js +1 -0
  14. package/dist/assets/framework-CoXA0nY6.js +2 -0
  15. package/dist/assets/getIcon-vBP44wSb.js +1 -0
  16. package/dist/assets/index-98Lfd5ty.js +2 -0
  17. package/dist/assets/index-C162ArSl.css +2 -0
  18. package/dist/assets/{infrastructure-94fpO8jL.js → infrastructure-Djv3I7gr.js} +2 -2
  19. package/dist/assets/plugin-calendar-DX_UWouT.js +1 -0
  20. package/dist/assets/plugin-charts-BvZ1cSiZ.js +7 -0
  21. package/dist/assets/plugin-chatbot-DeSEtutf.js +24 -0
  22. package/dist/assets/plugin-form-BhbVu8jO.js +1 -0
  23. package/dist/assets/plugin-gantt-BG1WaV_b.js +1 -0
  24. package/dist/assets/plugin-grid-DwpWK0E8.js +8 -0
  25. package/dist/assets/plugin-kanban-Dzjqra5U.js +1 -0
  26. package/dist/assets/plugin-map-B7EfyDsf.js +1 -0
  27. package/dist/assets/plugin-map-CsMXqW6n.css +1 -0
  28. package/dist/assets/plugin-markdown-CiHluuxA.js +7 -0
  29. package/dist/assets/plugin-timeline-D8_YFDQQ.js +1 -0
  30. package/dist/assets/plugin-view-CXAFUa14.js +1 -0
  31. package/dist/assets/plugins-views-C5gstDGy.js +63 -0
  32. package/dist/assets/src-iMF4J4F7.js +1 -0
  33. package/dist/assets/ui-components-BCmPcwhR.js +36 -0
  34. package/dist/assets/ui-layout-BLl7ARoe.js +1 -0
  35. package/dist/assets/vendor-charts-DHZsyaJw.js +36 -0
  36. package/dist/assets/vendor-dndkit-BGB4qgc3.js +5 -0
  37. package/dist/assets/vendor-i18n-D3W5EAHR.js +1 -0
  38. package/dist/assets/vendor-icons-core-s9WPLoP3.js +1 -0
  39. package/dist/assets/vendor-markdown-D-LpQJes.js +29 -0
  40. package/dist/assets/vendor-objectstack-CBpPY_xk.js +39 -0
  41. package/dist/assets/vendor-radix-Bj7uHNWN.js +56 -0
  42. package/dist/assets/vendor-react-B1k2FF9f.js +11 -0
  43. package/dist/assets/vendor-ui-utils-AywTz3cM.js +1 -0
  44. package/dist/index.html +7 -26
  45. package/package.json +33 -33
  46. package/dist/assets/AdapterProvider-Cd4HYb7q.js +0 -1
  47. package/dist/assets/AdvancedChartImpl-AY6sVw1n.js +0 -7
  48. package/dist/assets/AppManagementPage-6l5ZKnv5.js +0 -1
  49. package/dist/assets/ChartImpl-DiKY5voi.js +0 -1
  50. package/dist/assets/DashboardView-BnX2k5Kx.js +0 -1
  51. package/dist/assets/KanbanEnhanced-BKCx2XIr.js +0 -1
  52. package/dist/assets/KanbanImpl-e9jzV-UD.js +0 -1
  53. package/dist/assets/MarkdownImpl-B-r7jSIS.js +0 -1
  54. package/dist/assets/MetadataDetailPage--3o8VI1T.js +0 -1
  55. package/dist/assets/MetadataFormDialog-Cy7k0Y55.js +0 -1
  56. package/dist/assets/MetadataInspector-DVtCDQtx.js +0 -1
  57. package/dist/assets/MetadataManagerPage-CYfvXG6X.js +0 -1
  58. package/dist/assets/MetadataProvider-Dvc9BxbC.js +0 -1
  59. package/dist/assets/PageView-CUDEz8Xo.js +0 -2
  60. package/dist/assets/ProfilePage-B0BXoAus.js +0 -1
  61. package/dist/assets/RecordDetailView-CYgcTNQp.js +0 -1
  62. package/dist/assets/ReportView-ovWyjJsZ.js +0 -1
  63. package/dist/assets/SearchResultsPage-B-NchFoJ.js +0 -1
  64. package/dist/assets/SystemHubPage-D8S1hN1a.js +0 -1
  65. package/dist/assets/data-adapter-v22lWuhc.js +0 -39
  66. package/dist/assets/framework-BW6KsEI0.js +0 -2
  67. package/dist/assets/getIcon-N5xWCMJy.js +0 -1
  68. package/dist/assets/index-DATdOX6r.js +0 -59
  69. package/dist/assets/index-nwlbpqhl.css +0 -2
  70. package/dist/assets/plugins-core-Ccvbi6db.js +0 -105
  71. package/dist/assets/plugins-views-CbLIJkBs.js +0 -62
  72. package/dist/assets/skeletons-CIQE_YYE.js +0 -1
  73. package/dist/assets/src-BGoL_8qF.js +0 -1
  74. package/dist/assets/ui-layout-CYz0tyDf.js +0 -3
  75. package/dist/assets/vendor-charts-D1AP0-EV.js +0 -33
  76. package/dist/assets/vendor-icons-CrSf7tAH.js +0 -1
  77. package/dist/assets/vendor-objectstack-Dhrq31KF.js +0 -1
  78. package/dist/assets/vendor-react-ryfytPb-.js +0 -9
  79. /package/dist/assets/{maplibre-gl-BR3qC6SX.js → maplibre-gl-ChgVR8ni.js} +0 -0
  80. /package/dist/assets/{plugins-core-B5ROGaJH.css → ui-components-B5ROGaJH.css} +0 -0
@@ -1,3 +1,3 @@
1
- import{r as e}from"./rolldown-runtime-S-ySWqyJ.js";import{U as t,W as n,a as r}from"./framework-BW6KsEI0.js";var i=new Set([`common`,`validation`,`form`,`table`,`grid`,`calendar`,`list`,`kanban`,`chart`,`dashboard`,`configPanel`,`appDesigner`,`console`,`errors`,`detail`]);function a(){let{t:e,i18n:t}=r(),n=()=>{if(!t||typeof t.getResourceBundle!=`function`)return[];let e=t.language||`en`,n=t.getResourceBundle(e,`translation`);return n?Object.keys(n).filter(e=>!i.has(e)&&n[e]&&typeof n[e]==`object`&&(n[e].objects||n[e].fields||n[e].apps)):[]},a=e=>{let t=e.indexOf(`__`);return t>0?e.slice(t+2):e},o=(t,r)=>{let i=Array.isArray(t)?t:[t];try{let t=n();for(let n of t)for(let t of i){let r=`${n}.${t}`,i=e(r,{defaultValue:``});if(i&&i!==r&&i!==``)return i}}catch{}return r},s=(e,t)=>{let n=a(e);return n===e?[`objects.${e}.${t}`]:[`objects.${e}.${t}`,`objects.${n}.${t}`]},c=(e,t)=>{let n=a(e);return n===e?[`fields.${e}.${t}`]:[`fields.${e}.${t}`,`fields.${n}.${t}`]},l=(e,t,n)=>{let r=a(e);return r===e?[`fieldOptions.${e}.${t}.${n}`]:[`fieldOptions.${e}.${t}.${n}`,`fieldOptions.${r}.${t}.${n}`]};return{objectLabel:e=>o(s(e.name,`label`),e.label),objectDescription:e=>{if(e.description)return o(s(e.name,`description`),e.description)},fieldLabel:(e,t,n)=>o(c(e,t),n),fieldOptionLabel:(e,t,n,r)=>o(l(e,t,n),r),translateOptions:(e,t,n)=>n.map(n=>({...n,label:o(l(e,t,n.value),n.label)})),appLabel:e=>o(`apps.${e.name}.label`,e.label??e.name),appDescription:e=>{let t=e.description??``;return o(`apps.${e.name}.description`,t)||void 0}}}function o(){try{let{fieldLabel:e,translateOptions:t}=a();return{fieldLabel:e,translateOptions:t}}catch{return{fieldLabel:(e,t,n)=>n,translateOptions:(e,t,n)=>n}}}var s=e(n(),1),c=(0,s.createContext)(null);c.displayName=`AuthContext`;var l=`1.6.9`,u=Symbol.for(`better-auth:broadcast-channel`),d=()=>Math.floor(Date.now()/1e3),f=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(!(typeof window>`u`))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:d()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event!==`session`||!t?.data||this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function p(e=`better-auth.message`){return globalThis[u]||(globalThis[u]=new f(e)),globalThis[u]}var m=Symbol.for(`better-auth:focus-manager`),h=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function g(){return globalThis[m]||(globalThis[m]=new h),globalThis[m]}var _=Symbol.for(`better-auth:online-manager`),v=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function y(){return globalThis[_]||(globalThis[_]=new v),globalThis[_]}var b={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},x=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,S={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},C=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function w(e){return e instanceof Date&&!isNaN(e.getTime())}function T(e){let t=C.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return w(f)?f:null}function ee(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim();if(o.length>0&&o[0]===`"`&&o.endsWith(`"`)&&!o.slice(1,-1).includes(`"`))return o.slice(1,-1);let s=o.toLowerCase();if(s.length<=9&&s in S)return S[s];if(!x.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(b).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=T(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function E(e,t={strict:!0}){return ee(e,t)}var D=[],O=0,k=4,te=globalThis.nanostoresGlobal||={epoch:0},A=e=>{let t=[],n={get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{for(let t=O+k;t<D.length;)D[t]===e?D.splice(t,k):t+=k;let r=t.indexOf(e);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(e,r){te.epoch++;let i=!D.length;for(let i of t)D.push(i,n.value,e,r);if(i){for(O=0;O<D.length;O+=k)D[O](D[O+1],D[O+2],D[O+3]);D.length=0}},off(){},set(e){let t=n.value;t!==e&&(n.value=e,n.notify(t))},subscribe(e){let t=n.listen(e);return e(n.value),t},value:e};return n},j=5,M=6,N=10,ne=(e,t,n,r)=>(e.events=e.events||{},e.events[n+N]||(e.events[n+N]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);r.splice(i,1),r.length||(delete e.events[n],e.events[n+N](),delete e.events[n+N])}),re=1e3,P=(e,t)=>ne(e,n=>{let r=t(n);r&&e.events[M].push(r)},j,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[M]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[M])t();e.events[M]=[]}},re)},()=>{e.listen=n,e.off=r}}),ie=()=>typeof window>`u`,F=(e,t,n,r)=>{let i=A({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>a(e)}),a=async e=>new Promise(a=>{let o=typeof r==`function`?r({data:i.get().data,error:i.get().error,isPending:i.get().isPending}):r;n(t,{...o,query:{...o?.query,...e?.query},async onSuccess(e){i.set({data:e.data,error:null,isPending:!1,isRefetching:!1,refetch:i.value.refetch}),await o?.onSuccess?.(e)},async onError(e){let{request:t}=e,n=typeof t.retry==`number`?t.retry:t.retry?.attempts,r=t.retryAttempt||0;if(n&&r<n)return;let a=e.error.status===401;i.set({error:e.error,data:a?null:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch}),await o?.onError?.(e)},async onRequest(e){let t=i.get();i.set({isPending:t.data===null,data:t.data,error:null,isRefetching:!0,refetch:i.value.refetch}),await o?.onRequest?.(e)}}).catch(e=>{i.set({error:e,data:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}).finally(()=>{a(void 0)})});e=Array.isArray(e)?e:[e];let o=!1;for(let t of e)t.subscribe(async()=>{ie()||(o?await a():P(i,()=>{let e=setTimeout(async()=>{o||(o=!0,await a())},0);return()=>{i.off(),t.off(),clearTimeout(e)}}))});return i},I=()=>Math.floor(Date.now()/1e3);function L(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}var ae=5;function R(e){let{sessionAtom:t,sessionSignal:n,$fetch:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={lastSync:0,lastSessionRequest:0,cachedSession:void 0},l=()=>s||y().isOnline,u=e=>{if(!l())return;if(e?.event===`storage`){c.lastSync=I(),n.set(!n.get());return}let i=t.get(),a=()=>{c.lastSessionRequest=I(),r(`/get-session`).then(async e=>{let{data:a,error:o}=L(e);if(a?.needsRefresh)try{let e=await r(`/get-session`,{method:`POST`});({data:a,error:o}=L(e))}catch{}let s=a?.session&&a?.user?a:null;t.set({...i,data:s,error:o}),c.lastSync=I(),n.set(!n.get())}).catch(()=>{})};if(e?.event===`poll`){a();return}if(e?.event===`visibilitychange`){if(I()-c.lastSessionRequest<ae)return;c.lastSessionRequest=I()}if(e?.event===`visibilitychange`){a();return}(i?.data===null||i?.data===void 0)&&(c.lastSync=I(),n.set(!n.get()))},d=e=>{p().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{t.get()?.data&&u({event:`poll`})},a*1e3))},m=()=>{c.unsubscribeBroadcast=p().subscribe(()=>{u({event:`storage`})})},h=()=>{o&&(c.unsubscribeFocus=g().subscribe(()=>{u({event:`visibilitychange`})}))},_=()=>{c.unsubscribeOnline=y().subscribe(e=>{e&&u({event:`visibilitychange`})})};return{init:()=>{f(),m(),h(),_(),p().setup(),g().setup(),y().setup()},cleanup:()=>{c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.lastSync=0,c.lastSessionRequest=0,c.cachedSession=void 0},triggerRefetch:u,broadcastSessionUpdate:d}}var z=Object.create(null),B=e=>({}),V=new Proxy(z,{get(e,t){return B()[t]??z[t]},has(e,t){return t in B()||t in z},set(e,t,n){let r=B(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=B(!0);return delete n[t],!0},ownKeys(){let e=B(!0);return Object.keys(e)}});function H(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return H(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return H(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return H(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return H(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return H(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return H(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return H(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});function oe(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}function se(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function ce(e){let t=e.split(`
1
+ import{r as e}from"./rolldown-runtime-S-ySWqyJ.js";import{_ as t,t as n}from"./vendor-react-B1k2FF9f.js";import{a as r}from"./framework-CoXA0nY6.js";var i=new Set([`common`,`validation`,`form`,`table`,`grid`,`calendar`,`list`,`kanban`,`chart`,`dashboard`,`configPanel`,`appDesigner`,`console`,`errors`,`detail`]);function a(){let{t:e,i18n:t}=r(),n=()=>{if(!t||typeof t.getResourceBundle!=`function`)return[];let e=t.language||`en`,n=t.getResourceBundle(e,`translation`);return n?Object.keys(n).filter(e=>!i.has(e)&&n[e]&&typeof n[e]==`object`&&(n[e].objects||n[e].fields||n[e].apps||n[e].dashboards||n[e].pages||n[e].reports)):[]},a=e=>{let t=e.indexOf(`__`);return t>0?e.slice(t+2):e},o=(t,r)=>{let i=Array.isArray(t)?t:[t];try{let t=n();for(let n of t)for(let t of i){let r=`${n}.${t}`,i=e(r,{defaultValue:``});if(i&&i!==r&&i!==``)return i}}catch{}return r},s=(e,t)=>{let n=a(e);return n===e?[`objects.${e}.${t}`]:[`objects.${e}.${t}`,`objects.${n}.${t}`]},c=(e,t)=>{let n=a(e);return n===e?[`fields.${e}.${t}`]:[`fields.${e}.${t}`,`fields.${n}.${t}`]},l=(e,t,n)=>{let r=a(e);return r===e?[`fieldOptions.${e}.${t}.${n}`]:[`fieldOptions.${e}.${t}.${n}`,`fieldOptions.${r}.${t}.${n}`]},u=(e,t)=>{let n=a(e);return n===e?[`dashboards.${e}.${t}`]:[`dashboards.${e}.${t}`,`dashboards.${n}.${t}`]},d=(e,t)=>{let n=a(e);return n===e?[`pages.${e}.${t}`]:[`pages.${e}.${t}`,`pages.${n}.${t}`]},f=(e,t)=>{let n=a(e);return n===e?[`reports.${e}.${t}`]:[`reports.${e}.${t}`,`reports.${n}.${t}`]};return{objectLabel:e=>o(s(e.name,`label`),e.label),objectDescription:e=>{if(e.description)return o(s(e.name,`description`),e.description)},fieldLabel:(e,t,n)=>o(c(e,t),n),fieldOptionLabel:(e,t,n,r)=>o(l(e,t,n),r),translateOptions:(e,t,n)=>n.map(n=>({...n,label:o(l(e,t,n.value),n.label)})),appLabel:e=>o(`apps.${e.name}.label`,e.label??e.name),appDescription:e=>{let t=e.description??``;return o(`apps.${e.name}.description`,t)||void 0},navGroupLabel:(e,t,n)=>o(`apps.${e}.navigation.${t}.label`,n),dashboardLabel:e=>o(u(e.name,`label`),e.label??e.name),dashboardDescription:e=>{let t=e.description??``;return o(u(e.name,`description`),t)||void 0},dashboardActionLabel:(e,t,n)=>o(u(e,`actions.${t}.label`),n),widgetTitle:(e,t,n)=>o(u(e,`widgets.${t}.title`),n),widgetDescription:(e,t,n)=>{let r=n??``;return o(u(e,`widgets.${t}.description`),r)||void 0},pageLabel:e=>o(d(e.name,`label`),e.label??e.name),reportLabel:e=>o(f(e.name,`label`),e.label??e.name)}}function o(){try{let{fieldLabel:e,translateOptions:t,fieldOptionLabel:n}=a();return{fieldLabel:e,translateOptions:t,fieldOptionLabel:n}}catch{return{fieldLabel:(e,t,n)=>n,translateOptions:(e,t,n)=>n,fieldOptionLabel:(e,t,n,r)=>r}}}var s=e(t(),1),c=(0,s.createContext)(null);c.displayName=`AuthContext`;var l=`1.6.9`,u=Symbol.for(`better-auth:broadcast-channel`),d=()=>Math.floor(Date.now()/1e3),f=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(!(typeof window>`u`))try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:d()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event!==`session`||!t?.data||this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function p(e=`better-auth.message`){return globalThis[u]||(globalThis[u]=new f(e)),globalThis[u]}var m=Symbol.for(`better-auth:focus-manager`),h=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function g(){return globalThis[m]||(globalThis[m]=new h),globalThis[m]}var _=Symbol.for(`better-auth:online-manager`),v=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function y(){return globalThis[_]||(globalThis[_]=new v),globalThis[_]}var b={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},x=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,S={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},C=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function w(e){return e instanceof Date&&!isNaN(e.getTime())}function T(e){let t=C.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return w(f)?f:null}function ee(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim();if(o.length>0&&o[0]===`"`&&o.endsWith(`"`)&&!o.slice(1,-1).includes(`"`))return o.slice(1,-1);let s=o.toLowerCase();if(s.length<=9&&s in S)return S[s];if(!x.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(b).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=T(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function E(e,t={strict:!0}){return ee(e,t)}var D=[],O=0,k=4,te=globalThis.nanostoresGlobal||={epoch:0},A=e=>{let t=[],n={get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{for(let t=O+k;t<D.length;)D[t]===e?D.splice(t,k):t+=k;let r=t.indexOf(e);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(e,r){te.epoch++;let i=!D.length;for(let i of t)D.push(i,n.value,e,r);if(i){for(O=0;O<D.length;O+=k)D[O](D[O+1],D[O+2],D[O+3]);D.length=0}},off(){},set(e){let t=n.value;t!==e&&(n.value=e,n.notify(t))},subscribe(e){let t=n.listen(e);return e(n.value),t},value:e};return n},j=5,M=6,N=10,ne=(e,t,n,r)=>(e.events=e.events||{},e.events[n+N]||(e.events[n+N]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);r.splice(i,1),r.length||(delete e.events[n],e.events[n+N](),delete e.events[n+N])}),re=1e3,P=(e,t)=>ne(e,n=>{let r=t(n);r&&e.events[M].push(r)},j,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[M]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[M])t();e.events[M]=[]}},re)},()=>{e.listen=n,e.off=r}}),ie=()=>typeof window>`u`,F=(e,t,n,r)=>{let i=A({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>a(e)}),a=async e=>new Promise(a=>{let o=typeof r==`function`?r({data:i.get().data,error:i.get().error,isPending:i.get().isPending}):r;n(t,{...o,query:{...o?.query,...e?.query},async onSuccess(e){i.set({data:e.data,error:null,isPending:!1,isRefetching:!1,refetch:i.value.refetch}),await o?.onSuccess?.(e)},async onError(e){let{request:t}=e,n=typeof t.retry==`number`?t.retry:t.retry?.attempts,r=t.retryAttempt||0;if(n&&r<n)return;let a=e.error.status===401;i.set({error:e.error,data:a?null:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch}),await o?.onError?.(e)},async onRequest(e){let t=i.get();i.set({isPending:t.data===null,data:t.data,error:null,isRefetching:!0,refetch:i.value.refetch}),await o?.onRequest?.(e)}}).catch(e=>{i.set({error:e,data:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}).finally(()=>{a(void 0)})});e=Array.isArray(e)?e:[e];let o=!1;for(let t of e)t.subscribe(async()=>{ie()||(o?await a():P(i,()=>{let e=setTimeout(async()=>{o||(o=!0,await a())},0);return()=>{i.off(),t.off(),clearTimeout(e)}}))});return i},I=()=>Math.floor(Date.now()/1e3);function L(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}var ae=5;function R(e){let{sessionAtom:t,sessionSignal:n,$fetch:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={lastSync:0,lastSessionRequest:0,cachedSession:void 0},l=()=>s||y().isOnline,u=e=>{if(!l())return;if(e?.event===`storage`){c.lastSync=I(),n.set(!n.get());return}let i=t.get(),a=()=>{c.lastSessionRequest=I(),r(`/get-session`).then(async e=>{let{data:a,error:o}=L(e);if(a?.needsRefresh)try{let e=await r(`/get-session`,{method:`POST`});({data:a,error:o}=L(e))}catch{}let s=a?.session&&a?.user?a:null;t.set({...i,data:s,error:o}),c.lastSync=I(),n.set(!n.get())}).catch(()=>{})};if(e?.event===`poll`){a();return}if(e?.event===`visibilitychange`){if(I()-c.lastSessionRequest<ae)return;c.lastSessionRequest=I()}if(e?.event===`visibilitychange`){a();return}(i?.data===null||i?.data===void 0)&&(c.lastSync=I(),n.set(!n.get()))},d=e=>{p().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{t.get()?.data&&u({event:`poll`})},a*1e3))},m=()=>{c.unsubscribeBroadcast=p().subscribe(()=>{u({event:`storage`})})},h=()=>{o&&(c.unsubscribeFocus=g().subscribe(()=>{u({event:`visibilitychange`})}))},_=()=>{c.unsubscribeOnline=y().subscribe(e=>{e&&u({event:`visibilitychange`})})};return{init:()=>{f(),m(),h(),_(),p().setup(),g().setup(),y().setup()},cleanup:()=>{c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.lastSync=0,c.lastSessionRequest=0,c.cachedSession=void 0},triggerRefetch:u,broadcastSessionUpdate:d}}var z=Object.create(null),B=e=>({}),V=new Proxy(z,{get(e,t){return B()[t]??z[t]},has(e,t){return t in B()||t in z},set(e,t,n){let r=B(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=B(!0);return delete n[t],!0},ownKeys(){let e=B(!0);return Object.keys(e)}});function H(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return H(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return H(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return H(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return H(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return H(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return H(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return H(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});function oe(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}function se(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function ce(e){let t=e.split(`
2
2
  at `);return t.length<=1?e:(t.splice(1,1),t.join(`
3
- at `))}function le(e,t){class n extends e{#e;constructor(...e){if(se()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=ce(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,`constructor`,{get(){return t},enumerable:!1,configurable:!0}),n}var ue={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};le(class extends Error{constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:ue[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var U=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}};function de(e){try{return(new URL(e).pathname.replace(/\/+$/,``)||`/`)!==`/`}catch{throw new U(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function fe(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new U(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof U?t:new U(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function W(e,t=`/api/auth`){if(fe(e),de(e))return e;let n=e.replace(/\/+$/,``);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function pe(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function me(e,t,n,r,i){if(e)return W(e,t);if(r!==!1){let e=V.BETTER_AUTH_URL||V.NEXT_PUBLIC_BETTER_AUTH_URL||V.PUBLIC_BETTER_AUTH_URL||V.NUXT_PUBLIC_BETTER_AUTH_URL||V.NUXT_PUBLIC_AUTH_URL||(V.BASE_URL===`/`?void 0:V.BASE_URL);if(e)return W(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&pe(o,`proto`)&&pe(a,`host`))try{return W(`${o}://${a}`,t)}catch{}if(n){let e=he(n.url);if(!e)throw new U(`Could not get origin from request. Please provide a valid base URL.`);return W(e,t)}if(typeof window<`u`&&window.location)return W(window.location.origin,t)}function he(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var ge={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};function _e(e,t){let n=A(!1),r=F(n,`/get-session`,e,{method:`GET`}),i=()=>{};return P(r,()=>{let a=R({sessionAtom:r,sessionSignal:n,$fetch:e,options:t});return a.init(),i=a.broadcastSessionUpdate,()=>{a.cleanup()}}),{session:r,$sessionSignal:n,broadcastSessionUpdate:e=>i(e)}}function G(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function K(e,t,n=`.`,r){if(!G(t))return K(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(Array.isArray(a)&&Array.isArray(i[t])?i[t]=[...a,...i[t]]:G(a)&&G(i[t])?i[t]=K(a,i[t],(n?`${n}.`:``)+t.toString(),r):i[t]=a))}return i}function ve(e){return(...t)=>t.reduce((t,n)=>K(t,n,``,e),{})}var ye=ve(),be=Object.defineProperty,xe=Object.defineProperties,Se=Object.getOwnPropertyDescriptors,Ce=Object.getOwnPropertySymbols,we=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable,Ee=(e,t,n)=>t in e?be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,q=(e,t)=>{for(var n in t||={})we.call(t,n)&&Ee(e,n,t[n]);if(Ce)for(var n of Ce(t))Te.call(t,n)&&Ee(e,n,t[n]);return e},J=(e,t)=>xe(e,Se(t)),De=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Oe=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let r=await i.init?.call(i,e.toString(),t);n=r.options||n,e=r.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},ke=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Ae=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function je(e){if(typeof e==`number`)return new ke({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new ke(e);case`exponential`:return new Ae(e);default:throw Error(`Invalid retry strategy`)}}var Me=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Ne=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Pe(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Ne.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function Fe(e){try{return JSON.parse(e),!0}catch{return!1}}function Ie(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function Le(e){try{return JSON.parse(e)}catch{return e}}function Re(e){return typeof e==`function`}function ze(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Re(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Re(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}async function Be(e){let t=new Headers(e?.headers),n=await Me(e);for(let[e,r]of Object.entries(n||{}))t.set(e,r);if(!t.has(`content-type`)){let n=Ve(e?.body);n&&t.set(`content-type`,n)}return t}function Ve(e){return Ie(e)?`application/json`:null}function He(e){if(!e?.body)return null;let t=new Headers(e?.headers);if(Ie(e.body)&&!t.has(`content-type`)){for(let[t,n]of Object.entries(e?.body))n instanceof Date&&(e.body[t]=n.toISOString());return JSON.stringify(e.body)}return t.has(`content-type`)&&t.get(`content-type`)===`application/x-www-form-urlencoded`&&Ie(e.body)?new URLSearchParams(e.body).toString():e.body}function Ue(e,t){if(t?.method)return t.method.toUpperCase();if(e.startsWith(`@`)){let n=e.split(`@`)[1]?.split(`/`)[0];return Ke.includes(n)?n.toUpperCase():t?.body?`POST`:`GET`}return t?.body?`POST`:`GET`}function We(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var Ge=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function Y(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new Ge(n.issues);return n.value}var Ke=[`get`,`post`,`put`,`patch`,`delete`],qe=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){let r=e.plugins?.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1)?.schema||e.schema;if(r){let e=t;r.config?.prefix&&e.startsWith(r.config.prefix)&&(e=e.replace(r.config.prefix,``),r.config.baseURL&&(t=t.replace(r.config.prefix,r.config.baseURL))),r.config?.baseURL&&e.startsWith(r.config.baseURL)&&(e=e.replace(r.config.baseURL,``));let i=r.schema[e];if(i){let e=J(q({},n),{method:i.method,output:i.output});return n?.disableValidation||(e=J(q({},e),{body:i.input?await Y(i.input,n?.body):n?.body,params:i.params?await Y(i.params,n?.params):n?.params,query:i.query?await Y(i.query,n?.query):n?.query})),{url:t,options:e}}}return{url:t,options:n}}}),Je=e=>{async function t(t,n){let r=J(q(q({},e),n),{plugins:[...e?.plugins||[],qe(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Xe(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await Xe(t,r)}return t};function Ye(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``;if(e.startsWith(`@`)){let t=e.toString().split(`@`)[1].split(`/`)[0];Ke.includes(t)&&(e=e.replace(`@${t}/`,`/`))}a.endsWith(`/`)||(a+=`/`);let[o,s]=e.replace(a,``).split(`?`),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)c.append(e,n);continue}else n=JSON.stringify(t);c.set(e,n)}if(r)if(Array.isArray(r)){let e=o.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];o=o.replace(n,e)}}else for(let[e,t]of Object.entries(r))o=o.replace(`:${e}`,String(t));o=o.split(`/`).map(encodeURIComponent).join(`/`),o.startsWith(`/`)&&(o=o.slice(1));let l=c.toString();return l=l.length>0?`?${l}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${o}${l}`,a):`${a}${o}${l}`}var Xe=async(e,t)=>{let{hooks:n,url:r,options:i}=await Oe(e,t),a=ze(i),o=new AbortController,s=i.signal??o.signal,c=Ye(r,i),l=He(i),u=await Be(i),d=Ue(r,i),f=J(q({},i),{url:c,headers:u,body:l,method:d,signal:s});for(let e of n.onRequest)if(e){let t=await e(f);typeof t==`object`&&t&&(f=t)}(`pipeTo`in f&&typeof f.pipeTo==`function`||typeof t?.body?.pipe==`function`)&&(`duplex`in f||(f.duplex=`half`));let{clearTimeout:p}=We(i,o),m=await a(f.url,f);p();let h={response:m,request:f};for(let e of n.onResponse)if(e){let n=await e(J(q({},h),{response:t?.hookOptions?.cloneResponse?m.clone():m}));n instanceof Response?m=n:typeof n==`object`&&n&&(m=n.response)}if(m.ok){if(f.method===`HEAD`)return{data:``,error:null};let e=Pe(m),r={data:null,response:m,request:f};if(e===`json`||e===`text`){let e=await m.text();r.data=await(f.jsonParser??Le)(e)}else r.data=await m[e]();f?.output&&f.output&&!f.disableValidation&&(r.data=await Y(f.output,r.data));for(let e of n.onSuccess)e&&await e(J(q({},r),{response:t?.hookOptions?.cloneResponse?m.clone():m}));return t?.throw?r.data:{data:r.data,error:null}}let g=t?.jsonParser??Le,_=await m.text(),v=Fe(_),y=v?await g(_):null,b={response:m,responseText:_,request:f,error:J(q({},y),{status:m.status,statusText:m.statusText})};for(let e of n.onError)e&&await e(J(q({},b),{response:t?.hookOptions?.cloneResponse?m.clone():m}));if(t?.retry){let r=je(t.retry),i=t.retryAttempt??0;if(await r.shouldAttemptRetry(i,m)){for(let e of n.onRetry)e&&await e(h);let a=r.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await Xe(e,J(q({},t),{retryAttempt:i+1}))}}if(t?.throw)throw new De(m.status,m.statusText,v?y:_);return{data:null,error:J(q({},y),{status:m.status,statusText:m.statusText})}},Ze=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},Qe=(e,t)=>{let n=`credentials`in Request.prototype,r=me(e?.baseURL,e?.basePath,void 0,t)??Ze(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=Je({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?E(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[ge],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=_e(d,e),h=e?.plugins||[],g={},_={$sessionSignal:f,session:p},v={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},y=[{signal:`$sessionSignal`,matcher(e){return e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`},callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of h)e.getAtoms&&Object.assign(_,e.getAtoms?.(d)),e.pathMethods&&Object.assign(v,e.pathMethods),e.atomListeners&&y.push(...e.atomListeners);let b={notify:e=>{_[e].set(!_[e].get())},listen:(e,t)=>{_[e].subscribe(t)},atoms:_};for(let t of h)t.getActions&&(g=ye(t.getActions?.(d,b,e)??{},g));return{get baseURL(){return r},pluginsActions:g,pluginsAtoms:_,pluginPathMethods:v,atomListeners:y,$fetch:d,$store:b}};function $e(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function et(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function tt(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||$e(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(e=>e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=et(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}function nt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function rt(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,$fetch:i,atomListeners:a,$store:o}=Qe(e),s={};for(let[e,t]of Object.entries(r))s[`use${nt(e)}`]=t;return tt({...n,...s,$fetch:i,$store:o},i,t,r,a)}function it(e){return{authorize(t,n=`AND`){let r=!1;for(let[i,a]of Object.entries(t)){let t=e[i];if(!t)return{success:!1,error:`You are not allowed to access resource: ${i}`};if(Array.isArray(a))r=a.every(e=>t.includes(e));else if(typeof a==`object`){let e=a;r=e.connector===`OR`?e.actions.some(e=>t.includes(e)):e.actions.every(e=>t.includes(e))}else throw new U(`Invalid access control request`);if(r&&n===`OR`)return{success:r};if(!r&&n===`AND`)return{success:!1,error:`unauthorized to access resource "${i}"`}}return r?{success:r}:{success:!1,error:`Not authorized`}},statements:e}}function at(e){return{newRole(e){return it(e)},statements:e}}var ot=oe({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:`You are not allowed to create a new organization`,YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:`You have reached the maximum number of organizations`,ORGANIZATION_ALREADY_EXISTS:`Organization already exists`,ORGANIZATION_SLUG_ALREADY_TAKEN:`Organization slug already taken`,ORGANIZATION_NOT_FOUND:`Organization not found`,USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:`User is not a member of the organization`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:`You are not allowed to update this organization`,YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:`You are not allowed to delete this organization`,NO_ACTIVE_ORGANIZATION:`No active organization`,USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:`User is already a member of this organization`,MEMBER_NOT_FOUND:`Member not found`,ROLE_NOT_FOUND:`Role not found`,YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:`You are not allowed to create a new team`,TEAM_ALREADY_EXISTS:`Team already exists`,TEAM_NOT_FOUND:`Team not found`,YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:`You cannot leave the organization as the only owner`,YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:`You cannot leave the organization without an owner`,YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:`You are not allowed to delete this member`,YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:`You are not allowed to invite users to this organization`,USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:`User is already invited to this organization`,INVITATION_NOT_FOUND:`Invitation not found`,YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:`You are not the recipient of the invitation`,EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:`Email verification required before accepting or rejecting invitation`,YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:`You are not allowed to cancel this invitation`,INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:`Inviter is no longer a member of the organization`,YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:`You are not allowed to invite a user with this role`,FAILED_TO_RETRIEVE_INVITATION:`Failed to retrieve invitation`,YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:`You have reached the maximum number of teams`,UNABLE_TO_REMOVE_LAST_TEAM:`Unable to remove last team`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:`You are not allowed to update this member`,ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:`Organization membership limit reached`,YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:`You are not allowed to create teams in this organization`,YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:`You are not allowed to delete teams in this organization`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:`You are not allowed to update this team`,YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:`You are not allowed to delete this team`,INVITATION_LIMIT_REACHED:`Invitation limit reached`,TEAM_MEMBER_LIMIT_REACHED:`Team member limit reached`,USER_IS_NOT_A_MEMBER_OF_THE_TEAM:`User is not a member of the team`,YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:`You are not allowed to list the members of this team`,YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:`You do not have an active team`,YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:`You are not allowed to create a new member`,YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:`You are not allowed to remove a team member`,YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:`You are not allowed to access this organization as an owner`,YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:`You are not a member of this organization`,MISSING_AC_INSTANCE:`Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information`,YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:`You must be in an organization to create a role`,YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:`You are not allowed to create a role`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:`You are not allowed to update a role`,YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:`You are not allowed to delete a role`,YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:`You are not allowed to read a role`,YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:`You are not allowed to list a role`,YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:`You are not allowed to get a role`,TOO_MANY_ROLES:`This organization has too many roles`,INVALID_RESOURCE:`The provided permission includes an invalid resource`,ROLE_NAME_IS_ALREADY_TAKEN:`That role name is already taken`,CANNOT_DELETE_A_PRE_DEFINED_ROLE:`Cannot delete a pre-defined role`,ROLE_IS_ASSIGNED_TO_MEMBERS:`Cannot delete a role that is assigned to members. Please reassign the members to a different role first`}),st=at({organization:[`update`,`delete`],member:[`create`,`update`,`delete`],invitation:[`create`,`cancel`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),ct=st.newRole({organization:[`update`],invitation:[`create`,`cancel`],member:[`create`,`update`,`delete`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),lt=st.newRole({organization:[`update`,`delete`],member:[`create`,`update`,`delete`],invitation:[`create`,`cancel`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),ut=st.newRole({organization:[],member:[],invitation:[],team:[],ac:[`read`]}),dt={admin:ct,owner:lt,member:ut},ft=(e,t)=>{if(!e.permissions)return!1;let n=e.role.split(`,`),r=e.options.creatorRole||`owner`,i=n.includes(r),a=e.allowCreatorAllPermissions||!1;if(i&&a)return!0;for(let r of n)if(t[r]?.authorize(e.permissions)?.success)return!0;return!1},pt=e=>ft(e,e.options.roles||dt),mt=e=>{let t=A(!1),n=A(!1),r=A(!1),i=A(!1),a={admin:ct,member:ut,owner:lt,...e?.roles};return{id:`organization`,version:l,$InferServerPlugin:{},getActions:(t,n,r)=>({$Infer:{ActiveOrganization:{},Organization:{},Invitation:{},Member:{},Team:{}},organization:{checkRolePermission:t=>pt({role:t.role,options:{ac:e?.ac,roles:a},permissions:t.permissions})}}),getAtoms:e=>{let a=F(t,`/organization/list`,e,{method:`GET`});return{$listOrg:t,$activeOrgSignal:n,$activeMemberSignal:r,$activeMemberRoleSignal:i,activeOrganization:F([n],`/organization/get-full-organization`,e,()=>({method:`GET`})),listOrganizations:a,activeMember:F([n,r],`/organization/get-active-member`,e,{method:`GET`}),activeMemberRole:F([n,i],`/organization/get-active-member-role`,e,{method:`GET`})}},pathMethods:{"/organization/get-full-organization":`GET`,"/organization/list-user-teams":`GET`},atomListeners:[{matcher(e){return e===`/organization/create`||e===`/organization/delete`||e===`/organization/update`},signal:`$listOrg`},{matcher(e){return e.startsWith(`/organization`)},signal:`$activeOrgSignal`},{matcher(e){return e.startsWith(`/organization/set-active`)||e===`/organization/create`||e===`/organization/delete`||e===`/organization/remove-member`||e===`/organization/leave`||e===`/organization/accept-invitation`},signal:`$sessionSignal`},{matcher(e){return e.includes(`/organization/update-member-role`)||e.startsWith(`/organization/set-active`)},signal:`$activeMemberSignal`},{matcher(e){return e.includes(`/organization/update-member-role`)||e.startsWith(`/organization/set-active`)},signal:`$activeMemberRoleSignal`}],$ERROR_CODES:ot}},ht=`auth-session-token`,X={_memoryToken:null,get(){try{if(typeof localStorage<`u`)return localStorage.getItem(ht)}catch{}return this._memoryToken},set(e){this._memoryToken=e;try{typeof localStorage<`u`&&localStorage.setItem(ht,e)}catch{}},clear(){this._memoryToken=null;try{typeof localStorage<`u`&&localStorage.removeItem(ht)}catch{}}};function gt(e){try{let t=new URL(e);return{origin:t.origin,basePath:t.pathname.replace(/\/$/,``)}}catch{return{origin:_t()??`http://localhost`,basePath:e.replace(/\/$/,``)}}}function _t(){try{if(typeof window<`u`&&window.location?.origin)return window.location.origin}catch{}}function vt(e){let t=e||globalThis.fetch.bind(globalThis);return async(e,n)=>{let r=new Headers(n?.headers),i=X.get();if(i){let t=typeof e==`string`?e:e instanceof URL?e.href:e.url;/\/api\//i.test(t)&&r.set(`Authorization`,`Bearer ${i}`)}let a=await t(e,{...n,headers:r}),o=a.headers.get(`set-auth-token`);return o&&X.set(o),a}}function yt(e){let{baseURL:t,fetchFn:n}=e,{origin:r,basePath:i}=gt(t),a=vt(n),o=rt({baseURL:r,basePath:i,disableDefaultFetchPlugins:!0,fetchOptions:{customFetchImpl:a},plugins:[mt()]});return{async signIn(e){let{data:t,error:n}=await o.signIn.email({email:e.email,password:e.password});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`);let r=t;return r.session?.token&&X.set(r.session.token),{user:r.user,session:r.session}},async signUp(e){let{data:t,error:n}=await o.signUp.email({email:e.email,password:e.password,name:e.name});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`);let r=t;return r.session?.token&&X.set(r.session.token),{user:r.user,session:r.session}},async signOut(){let{error:e}=await o.signOut();if(X.clear(),e)throw Error(e.message??`Auth request failed with status ${e.status}`)},async getSession(){let{data:e,error:t}=await o.getSession();if(t||!e)return null;let n=e;return n.session?.token&&X.set(n.session.token),{user:n.user,session:n.session}},async forgotPassword(e){let t=o.forgetPassword,{error:n}=await t({email:e,redirectTo:`/`});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`)},async resetPassword(e,t){let{error:n}=await o.resetPassword({token:e,newPassword:t});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`)},async updateUser(e){let{data:t,error:n}=await o.updateUser(e);if(n)throw Error(n.message??`Auth request failed with status ${n.status}`);if(!t)throw Error(`Update user returned no data`);let r=t;return r&&typeof r==`object`&&`user`in r?r.user:r},async getConfig(){let e=await a(`${r}${i}/config`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(!e.ok)throw Error(`Failed to load auth config (status ${e.status})`);let t=await e.json();return t&&typeof t==`object`&&`data`in t&&t.data?t.data:t},async signInWithProvider(e,t={}){let{type:n=`social`,callbackURL:r,errorCallbackURL:i}=t;if(n===`oidc`){let t=o.signIn.oauth2;if(!t)throw Error(`OIDC sign-in is not supported by this auth client build`);let{error:n}=await t({providerId:e,callbackURL:r,errorCallbackURL:i});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`);return}let{error:a}=await o.signIn.social({provider:e,callbackURL:r,errorCallbackURL:i});if(a)throw Error(a.message??`Auth request failed with status ${a.status}`)},async listOrganizations(){let{data:e,error:t}=await o.organization.list();if(t)throw Error(t.message??`Failed to list organizations`);return e??[]},async createOrganization(e){let{data:t,error:n}=await o.organization.create({name:e.name,slug:e.slug,logo:e.logo});if(n)throw Error(n.message??`Failed to create organization`);return t},async setActiveOrganization(e){let{data:t,error:n}=await o.organization.setActive({organizationId:e});if(n)throw Error(n.message??`Failed to set active organization`);return t??null},async getActiveOrganization(){let{data:e,error:t}=await o.organization.getFullOrganization();return t||!e?null:e},async getMembers(e){let{data:t,error:n}=await o.organization.listMembers({query:{organizationId:e}});if(n)throw Error(n.message??`Failed to get members`);let r=t;return Array.isArray(r)?r:r?.members??[]},async inviteMember(e){let{data:t,error:n}=await o.organization.inviteMember({organizationId:e.organizationId,email:e.email,role:e.role});if(n)throw Error(n.message??`Failed to invite member`);return t},async removeMember(e){let{error:t}=await o.organization.removeMember({organizationId:e.organizationId,memberIdOrUserId:e.memberIdOrUserId});if(t)throw Error(t.message??`Failed to remove member`)},async updateMemberRole(e){let{error:t}=await o.organization.updateMemberRole({organizationId:e.organizationId,memberId:e.memberId,role:e.role});if(t)throw Error(t.message??`Failed to update member role`)},async updateOrganization(e,t){let{data:n,error:r}=await o.organization.update({organizationId:e,data:t});if(r)throw Error(r.message??`Failed to update organization`);return n},async deleteOrganization(e){let{error:t}=await o.organization.delete({organizationId:e});if(t)throw Error(t.message??`Failed to delete organization`)},async leaveOrganization(e){let{error:t}=await o.organization.leave({organizationId:e});if(t)throw Error(t.message??`Failed to leave organization`)},async listInvitations(e){let{data:t,error:n}=await o.organization.listInvitations({query:{organizationId:e}});if(n)throw Error(n.message??`Failed to list invitations`);return t??[]},async cancelInvitation(e){let{error:t}=await o.organization.cancelInvitation({invitationId:e});if(t)throw Error(t.message??`Failed to cancel invitation`)},async getInvitation(e){let{data:t,error:n}=await o.organization.getInvitation({query:{id:e}});if(n)throw Error(n.message??`Failed to load invitation`);return t},async acceptInvitation(e){let{error:t}=await o.organization.acceptInvitation({invitationId:e});if(t)throw Error(t.message??`Failed to accept invitation`)},async rejectInvitation(e){let{error:t}=await o.organization.rejectInvitation({invitationId:e});if(t)throw Error(t.message??`Failed to reject invitation`)},async listUserInvitations(){let{data:e,error:t}=await o.organization.listUserInvitations();if(t)throw Error(t.message??`Failed to list invitations`);return e??[]}}}var bt=`auth-active-organization-id`,Z={_memoryValue:null,get(){try{if(typeof localStorage<`u`)return localStorage.getItem(bt)}catch{}return this._memoryValue},set(e){this._memoryValue=e;try{typeof localStorage<`u`&&localStorage.setItem(bt,e)}catch{}},clear(){this._memoryValue=null;try{typeof localStorage<`u`&&localStorage.removeItem(bt)}catch{}}};function xt(){return async(e,t)=>{let n=new Headers(t?.headers),r=X.get();if(r){let t=typeof e==`string`?e:e instanceof URL?e.href:e.url;/\/api\//i.test(t)&&n.set(`Authorization`,`Bearer ${r}`)}let i=Z.get();return i&&n.set(`X-Tenant-ID`,i),fetch(e,{...t,headers:n})}}var Q=t();function St({authUrl:e,client:t,onAuthStateChange:n,enabled:r=!0,previewMode:i,children:a}){let o=(0,s.useMemo)(()=>t??yt({baseURL:e}),[t,e]),[l,u]=(0,s.useState)(null),[d,f]=(0,s.useState)(null),[p,m]=(0,s.useState)(!0),[h,g]=(0,s.useState)(null),[_,v]=(0,s.useState)([]),[y,b]=(0,s.useState)(null),[x,S]=(0,s.useState)(!1),C=i!=null,w=r&&!C?l!==null&&d!==null:!0;(0,s.useEffect)(()=>{if(C){let e=i.simulatedRole??`admin`,t=i.simulatedUserName??`Preview User`,n=i.expiresInSeconds??0;u({id:`preview-user`,email:`preview@preview.local`,name:t,role:e,roles:[e]}),f({token:`preview-token`,expiresAt:n>0?new Date(Date.now()+n*1e3):new Date(Date.now()+365*24*60*60*1e3)}),m(!1);return}if(!r){u({id:`guest`,email:`guest@local`,name:`Guest User`,role:`admin`}),f({token:`guest-token`,expiresAt:new Date(Date.now()+365*24*60*60*1e3)}),m(!1);return}let e=!1;async function t(){try{let t=await o.getSession();if(e)return;t&&(u(t.user),f(t.session))}catch(t){if(e)return;g(t instanceof Error?t:Error(String(t)))}finally{e||m(!1)}}return t(),()=>{e=!0}},[o,r,C,i]),(0,s.useEffect)(()=>{n?.({user:l,session:d,isAuthenticated:w,isLoading:p,error:h})},[l,d,w,p,h,n]);let T=(0,s.useCallback)(async(e,t)=>{m(!0),g(null);try{let n=await o.signIn({email:e,password:t});u(n.user),f(n.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{m(!1)}},[o]),ee=(0,s.useCallback)(async(e,t,n)=>{m(!0),g(null);try{let r=await o.signUp({name:e,email:t,password:n});u(r.user),f(r.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{m(!1)}},[o]),E=(0,s.useCallback)(async()=>{m(!0);try{await o.signOut(),u(null),f(null),g(null)}catch(e){g(e instanceof Error?e:Error(String(e)))}finally{m(!1)}},[o]),D=(0,s.useCallback)(async e=>{g(null);try{u(await o.updateUser(e))}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),O=(0,s.useCallback)(async e=>{g(null);try{await o.forgotPassword(e)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),k=(0,s.useCallback)(async(e,t)=>{g(null);try{await o.resetPassword(e,t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),te=(0,s.useCallback)(()=>o.getConfig(),[o]),A=(0,s.useCallback)(async(e,t)=>{g(null);try{await o.signInWithProvider(e,t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),j=(0,s.useCallback)(async()=>{if(!(!r||C)){S(!0);try{let e=await o.listOrganizations();if(v(e),e.length>0&&!y)try{let e=await o.getActiveOrganization();e&&(b(e),Z.set(e.id))}catch{}}catch(e){console.warn(`[AuthProvider] Failed to load organizations:`,e)}finally{S(!1)}}},[o,r,C,y]);(0,s.useEffect)(()=>{l&&r&&!C&&j()},[l,r,C]);let M=(0,s.useCallback)(async e=>{g(null);try{let t=await o.setActiveOrganization(e);b(t),t?Z.set(t.id):Z.clear()}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),N=(0,s.useCallback)(async e=>{g(null);try{let t=await o.createOrganization(e);return await j(),await M(t.id),t}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o,j,M]),ne=(0,s.useCallback)(async(e,t)=>{let n=await o.updateOrganization(e,t);return await j(),y?.id===e&&b(n),n},[o,j,y]),re=(0,s.useCallback)(async e=>{await o.deleteOrganization(e),y?.id===e&&(b(null),Z.clear()),await j()},[o,y,j]),P=(0,s.useCallback)(async e=>{await o.leaveOrganization(e),y?.id===e&&(b(null),Z.clear()),await j()},[o,y,j]),ie=(0,s.useCallback)(e=>o.getMembers(e),[o]),F=(0,s.useCallback)(e=>o.inviteMember(e),[o]),I=(0,s.useCallback)(e=>o.removeMember(e),[o]),L=(0,s.useCallback)(e=>o.updateMemberRole(e),[o]),ae=(0,s.useCallback)(e=>o.listInvitations(e),[o]),R=(0,s.useCallback)(e=>o.cancelInvitation(e),[o]),z=(0,s.useCallback)(e=>o.getInvitation(e),[o]),B=(0,s.useCallback)(async e=>{await o.acceptInvitation(e),await j()},[o,j]),V=(0,s.useCallback)(e=>o.rejectInvitation(e),[o]),H=(0,s.useCallback)(()=>o.listUserInvitations(),[o]),oe=(0,s.useMemo)(()=>({user:l,session:d,isAuthenticated:w,isLoading:p,error:h,isPreviewMode:C,previewMode:C?i:null,signIn:T,signUp:ee,signOut:E,updateUser:D,forgotPassword:O,resetPassword:k,getAuthConfig:te,signInWithProvider:A,organizations:_,activeOrganization:y,isOrganizationsLoading:x,switchOrganization:M,createOrganization:N,refreshOrganizations:j,updateOrganization:ne,deleteOrganization:re,leaveOrganization:P,getMembers:ie,inviteMember:F,removeMember:I,updateMemberRole:L,listInvitations:ae,cancelInvitation:R,getInvitation:z,acceptInvitation:B,rejectInvitation:V,listUserInvitations:H}),[l,d,w,p,h,C,i,T,ee,E,D,O,k,te,A,_,y,x,M,N,j,ne,re,P,ie,F,I,L,ae,R,z,B,V,H]);return(0,Q.jsx)(c.Provider,{value:oe,children:a})}function $(){return(0,s.useContext)(c)||{user:null,session:null,isAuthenticated:!1,isLoading:!1,error:null,isPreviewMode:!1,previewMode:null,signIn:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},signUp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},signOut:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},updateUser:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},forgotPassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},resetPassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},getAuthConfig:async()=>({}),signInWithProvider:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},organizations:[],activeOrganization:null,isOrganizationsLoading:!1,switchOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},createOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},refreshOrganizations:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},updateOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},deleteOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},leaveOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},getMembers:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},inviteMember:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},removeMember:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},updateMemberRole:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},listInvitations:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},cancelInvitation:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},getInvitation:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},acceptInvitation:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},rejectInvitation:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},listUserInvitations:async()=>{throw Error(`useAuth must be used within an AuthProvider`)}}}function Ct({fallback:e=null,requiredRoles:t,loadingFallback:n,children:r}){let{isAuthenticated:i,isLoading:a,user:o}=$();if(a)return(0,Q.jsx)(Q.Fragment,{children:n??null});if(!i)return(0,Q.jsx)(Q.Fragment,{children:e});if(t&&t.length>0&&o){let n=o.roles??(o.role?[o.role]:[]);if(!t.some(e=>n.includes(e)))return(0,Q.jsx)(Q.Fragment,{children:e})}return(0,Q.jsx)(Q.Fragment,{children:r})}var wt={google:`Google`,github:`GitHub`,microsoft:`Microsoft`,apple:`Apple`,facebook:`Facebook`,twitter:`Twitter`,discord:`Discord`,gitlab:`GitLab`,linkedin:`LinkedIn`},Tt={google:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#EA4335`,d:`M12 10.2v3.9h5.5c-.24 1.4-1.7 4.1-5.5 4.1-3.3 0-6-2.74-6-6.1s2.7-6.1 6-6.1c1.88 0 3.14.8 3.86 1.5l2.64-2.55C16.84 3.36 14.66 2.4 12 2.4 6.92 2.4 2.8 6.52 2.8 11.6S6.92 20.8 12 20.8c6.92 0 9.2-4.86 9.2-7.4 0-.5-.06-.88-.14-1.2H12z`})}),github:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56v-2.07c-3.2.7-3.87-1.37-3.87-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.68 1.25 3.34.96.1-.74.4-1.25.73-1.54-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.18-3.1-.12-.29-.51-1.46.11-3.04 0 0 .97-.31 3.18 1.18a11.04 11.04 0 015.79 0c2.21-1.49 3.18-1.18 3.18-1.18.62 1.58.23 2.75.11 3.04.74.81 1.18 1.84 1.18 3.1 0 4.42-2.7 5.39-5.27 5.68.41.36.78 1.06.78 2.13v3.16c0 .31.21.68.8.56C20.21 21.39 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5z`})}),microsoft:(0,Q.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{fill:`#F25022`,d:`M2 2h9.5v9.5H2z`}),(0,Q.jsx)(`path`,{fill:`#7FBA00`,d:`M12.5 2H22v9.5h-9.5z`}),(0,Q.jsx)(`path`,{fill:`#00A4EF`,d:`M2 12.5h9.5V22H2z`}),(0,Q.jsx)(`path`,{fill:`#FFB900`,d:`M12.5 12.5H22V22h-9.5z`})]}),apple:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M16.37 12.55c-.02-2.27 1.85-3.36 1.94-3.42-1.06-1.55-2.71-1.76-3.3-1.79-1.4-.14-2.74.83-3.45.83-.71 0-1.81-.81-2.98-.79-1.53.02-2.95.89-3.74 2.27-1.6 2.77-.41 6.86 1.14 9.11.76 1.1 1.66 2.34 2.83 2.3 1.14-.05 1.57-.74 2.94-.74 1.37 0 1.76.74 2.96.71 1.22-.02 2-1.12 2.75-2.23.87-1.28 1.22-2.52 1.24-2.59-.03-.01-2.38-.91-2.4-3.66zM14.1 5.31c.62-.76 1.05-1.81.93-2.86-.9.04-2 .6-2.65 1.35-.58.66-1.1 1.74-.96 2.76 1.01.08 2.04-.51 2.68-1.25z`})}),facebook:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#1877F2`,d:`M24 12C24 5.37 18.63 0 12 0S0 5.37 0 12c0 5.99 4.39 10.95 10.13 11.85V15.47H7.08V12h3.05V9.36c0-3.01 1.79-4.67 4.53-4.67 1.31 0 2.69.23 2.69.23v2.96h-1.51c-1.49 0-1.96.93-1.96 1.88V12h3.33l-.53 3.47h-2.8v8.38C19.61 22.95 24 17.99 24 12z`})}),twitter:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z`})}),discord:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#5865F2`,d:`M20.32 4.37A19.79 19.79 0 0016.56 3l-.18.36a18.27 18.27 0 00-8.76 0L7.44 3a19.79 19.79 0 00-3.76 1.37C.99 8.4.27 12.34.63 16.22a19.94 19.94 0 006.07 3.07l.49-.7a13.2 13.2 0 01-2.07-.99c.17-.13.34-.27.5-.41a14.13 14.13 0 0012.76 0c.16.14.33.28.5.41-.66.4-1.36.73-2.07.99l.49.7a19.92 19.92 0 006.07-3.07c.43-4.5-.66-8.41-2.95-11.85zM8.52 14.12c-1.18 0-2.15-1.08-2.15-2.41 0-1.33.95-2.42 2.15-2.42 1.2 0 2.17 1.09 2.15 2.42 0 1.33-.96 2.41-2.15 2.41zm6.96 0c-1.18 0-2.15-1.08-2.15-2.41 0-1.33.95-2.42 2.15-2.42 1.2 0 2.17 1.09 2.15 2.42 0 1.33-.95 2.41-2.15 2.41z`})}),gitlab:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#FC6D26`,d:`M23.6 9.6L23.57 9.5 20.3.81a.84.84 0 00-1.6.05L16.5 7.6H7.5L5.3.86a.84.84 0 00-1.6-.05L.43 9.5l-.03.1a5.84 5.84 0 001.94 6.74l.01.01.03.02 4.8 3.6 2.38 1.8 1.45 1.1a1 1 0 001.2 0l1.45-1.1 2.38-1.8 4.83-3.62.01-.01a5.84 5.84 0 001.93-6.74z`})}),linkedin:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#0A66C2`,d:`M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.13 1.45-2.13 2.94v5.67H9.36V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.45v6.29zM5.34 7.43a2.06 2.06 0 11.01-4.13 2.06 2.06 0 010 4.13zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z`})})};function Et({id:e}){let t=Tt[e];return t?(0,Q.jsx)(`span`,{className:`mr-2 flex h-4 w-4 items-center justify-center`,children:t}):(0,Q.jsx)(`span`,{className:`mr-2 flex h-4 w-4 items-center justify-center rounded-sm bg-muted text-[10px] font-bold uppercase`,children:e[0]})}function Dt({mode:e=`sign-in`,callbackURL:t,errorCallbackURL:n,dividerText:r=`or continue with email`}){let{getAuthConfig:i,signInWithProvider:a}=$(),[o,c]=(0,s.useState)([]),[l,u]=(0,s.useState)(!0),[d,f]=(0,s.useState)(null);if((0,s.useEffect)(()=>{let e=!1;return Promise.resolve().then(()=>i()).then(t=>{e||c((t?.socialProviders??[]).filter(e=>e.enabled))}).catch(t=>{e||console.warn(`[SocialSignInButtons] failed to load auth config`,t)}).finally(()=>{e||u(!1)}),()=>{e=!0}},[i]),l||o.length===0)return null;let p=e===`sign-in`?`Continue with`:`Sign up with`,m=typeof window<`u`?window.location.href:void 0,h=async e=>{f(null);try{await a(e.id,{callbackURL:t??m,errorCallbackURL:n??t??m,type:e.type??`social`})}catch(e){f(e instanceof Error?e.message:String(e))}};return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[d&&(0,Q.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:d}),o.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>h(e),className:`inline-flex h-10 w-full items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium ring-offset-background transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,children:[(0,Q.jsx)(Et,{id:e.id}),p,` `,wt[e.id]??e.name]},e.id)),(0,Q.jsxs)(`div`,{className:`relative my-1`,children:[(0,Q.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,Q.jsx)(`span`,{className:`w-full border-t`})}),(0,Q.jsx)(`div`,{className:`relative flex justify-center text-xs uppercase`,children:(0,Q.jsx)(`span`,{className:`bg-background px-2 text-muted-foreground`,children:r})})]})]})}var Ot=({href:e,className:t,children:n})=>(0,Q.jsx)(`a`,{href:e,className:t,children:n});function kt({onSuccess:e,onError:t,registerUrl:n=`/register`,forgotPasswordUrl:r=`/forgot-password`,title:i=`Sign in to your account`,description:a=`Enter your email and password to continue`,linkComponent:o=Ot,labels:c={}}){let{signIn:l,isLoading:u}=$(),[d,f]=(0,s.useState)(``),[p,m]=(0,s.useState)(``),[h,g]=(0,s.useState)(null),_={emailLabel:c.emailLabel??`Email`,emailPlaceholder:c.emailPlaceholder??`name@example.com`,passwordLabel:c.passwordLabel??`Password`,passwordPlaceholder:c.passwordPlaceholder??`Enter your password`,forgotPasswordText:c.forgotPasswordText??`Forgot password?`,submitButton:c.submitButton??`Sign In`,submittingButton:c.submittingButton??`Signing in...`,noAccountText:c.noAccountText??`Don't have an account?`,signUpText:c.signUpText??`Sign up`};return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[380px]`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:i}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:a})]}),(0,Q.jsxs)(`form`,{onSubmit:async n=>{n.preventDefault(),g(null);try{await l(d,p),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));g(n.message),t?.(n)}},className:`space-y-4`,children:[(0,Q.jsx)(Dt,{mode:`sign-in`}),h&&(0,Q.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:h}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`login-email`,className:`text-sm font-medium leading-none`,children:_.emailLabel}),(0,Q.jsx)(`input`,{id:`login-email`,type:`email`,placeholder:_.emailPlaceholder,value:d,onChange:e=>f(e.target.value),required:!0,autoComplete:`email`,disabled:u,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Q.jsx)(`label`,{htmlFor:`login-password`,className:`text-sm font-medium leading-none`,children:_.passwordLabel}),r&&(0,Q.jsx)(o,{href:r,className:`text-sm text-primary underline-offset-4 hover:underline`,children:_.forgotPasswordText})]}),(0,Q.jsx)(`input`,{id:`login-password`,type:`password`,placeholder:_.passwordPlaceholder,value:p,onChange:e=>m(e.target.value),required:!0,autoComplete:`current-password`,disabled:u,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsx)(`button`,{type:`submit`,disabled:u,className:`inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,children:u?_.submittingButton:_.submitButton})]}),n&&(0,Q.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[_.noAccountText,` `,(0,Q.jsx)(o,{href:n,className:`text-primary underline-offset-4 hover:underline`,children:_.signUpText})]})]})}var At=({href:e,className:t,children:n})=>(0,Q.jsx)(`a`,{href:e,className:t,children:n});function jt({onSuccess:e,onError:t,loginUrl:n=`/login`,title:r=`Create an account`,description:i=`Enter your information to get started`,linkComponent:a=At,labels:o={}}){let{signUp:c,isLoading:l}=$(),[u,d]=(0,s.useState)(``),[f,p]=(0,s.useState)(``),[m,h]=(0,s.useState)(``),[g,_]=(0,s.useState)(``),[v,y]=(0,s.useState)(null),b={nameLabel:o.nameLabel??`Name`,namePlaceholder:o.namePlaceholder??`John Doe`,emailLabel:o.emailLabel??`Email`,emailPlaceholder:o.emailPlaceholder??`name@example.com`,passwordLabel:o.passwordLabel??`Password`,passwordPlaceholder:o.passwordPlaceholder??`Create a password (min. 8 characters)`,confirmPasswordLabel:o.confirmPasswordLabel??`Confirm Password`,confirmPasswordPlaceholder:o.confirmPasswordPlaceholder??`Confirm your password`,passwordMismatchError:o.passwordMismatchError??`Passwords do not match`,passwordTooShortError:o.passwordTooShortError??`Password must be at least 8 characters`,submitButton:o.submitButton??`Create Account`,submittingButton:o.submittingButton??`Creating account...`,hasAccountText:o.hasAccountText??`Already have an account?`,signInText:o.signInText??`Sign in`};return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[380px]`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:r}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:i})]}),(0,Q.jsxs)(`form`,{onSubmit:async n=>{if(n.preventDefault(),y(null),m!==g){y(b.passwordMismatchError);return}if(m.length<8){y(b.passwordTooShortError);return}try{await c(u,f,m),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));y(n.message),t?.(n)}},className:`space-y-4`,children:[(0,Q.jsx)(Dt,{mode:`sign-up`}),v&&(0,Q.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:v}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`register-name`,className:`text-sm font-medium leading-none`,children:b.nameLabel}),(0,Q.jsx)(`input`,{id:`register-name`,type:`text`,placeholder:b.namePlaceholder,value:u,onChange:e=>d(e.target.value),required:!0,autoComplete:`name`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`register-email`,className:`text-sm font-medium leading-none`,children:b.emailLabel}),(0,Q.jsx)(`input`,{id:`register-email`,type:`email`,placeholder:b.emailPlaceholder,value:f,onChange:e=>p(e.target.value),required:!0,autoComplete:`email`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`register-password`,className:`text-sm font-medium leading-none`,children:b.passwordLabel}),(0,Q.jsx)(`input`,{id:`register-password`,type:`password`,placeholder:b.passwordPlaceholder,value:m,onChange:e=>h(e.target.value),required:!0,minLength:8,autoComplete:`new-password`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`register-confirm-password`,className:`text-sm font-medium leading-none`,children:b.confirmPasswordLabel}),(0,Q.jsx)(`input`,{id:`register-confirm-password`,type:`password`,placeholder:b.confirmPasswordPlaceholder,value:g,onChange:e=>_(e.target.value),required:!0,minLength:8,autoComplete:`new-password`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsx)(`button`,{type:`submit`,disabled:l,className:`inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,children:l?b.submittingButton:b.submitButton})]}),n&&(0,Q.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[b.hasAccountText,` `,(0,Q.jsx)(a,{href:n,className:`text-primary underline-offset-4 hover:underline`,children:b.signInText})]})]})}var Mt=({href:e,className:t,children:n})=>(0,Q.jsx)(`a`,{href:e,className:t,children:n});function Nt({onSuccess:e,onError:t,loginUrl:n=`/login`,title:r=`Reset your password`,description:i=`Enter your email address and we'll send you a link to reset your password`,linkComponent:a=Mt,labels:o={}}){let{forgotPassword:c,isLoading:l}=$(),[u,d]=(0,s.useState)(``),[f,p]=(0,s.useState)(null),[m,h]=(0,s.useState)(!1),g={emailLabel:o.emailLabel??`Email`,emailPlaceholder:o.emailPlaceholder??`name@example.com`,submitButton:o.submitButton??`Send Reset Link`,submittingButton:o.submittingButton??`Sending...`,successTitle:o.successTitle??`Check your email`,successDescription:o.successDescription??`We've sent a password reset link to {{email}}. Please check your inbox.`,backToSignInText:o.backToSignInText??`Back to sign in`,rememberPasswordText:o.rememberPasswordText??`Remember your password?`,signInText:o.signInText??`Sign in`},_=async n=>{n.preventDefault(),p(null);try{await c(u),h(!0),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));p(n.message),t?.(n)}};if(m){let e=g.successDescription.includes(`{{email}}`)?g.successDescription.replace(`{{email}}`,u):`${g.successDescription} ${u}`;return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[380px]`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:g.successTitle}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e})]}),n&&(0,Q.jsx)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:(0,Q.jsx)(a,{href:n,className:`text-primary underline-offset-4 hover:underline`,children:g.backToSignInText})})]})}return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[380px]`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:r}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:i})]}),(0,Q.jsxs)(`form`,{onSubmit:_,className:`space-y-4`,children:[f&&(0,Q.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:f}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`forgot-email`,className:`text-sm font-medium leading-none`,children:g.emailLabel}),(0,Q.jsx)(`input`,{id:`forgot-email`,type:`email`,placeholder:g.emailPlaceholder,value:u,onChange:e=>d(e.target.value),required:!0,autoComplete:`email`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsx)(`button`,{type:`submit`,disabled:l,className:`inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,children:l?g.submittingButton:g.submitButton})]}),n&&(0,Q.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[g.rememberPasswordText,` `,(0,Q.jsx)(a,{href:n,className:`text-primary underline-offset-4 hover:underline`,children:g.signInText})]})]})}function Pt(e){return e?e.name?e.name.split(` `).map(e=>e[0]).join(``).toUpperCase().slice(0,2):e.email?.[0]?.toUpperCase()??`?`:`?`}function Ft({className:e}){let{isPreviewMode:t,previewMode:n}=$();return t?(0,Q.jsx)(`div`,{role:`status`,className:e,style:{padding:`8px 16px`,backgroundColor:`#fef3c7`,color:`#92400e`,textAlign:`center`,fontSize:`14px`,borderBottom:`1px solid #fcd34d`},children:n?.bannerMessage??`You are in preview mode.`}):null}var It=(0,s.createContext)(null);It.displayName=`PermissionContext`;function Lt(){let e=(0,s.useContext)(It);return e?{...e,can:(t,n)=>e.check(t,n).allowed,cannot:(t,n)=>!e.check(t,n).allowed}:{check:()=>({allowed:!0}),checkField:()=>!0,getFieldPermissions:()=>[],getRowFilter:()=>void 0,roles:[],isLoaded:!1,can:()=>!0,cannot:()=>!1}}export{jt as a,$ as c,a as d,o as f,Nt as i,St as l,Ft as n,kt as o,Pt as r,Ct as s,Lt as t,xt as u};
3
+ at `))}function le(e,t){class n extends e{#e;constructor(...e){if(se()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=ce(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,`constructor`,{get(){return t},enumerable:!1,configurable:!0}),n}var ue={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};le(class extends Error{constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:ue[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var U=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}};function de(e){try{return(new URL(e).pathname.replace(/\/+$/,``)||`/`)!==`/`}catch{throw new U(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function fe(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new U(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof U?t:new U(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function W(e,t=`/api/auth`){if(fe(e),de(e))return e;let n=e.replace(/\/+$/,``);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function pe(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function me(e,t,n,r,i){if(e)return W(e,t);if(r!==!1){let e=V.BETTER_AUTH_URL||V.NEXT_PUBLIC_BETTER_AUTH_URL||V.PUBLIC_BETTER_AUTH_URL||V.NUXT_PUBLIC_BETTER_AUTH_URL||V.NUXT_PUBLIC_AUTH_URL||(V.BASE_URL===`/`?void 0:V.BASE_URL);if(e)return W(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&pe(o,`proto`)&&pe(a,`host`))try{return W(`${o}://${a}`,t)}catch{}if(n){let e=he(n.url);if(!e)throw new U(`Could not get origin from request. Please provide a valid base URL.`);return W(e,t)}if(typeof window<`u`&&window.location)return W(window.location.origin,t)}function he(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var ge={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}};function _e(e,t){let n=A(!1),r=F(n,`/get-session`,e,{method:`GET`}),i=()=>{};return P(r,()=>{let a=R({sessionAtom:r,sessionSignal:n,$fetch:e,options:t});return a.init(),i=a.broadcastSessionUpdate,()=>{a.cleanup()}}),{session:r,$sessionSignal:n,broadcastSessionUpdate:e=>i(e)}}function G(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function K(e,t,n=`.`,r){if(!G(t))return K(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(Array.isArray(a)&&Array.isArray(i[t])?i[t]=[...a,...i[t]]:G(a)&&G(i[t])?i[t]=K(a,i[t],(n?`${n}.`:``)+t.toString(),r):i[t]=a))}return i}function ve(e){return(...t)=>t.reduce((t,n)=>K(t,n,``,e),{})}var ye=ve(),be=Object.defineProperty,xe=Object.defineProperties,Se=Object.getOwnPropertyDescriptors,Ce=Object.getOwnPropertySymbols,we=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable,Ee=(e,t,n)=>t in e?be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,q=(e,t)=>{for(var n in t||={})we.call(t,n)&&Ee(e,n,t[n]);if(Ce)for(var n of Ce(t))Te.call(t,n)&&Ee(e,n,t[n]);return e},J=(e,t)=>xe(e,Se(t)),De=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Oe=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let r=await i.init?.call(i,e.toString(),t);n=r.options||n,e=r.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},ke=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Ae=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function je(e){if(typeof e==`number`)return new ke({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new ke(e);case`exponential`:return new Ae(e);default:throw Error(`Invalid retry strategy`)}}var Me=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Ne=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Pe(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Ne.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function Fe(e){try{return JSON.parse(e),!0}catch{return!1}}function Ie(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function Le(e){try{return JSON.parse(e)}catch{return e}}function Re(e){return typeof e==`function`}function ze(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&Re(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&Re(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}async function Be(e){let t=new Headers(e?.headers),n=await Me(e);for(let[e,r]of Object.entries(n||{}))t.set(e,r);if(!t.has(`content-type`)){let n=Ve(e?.body);n&&t.set(`content-type`,n)}return t}function Ve(e){return Ie(e)?`application/json`:null}function He(e){if(!e?.body)return null;let t=new Headers(e?.headers);if(Ie(e.body)&&!t.has(`content-type`)){for(let[t,n]of Object.entries(e?.body))n instanceof Date&&(e.body[t]=n.toISOString());return JSON.stringify(e.body)}return t.has(`content-type`)&&t.get(`content-type`)===`application/x-www-form-urlencoded`&&Ie(e.body)?new URLSearchParams(e.body).toString():e.body}function Ue(e,t){if(t?.method)return t.method.toUpperCase();if(e.startsWith(`@`)){let n=e.split(`@`)[1]?.split(`/`)[0];return Ke.includes(n)?n.toUpperCase():t?.body?`POST`:`GET`}return t?.body?`POST`:`GET`}function We(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var Ge=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function Y(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new Ge(n.issues);return n.value}var Ke=[`get`,`post`,`put`,`patch`,`delete`],qe=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){let r=e.plugins?.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1)?.schema||e.schema;if(r){let e=t;r.config?.prefix&&e.startsWith(r.config.prefix)&&(e=e.replace(r.config.prefix,``),r.config.baseURL&&(t=t.replace(r.config.prefix,r.config.baseURL))),r.config?.baseURL&&e.startsWith(r.config.baseURL)&&(e=e.replace(r.config.baseURL,``));let i=r.schema[e];if(i){let e=J(q({},n),{method:i.method,output:i.output});return n?.disableValidation||(e=J(q({},e),{body:i.input?await Y(i.input,n?.body):n?.body,params:i.params?await Y(i.params,n?.params):n?.params,query:i.query?await Y(i.query,n?.query):n?.query})),{url:t,options:e}}}return{url:t,options:n}}}),Je=e=>{async function t(t,n){let r=J(q(q({},e),n),{plugins:[...e?.plugins||[],qe(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Xe(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await Xe(t,r)}return t};function Ye(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``;if(e.startsWith(`@`)){let t=e.toString().split(`@`)[1].split(`/`)[0];Ke.includes(t)&&(e=e.replace(`@${t}/`,`/`))}a.endsWith(`/`)||(a+=`/`);let[o,s]=e.replace(a,``).split(`?`),c=new URLSearchParams(s);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)c.append(e,n);continue}else n=JSON.stringify(t);c.set(e,n)}if(r)if(Array.isArray(r)){let e=o.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];o=o.replace(n,e)}}else for(let[e,t]of Object.entries(r))o=o.replace(`:${e}`,String(t));o=o.split(`/`).map(encodeURIComponent).join(`/`),o.startsWith(`/`)&&(o=o.slice(1));let l=c.toString();return l=l.length>0?`?${l}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${o}${l}`,a):`${a}${o}${l}`}var Xe=async(e,t)=>{let{hooks:n,url:r,options:i}=await Oe(e,t),a=ze(i),o=new AbortController,s=i.signal??o.signal,c=Ye(r,i),l=He(i),u=await Be(i),d=Ue(r,i),f=J(q({},i),{url:c,headers:u,body:l,method:d,signal:s});for(let e of n.onRequest)if(e){let t=await e(f);typeof t==`object`&&t&&(f=t)}(`pipeTo`in f&&typeof f.pipeTo==`function`||typeof t?.body?.pipe==`function`)&&(`duplex`in f||(f.duplex=`half`));let{clearTimeout:p}=We(i,o),m=await a(f.url,f);p();let h={response:m,request:f};for(let e of n.onResponse)if(e){let n=await e(J(q({},h),{response:t?.hookOptions?.cloneResponse?m.clone():m}));n instanceof Response?m=n:typeof n==`object`&&n&&(m=n.response)}if(m.ok){if(f.method===`HEAD`)return{data:``,error:null};let e=Pe(m),r={data:null,response:m,request:f};if(e===`json`||e===`text`){let e=await m.text();r.data=await(f.jsonParser??Le)(e)}else r.data=await m[e]();f?.output&&f.output&&!f.disableValidation&&(r.data=await Y(f.output,r.data));for(let e of n.onSuccess)e&&await e(J(q({},r),{response:t?.hookOptions?.cloneResponse?m.clone():m}));return t?.throw?r.data:{data:r.data,error:null}}let g=t?.jsonParser??Le,_=await m.text(),v=Fe(_),y=v?await g(_):null,b={response:m,responseText:_,request:f,error:J(q({},y),{status:m.status,statusText:m.statusText})};for(let e of n.onError)e&&await e(J(q({},b),{response:t?.hookOptions?.cloneResponse?m.clone():m}));if(t?.retry){let r=je(t.retry),i=t.retryAttempt??0;if(await r.shouldAttemptRetry(i,m)){for(let e of n.onRetry)e&&await e(h);let a=r.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await Xe(e,J(q({},t),{retryAttempt:i+1}))}}if(t?.throw)throw new De(m.status,m.statusText,v?y:_);return{data:null,error:J(q({},y),{status:m.status,statusText:m.statusText})}},Ze=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},Qe=(e,t)=>{let n=`credentials`in Request.prototype,r=me(e?.baseURL,e?.basePath,void 0,t)??Ze(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=Je({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?E(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[ge],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=_e(d,e),h=e?.plugins||[],g={},_={$sessionSignal:f,session:p},v={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},y=[{signal:`$sessionSignal`,matcher(e){return e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`},callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of h)e.getAtoms&&Object.assign(_,e.getAtoms?.(d)),e.pathMethods&&Object.assign(v,e.pathMethods),e.atomListeners&&y.push(...e.atomListeners);let b={notify:e=>{_[e].set(!_[e].get())},listen:(e,t)=>{_[e].subscribe(t)},atoms:_};for(let t of h)t.getActions&&(g=ye(t.getActions?.(d,b,e)??{},g));return{get baseURL(){return r},pluginsActions:g,pluginsAtoms:_,pluginPathMethods:v,atomListeners:y,$fetch:d,$store:b}};function $e(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function et(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function tt(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||$e(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(e=>e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=et(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}function nt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function rt(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,$fetch:i,atomListeners:a,$store:o}=Qe(e),s={};for(let[e,t]of Object.entries(r))s[`use${nt(e)}`]=t;return tt({...n,...s,$fetch:i,$store:o},i,t,r,a)}function it(e){return{authorize(t,n=`AND`){let r=!1;for(let[i,a]of Object.entries(t)){let t=e[i];if(!t)return{success:!1,error:`You are not allowed to access resource: ${i}`};if(Array.isArray(a))r=a.every(e=>t.includes(e));else if(typeof a==`object`){let e=a;r=e.connector===`OR`?e.actions.some(e=>t.includes(e)):e.actions.every(e=>t.includes(e))}else throw new U(`Invalid access control request`);if(r&&n===`OR`)return{success:r};if(!r&&n===`AND`)return{success:!1,error:`unauthorized to access resource "${i}"`}}return r?{success:r}:{success:!1,error:`Not authorized`}},statements:e}}function at(e){return{newRole(e){return it(e)},statements:e}}var ot=oe({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:`You are not allowed to create a new organization`,YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:`You have reached the maximum number of organizations`,ORGANIZATION_ALREADY_EXISTS:`Organization already exists`,ORGANIZATION_SLUG_ALREADY_TAKEN:`Organization slug already taken`,ORGANIZATION_NOT_FOUND:`Organization not found`,USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:`User is not a member of the organization`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:`You are not allowed to update this organization`,YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:`You are not allowed to delete this organization`,NO_ACTIVE_ORGANIZATION:`No active organization`,USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:`User is already a member of this organization`,MEMBER_NOT_FOUND:`Member not found`,ROLE_NOT_FOUND:`Role not found`,YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:`You are not allowed to create a new team`,TEAM_ALREADY_EXISTS:`Team already exists`,TEAM_NOT_FOUND:`Team not found`,YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:`You cannot leave the organization as the only owner`,YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:`You cannot leave the organization without an owner`,YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:`You are not allowed to delete this member`,YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:`You are not allowed to invite users to this organization`,USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:`User is already invited to this organization`,INVITATION_NOT_FOUND:`Invitation not found`,YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:`You are not the recipient of the invitation`,EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:`Email verification required before accepting or rejecting invitation`,YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:`You are not allowed to cancel this invitation`,INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:`Inviter is no longer a member of the organization`,YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:`You are not allowed to invite a user with this role`,FAILED_TO_RETRIEVE_INVITATION:`Failed to retrieve invitation`,YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:`You have reached the maximum number of teams`,UNABLE_TO_REMOVE_LAST_TEAM:`Unable to remove last team`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:`You are not allowed to update this member`,ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:`Organization membership limit reached`,YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:`You are not allowed to create teams in this organization`,YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:`You are not allowed to delete teams in this organization`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:`You are not allowed to update this team`,YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:`You are not allowed to delete this team`,INVITATION_LIMIT_REACHED:`Invitation limit reached`,TEAM_MEMBER_LIMIT_REACHED:`Team member limit reached`,USER_IS_NOT_A_MEMBER_OF_THE_TEAM:`User is not a member of the team`,YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:`You are not allowed to list the members of this team`,YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:`You do not have an active team`,YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:`You are not allowed to create a new member`,YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:`You are not allowed to remove a team member`,YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:`You are not allowed to access this organization as an owner`,YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:`You are not a member of this organization`,MISSING_AC_INSTANCE:`Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information`,YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:`You must be in an organization to create a role`,YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:`You are not allowed to create a role`,YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:`You are not allowed to update a role`,YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:`You are not allowed to delete a role`,YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:`You are not allowed to read a role`,YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:`You are not allowed to list a role`,YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:`You are not allowed to get a role`,TOO_MANY_ROLES:`This organization has too many roles`,INVALID_RESOURCE:`The provided permission includes an invalid resource`,ROLE_NAME_IS_ALREADY_TAKEN:`That role name is already taken`,CANNOT_DELETE_A_PRE_DEFINED_ROLE:`Cannot delete a pre-defined role`,ROLE_IS_ASSIGNED_TO_MEMBERS:`Cannot delete a role that is assigned to members. Please reassign the members to a different role first`}),st=at({organization:[`update`,`delete`],member:[`create`,`update`,`delete`],invitation:[`create`,`cancel`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),ct=st.newRole({organization:[`update`],invitation:[`create`,`cancel`],member:[`create`,`update`,`delete`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),lt=st.newRole({organization:[`update`,`delete`],member:[`create`,`update`,`delete`],invitation:[`create`,`cancel`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),ut=st.newRole({organization:[],member:[],invitation:[],team:[],ac:[`read`]}),dt={admin:ct,owner:lt,member:ut},ft=(e,t)=>{if(!e.permissions)return!1;let n=e.role.split(`,`),r=e.options.creatorRole||`owner`,i=n.includes(r),a=e.allowCreatorAllPermissions||!1;if(i&&a)return!0;for(let r of n)if(t[r]?.authorize(e.permissions)?.success)return!0;return!1},pt=e=>ft(e,e.options.roles||dt),mt=e=>{let t=A(!1),n=A(!1),r=A(!1),i=A(!1),a={admin:ct,member:ut,owner:lt,...e?.roles};return{id:`organization`,version:l,$InferServerPlugin:{},getActions:(t,n,r)=>({$Infer:{ActiveOrganization:{},Organization:{},Invitation:{},Member:{},Team:{}},organization:{checkRolePermission:t=>pt({role:t.role,options:{ac:e?.ac,roles:a},permissions:t.permissions})}}),getAtoms:e=>{let a=F(t,`/organization/list`,e,{method:`GET`});return{$listOrg:t,$activeOrgSignal:n,$activeMemberSignal:r,$activeMemberRoleSignal:i,activeOrganization:F([n],`/organization/get-full-organization`,e,()=>({method:`GET`})),listOrganizations:a,activeMember:F([n,r],`/organization/get-active-member`,e,{method:`GET`}),activeMemberRole:F([n,i],`/organization/get-active-member-role`,e,{method:`GET`})}},pathMethods:{"/organization/get-full-organization":`GET`,"/organization/list-user-teams":`GET`},atomListeners:[{matcher(e){return e===`/organization/create`||e===`/organization/delete`||e===`/organization/update`},signal:`$listOrg`},{matcher(e){return e.startsWith(`/organization`)},signal:`$activeOrgSignal`},{matcher(e){return e.startsWith(`/organization/set-active`)||e===`/organization/create`||e===`/organization/delete`||e===`/organization/remove-member`||e===`/organization/leave`||e===`/organization/accept-invitation`},signal:`$sessionSignal`},{matcher(e){return e.includes(`/organization/update-member-role`)||e.startsWith(`/organization/set-active`)},signal:`$activeMemberSignal`},{matcher(e){return e.includes(`/organization/update-member-role`)||e.startsWith(`/organization/set-active`)},signal:`$activeMemberRoleSignal`}],$ERROR_CODES:ot}},ht=`auth-session-token`,X={_memoryToken:null,get(){try{if(typeof localStorage<`u`)return localStorage.getItem(ht)}catch{}return this._memoryToken},set(e){this._memoryToken=e;try{typeof localStorage<`u`&&localStorage.setItem(ht,e)}catch{}},clear(){this._memoryToken=null;try{typeof localStorage<`u`&&localStorage.removeItem(ht)}catch{}}};function gt(e){try{let t=new URL(e);return{origin:t.origin,basePath:t.pathname.replace(/\/$/,``)}}catch{return{origin:_t()??`http://localhost`,basePath:e.replace(/\/$/,``)}}}function _t(){try{if(typeof window<`u`&&window.location?.origin)return window.location.origin}catch{}}function vt(e){let t=e||globalThis.fetch.bind(globalThis);return async(e,n)=>{let r=new Headers(n?.headers),i=X.get();if(i){let t=typeof e==`string`?e:e instanceof URL?e.href:e.url;/\/api\//i.test(t)&&r.set(`Authorization`,`Bearer ${i}`)}let a=await t(e,{...n,headers:r}),o=a.headers.get(`set-auth-token`);return o&&X.set(o),a}}function yt(e){let{baseURL:t,fetchFn:n}=e,{origin:r,basePath:i}=gt(t),a=vt(n),o=rt({baseURL:r,basePath:i,disableDefaultFetchPlugins:!0,fetchOptions:{customFetchImpl:a},plugins:[mt()]});return{async signIn(e){let{data:t,error:n}=await o.signIn.email({email:e.email,password:e.password});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`);let r=t;return r.session?.token&&X.set(r.session.token),{user:r.user,session:r.session}},async signUp(e){let{data:t,error:n}=await o.signUp.email({email:e.email,password:e.password,name:e.name});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`);let r=t;return r.session?.token&&X.set(r.session.token),{user:r.user,session:r.session}},async signOut(){let{error:e}=await o.signOut();if(X.clear(),e)throw Error(e.message??`Auth request failed with status ${e.status}`)},async getSession(){let{data:e,error:t}=await o.getSession();if(t||!e)return null;let n=e;return n.session?.token&&X.set(n.session.token),{user:n.user,session:n.session}},async forgotPassword(e){let t=o.forgetPassword,{error:n}=await t({email:e,redirectTo:`/`});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`)},async resetPassword(e,t){let{error:n}=await o.resetPassword({token:e,newPassword:t});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`)},async updateUser(e){let{data:t,error:n}=await o.updateUser(e);if(n)throw Error(n.message??`Auth request failed with status ${n.status}`);if(!t)throw Error(`Update user returned no data`);let r=t;return r&&typeof r==`object`&&`user`in r?r.user:r},async getConfig(){let e=await a(`${r}${i}/config`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(!e.ok)throw Error(`Failed to load auth config (status ${e.status})`);let t=await e.json();return t&&typeof t==`object`&&`data`in t&&t.data?t.data:t},async signInWithProvider(e,t={}){let{type:n=`social`,callbackURL:r,errorCallbackURL:i}=t;if(n===`oidc`){let t=o.signIn.oauth2;if(!t)throw Error(`OIDC sign-in is not supported by this auth client build`);let{error:n}=await t({providerId:e,callbackURL:r,errorCallbackURL:i});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`);return}let{error:a}=await o.signIn.social({provider:e,callbackURL:r,errorCallbackURL:i});if(a)throw Error(a.message??`Auth request failed with status ${a.status}`)},async listOrganizations(){let{data:e,error:t}=await o.organization.list();if(t)throw Error(t.message??`Failed to list organizations`);return e??[]},async createOrganization(e){let{data:t,error:n}=await o.organization.create({name:e.name,slug:e.slug,logo:e.logo});if(n)throw Error(n.message??`Failed to create organization`);return t},async setActiveOrganization(e){let{data:t,error:n}=await o.organization.setActive({organizationId:e});if(n)throw Error(n.message??`Failed to set active organization`);return t??null},async getActiveOrganization(){let{data:e,error:t}=await o.organization.getFullOrganization();return t||!e?null:e},async getMembers(e){let{data:t,error:n}=await o.organization.listMembers({query:{organizationId:e}});if(n)throw Error(n.message??`Failed to get members`);let r=t;return Array.isArray(r)?r:r?.members??[]},async inviteMember(e){let{data:t,error:n}=await o.organization.inviteMember({organizationId:e.organizationId,email:e.email,role:e.role});if(n)throw Error(n.message??`Failed to invite member`);return t},async removeMember(e){let{error:t}=await o.organization.removeMember({organizationId:e.organizationId,memberIdOrUserId:e.memberIdOrUserId});if(t)throw Error(t.message??`Failed to remove member`)},async updateMemberRole(e){let{error:t}=await o.organization.updateMemberRole({organizationId:e.organizationId,memberId:e.memberId,role:e.role});if(t)throw Error(t.message??`Failed to update member role`)},async updateOrganization(e,t){let{data:n,error:r}=await o.organization.update({organizationId:e,data:t});if(r)throw Error(r.message??`Failed to update organization`);return n},async deleteOrganization(e){let{error:t}=await o.organization.delete({organizationId:e});if(t)throw Error(t.message??`Failed to delete organization`)},async leaveOrganization(e){let{error:t}=await o.organization.leave({organizationId:e});if(t)throw Error(t.message??`Failed to leave organization`)},async listInvitations(e){let{data:t,error:n}=await o.organization.listInvitations({query:{organizationId:e}});if(n)throw Error(n.message??`Failed to list invitations`);return t??[]},async cancelInvitation(e){let{error:t}=await o.organization.cancelInvitation({invitationId:e});if(t)throw Error(t.message??`Failed to cancel invitation`)},async getInvitation(e){let{data:t,error:n}=await o.organization.getInvitation({query:{id:e}});if(n)throw Error(n.message??`Failed to load invitation`);return t},async acceptInvitation(e){let{error:t}=await o.organization.acceptInvitation({invitationId:e});if(t)throw Error(t.message??`Failed to accept invitation`)},async rejectInvitation(e){let{error:t}=await o.organization.rejectInvitation({invitationId:e});if(t)throw Error(t.message??`Failed to reject invitation`)},async listUserInvitations(){let{data:e,error:t}=await o.organization.listUserInvitations();if(t)throw Error(t.message??`Failed to list invitations`);return e??[]}}}var bt=`auth-active-organization-id`,Z={_memoryValue:null,get(){try{if(typeof localStorage<`u`)return localStorage.getItem(bt)}catch{}return this._memoryValue},set(e){this._memoryValue=e;try{typeof localStorage<`u`&&localStorage.setItem(bt,e)}catch{}},clear(){this._memoryValue=null;try{typeof localStorage<`u`&&localStorage.removeItem(bt)}catch{}}};function xt(){return async(e,t)=>{let n=new Headers(t?.headers),r=X.get();if(r){let t=typeof e==`string`?e:e instanceof URL?e.href:e.url;/\/api\//i.test(t)&&n.set(`Authorization`,`Bearer ${r}`)}let i=Z.get();return i&&n.set(`X-Tenant-ID`,i),fetch(e,{...t,headers:n})}}var Q=n();function St({authUrl:e,client:t,onAuthStateChange:n,enabled:r=!0,previewMode:i,children:a}){let o=(0,s.useMemo)(()=>t??yt({baseURL:e}),[t,e]),[l,u]=(0,s.useState)(null),[d,f]=(0,s.useState)(null),[p,m]=(0,s.useState)(!0),[h,g]=(0,s.useState)(null),[_,v]=(0,s.useState)([]),[y,b]=(0,s.useState)(null),[x,S]=(0,s.useState)(!1),C=i!=null,w=r&&!C?l!==null&&d!==null:!0;(0,s.useEffect)(()=>{if(C){let e=i.simulatedRole??`admin`,t=i.simulatedUserName??`Preview User`,n=i.expiresInSeconds??0;u({id:`preview-user`,email:`preview@preview.local`,name:t,role:e,roles:[e]}),f({token:`preview-token`,expiresAt:n>0?new Date(Date.now()+n*1e3):new Date(Date.now()+365*24*60*60*1e3)}),m(!1);return}if(!r){u({id:`guest`,email:`guest@local`,name:`Guest User`,role:`admin`}),f({token:`guest-token`,expiresAt:new Date(Date.now()+365*24*60*60*1e3)}),m(!1);return}let e=!1;async function t(){try{let t=await o.getSession();if(e)return;t&&(u(t.user),f(t.session))}catch(t){if(e)return;g(t instanceof Error?t:Error(String(t)))}finally{e||m(!1)}}return t(),()=>{e=!0}},[o,r,C,i]),(0,s.useEffect)(()=>{n?.({user:l,session:d,isAuthenticated:w,isLoading:p,error:h})},[l,d,w,p,h,n]);let T=(0,s.useCallback)(async(e,t)=>{m(!0),g(null);try{let n=await o.signIn({email:e,password:t});u(n.user),f(n.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{m(!1)}},[o]),ee=(0,s.useCallback)(async(e,t,n)=>{m(!0),g(null);try{let r=await o.signUp({name:e,email:t,password:n});u(r.user),f(r.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{m(!1)}},[o]),E=(0,s.useCallback)(async()=>{m(!0);try{await o.signOut(),u(null),f(null),g(null)}catch(e){g(e instanceof Error?e:Error(String(e)))}finally{m(!1)}},[o]),D=(0,s.useCallback)(async e=>{g(null);try{u(await o.updateUser(e))}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),O=(0,s.useCallback)(async e=>{g(null);try{await o.forgotPassword(e)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),k=(0,s.useCallback)(async(e,t)=>{g(null);try{await o.resetPassword(e,t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),te=(0,s.useCallback)(()=>o.getConfig(),[o]),A=(0,s.useCallback)(async(e,t)=>{g(null);try{await o.signInWithProvider(e,t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),j=(0,s.useCallback)(async()=>{if(!(!r||C)){S(!0);try{let e=await o.listOrganizations();if(v(e),e.length>0&&!y)try{let e=await o.getActiveOrganization();e&&(b(e),Z.set(e.id))}catch{}}catch(e){console.warn(`[AuthProvider] Failed to load organizations:`,e)}finally{S(!1)}}},[o,r,C,y]);(0,s.useEffect)(()=>{l&&r&&!C&&j()},[l,r,C]);let M=(0,s.useCallback)(async e=>{g(null);try{let t=await o.setActiveOrganization(e);b(t),t?Z.set(t.id):Z.clear()}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),N=(0,s.useCallback)(async e=>{g(null);try{let t=await o.createOrganization(e);return await j(),await M(t.id),t}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o,j,M]),ne=(0,s.useCallback)(async(e,t)=>{let n=await o.updateOrganization(e,t);return await j(),y?.id===e&&b(n),n},[o,j,y]),re=(0,s.useCallback)(async e=>{await o.deleteOrganization(e),y?.id===e&&(b(null),Z.clear()),await j()},[o,y,j]),P=(0,s.useCallback)(async e=>{await o.leaveOrganization(e),y?.id===e&&(b(null),Z.clear()),await j()},[o,y,j]),ie=(0,s.useCallback)(e=>o.getMembers(e),[o]),F=(0,s.useCallback)(e=>o.inviteMember(e),[o]),I=(0,s.useCallback)(e=>o.removeMember(e),[o]),L=(0,s.useCallback)(e=>o.updateMemberRole(e),[o]),ae=(0,s.useCallback)(e=>o.listInvitations(e),[o]),R=(0,s.useCallback)(e=>o.cancelInvitation(e),[o]),z=(0,s.useCallback)(e=>o.getInvitation(e),[o]),B=(0,s.useCallback)(async e=>{await o.acceptInvitation(e),await j()},[o,j]),V=(0,s.useCallback)(e=>o.rejectInvitation(e),[o]),H=(0,s.useCallback)(()=>o.listUserInvitations(),[o]),oe=(0,s.useMemo)(()=>({user:l,session:d,isAuthenticated:w,isLoading:p,error:h,isPreviewMode:C,previewMode:C?i:null,signIn:T,signUp:ee,signOut:E,updateUser:D,forgotPassword:O,resetPassword:k,getAuthConfig:te,signInWithProvider:A,organizations:_,activeOrganization:y,isOrganizationsLoading:x,switchOrganization:M,createOrganization:N,refreshOrganizations:j,updateOrganization:ne,deleteOrganization:re,leaveOrganization:P,getMembers:ie,inviteMember:F,removeMember:I,updateMemberRole:L,listInvitations:ae,cancelInvitation:R,getInvitation:z,acceptInvitation:B,rejectInvitation:V,listUserInvitations:H}),[l,d,w,p,h,C,i,T,ee,E,D,O,k,te,A,_,y,x,M,N,j,ne,re,P,ie,F,I,L,ae,R,z,B,V,H]);return(0,Q.jsx)(c.Provider,{value:oe,children:a})}function $(){return(0,s.useContext)(c)||{user:null,session:null,isAuthenticated:!1,isLoading:!1,error:null,isPreviewMode:!1,previewMode:null,signIn:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},signUp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},signOut:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},updateUser:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},forgotPassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},resetPassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},getAuthConfig:async()=>({}),signInWithProvider:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},organizations:[],activeOrganization:null,isOrganizationsLoading:!1,switchOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},createOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},refreshOrganizations:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},updateOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},deleteOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},leaveOrganization:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},getMembers:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},inviteMember:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},removeMember:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},updateMemberRole:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},listInvitations:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},cancelInvitation:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},getInvitation:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},acceptInvitation:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},rejectInvitation:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},listUserInvitations:async()=>{throw Error(`useAuth must be used within an AuthProvider`)}}}function Ct({fallback:e=null,requiredRoles:t,loadingFallback:n,children:r}){let{isAuthenticated:i,isLoading:a,user:o}=$();if(a)return(0,Q.jsx)(Q.Fragment,{children:n??null});if(!i)return(0,Q.jsx)(Q.Fragment,{children:e});if(t&&t.length>0&&o){let n=o.roles??(o.role?[o.role]:[]);if(!t.some(e=>n.includes(e)))return(0,Q.jsx)(Q.Fragment,{children:e})}return(0,Q.jsx)(Q.Fragment,{children:r})}var wt={google:`Google`,github:`GitHub`,microsoft:`Microsoft`,apple:`Apple`,facebook:`Facebook`,twitter:`Twitter`,discord:`Discord`,gitlab:`GitLab`,linkedin:`LinkedIn`},Tt={google:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#EA4335`,d:`M12 10.2v3.9h5.5c-.24 1.4-1.7 4.1-5.5 4.1-3.3 0-6-2.74-6-6.1s2.7-6.1 6-6.1c1.88 0 3.14.8 3.86 1.5l2.64-2.55C16.84 3.36 14.66 2.4 12 2.4 6.92 2.4 2.8 6.52 2.8 11.6S6.92 20.8 12 20.8c6.92 0 9.2-4.86 9.2-7.4 0-.5-.06-.88-.14-1.2H12z`})}),github:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56v-2.07c-3.2.7-3.87-1.37-3.87-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.68 1.25 3.34.96.1-.74.4-1.25.73-1.54-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.18-3.1-.12-.29-.51-1.46.11-3.04 0 0 .97-.31 3.18 1.18a11.04 11.04 0 015.79 0c2.21-1.49 3.18-1.18 3.18-1.18.62 1.58.23 2.75.11 3.04.74.81 1.18 1.84 1.18 3.1 0 4.42-2.7 5.39-5.27 5.68.41.36.78 1.06.78 2.13v3.16c0 .31.21.68.8.56C20.21 21.39 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5z`})}),microsoft:(0,Q.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:[(0,Q.jsx)(`path`,{fill:`#F25022`,d:`M2 2h9.5v9.5H2z`}),(0,Q.jsx)(`path`,{fill:`#7FBA00`,d:`M12.5 2H22v9.5h-9.5z`}),(0,Q.jsx)(`path`,{fill:`#00A4EF`,d:`M2 12.5h9.5V22H2z`}),(0,Q.jsx)(`path`,{fill:`#FFB900`,d:`M12.5 12.5H22V22h-9.5z`})]}),apple:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M16.37 12.55c-.02-2.27 1.85-3.36 1.94-3.42-1.06-1.55-2.71-1.76-3.3-1.79-1.4-.14-2.74.83-3.45.83-.71 0-1.81-.81-2.98-.79-1.53.02-2.95.89-3.74 2.27-1.6 2.77-.41 6.86 1.14 9.11.76 1.1 1.66 2.34 2.83 2.3 1.14-.05 1.57-.74 2.94-.74 1.37 0 1.76.74 2.96.71 1.22-.02 2-1.12 2.75-2.23.87-1.28 1.22-2.52 1.24-2.59-.03-.01-2.38-.91-2.4-3.66zM14.1 5.31c.62-.76 1.05-1.81.93-2.86-.9.04-2 .6-2.65 1.35-.58.66-1.1 1.74-.96 2.76 1.01.08 2.04-.51 2.68-1.25z`})}),facebook:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#1877F2`,d:`M24 12C24 5.37 18.63 0 12 0S0 5.37 0 12c0 5.99 4.39 10.95 10.13 11.85V15.47H7.08V12h3.05V9.36c0-3.01 1.79-4.67 4.53-4.67 1.31 0 2.69.23 2.69.23v2.96h-1.51c-1.49 0-1.96.93-1.96 1.88V12h3.33l-.53 3.47h-2.8v8.38C19.61 22.95 24 17.99 24 12z`})}),twitter:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{d:`M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z`})}),discord:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#5865F2`,d:`M20.32 4.37A19.79 19.79 0 0016.56 3l-.18.36a18.27 18.27 0 00-8.76 0L7.44 3a19.79 19.79 0 00-3.76 1.37C.99 8.4.27 12.34.63 16.22a19.94 19.94 0 006.07 3.07l.49-.7a13.2 13.2 0 01-2.07-.99c.17-.13.34-.27.5-.41a14.13 14.13 0 0012.76 0c.16.14.33.28.5.41-.66.4-1.36.73-2.07.99l.49.7a19.92 19.92 0 006.07-3.07c.43-4.5-.66-8.41-2.95-11.85zM8.52 14.12c-1.18 0-2.15-1.08-2.15-2.41 0-1.33.95-2.42 2.15-2.42 1.2 0 2.17 1.09 2.15 2.42 0 1.33-.96 2.41-2.15 2.41zm6.96 0c-1.18 0-2.15-1.08-2.15-2.41 0-1.33.95-2.42 2.15-2.42 1.2 0 2.17 1.09 2.15 2.42 0 1.33-.95 2.41-2.15 2.41z`})}),gitlab:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#FC6D26`,d:`M23.6 9.6L23.57 9.5 20.3.81a.84.84 0 00-1.6.05L16.5 7.6H7.5L5.3.86a.84.84 0 00-1.6-.05L.43 9.5l-.03.1a5.84 5.84 0 001.94 6.74l.01.01.03.02 4.8 3.6 2.38 1.8 1.45 1.1a1 1 0 001.2 0l1.45-1.1 2.38-1.8 4.83-3.62.01-.01a5.84 5.84 0 001.93-6.74z`})}),linkedin:(0,Q.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Q.jsx)(`path`,{fill:`#0A66C2`,d:`M20.45 20.45h-3.55v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.13 1.45-2.13 2.94v5.67H9.36V9h3.41v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.45v6.29zM5.34 7.43a2.06 2.06 0 11.01-4.13 2.06 2.06 0 010 4.13zM7.12 20.45H3.56V9h3.56v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.72v20.56C0 23.23.79 24 1.77 24h20.45c.98 0 1.78-.77 1.78-1.72V1.72C24 .77 23.2 0 22.22 0z`})})};function Et({id:e}){let t=Tt[e];return t?(0,Q.jsx)(`span`,{className:`mr-2 flex h-4 w-4 items-center justify-center`,children:t}):(0,Q.jsx)(`span`,{className:`mr-2 flex h-4 w-4 items-center justify-center rounded-sm bg-muted text-[10px] font-bold uppercase`,children:e[0]})}function Dt({mode:e=`sign-in`,callbackURL:t,errorCallbackURL:n,dividerText:r=`or continue with email`}){let{getAuthConfig:i,signInWithProvider:a}=$(),[o,c]=(0,s.useState)([]),[l,u]=(0,s.useState)(!0),[d,f]=(0,s.useState)(null);if((0,s.useEffect)(()=>{let e=!1;return Promise.resolve().then(()=>i()).then(t=>{e||c((t?.socialProviders??[]).filter(e=>e.enabled))}).catch(t=>{e||console.warn(`[SocialSignInButtons] failed to load auth config`,t)}).finally(()=>{e||u(!1)}),()=>{e=!0}},[i]),l||o.length===0)return null;let p=e===`sign-in`?`Continue with`:`Sign up with`,m=typeof window<`u`?window.location.href:void 0,h=async e=>{f(null);try{await a(e.id,{callbackURL:t??m,errorCallbackURL:n??t??m,type:e.type??`social`})}catch(e){f(e instanceof Error?e.message:String(e))}};return(0,Q.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[d&&(0,Q.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:d}),o.map(e=>(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>h(e),className:`inline-flex h-10 w-full items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium ring-offset-background transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,children:[(0,Q.jsx)(Et,{id:e.id}),p,` `,wt[e.id]??e.name]},e.id)),(0,Q.jsxs)(`div`,{className:`relative my-1`,children:[(0,Q.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,Q.jsx)(`span`,{className:`w-full border-t`})}),(0,Q.jsx)(`div`,{className:`relative flex justify-center text-xs uppercase`,children:(0,Q.jsx)(`span`,{className:`bg-background px-2 text-muted-foreground`,children:r})})]})]})}var Ot=({href:e,className:t,children:n})=>(0,Q.jsx)(`a`,{href:e,className:t,children:n});function kt({onSuccess:e,onError:t,registerUrl:n=`/register`,forgotPasswordUrl:r=`/forgot-password`,title:i=`Sign in to your account`,description:a=`Enter your email and password to continue`,linkComponent:o=Ot,labels:c={}}){let{signIn:l,isLoading:u}=$(),[d,f]=(0,s.useState)(``),[p,m]=(0,s.useState)(``),[h,g]=(0,s.useState)(null),_={emailLabel:c.emailLabel??`Email`,emailPlaceholder:c.emailPlaceholder??`name@example.com`,passwordLabel:c.passwordLabel??`Password`,passwordPlaceholder:c.passwordPlaceholder??`Enter your password`,forgotPasswordText:c.forgotPasswordText??`Forgot password?`,submitButton:c.submitButton??`Sign In`,submittingButton:c.submittingButton??`Signing in...`,noAccountText:c.noAccountText??`Don't have an account?`,signUpText:c.signUpText??`Sign up`};return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[380px]`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:i}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:a})]}),(0,Q.jsxs)(`form`,{onSubmit:async n=>{n.preventDefault(),g(null);try{await l(d,p),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));g(n.message),t?.(n)}},className:`space-y-4`,children:[(0,Q.jsx)(Dt,{mode:`sign-in`}),h&&(0,Q.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:h}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`login-email`,className:`text-sm font-medium leading-none`,children:_.emailLabel}),(0,Q.jsx)(`input`,{id:`login-email`,type:`email`,placeholder:_.emailPlaceholder,value:d,onChange:e=>f(e.target.value),required:!0,autoComplete:`email`,disabled:u,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Q.jsx)(`label`,{htmlFor:`login-password`,className:`text-sm font-medium leading-none`,children:_.passwordLabel}),r&&(0,Q.jsx)(o,{href:r,className:`text-sm text-primary underline-offset-4 hover:underline`,children:_.forgotPasswordText})]}),(0,Q.jsx)(`input`,{id:`login-password`,type:`password`,placeholder:_.passwordPlaceholder,value:p,onChange:e=>m(e.target.value),required:!0,autoComplete:`current-password`,disabled:u,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsx)(`button`,{type:`submit`,disabled:u,className:`inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,children:u?_.submittingButton:_.submitButton})]}),n&&(0,Q.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[_.noAccountText,` `,(0,Q.jsx)(o,{href:n,className:`text-primary underline-offset-4 hover:underline`,children:_.signUpText})]})]})}var At=({href:e,className:t,children:n})=>(0,Q.jsx)(`a`,{href:e,className:t,children:n});function jt({onSuccess:e,onError:t,loginUrl:n=`/login`,title:r=`Create an account`,description:i=`Enter your information to get started`,linkComponent:a=At,labels:o={}}){let{signUp:c,isLoading:l}=$(),[u,d]=(0,s.useState)(``),[f,p]=(0,s.useState)(``),[m,h]=(0,s.useState)(``),[g,_]=(0,s.useState)(``),[v,y]=(0,s.useState)(null),b={nameLabel:o.nameLabel??`Name`,namePlaceholder:o.namePlaceholder??`John Doe`,emailLabel:o.emailLabel??`Email`,emailPlaceholder:o.emailPlaceholder??`name@example.com`,passwordLabel:o.passwordLabel??`Password`,passwordPlaceholder:o.passwordPlaceholder??`Create a password (min. 8 characters)`,confirmPasswordLabel:o.confirmPasswordLabel??`Confirm Password`,confirmPasswordPlaceholder:o.confirmPasswordPlaceholder??`Confirm your password`,passwordMismatchError:o.passwordMismatchError??`Passwords do not match`,passwordTooShortError:o.passwordTooShortError??`Password must be at least 8 characters`,submitButton:o.submitButton??`Create Account`,submittingButton:o.submittingButton??`Creating account...`,hasAccountText:o.hasAccountText??`Already have an account?`,signInText:o.signInText??`Sign in`};return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[380px]`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:r}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:i})]}),(0,Q.jsxs)(`form`,{onSubmit:async n=>{if(n.preventDefault(),y(null),m!==g){y(b.passwordMismatchError);return}if(m.length<8){y(b.passwordTooShortError);return}try{await c(u,f,m),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));y(n.message),t?.(n)}},className:`space-y-4`,children:[(0,Q.jsx)(Dt,{mode:`sign-up`}),v&&(0,Q.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:v}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`register-name`,className:`text-sm font-medium leading-none`,children:b.nameLabel}),(0,Q.jsx)(`input`,{id:`register-name`,type:`text`,placeholder:b.namePlaceholder,value:u,onChange:e=>d(e.target.value),required:!0,autoComplete:`name`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`register-email`,className:`text-sm font-medium leading-none`,children:b.emailLabel}),(0,Q.jsx)(`input`,{id:`register-email`,type:`email`,placeholder:b.emailPlaceholder,value:f,onChange:e=>p(e.target.value),required:!0,autoComplete:`email`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`register-password`,className:`text-sm font-medium leading-none`,children:b.passwordLabel}),(0,Q.jsx)(`input`,{id:`register-password`,type:`password`,placeholder:b.passwordPlaceholder,value:m,onChange:e=>h(e.target.value),required:!0,minLength:8,autoComplete:`new-password`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`register-confirm-password`,className:`text-sm font-medium leading-none`,children:b.confirmPasswordLabel}),(0,Q.jsx)(`input`,{id:`register-confirm-password`,type:`password`,placeholder:b.confirmPasswordPlaceholder,value:g,onChange:e=>_(e.target.value),required:!0,minLength:8,autoComplete:`new-password`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsx)(`button`,{type:`submit`,disabled:l,className:`inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,children:l?b.submittingButton:b.submitButton})]}),n&&(0,Q.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[b.hasAccountText,` `,(0,Q.jsx)(a,{href:n,className:`text-primary underline-offset-4 hover:underline`,children:b.signInText})]})]})}var Mt=({href:e,className:t,children:n})=>(0,Q.jsx)(`a`,{href:e,className:t,children:n});function Nt({onSuccess:e,onError:t,loginUrl:n=`/login`,title:r=`Reset your password`,description:i=`Enter your email address and we'll send you a link to reset your password`,linkComponent:a=Mt,labels:o={}}){let{forgotPassword:c,isLoading:l}=$(),[u,d]=(0,s.useState)(``),[f,p]=(0,s.useState)(null),[m,h]=(0,s.useState)(!1),g={emailLabel:o.emailLabel??`Email`,emailPlaceholder:o.emailPlaceholder??`name@example.com`,submitButton:o.submitButton??`Send Reset Link`,submittingButton:o.submittingButton??`Sending...`,successTitle:o.successTitle??`Check your email`,successDescription:o.successDescription??`We've sent a password reset link to {{email}}. Please check your inbox.`,backToSignInText:o.backToSignInText??`Back to sign in`,rememberPasswordText:o.rememberPasswordText??`Remember your password?`,signInText:o.signInText??`Sign in`},_=async n=>{n.preventDefault(),p(null);try{await c(u),h(!0),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));p(n.message),t?.(n)}};if(m){let e=g.successDescription.includes(`{{email}}`)?g.successDescription.replace(`{{email}}`,u):`${g.successDescription} ${u}`;return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[380px]`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:g.successTitle}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e})]}),n&&(0,Q.jsx)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:(0,Q.jsx)(a,{href:n,className:`text-primary underline-offset-4 hover:underline`,children:g.backToSignInText})})]})}return(0,Q.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[380px]`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-col space-y-2 text-center`,children:[(0,Q.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight`,children:r}),(0,Q.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:i})]}),(0,Q.jsxs)(`form`,{onSubmit:_,className:`space-y-4`,children:[f&&(0,Q.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:f}),(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(`label`,{htmlFor:`forgot-email`,className:`text-sm font-medium leading-none`,children:g.emailLabel}),(0,Q.jsx)(`input`,{id:`forgot-email`,type:`email`,placeholder:g.emailPlaceholder,value:u,onChange:e=>d(e.target.value),required:!0,autoComplete:`email`,disabled:l,className:`flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50`})]}),(0,Q.jsx)(`button`,{type:`submit`,disabled:l,className:`inline-flex h-10 w-full items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50`,children:l?g.submittingButton:g.submitButton})]}),n&&(0,Q.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[g.rememberPasswordText,` `,(0,Q.jsx)(a,{href:n,className:`text-primary underline-offset-4 hover:underline`,children:g.signInText})]})]})}function Pt(e){return e?e.name?e.name.split(` `).map(e=>e[0]).join(``).toUpperCase().slice(0,2):e.email?.[0]?.toUpperCase()??`?`:`?`}function Ft({className:e}){let{isPreviewMode:t,previewMode:n}=$();return t?(0,Q.jsx)(`div`,{role:`status`,className:e,style:{padding:`8px 16px`,backgroundColor:`#fef3c7`,color:`#92400e`,textAlign:`center`,fontSize:`14px`,borderBottom:`1px solid #fcd34d`},children:n?.bannerMessage??`You are in preview mode.`}):null}var It=(0,s.createContext)(null);It.displayName=`PermissionContext`;function Lt(){let e=(0,s.useContext)(It);return e?{...e,can:(t,n)=>e.check(t,n).allowed,cannot:(t,n)=>!e.check(t,n).allowed}:{check:()=>({allowed:!0}),checkField:()=>!0,getFieldPermissions:()=>[],getRowFilter:()=>void 0,roles:[],isLoaded:!1,can:()=>!0,cannot:()=>!1}}export{jt as a,$ as c,a as d,o as f,Nt as i,St as l,Ft as n,kt as o,Pt as r,Ct as s,Lt as t,xt as u};
@@ -0,0 +1 @@
1
+ import{n as e,r as t}from"./rolldown-runtime-S-ySWqyJ.js";import{_ as n,t as r}from"./vendor-react-B1k2FF9f.js";import{H as i,L as a,M as o,R as s,a as c,w as l}from"./framework-CoXA0nY6.js";import{$t as u,NL as d,QA as f,Qt as p,Ut as m,XA as h,Zt as g,cn as _,en as v,lm as y,ln as b,nt as x,pM as S,rr as C,sn as w,tn as T,vr as E}from"./ui-components-BCmPcwhR.js";import{i as D}from"./plugin-grid-DwpWK0E8.js";var O=t(n(),1),k=r(),A=`bg-blue-500 text-white`,j=new Date,M={"calendar.today":`Today`,"calendar.month":`Month`,"calendar.week":`Week`,"calendar.day":`Day`,"calendar.newEvent":`New event`,"calendar.moreEvents":`+{{count}} more`};function N(){try{let e=c();return e.t(`calendar.today`)===`calendar.today`?{t:(e,t)=>{let n=M[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n},language:`en`}:{t:e.t,language:e.language}}catch{return{t:(e,t)=>{let n=M[e]||e;if(t)for(let[e,r]of Object.entries(t))n=n.replace(`{{${e}}}`,String(r));return n},language:`en`}}}function P({events:e=[],view:t=`month`,currentDate:n=j,locale:r=`default`,onEventClick:i,onDateClick:a,onViewChange:o,onNavigate:s,onAddClick:c,onEventDrop:l,className:m}){let[x,D]=O.useState(t),[A,M]=O.useState(n),{t:P,language:I}=N(),L=r===`default`?I:r;O.useEffect(()=>{M(n)},[n]),O.useEffect(()=>{D(t)},[t]);let R=O.useRef(o);R.current=o,O.useEffect(()=>{let e=window.matchMedia(`(max-width: 639px)`),t=e=>{e.matches&&(D(`day`),R.current?.(`day`))};return t(e),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]);let H=()=>{let e=new Date(A);x===`month`?e.setMonth(e.getMonth()-1):x===`week`?e.setDate(e.getDate()-7):e.setDate(e.getDate()-1),M(e),s?.(e)},U=()=>{let e=new Date(A);x===`month`?e.setMonth(e.getMonth()+1):x===`week`?e.setDate(e.getDate()+7):e.setDate(e.getDate()+1),M(e),s?.(e)},W=()=>{let e=new Date;M(e),s?.(e)},G=e=>{D(e),o?.(e)},K=()=>{if(x===`month`)return A.toLocaleDateString(L,{month:`long`,year:`numeric`});if(x===`week`){let e=F(A),t=new Date(e);return t.setDate(t.getDate()+6),`${e.toLocaleDateString(L,{month:`short`,day:`numeric`})} - ${t.toLocaleDateString(L,{month:`short`,day:`numeric`,year:`numeric`})}`}else return A.toLocaleDateString(L,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`})},q=O.useRef(0);return(0,k.jsxs)(`div`,{role:`region`,"aria-label":`Calendar`,className:d(`flex flex-col h-full bg-background min-w-0 overflow-hidden`,m),children:[(0,k.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 p-2 sm:p-4 border-b min-w-0`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,k.jsxs)(`div`,{className:`flex items-center bg-muted/50 rounded-lg p-1 gap-1`,children:[(0,k.jsx)(E,{variant:`ghost`,size:`sm`,onClick:W,className:`h-8`,"aria-label":`Go to today`,children:P(`calendar.today`)}),(0,k.jsx)(`div`,{className:`h-4 w-px bg-border mx-1`}),(0,k.jsx)(E,{variant:`ghost`,size:`icon`,"aria-label":`Previous period`,onClick:H,className:`h-8 w-8`,children:(0,k.jsx)(f,{className:`h-4 w-4`})}),(0,k.jsx)(E,{variant:`ghost`,size:`icon`,"aria-label":`Next period`,onClick:U,className:`h-8 w-8`,children:(0,k.jsx)(h,{className:`h-4 w-4`})})]}),(0,k.jsxs)(w,{children:[(0,k.jsx)(b,{asChild:!0,children:(0,k.jsxs)(E,{variant:`ghost`,"aria-label":`Current date: ${K()}`,className:d(`text-base sm:text-xl font-semibold h-auto px-2 sm:px-3 py-1 hover:bg-muted/50 transition-colors`,`flex items-center gap-2`),children:[(0,k.jsx)(S,{className:`h-5 w-5 text-muted-foreground`}),(0,k.jsx)(`span`,{children:K()})]})}),(0,k.jsx)(_,{className:`w-auto p-0`,align:`start`,children:(0,k.jsx)(C,{mode:`single`,selected:A,onSelect:e=>{e&&(M(e),s?.(e))},initialFocus:!0,fromYear:2e3,toYear:2050})})]})]}),(0,k.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,k.jsxs)(g,{value:x,onValueChange:G,children:[(0,k.jsx)(v,{className:`w-32 bg-background`,children:(0,k.jsx)(T,{})}),(0,k.jsxs)(p,{children:[(0,k.jsx)(u,{value:`day`,children:P(`calendar.day`)}),(0,k.jsx)(u,{value:`week`,children:P(`calendar.week`)}),(0,k.jsx)(u,{value:`month`,children:P(`calendar.month`)})]})]}),c&&(0,k.jsxs)(E,{onClick:c,size:`sm`,className:`gap-1`,children:[(0,k.jsx)(y,{className:`h-4 w-4`}),P(`calendar.newEvent`)]})]})]}),(0,k.jsxs)(`div`,{className:`flex-1 overflow-auto`,onTouchStart:e=>{q.current=e.touches[0].clientX},onTouchEnd:e=>{let t=q.current-e.changedTouches[0].clientX;if(Math.abs(t)>50){let e=new Date(A);x===`day`?e.setDate(e.getDate()+(t>0?1:-1)):x===`week`?e.setDate(e.getDate()+(t>0?7:-7)):e.setMonth(e.getMonth()+(t>0?1:-1)),M(e),s?.(e)}},children:[x===`month`&&(0,k.jsx)(z,{date:A,events:e,locale:L,onEventClick:i,onDateClick:a,onEventDrop:l}),x===`week`&&(0,k.jsx)(B,{date:A,events:e,locale:L,onEventClick:i,onDateClick:a}),x===`day`&&(0,k.jsx)(V,{date:A,events:e,onEventClick:i,onDateClick:a})]})]})}function F(e){let t=new Date(e),n=t.getDay(),r=t.getDate()-n;return t.setDate(r),t}function I(e){let t=e.getFullYear(),n=e.getMonth(),r=new Date(t,n,1),i=new Date(t,n+1,0),a=r.getDay(),o=[];for(let e=a-1;e>=0;e--){let t=new Date(r.getTime());t.setDate(t.getDate()-(e+1)),o.push(t)}for(let e=1;e<=i.getDate();e++)o.push(new Date(t,n,e));let s=42-o.length;for(let e=1;e<=s;e++){let t=new Date(i.getTime());t.setDate(t.getDate()+e),o.push(t)}return o}function L(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function R(e,t){return t.filter(t=>{let n=new Date(t.start),r=t.end?new Date(t.end):new Date(n),i=new Date(e);i.setHours(0,0,0,0);let a=new Date(e);a.setHours(23,59,59,999);let o=new Date(n);o.setHours(0,0,0,0);let s=new Date(r);return s.setHours(23,59,59,999),i<=s&&a>=o})}function z({date:e,events:t,locale:n=`default`,onEventClick:r,onDateClick:i,onEventDrop:a}){let o=O.useMemo(()=>I(e),[e.getFullYear(),e.getMonth()]),s=O.useMemo(()=>new Date,[]),{t:c}=N(),l=O.useMemo(()=>{let e=new Date(2024,0,7);return Array.from({length:7},(t,r)=>{let i=new Date(e);return i.setDate(i.getDate()+r),i.toLocaleDateString(n,{weekday:`short`})})},[n]),[u,f]=O.useState(null),[p,m]=O.useState(null),h=O.useMemo(()=>{let e=new Map;for(let n of t){let t=new Date(n.start),r=n.end?new Date(n.end):new Date(t);t.setHours(0,0,0,0),r.setHours(0,0,0,0);let i=new Date(t);for(;i<=r;){let t=`${i.getFullYear()}-${i.getMonth()}-${i.getDate()}`,r=e.get(t);r?r.push(n):e.set(t,[n]),i.setDate(i.getDate()+1)}}return e},[t]),g=(e,t)=>{f(t.id),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(t.id))},_=()=>{f(null),m(null)},v=(e,t)=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,m(t)},y=e=>{e.currentTarget.contains(e.relatedTarget)||m(null)},b=(e,n)=>{if(e.preventDefault(),m(null),f(null),!a)return;let r=e.dataTransfer.getData(`text/plain`),i=t.find(e=>String(e.id)===r);if(!i)return;let o=new Date(i.start),s=new Date(o);s.setHours(0,0,0,0);let c=new Date(n);c.setHours(0,0,0,0);let l=c.getTime()-s.getTime();if(l===0)return;let u=new Date(o.getTime()+l),d;i.end&&(d=new Date(new Date(i.end).getTime()+l)),a(i,u,d)};return(0,k.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,k.jsx)(`div`,{role:`row`,className:`grid grid-cols-7 border-b`,children:l.map(e=>(0,k.jsx)(`div`,{role:`columnheader`,className:`p-2 text-center text-sm font-medium text-muted-foreground border-r last:border-r-0`,children:e},e))}),(0,k.jsx)(`div`,{role:`grid`,"aria-label":`Calendar grid`,className:`grid grid-cols-7 flex-1 auto-rows-fr`,children:o.map((t,n)=>{let o=`${t.getFullYear()}-${t.getMonth()}-${t.getDate()}`,l=h.get(o)||[],f=t.getMonth()===e.getMonth(),m=L(t,s);return(0,k.jsxs)(`div`,{role:`gridcell`,"aria-label":`${t.toLocaleDateString(`default`,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`})}${l.length>0?`, ${l.length} event${l.length>1?`s`:``}`:``}`,className:d(`border-b border-r last:border-r-0 p-2 min-h-[100px] cursor-pointer hover:bg-accent/50`,!f&&`bg-muted/50 text-muted-foreground opacity-50`,p===n&&`ring-2 ring-primary`),onClick:()=>i?.(t),onDragOver:e=>v(e,n),onDragLeave:y,onDrop:e=>b(e,t),children:[(0,k.jsx)(`div`,{className:d(`text-sm font-medium mb-2`,m&&`inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground h-6 w-6`),...m?{"aria-current":`date`}:{},children:t.getDate()}),(0,k.jsxs)(`div`,{className:`space-y-1`,children:[l.slice(0,3).map(e=>(0,k.jsx)(`div`,{role:`button`,title:e.title,"aria-label":e.title,draggable:!!a,onDragStart:t=>g(t,e),onDragEnd:_,className:d(`text-xs px-2 py-1 rounded truncate cursor-pointer hover:opacity-80`,e.color?.startsWith(`#`)?`text-white`:e.color||A,u===e.id&&`opacity-50`),style:e.color&&e.color.startsWith(`#`)?{backgroundColor:e.color}:void 0,onClick:t=>{t.stopPropagation(),r?.(e)},children:e.title},e.id)),l.length>3&&(0,k.jsx)(`div`,{className:`text-xs text-muted-foreground px-2`,children:c(`calendar.moreEvents`,{count:l.length-3})})]})]},n)})})]})}function B({date:e,events:t,locale:n=`default`,onEventClick:r,onDateClick:i}){let a=O.useRef(null),o=e=>{i&&(a.current=setTimeout(()=>{i(e)},500))},s=()=>{a.current&&=(clearTimeout(a.current),null)},c=F(e),l=Array.from({length:7},(e,t)=>{let n=new Date(c);return n.setDate(n.getDate()+t),n}),u=new Date;return(0,k.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,k.jsx)(`div`,{className:`grid grid-cols-7 border-b`,children:l.map(e=>{let t=L(e,u);return(0,k.jsxs)(`div`,{className:`p-3 text-center border-r last:border-r-0`,children:[(0,k.jsx)(`div`,{className:`text-sm font-medium text-muted-foreground`,children:e.toLocaleDateString(n,{weekday:`short`})}),(0,k.jsx)(`div`,{className:d(`text-lg font-semibold mt-1`,t&&`inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground h-8 w-8`),children:e.getDate()})]},e.toISOString())})}),(0,k.jsx)(`div`,{role:`grid`,className:`grid grid-cols-7 flex-1`,children:l.map(e=>{let n=R(e,t);return(0,k.jsx)(`div`,{role:`gridcell`,"aria-label":`${e.toLocaleDateString(`default`,{weekday:`long`,month:`long`,day:`numeric`,year:`numeric`})}${n.length>0?`, ${n.length} event${n.length>1?`s`:``}`:``}`,className:`border-r last:border-r-0 p-2 min-h-[400px] cursor-pointer hover:bg-accent/50`,onClick:()=>i?.(e),onTouchStart:()=>o(e),onTouchEnd:s,children:(0,k.jsx)(`div`,{className:`space-y-2`,children:n.map(e=>(0,k.jsxs)(`div`,{role:`button`,title:e.title,"aria-label":e.title,className:d(`text-xs sm:text-sm px-2 sm:px-3 py-1.5 sm:py-2 rounded cursor-pointer hover:opacity-80`,e.color?.startsWith(`#`)?`text-white`:e.color||A),style:e.color&&e.color.startsWith(`#`)?{backgroundColor:e.color}:void 0,onClick:t=>{t.stopPropagation(),r?.(e)},children:[(0,k.jsx)(`div`,{className:`font-medium truncate`,children:e.title}),!e.allDay&&(0,k.jsx)(`div`,{className:`text-xs opacity-90 mt-1`,children:e.start.toLocaleTimeString(`default`,{hour:`numeric`,minute:`2-digit`})})]},e.id))})},e.toISOString())})})]})}function V({date:e,events:t,onEventClick:n,onDateClick:r}){let i=R(e,t),a=Array.from({length:24},(e,t)=>t),o=O.useRef(null),s=t=>{r&&(o.current=setTimeout(()=>{let n=new Date(e);n.setHours(t,0,0,0),r(n)},500))},c=()=>{o.current&&=(clearTimeout(o.current),null)};return(0,k.jsx)(`div`,{className:`flex flex-col h-full`,children:(0,k.jsx)(`div`,{role:`list`,className:`flex-1 overflow-auto`,children:a.map(e=>{let t=i.filter(t=>t.allDay?e===0:t.start.getHours()===e);return(0,k.jsxs)(`div`,{role:`listitem`,className:`flex border-b min-h-[60px]`,children:[(0,k.jsx)(`div`,{className:`w-20 p-2 text-sm text-muted-foreground border-r`,children:e===0?`12 AM`:e<12?`${e} AM`:e===12?`12 PM`:`${e-12} PM`}),(0,k.jsx)(`div`,{className:`flex-1 p-2 space-y-2`,onTouchStart:()=>s(e),onTouchEnd:c,children:t.map(e=>(0,k.jsxs)(`div`,{title:e.title,"aria-label":e.title,className:d(`px-2 sm:px-3 py-1.5 sm:py-2 rounded cursor-pointer hover:opacity-80`,e.color?.startsWith(`#`)?`text-white`:e.color||A),style:e.color&&e.color.startsWith(`#`)?{backgroundColor:e.color}:void 0,onClick:()=>n?.(e),children:[(0,k.jsx)(`div`,{className:`font-medium truncate`,children:e.title}),!e.allDay&&(0,k.jsxs)(`div`,{className:`text-xs opacity-90 mt-1`,children:[e.start.toLocaleTimeString(`default`,{hour:`numeric`,minute:`2-digit`}),e.end&&` - ${e.end.toLocaleTimeString(`default`,{hour:`numeric`,minute:`2-digit`})}`]})]},e.id))})]},e)})})})}function H(e){return`data`in e&&e.data?e.data:`staticData`in e&&e.staticData?{provider:`value`,items:e.staticData}:e.objectName?{provider:`object`,object:e.objectName}:null}function U(e){if(e){if(typeof e==`string`){let t=e.split(` `),n=t[0],r=t[1]?.toLowerCase()===`desc`?`desc`:`asc`;return{[n]:r}}if(Array.isArray(e))return e.reduce((e,t)=>(t.field&&t.order&&(e[t.field]=t.order),e),{})}}function W(e){return`filter`in e&&e.filter&&typeof e.filter==`object`&&`calendar`in e.filter?e.filter.calendar:e.calendar?e.calendar:e.startDateField||e.dateField?{startDateField:e.startDateField||e.dateField,endDateField:e.endDateField||e.endField,titleField:e.titleField,colorField:e.colorField,allDayField:e.allDayField}:null}var G=({schema:e,dataSource:t,className:n,data:r,loading:i,onEventClick:o,onRowClick:c,onDateClick:u,onNavigate:d,onViewChange:f,onEventDrop:p,locale:h})=>{let g=Array.isArray(r),[_,v]=(0,O.useState)(g?r:[]),[y,b]=(0,O.useState)(g?i??!1:!0),[S,C]=(0,O.useState)(null),[w,T]=(0,O.useState)(null),[E,A]=(0,O.useState)(new Date),j=m(),M=e.defaultView,[N,F]=(0,O.useState)(()=>{let e=M===`day`||!M;return typeof window<`u`&&window.innerWidth<768&&e?`month`:M||`month`});(0,O.useEffect)(()=>{j&&N===`day`&&(M===`day`||!M)&&F(`month`)},[j]);let[I,L]=(0,O.useState)(0);(0,O.useEffect)(()=>{if(!g&&!(!t?.onMutation||!e.objectName))return t.onMutation(t=>{t.resource===e.objectName&&L(e=>e+1)})},[t,e.objectName,g]);let{ref:R,isRefreshing:z,pullDistance:B}=D({onRefresh:(0,O.useCallback)(async()=>{L(e=>e+1)},[]),enabled:!!t&&!!e.objectName}),V=(0,O.useMemo)(()=>H(e),[e.data,e.staticData,e.objectName]),G=(0,O.useMemo)(()=>W(e),[e.filter,e.calendar,e.dateField,e.endField,e.titleField,e.colorField]),K=V?.provider===`value`,q=(0,O.useRef)(null);q.current=w,(0,O.useEffect)(()=>{g&&v(r)},[r,g]),(0,O.useEffect)(()=>{g&&i!==void 0&&b(i)},[i,g]),(0,O.useEffect)(()=>{if(g)return;let n=!0;return(async()=>{try{if(!n)return;if(b(!0),K&&V?.provider===`value`){n&&(v(V.items),b(!1));return}if(!t||typeof t.find!=`function`)throw Error(`DataSource required for object/api providers`);if(V?.provider===`object`){let r=V.object,i=a(q.current?.fields),o=s(await t.find(r,{$filter:e.filter,$orderby:U(e.sort),...i.length>0?{$expand:i}:{}}));n&&v(o)}else V?.provider===`api`&&(console.warn(`API provider not yet implemented for ObjectCalendar`),n&&v([]));n&&b(!1)}catch(e){console.error(`[ObjectCalendar] Error fetching data:`,e),n&&(C(e),b(!1))}})(),()=>{n=!1}},[g,V,t,K,e.filter,e.sort,I]),(0,O.useEffect)(()=>{!K&&t&&(async()=>{try{if(!t)return;let n=V?.provider===`object`?V.object:e.objectName;if(!n)return;T(await t.getObjectSchema(n))}catch(e){console.error(`Failed to fetch object schema:`,e)}})()},[e.objectName,t,K,V]);let J=(0,O.useMemo)(()=>{if(!G||!_.length)return[];let{startDateField:e,endDateField:t,titleField:n,colorField:r}=G,i=w?.titleFormat,a=w?.NAME_FIELD_KEY,o=[`name`,`full_name`,`fullName`,`title`,`subject`,`label`,`display_name`,`displayName`],s=(e,t)=>{let n=!1,r=e.replace(/\{(.+?)\}/g,(e,r)=>{let i=t[r.trim()];return i!=null&&i!==``?(n=!0,String(i)):``}).replace(/\s+-\s+(?=$|\s*$)/,``).trim();return n?r:``},c=e=>{let t;if(n&&(t=e[n],typeof t==`string`&&(t=t.trim())),!t&&i){let n=s(i,e);n&&(t=n)}if(!t&&a){let n=e[a];typeof n==`string`?t=n.trim():n&&(t=n)}if(!t)for(let n of o){let r=e[n],i=typeof r==`string`?r.trim():r;if(i){t=i;break}}return t||`Untitled`};return _.map((n,i)=>{let a=n[e],o=t?n[t]:null,s=c(n),l=r?n[r]:void 0;return{id:n.id||n._id||`event-${i}`,title:s,start:a?new Date(a):new Date,end:o?new Date(o):void 0,color:l,allDay:!o,data:n}}).filter(e=>!isNaN(e.start.getTime()))},[_,G,w]);(0,O.useCallback)(()=>{u?.(new Date)},[u]);let Y=l({navigation:e.navigation,objectName:e.objectName,onRowClick:c});return y?(0,k.jsx)(`div`,{className:n,children:(0,k.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,k.jsx)(`div`,{className:`text-muted-foreground`,children:`Loading calendar...`})})}):S?(0,k.jsx)(`div`,{className:n,children:(0,k.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,k.jsxs)(`div`,{className:`text-destructive`,children:[`Error: `,S.message]})})}):G?(0,k.jsxs)(`div`,{ref:R,className:n,children:[B>0&&(0,k.jsx)(`div`,{className:`flex items-center justify-center text-xs text-muted-foreground`,style:{height:B},children:z?`Refreshing…`:`Pull to refresh`}),(0,k.jsx)(`div`,{className:`border rounded-lg bg-background h-[calc(100vh-120px)] sm:h-[calc(100vh-160px)] md:h-[calc(100vh-200px)] min-h-[400px] sm:min-h-[600px]`,children:(0,k.jsx)(P,{events:J,currentDate:E,view:N,locale:h,onEventClick:e=>{Y.handleClick(e.data),o?.(e.data)},onDateClick:u,onNavigate:e=>{A(e),d?.(e)},onViewChange:e=>{F(e),f?.(e)},onAddClick:void 0,onEventDrop:p?(e,t,n)=>{p(e.data,t,n)}:void 0})}),Y.isOverlay&&(0,k.jsx)(x,{...Y,title:`Event Details`,children:e=>(0,k.jsx)(`div`,{className:`space-y-3`,children:Object.entries(e).map(([e,t])=>(0,k.jsxs)(`div`,{className:`flex flex-col`,children:[(0,k.jsx)(`span`,{className:`text-xs font-medium text-muted-foreground uppercase tracking-wide`,children:e.replace(/_/g,` `)}),(0,k.jsx)(`span`,{className:`text-sm`,children:String(t??`—`)})]},e))})})]}):(0,k.jsx)(`div`,{className:n,children:(0,k.jsx)(`div`,{className:`flex items-center justify-center h-96`,children:(0,k.jsx)(`div`,{className:`text-muted-foreground`,children:`Calendar configuration required. Please specify startDateField and titleField.`})})})};i.register(`calendar-view`,({schema:e,className:t,onAction:n,...r})=>{let i=O.useMemo(()=>!e.data||!Array.isArray(e.data)?[]:e.data.map((t,n)=>{let r=e.titleField||`title`,i=e.startDateField||`start`,a=e.endDateField||`end`,o=e.colorField||`color`,s=e.allDayField||`allDay`;return{id:t.id||t._id||n,title:t[r]||`Untitled Event`,start:new Date(t[i]),end:t[a]?new Date(t[a]):void 0,allDay:t[s],color:t[o],data:t}}),[e.data,e.titleField,e.startDateField,e.endDateField,e.colorField,e.allDayField]);return(0,k.jsx)(P,{className:t,events:i,onEventClick:e=>{n?.({type:`event-click`,payload:e})},...r})},{namespace:`plugin-calendar`,label:`Calendar View`,inputs:[{name:`data`,type:`array`,label:`Data`,description:`Array of record objects to display as events`},{name:`titleField`,type:`string`,label:`Title Field`,defaultValue:`title`,description:`Field name to use for event title`},{name:`startDateField`,type:`string`,label:`Start Date Field`,defaultValue:`start`,description:`Field name for event start date`},{name:`endDateField`,type:`string`,label:`End Date Field`,defaultValue:`end`,description:`Field name for event end date (optional)`},{name:`allDayField`,type:`string`,label:`All Day Field`,defaultValue:`allDay`,description:`Field name for all-day flag`},{name:`colorField`,type:`string`,label:`Color Field`,defaultValue:`color`,description:`Field name for event color`},{name:`colorMapping`,type:`object`,label:`Color Mapping`,description:`Map field values to colors (e.g., {meeting: "blue", deadline: "red"})`},{name:`view`,type:`enum`,enum:[`month`,`week`,`day`],defaultValue:`month`,label:`View Mode`,description:`Calendar view mode (month, week, or day)`},{name:`currentDate`,type:`string`,label:`Current Date`,description:`ISO date string for initial calendar date`},{name:`allowCreate`,type:`boolean`,label:`Allow Create`,defaultValue:!1,description:`Allow creating events by clicking on dates`},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{view:`month`,titleField:`title`,startDateField:`start`,endDateField:`end`,allDayField:`allDay`,colorField:`color`,allowCreate:!1,data:[{id:1,title:`Team Meeting`,start:new Date(new Date().setHours(10,0,0,0)).toISOString(),end:new Date(new Date().setHours(11,0,0,0)).toISOString(),color:`#3b82f6`,allDay:!1},{id:2,title:`Project Deadline`,start:new Date(new Date().setDate(new Date().getDate()+3)).toISOString(),color:`#ef4444`,allDay:!0},{id:3,title:`Conference`,start:new Date(new Date().setDate(new Date().getDate()+7)).toISOString(),end:new Date(new Date().setDate(new Date().getDate()+9)).toISOString(),color:`#10b981`,allDay:!0}],className:`h-[600px] border rounded-lg`}});var K=e({CalendarView:()=>P,ObjectCalendar:()=>G,ObjectCalendarRenderer:()=>q}),q=({schema:e,...t})=>{let{dataSource:n}=o()||{};return(0,k.jsx)(G,{schema:e,dataSource:n,...t})};i.register(`object-calendar`,q,{namespace:`plugin-calendar`,label:`Object Calendar`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`calendar`,type:`object`,label:`Calendar Config`,description:`startDateField, endDateField, titleField, colorField`}]}),i.register(`calendar`,q,{namespace:`view`,label:`Calendar View`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`calendar`,type:`object`,label:`Calendar Config`,description:`startDateField, endDateField, titleField, colorField`}]});export{K as t};
@@ -0,0 +1,7 @@
1
+ import{n as e,r as t}from"./rolldown-runtime-S-ySWqyJ.js";import{_ as n,m as r,t as i}from"./vendor-react-B1k2FF9f.js";import{H as a,R as o,j as s,k as c}from"./framework-CoXA0nY6.js";import{f as l}from"./infrastructure-Djv3I7gr.js";import{FA as u,Ht as d}from"./ui-components-BCmPcwhR.js";import{C as f,S as p,_ as m,a as h,b as g,c as _,d as v,f as y,g as b,h as x,i as S,l as C,m as w,n as T,o as ee,p as E,r as D,s as O,t as k,u as A,v as j,x as M,y as N}from"./vendor-charts-DHZsyaJw.js";var P=t(n(),1),F=i(),I=(...e)=>e.filter(Boolean).join(` `),te={light:``,dark:`.dark`},L=P.createContext(null);function R(){let e=P.useContext(L);if(!e)throw Error(`useChart must be used within a <ChartContainer />`);return e}function z({id:e,className:t,children:n,config:r,...i}){let a=P.useId(),o=`chart-${e||a.replace(/:/g,``)}`;return(0,F.jsx)(L.Provider,{value:{config:r},children:(0,F.jsxs)(`div`,{"data-slot":`chart`,"data-chart":o,className:I(`flex w-full h-[350px] justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground`,t),...i,children:[(0,F.jsx)(B,{id:o,config:r}),(0,F.jsx)(f,{width:`100%`,height:`100%`,children:n})]})})}var B=({id:e,config:t})=>{let n=Object.entries(t).filter(([,e])=>e.theme||e.color);return n.length?(0,F.jsx)(`style`,{dangerouslySetInnerHTML:{__html:Object.entries(te).map(([t,r])=>`
2
+ ${r} [data-chart=${e}] {
3
+ ${n.map(([e,n])=>{let r=n.theme?.[t]||n.color;return r?` --color-${e}: ${r};`:null}).join(`
4
+ `)}
5
+ }
6
+ `).join(`
7
+ `)}}):null},V=M;function H({active:e,payload:t,className:n,indicator:r=`dot`,hideLabel:i=!1,hideIndicator:a=!1,label:o,labelFormatter:s,labelClassName:c,formatter:l,color:u,nameKey:d,labelKey:f}){let{config:p}=R(),m=P.useMemo(()=>{if(i||!t?.length)return null;let[e]=t,n=G(p,e,`${f||e?.dataKey||e?.name||`value`}`),r=!f&&typeof o==`string`?p[o]?.label||o:n?.label;return s?(0,F.jsx)(`div`,{className:I(`font-medium`,c),children:s(r,t)}):r?(0,F.jsx)(`div`,{className:I(`font-medium`,c),children:r}):null},[o,s,t,i,c,p,f]);if(!e||!t?.length)return null;let h=t.length===1&&r!==`dot`;return(0,F.jsxs)(`div`,{className:I(`border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl`,n),children:[h?null:m,(0,F.jsx)(`div`,{className:`grid gap-1.5`,children:t.filter(e=>e.type!==`none`).map((e,t)=>{let n=G(p,e,`${d||e.name||e.dataKey||`value`}`),i=u||e.payload.fill||e.color;return(0,F.jsx)(`div`,{className:I(`[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5`,r===`dot`?`items-center`:``),children:l&&e?.value!==void 0&&e.name?l(e.value,e.name,e,t,e.payload):(0,F.jsxs)(F.Fragment,{children:[n?.icon?(0,F.jsx)(n.icon,{}):!a&&(0,F.jsx)(`div`,{className:I(`shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)`,r===`dot`?`h-2.5 w-2.5`:``,r===`line`?`w-1`:``,r===`dashed`?`w-0 border-[1.5px] border-dashed bg-transparent`:``,h&&r===`dashed`?`my-0.5`:``),style:{"--color-bg":i,"--color-border":i}}),(0,F.jsxs)(`div`,{className:I(`flex flex-1 justify-between leading-none`,h?`items-end`:`items-center`),children:[(0,F.jsxs)(`div`,{className:`grid gap-1.5`,children:[h?m:null,(0,F.jsx)(`span`,{className:`text-muted-foreground`,children:n?.label||e.name})]}),e.value&&(0,F.jsx)(`span`,{className:`text-foreground font-mono font-medium tabular-nums`,children:e.value.toLocaleString()})]})]})},e.dataKey)})})]})}var U=p;function W({className:e,hideIcon:t=!1,payload:n,verticalAlign:r=`bottom`,nameKey:i}){let{config:a}=R();return n?.length?(0,F.jsx)(`div`,{className:I(`flex items-center justify-center gap-4`,r===`top`?`pb-3`:`pt-3`,e),children:n.filter(e=>e.type!==`none`).map(e=>{let n=G(a,e,`${i||e.dataKey||`value`}`);return(0,F.jsxs)(`div`,{className:I(`[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3`),children:[n?.icon&&!t?(0,F.jsx)(n.icon,{}):(0,F.jsx)(`div`,{className:`h-2 w-2 shrink-0 rounded-[2px]`,style:{backgroundColor:e.color}}),n?.label]},e.value)})}):null}function G(e,t,n){if(typeof t!=`object`||!t)return;let r=`payload`in t&&typeof t.payload==`object`&&t.payload!==null?t.payload:void 0,i=n;return n in t&&typeof t[n]==`string`?i=t[n]:r&&n in r&&typeof r[n]==`string`&&(i=r[n]),i in e?e[i]:e[n]}var K=e({default:()=>re}),q=`hsl(var(--primary))`,ne={slate:`#64748b`,gray:`#6b7280`,zinc:`#71717a`,neutral:`#737373`,stone:`#78716c`,red:`#ef4444`,orange:`#f97316`,amber:`#f59e0b`,yellow:`#eab308`,lime:`#84cc16`,green:`#22c55e`,emerald:`#10b981`,teal:`#14b8a6`,cyan:`#06b6d4`,sky:`#0ea5e9`,blue:`#3b82f6`,indigo:`#6366f1`,violet:`#8b5cf6`,purple:`#a855f7`,fuchsia:`#d946ef`,pink:`#ec4899`,rose:`#f43f5e`},J=e=>ne[e]||e;function re({chartType:e=`bar`,data:t=[],config:n={},xAxisKey:r=`name`,series:i=[],className:a=``}){let o=Array.isArray(t)?t:[],[s,c]=P.useState(!1);P.useEffect(()=>{let e=()=>c(window.innerWidth<640);return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let l={bar:h,line:ee,area:k,pie:S,donut:S,radar:D,scatter:T,combo:h}[e]||h,u=P.useMemo(()=>o.some(e=>String(e[r]||``).length>5),[o,r]),d=()=>[`hsl(var(--chart-1))`,`hsl(var(--chart-2))`,`hsl(var(--chart-3))`,`hsl(var(--chart-4))`,`hsl(var(--chart-5))`];if(e===`pie`||e===`donut`){let t=e===`donut`?60:0;return(0,F.jsx)(z,{config:n,className:a,children:(0,F.jsxs)(S,{children:[(0,F.jsx)(V,{cursor:!1,content:(0,F.jsx)(H,{hideLabel:!0})}),(0,F.jsx)(b,{data:o,dataKey:i[0]?.dataKey||`value`,nameKey:r||`name`,innerRadius:t,strokeWidth:5,paddingAngle:2,outerRadius:80,children:o.map((e,t)=>{let i=n[e[r]]?.color;if(!i){let e=d();i=e[t%e.length]}return(0,F.jsx)(g,{fill:J(i)},`cell-${t}`)})}),(0,F.jsx)(U,{content:(0,F.jsx)(W,{nameKey:r}),...s&&{verticalAlign:`bottom`,wrapperStyle:{fontSize:`11px`,paddingTop:`8px`}}})]})})}return e===`radar`?(0,F.jsx)(z,{config:n,className:a,children:(0,F.jsxs)(D,{data:o,children:[(0,F.jsx)(N,{}),(0,F.jsx)(m,{dataKey:r}),(0,F.jsx)(j,{}),(0,F.jsx)(V,{content:(0,F.jsx)(H,{})}),(0,F.jsx)(U,{content:(0,F.jsx)(W,{}),...s&&{verticalAlign:`bottom`,wrapperStyle:{fontSize:`11px`,paddingTop:`8px`}}}),i.map(e=>{let t=J(n[e.dataKey]?.color||q);return(0,F.jsx)(x,{dataKey:e.dataKey,stroke:t,fill:t,fillOpacity:.6},e.dataKey)})]})}):e===`scatter`?(0,F.jsx)(z,{config:n,className:a,children:(0,F.jsxs)(T,{children:[(0,F.jsx)(w,{vertical:!1}),(0,F.jsx)(C,{type:`number`,dataKey:r,name:String(n[r]?.label||r),tickLine:!1,axisLine:!1,interval:s?Math.ceil(o.length/5):0}),(0,F.jsx)(_,{type:`number`,dataKey:i[0]?.dataKey||`value`,name:String(n[i[0]?.dataKey]?.label||i[0]?.dataKey),tickLine:!1,axisLine:!1}),(0,F.jsx)(O,{type:`number`,range:[60,400]}),(0,F.jsx)(V,{content:(0,F.jsx)(H,{})}),(0,F.jsx)(U,{content:(0,F.jsx)(W,{}),...s&&{verticalAlign:`bottom`,wrapperStyle:{fontSize:`11px`,paddingTop:`8px`}}}),i.map((e,t)=>{let r=d(),i=J(n[e.dataKey]?.color||r[t%r.length]);return(0,F.jsx)(A,{name:n[e.dataKey]?.label||e.dataKey,data:o,fill:i},e.dataKey)})]})}):e===`combo`?(0,F.jsx)(z,{config:n,className:a,children:(0,F.jsxs)(h,{data:o,children:[(0,F.jsx)(w,{vertical:!1}),(0,F.jsx)(C,{dataKey:r,tickLine:!1,tickMargin:10,axisLine:!1,interval:s?Math.ceil(o.length/5):0,tickFormatter:e=>!e||typeof e!=`string`?e:s&&e.length>8?e.slice(0,8)+`…`:e,...!s&&u&&{angle:-35,textAnchor:`end`,height:60}}),(0,F.jsx)(_,{yAxisId:`left`,tickLine:!1,axisLine:!1}),(0,F.jsx)(_,{yAxisId:`right`,orientation:`right`,tickLine:!1,axisLine:!1}),(0,F.jsx)(V,{content:(0,F.jsx)(H,{})}),(0,F.jsx)(U,{content:(0,F.jsx)(W,{}),...s&&{verticalAlign:`bottom`,wrapperStyle:{fontSize:`11px`,paddingTop:`8px`}}}),i.map((e,t)=>{let r=J(n[e.dataKey]?.color||q),i=e.chartType||(t===0?`bar`:`line`),a=i===`bar`?`left`:`right`;return i===`line`?(0,F.jsx)(E,{yAxisId:a,type:`monotone`,dataKey:e.dataKey,stroke:r,strokeWidth:2,dot:!1},e.dataKey):i===`area`?(0,F.jsx)(y,{yAxisId:a,type:`monotone`,dataKey:e.dataKey,fill:r,stroke:r,fillOpacity:.4},e.dataKey):(0,F.jsx)(v,{yAxisId:a,dataKey:e.dataKey,fill:r,radius:4},e.dataKey)})]})}):(0,F.jsx)(z,{config:n,className:a,children:(0,F.jsxs)(l,{data:o,children:[(0,F.jsx)(w,{vertical:!1}),(0,F.jsx)(C,{dataKey:r,tickLine:!1,tickMargin:10,axisLine:!1,interval:s?Math.ceil(o.length/5):0,tickFormatter:e=>!e||typeof e!=`string`?e:s&&e.length>8?e.slice(0,8)+`…`:e,...!s&&u&&{angle:-35,textAnchor:`end`,height:60}}),(0,F.jsx)(V,{content:(0,F.jsx)(H,{})}),(0,F.jsx)(U,{content:(0,F.jsx)(W,{}),...s&&{verticalAlign:`bottom`,wrapperStyle:{fontSize:`11px`,paddingTop:`8px`}}}),i.map((t,r)=>{let a=d(),s=J(n[t.dataKey]?.color||a[r%a.length]||q);if(e===`bar`){let e=i.length===1&&o.length>1;return(0,F.jsx)(v,{dataKey:t.dataKey,fill:s,radius:4,children:e&&o.map((e,t)=>(0,F.jsx)(g,{fill:J(a[t%a.length])},`cell-${t}`))},t.dataKey)}return e===`line`?(0,F.jsx)(E,{type:`monotone`,dataKey:t.dataKey,stroke:s,strokeWidth:2,dot:!1},t.dataKey):e===`area`?(0,F.jsx)(y,{type:`monotone`,dataKey:t.dataKey,fill:s,stroke:s,fillOpacity:.4},t.dataKey):null})]})})}var Y=e({default:()=>ie});function ie({data:e=[],dataKey:t=`value`,xAxisKey:n=`name`,height:r=400,className:i=``,color:a=`hsl(var(--primary))`}){return(0,F.jsx)(`div`,{className:`p-2 sm:p-3 md:p-4 rounded-xl border border-border bg-card/40 backdrop-blur-sm shadow-lg shadow-background/5 ${i}`,children:(0,F.jsx)(f,{width:`100%`,height:r,children:(0,F.jsxs)(h,{data:e,margin:{top:10,right:10,left:10,bottom:5},children:[(0,F.jsxs)(`defs`,{children:[(0,F.jsxs)(`linearGradient`,{id:`barGradient`,x1:`0`,y1:`0`,x2:`0`,y2:`1`,children:[(0,F.jsx)(`stop`,{offset:`0%`,stopColor:a,stopOpacity:1}),(0,F.jsx)(`stop`,{offset:`90%`,stopColor:a,stopOpacity:.6}),(0,F.jsx)(`stop`,{offset:`100%`,stopColor:a,stopOpacity:.3})]}),(0,F.jsxs)(`filter`,{id:`glow`,height:`130%`,children:[(0,F.jsx)(`feGaussianBlur`,{in:`SourceAlpha`,stdDeviation:`3`,result:`blur`}),(0,F.jsx)(`feOffset`,{in:`blur`,dx:`0`,dy:`0`,result:`offsetBlur`}),(0,F.jsx)(`feFlood`,{floodColor:a,floodOpacity:`0.5`,result:`offsetColor`}),(0,F.jsx)(`feComposite`,{in:`offsetColor`,in2:`offsetBlur`,operator:`in`,result:`offsetBlur`}),(0,F.jsxs)(`feMerge`,{children:[(0,F.jsx)(`feMergeNode`,{in:`offsetBlur`}),(0,F.jsx)(`feMergeNode`,{in:`SourceGraphic`})]})]})]}),(0,F.jsx)(w,{strokeDasharray:`3 3`,stroke:`hsl(var(--border))`,vertical:!1}),(0,F.jsx)(C,{dataKey:n,tick:{fill:`hsl(var(--muted-foreground))`,fontSize:12,fontFamily:`monospace`},tickLine:!1,axisLine:{stroke:`hsl(var(--border))`},dy:10}),(0,F.jsx)(_,{tick:{fill:`hsl(var(--muted-foreground))`,fontSize:12,fontFamily:`monospace`},tickLine:!1,axisLine:!1}),(0,F.jsx)(M,{cursor:{fill:`hsl(var(--muted))`,opacity:.2},contentStyle:{backgroundColor:`hsl(var(--popover))`,borderColor:`hsl(var(--border))`,color:`hsl(var(--popover-foreground))`,borderRadius:`8px`,fontFamily:`monospace`,boxShadow:`0 4px 6px -1px rgb(0 0 0 / 0.1)`},itemStyle:{color:`hsl(var(--primary))`}}),(0,F.jsx)(p,{wrapperStyle:{paddingTop:`20px`,fontFamily:`monospace`}}),(0,F.jsx)(v,{dataKey:t,fill:`url(#barGradient)`,radius:[4,4,0,0],filter:`url(#glow)`,animationDuration:1500})]})})})}var ae=P.lazy(()=>r(()=>Promise.resolve().then(()=>Y),void 0)),oe=P.lazy(()=>r(()=>Promise.resolve().then(()=>K),void 0)),X=({schema:e})=>(0,F.jsx)(P.Suspense,{fallback:(0,F.jsx)(d,{className:`w-full h-48 sm:h-64 md:h-80 lg:h-[400px]`}),children:(0,F.jsx)(ae,{data:e.data,dataKey:e.dataKey,xAxisKey:e.xAxisKey,height:e.height,className:e.className,color:e.color})}),Z=({schema:e})=>{let t=P.useMemo(()=>{let t=e.series,n=e.xAxisKey,r=e.config;if(n||(e.index?n=e.index:e.category&&(n=e.category)),t||(e.categories?t=e.categories.map(e=>({dataKey:e})):e.value&&(t=[{dataKey:e.value}])),!r&&t){let n=e.colors||[`hsl(var(--chart-1))`,`hsl(var(--chart-2))`,`hsl(var(--chart-3))`],i={};t.forEach((e,t)=>{i[e.dataKey]={label:e.label||e.dataKey,color:n[t%n.length]}}),r=i}return{chartType:e.chartType,data:Array.isArray(e.data)?e.data:[],config:r,xAxisKey:n,series:t,className:e.className}},[e]);return(0,F.jsx)(P.Suspense,{fallback:(0,F.jsx)(d,{className:`w-full h-48 sm:h-64 md:h-80 lg:h-[400px]`}),children:(0,F.jsx)(oe,{chartType:t.chartType,data:t.data,config:t.config,xAxisKey:t.xAxisKey,series:t.series,className:t.className})})};function Q(e){return e.replace(/[_-]/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}function se(e,t){let{field:n,function:r,groupBy:i}=t,a={};for(let t of e){let e=String(t[i]??`Unknown`);a[e]||(a[e]=[]),a[e].push(t)}return Object.entries(a).map(([e,t])=>{let a=t.map(e=>Number(e[n])||0),o;switch(r){case`count`:o=t.length;break;case`avg`:o=a.length>0?a.reduce((e,t)=>e+t,0)/a.length:0;break;case`min`:o=a.length>0?Math.min(...a):0;break;case`max`:o=a.length>0?Math.max(...a):0;break;default:o=a.reduce((e,t)=>e+t,0);break}return{[i]:e,[n]:o}})}async function ce(e,t,n,r,i){if(!e.length||!t)return e;let a=i||((e,t)=>t),s=n?.fields?.[t];if(!s)return e.map(e=>{let n=String(e[t]??``),r=Q(n);return{...e,[t]:a(n,r)}});let c=s.type;if(c===`select`||c===`picklist`||c===`dropdown`){let n=s.options||[];if(n.length===0)return e.map(e=>{let n=String(e[t]??``),r=Q(n);return{...e,[t]:a(n,r)}});let r={};for(let e of n)typeof e==`string`?r[e]=e:e&&typeof e==`object`&&(r[String(e.value)]=e.label||String(e.value));return e.map(e=>{let n=String(e[t]??``),i=r[n]||Q(n);return{...e,[t]:a(n,i)}})}if(c===`lookup`||c===`master_detail`){let n=s.reference_to||s.reference;if(!n||!r||typeof r.find!=`function`)return e;let i=[...new Set(e.map(e=>e[t]).filter(e=>e!=null))];if(i.length===0)return e;let a=s.id_field||`id`;try{let c=o(await r.find(n,{$filter:{[a]:{$in:i}},$top:i.length})),l=s.reference_field||s.display_field||`name`,u={};for(let e of c){let t=String(e[a]??e.id??e._id??``),n=e[l]||e.name||e.label||e.title||t;t&&(u[t]=String(n))}return e.map(e=>{let n=String(e[t]??``);return{...e,[t]:u[n]||n}})}catch(t){return console.warn(`[ObjectChart] Failed to resolve lookup labels:`,t),e}}return e.map(e=>({...e,[t]:Q(String(e[t]??``))}))}var $=e=>{let{schema:t}=e,n=(0,P.useContext)(c),r=e.dataSource||n?.dataSource,i=s(t.bind),{fieldOptionLabel:a}=l(),d=(0,P.useRef)(a);(0,P.useEffect)(()=>{d.current=a},[a]);let[f,p]=(0,P.useState)([]),[m,h]=(0,P.useState)(!1),[g,_]=(0,P.useState)(null),v=(0,P.useMemo)(()=>t.aggregate?JSON.stringify(t.aggregate):``,[t.aggregate]),y=(0,P.useMemo)(()=>t.filter?JSON.stringify(t.filter):``,[t.filter]),b=(0,P.useCallback)(async(e,n)=>{if(!(!e||!t.objectName)){n.current&&(h(!0),_(null));try{let r;if(t.aggregate&&typeof e.aggregate==`function`){let n=await e.aggregate(t.objectName,{field:t.aggregate.field,function:t.aggregate.function,groupBy:t.aggregate.groupBy,filter:t.filter});r=Array.isArray(n)?n:[]}else if(typeof e.find==`function`)r=o(await e.find(t.objectName,{$filter:t.filter})),t.aggregate&&r.length>0&&(r=se(r,t.aggregate));else return;let i=t.aggregate?.groupBy||t.xAxisKey;if(i&&typeof e.getObjectSchema==`function`)try{let n=await e.getObjectSchema(t.objectName);r=await ce(r,i,n,e,(e,n)=>d.current(t.objectName,i,e,n))}catch{}n.current&&p(r)}catch(e){console.error(`[ObjectChart] Fetch error:`,e),n.current&&_(e instanceof Error?e.message:`Failed to load chart data`)}finally{n.current&&h(!1)}}},[t.objectName,v,y,t.xAxisKey]);(0,P.useEffect)(()=>{let e={current:!0};return t.objectName&&!i&&!t.data&&b(r,e),()=>{e.current=!1}},[t.objectName,r,i,t.data,y,v,b]);let x=i||t.data||f,S=Array.isArray(x)?x:[],C={...t,data:S};return m&&S.length===0?(0,F.jsx)(`div`,{className:`flex items-center justify-center text-muted-foreground text-sm p-4 `+(t.className||``),"data-testid":`chart-loading`,children:`Loading chart data…`}):g?(0,F.jsxs)(`div`,{className:`flex flex-col items-center justify-center gap-2 p-4 `+(t.className||``),"data-testid":`chart-error`,role:`alert`,children:[(0,F.jsx)(u,{className:`h-6 w-6 text-destructive opacity-60`}),(0,F.jsx)(`p`,{className:`text-xs text-destructive font-medium`,children:`Failed to load chart data`}),(0,F.jsx)(`p`,{className:`text-xs text-muted-foreground max-w-xs text-center`,children:g})]}):!r&&t.objectName&&S.length===0?(0,F.jsxs)(`div`,{className:`flex items-center justify-center text-muted-foreground text-sm p-4 `+(t.className||``),"data-testid":`chart-no-datasource`,children:[`No data source available for “`,t.objectName,`”`]}):(0,F.jsx)(Z,{...e,schema:C})};a.register(`object-chart`,$,{namespace:`plugin-charts`,label:`Object Chart`,category:`view`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`data`,type:`array`,label:`Data`,description:`Optional static data`},{name:`filter`,type:`array`,label:`Filter`},{name:`aggregate`,type:`object`,label:`Aggregate`,description:`Aggregation config: { field, function, groupBy }`}]});var le=e({ChartBarRenderer:()=>X,ChartRenderer:()=>Z,ObjectChart:()=>$,chartComponents:()=>ue}),ue={"bar-chart":X,chart:Z};a.register(`bar-chart`,X,{namespace:`plugin-charts`,label:`Bar Chart`,category:`plugin`,inputs:[{name:`data`,type:`array`,label:`Data`,required:!0},{name:`dataKey`,type:`string`,label:`Data Key`,defaultValue:`value`},{name:`xAxisKey`,type:`string`,label:`X-Axis Key`,defaultValue:`name`},{name:`height`,type:`number`,label:`Height`,defaultValue:400},{name:`color`,type:`color`,label:`Color`,defaultValue:`#8884d8`}],defaultProps:{data:[{name:`Jan`,value:400},{name:`Feb`,value:300},{name:`Mar`,value:600},{name:`Apr`,value:800},{name:`May`,value:500}],dataKey:`value`,xAxisKey:`name`,height:400,color:`#8884d8`}}),a.register(`chart`,$,{namespace:`view`,category:`view`,label:`Chart`,inputs:[{name:`objectName`,type:`string`,label:`Object Name`,required:!0},{name:`type`,type:`string`,label:`Chart Type`},{name:`categoryField`,type:`string`,label:`Category Field`},{name:`valueField`,type:`string`,label:`Value Field`}]}),a.register(`chart`,Z,{namespace:`plugin-charts`,label:`Chart`,category:`plugin`,inputs:[{name:`chartType`,type:`enum`,label:`Chart Type`,enum:[{label:`Bar`,value:`bar`},{label:`Line`,value:`line`},{label:`Area`,value:`area`},{label:`Pie`,value:`pie`},{label:`Donut`,value:`donut`},{label:`Radar`,value:`radar`},{label:`Scatter`,value:`scatter`}],defaultValue:`bar`},{name:`data`,type:`code`,label:`Data (JSON)`,required:!0},{name:`config`,type:`code`,label:`Config (JSON)`},{name:`xAxisKey`,type:`string`,label:`X Axis Key`,defaultValue:`name`},{name:`series`,type:`code`,label:`Series (JSON Array)`,required:!0},{name:`className`,type:`string`,label:`CSS Class`}],defaultProps:{chartType:`bar`,data:[{name:`Jan`,sales:400,revenue:240},{name:`Feb`,sales:300,revenue:139},{name:`Mar`,sales:600,revenue:380},{name:`Apr`,sales:800,revenue:430},{name:`May`,sales:500,revenue:220}],config:{sales:{label:`Sales`,color:`#8884d8`},revenue:{label:`Revenue`,color:`#82ca9d`}},xAxisKey:`name`,series:[{dataKey:`sales`},{dataKey:`revenue`}]}}),a.register(`chart:bar`,Z,{namespace:`plugin-charts`,label:`Bar Chart (Alias)`,category:`plugin`,defaultProps:{chartType:`bar`}}),a.register(`pie-chart`,Z,{namespace:`plugin-charts`,label:`Pie Chart`,category:`plugin`,defaultProps:{chartType:`pie`}}),a.register(`donut-chart`,Z,{namespace:`plugin-charts`,label:`Donut Chart`,category:`plugin`,defaultProps:{chartType:`donut`}}),a.register(`radar-chart`,Z,{namespace:`plugin-charts`,label:`Radar Chart`,category:`plugin`,defaultProps:{chartType:`radar`}}),a.register(`scatter-chart`,Z,{namespace:`plugin-charts`,label:`Scatter Chart`,category:`plugin`,defaultProps:{chartType:`scatter`}});export{Y as n,K as r,le as t};