@objectstack/console 17.0.0-rc.2 → 17.0.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +75 -0
- package/dist/.objectui-sha +1 -1
- package/dist/assets/{AdapterProvider-CtRy19L4.js → AdapterProvider-BJ47DW1h.js} +1 -1
- package/dist/assets/{AiPendingActionsPage-CJwQWg1W.js → AiPendingActionsPage-UIynjb20.js} +1 -1
- package/dist/assets/{ApiConsolePage-CGg1YX-S.js → ApiConsolePage-B7CzUZnr.js} +1 -1
- package/dist/assets/{AppDocsIndex-BhbMTMti.js → AppDocsIndex-DUsMqAwN.js} +1 -1
- package/dist/assets/{AppManagementPage-H6lFpmYT.js → AppManagementPage-DJ6118-F.js} +1 -1
- package/dist/assets/ApprovalsInboxPage-CTVm3l-x.js +1 -0
- package/dist/assets/AuditLogPage-Riqi0U7P.js +1 -0
- package/dist/assets/{ComponentNavView-4vcZh2oX.js → ComponentNavView-B2otfGZ7.js} +1 -1
- package/dist/assets/CreateViewDialog-z6h6V9xj.js +1 -0
- package/dist/assets/{DashboardView-OZHG8o0x.js → DashboardView-6_sxqUcT.js} +1 -1
- package/dist/assets/{DeveloperHubPage-yTPx0th5.js → DeveloperHubPage-NbNGfp6j.js} +1 -1
- package/dist/assets/{DocShell-BhkelvR8.js → DocShell-DvmmtwpW.js} +1 -1
- package/dist/assets/{ExpressionProvider-BQFSoabd.js → ExpressionProvider-_qLpGaJS.js} +1 -1
- package/dist/assets/FlowRunsPage-ZTpe0n1O.js +1 -0
- package/dist/assets/{IntegrationsPage-BWBfrCWI.js → IntegrationsPage-DMuzWjMr.js} +2 -2
- package/dist/assets/{InterfaceListPage-bZdYVg1W.js → InterfaceListPage-BHcPP_6g.js} +1 -1
- package/dist/assets/{ManagedByBadge-pdWk_Jcc.js → ManagedByBadge-DNLmY8V4.js} +1 -1
- package/dist/assets/{MarketplaceAccessDenied-DDTfnIA8.js → MarketplaceAccessDenied-Drlrrrd9.js} +1 -1
- package/dist/assets/{MarketplaceInstalledPage-Byn6Undk.js → MarketplaceInstalledPage-CYP2CaJz.js} +1 -1
- package/dist/assets/MarketplacePackagePage-DZwFKOQv.js +4 -0
- package/dist/assets/MarketplacePage-XU0PQLAW.js +1 -0
- package/dist/assets/{MetadataInspector-B7LigfJm.js → MetadataInspector-CoxLxxKN.js} +1 -1
- package/dist/assets/{MetadataProvider-87BSQkFa.js → MetadataProvider-DJXxy8nz.js} +1 -1
- package/dist/assets/ObjectDataPage-CHRZduUP.js +1 -0
- package/dist/assets/PageView-D27Yy4W9.js +1 -0
- package/dist/assets/ProfilePage-09XXYshY.js +1 -0
- package/dist/assets/{PublicFormsPage-Cu_VttTH.js → PublicFormsPage-O8fm4eBn.js} +1 -1
- package/dist/assets/RecordDetailView-aOOCQH95.js +9 -0
- package/dist/assets/RecordFormPage-oqNb9asS.js +1 -0
- package/dist/assets/ReportDefaultInspector-Bo94YiWL.js +3 -0
- package/dist/assets/ReportView-CwCw4i27.js +2 -0
- package/dist/assets/{SearchResultsPage-Dzm_0iUD.js → SearchResultsPage-I8ngrVdn.js} +1 -1
- package/dist/assets/SettingsHub-BY_utblN.js +1 -0
- package/dist/assets/SettingsView-DNKEl-i-.js +1 -0
- package/dist/assets/{SystemHubPage-B3uHe11N.js → SystemHubPage-WWns1vXN.js} +1 -1
- package/dist/assets/{createDerive-DmbuzviK.js → createDerive-CsNhKPNT.js} +1 -1
- package/dist/assets/data-adapter-Bh8GerYu.js +32 -0
- package/dist/assets/{drillUrlFilters-BL8PeMrH.js → drillUrlFilters-DHAQHZbx.js} +1 -1
- package/dist/assets/framework-s0wcPYfi.js +8 -0
- package/dist/assets/{getIcon-D3yCrAri.js → getIcon-CQlbi2Hn.js} +1 -1
- package/dist/assets/{highlighted-body-OFNGDK62-DrPiUj_V.js → highlighted-body-OFNGDK62-0kvj_GdK.js} +1 -1
- package/dist/assets/{i18n-DBmEJ9U1.js → i18n-BFepWCa9.js} +1 -1
- package/dist/assets/index-CB0grcA9.js +2 -0
- package/dist/assets/index-DwcytixP.css +2 -0
- package/dist/assets/{infrastructure-PXm1h5tB.js → infrastructure-BKCMsWnH.js} +2 -2
- package/dist/assets/maplibre-gl-shared.mjs +6 -0
- package/dist/assets/maplibre-gl-worker.mjs +6 -0
- package/dist/assets/mermaid-GHXKKRXX-CI_uxHoC.js +1 -0
- package/dist/assets/metadata-admin-CApOhXis.js +25 -0
- package/dist/assets/plugin-calendar-BOjBc2zc.js +1 -0
- package/dist/assets/plugin-charts-Bk48oCaW.js +7 -0
- package/dist/assets/{plugin-chatbot-DmEp7ZGx.js → plugin-chatbot-CEj8h-9I.js} +7 -7
- package/dist/assets/plugin-dashboard-B0k1x0iX.js +6 -0
- package/dist/assets/plugin-form-B_6Tki5r.js +1 -0
- package/dist/assets/plugin-gantt-va3r2kNG.js +63 -0
- package/dist/assets/plugin-grid-C0rE_dCh.js +8 -0
- package/dist/assets/plugin-kanban-BhzMbWNL.js +1 -0
- package/dist/assets/{plugin-map-D0SLy13S.js → plugin-map-zu5SGrw4.js} +1 -1
- package/dist/assets/{plugin-markdown-D7iZb8hK.js → plugin-markdown-BqKwZink.js} +1 -1
- package/dist/assets/plugin-report-DOylY2iS.js +59 -0
- package/dist/assets/{plugin-timeline-C_svagQ1.js → plugin-timeline-sB_LQnGB.js} +1 -1
- package/dist/assets/plugin-tree-CHZ2Wjl4.js +1 -0
- package/dist/assets/plugin-view-DoxfBkwY.js +1 -0
- package/dist/assets/plugins-views-DoZ6BQOM.js +4 -0
- package/dist/assets/{runtime-metadata-persistence-BsgvioOn.js → runtime-metadata-persistence-TwDeIZza.js} +1 -1
- package/dist/assets/{skeletons-C8REUFE6.js → skeletons-BZIrujxl.js} +1 -1
- package/dist/assets/src--uGAhLxY.js +19 -0
- package/dist/assets/{src-E-Ibo9NH.js → src-Boqr2A0h.js} +1 -1
- package/dist/assets/src-t-RiW1Dw.js +1 -0
- package/dist/assets/ui-components-BFOT5Gog.js +72 -0
- package/dist/assets/ui-layout-D4KJD2jH.js +1 -0
- package/dist/assets/{use-book-data-CAZ23DZb.js → use-book-data-BIflvfeG.js} +1 -1
- package/dist/assets/useOpenRecordList-CptPt5Mv.js +1 -0
- package/dist/assets/useSettingsLabel-CeykvoQ_.js +1 -0
- package/dist/assets/vendor-objectstack-Dm5CaPeY.js +184 -0
- package/dist/index.html +4 -4
- package/package.json +1 -1
- package/dist/assets/ApprovalsInboxPage-CbWL6D_v.js +0 -1
- package/dist/assets/AuditLogPage-CxGLPqlB.js +0 -1
- package/dist/assets/CreateViewDialog-Dt1MUhLX.js +0 -1
- package/dist/assets/FlowRunsPage-DTUvw7r2.js +0 -1
- package/dist/assets/MarketplacePackagePage-MX3QKebj.js +0 -4
- package/dist/assets/MarketplacePage-Dt4ldkBx.js +0 -1
- package/dist/assets/ObjectDataPage-JASSibf6.js +0 -1
- package/dist/assets/PageView-DwZUXknG.js +0 -1
- package/dist/assets/ProfilePage-Do9aTArT.js +0 -1
- package/dist/assets/RecordDetailView-CP1b5rdr.js +0 -9
- package/dist/assets/RecordFormPage-qcCOHj3T.js +0 -1
- package/dist/assets/ReportDefaultInspector-Byof8OYm.js +0 -3
- package/dist/assets/ReportView-D91loQjH.js +0 -2
- package/dist/assets/SettingsHub-C-7kyHtx.js +0 -1
- package/dist/assets/SettingsView-HmY6cAH1.js +0 -1
- package/dist/assets/data-adapter-sj_1S7TJ.js +0 -32
- package/dist/assets/framework-UESyszCj.js +0 -8
- package/dist/assets/index-AHnJRZYu.css +0 -2
- package/dist/assets/index-rkbFgKQu.js +0 -2
- package/dist/assets/mermaid-GHXKKRXX-DicGABpj.js +0 -1
- package/dist/assets/metadata-admin-DA08xWlg.js +0 -25
- package/dist/assets/plugin-calendar-WGoi_n7i.js +0 -1
- package/dist/assets/plugin-charts-CK8c0x6J.js +0 -7
- package/dist/assets/plugin-dashboard-Cz2sTF7I.js +0 -6
- package/dist/assets/plugin-form-D_JAwPGr.js +0 -1
- package/dist/assets/plugin-gantt-BQGs0Vpj.js +0 -63
- package/dist/assets/plugin-grid-CKEYn10A.js +0 -8
- package/dist/assets/plugin-kanban-TdXxukPA.js +0 -1
- package/dist/assets/plugin-report-CPE7yyd4.js +0 -59
- package/dist/assets/plugin-tree-ieUxQVUL.js +0 -1
- package/dist/assets/plugin-view-Dy9ZzWYn.js +0 -1
- package/dist/assets/plugins-views-CJKuyDvq.js +0 -4
- package/dist/assets/src-Chkzn0bG.js +0 -1
- package/dist/assets/src-D0ueU0ix.js +0 -19
- package/dist/assets/ui-components-BbC0qTrK.js +0 -72
- package/dist/assets/ui-layout-C3eKqnNJ.js +0 -1
- package/dist/assets/useOpenRecordList-aRVznRXU.js +0 -1
- package/dist/assets/useSettingsLabel-By0A6m6P.js +0 -1
- package/dist/assets/vendor-objectstack-CWf5hLam.js +0 -180
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{r as t,y as n}from"./vendor-react-DpRf6e0g.js";import{G as r,H as i,K as a,U as o,W as s}from"./vendor-objectstack-CWf5hLam.js";import{$t as c,Qt as l,en as u,nn as d,tn as f}from"./framework-UESyszCj.js";var p=e(n(),1),m=new Set,h={emit(e){for(let t of Array.from(m))try{t(e)}catch{}},subscribe(e){return m.add(e),()=>{m.delete(e)}}};function g(e,t){if(e!==403||!t||typeof t!=`object`)return null;let n=t.error;if(!n||typeof n!=`object`)return null;let r=n.code;if(r===`MFA_REQUIRED`||r===`PASSWORD_EXPIRED`){let e=n.message;return{code:r,message:typeof e==`string`?e:``}}return null}var _=(0,p.createContext)(null);_.displayName=`AuthContext`;var v=`1.6.25`,y=Symbol.for(`better-auth:broadcast-channel`),b=()=>Math.floor(Date.now()/1e3),ee=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:b()}))}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 x(e=`better-auth.message`){return globalThis[y]||(globalThis[y]=new ee(e)),globalThis[y]}var S=[],C=0,w=null,T=4,E=globalThis.nanostoresGlobal||={epoch:0},D=()=>{for(C=0;C<S.length;C+=T)S[C](S[C+1].value,S[C+2],S[C+3]);S.length=0},O=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=C+T;t<S.length;)S[t]===e?S.splice(t,T):t+=T;let r=t.indexOf(e);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(e,r){E.epoch++;let i=!S.length&&!0;for(let i of t)w?.has(i)||(w?.add(i),S.push(i,n,e,r));i&&D()},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},k=2,A=5,j=6,M=10,N=(e,t,n,r)=>(e.events=e.events||{},e.events[n+M]||(e.events[n+M]=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+M](),delete e.events[n+M])}),P=(e,t)=>N(e,t,k,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),te=1e3,ne=(e,t)=>N(e,n=>{let r=t(n);r&&e.events[j].push(r)},A,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[j]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[j])t();e.events[j]=[]}},te)},()=>{e.listen=n,e.off=r}});function F(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function I(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!I(e[n],t[n]))return!1;return!0}if(F(e)&&F(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!(r in t)||!I(e[r],t[r]))return!1;return!0}return!1}function re(e,t){return P(e,({newValue:n,abort:r})=>{t(e.value,n)&&r()})}var L=Symbol.for(`better-auth:focus-manager`),ie=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 ae(){return globalThis[L]||(globalThis[L]=new ie),globalThis[L]}var R=Symbol.for(`better-auth:online-manager`),oe=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 z(){return globalThis[R]||(globalThis[R]=new oe),globalThis[R]}var se={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*:/},B=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,V={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},ce=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function le(e){return e instanceof Date&&!isNaN(e.getTime())}function ue(e){let t=ce.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 le(f)?f:null}function H(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(),s=o.toLowerCase();if(s.length<=9&&s in V)return V[s];if(!B.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(se).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=ue(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function de(e,t={strict:!0}){return H(e,t)}var fe=()=>typeof window>`u`;function pe(e,t){return I(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}var me=(e,t,n,r)=>{let i=O({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>a(e)});re(i,pe);let 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){let t=i.get(),n=t.data!=null&&e.data!=null&&I(t.data,e.data)?t.data:e.data;i.set({data:n,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,s=!1,c=!1,l=()=>{if(o){c=!0;return}o=!0,a().finally(()=>{o=!1;let e=c&&s;c=!1,e&&l()})};return ne(i,()=>{if(fe())return;s=!0;let t=!1,n,r=e.map(e=>e.listen(()=>{t?a():(t=!0,clearTimeout(n),l())}));return n=setTimeout(()=>{t=!0,l()},0),()=>{s=!1;for(let e of r)e();clearTimeout(n)}}),i},he=()=>Math.floor(Date.now()/1e3),ge=5;function _e(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||z().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=he(),t();return}if(e?.event===`visibilitychange`){if(he()-c.lastSessionRequest<ge)return;c.lastSessionRequest=he(),t();return}t()}},d=e=>{x().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=x().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=ae().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=z().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=x().setup(),c.cleanupFocusSetup=ae().setup(),c.cleanupOnlineSetup=z().setup())},cleanup:()=>{c.isInitialized&&(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.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var ve=Object.create(null),U=e=>({}),W=new Proxy(ve,{get(e,t){return U()[t]??ve[t]},has(e,t){return t in U()||t in ve},set(e,t,n){let r=U(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=U(!0);return delete n[t],!0},ownKeys(){let e=U(!0);return Object.keys(e)}});W.NODE_ENV;function G(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 G(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return G(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return G(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return G(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return G(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return G(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return G(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});function ye(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}function be(){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 xe(e){let t=e.split(`
|
|
1
|
+
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{r as t,y as n}from"./vendor-react-DpRf6e0g.js";import{G as r,J as i,K as a,W as o,q as s}from"./vendor-objectstack-Dm5CaPeY.js";import{an as c,cn as l,ln as u,on as d,sn as f}from"./framework-s0wcPYfi.js";var p=e(n(),1),m=new Set,h={emit(e){for(let t of Array.from(m))try{t(e)}catch{}},subscribe(e){return m.add(e),()=>{m.delete(e)}}};function g(e,t){if(e!==403||!t||typeof t!=`object`)return null;let n=t.error;if(!n||typeof n!=`object`)return null;let r=n.code;if(r===`MFA_REQUIRED`||r===`PASSWORD_EXPIRED`){let e=n.message;return{code:r,message:typeof e==`string`?e:``}}return null}var _=(0,p.createContext)(null);_.displayName=`AuthContext`;var v=`1.6.25`,y=Symbol.for(`better-auth:broadcast-channel`),b=()=>Math.floor(Date.now()/1e3),ee=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:b()}))}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 x(e=`better-auth.message`){return globalThis[y]||(globalThis[y]=new ee(e)),globalThis[y]}var S=[],C=0,w=null,T=4,E=globalThis.nanostoresGlobal||={epoch:0},D=()=>{for(C=0;C<S.length;C+=T)S[C](S[C+1].value,S[C+2],S[C+3]);S.length=0},O=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=C+T;t<S.length;)S[t]===e?S.splice(t,T):t+=T;let r=t.indexOf(e);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(e,r){E.epoch++;let i=!S.length&&!0;for(let i of t)w?.has(i)||(w?.add(i),S.push(i,n,e,r));i&&D()},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},k=2,A=5,j=6,M=10,N=(e,t,n,r)=>(e.events=e.events||{},e.events[n+M]||(e.events[n+M]=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+M](),delete e.events[n+M])}),P=(e,t)=>N(e,t,k,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),te=1e3,ne=(e,t)=>N(e,n=>{let r=t(n);r&&e.events[j].push(r)},A,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[j]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[j])t();e.events[j]=[]}},te)},()=>{e.listen=n,e.off=r}});function F(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function I(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!I(e[n],t[n]))return!1;return!0}if(F(e)&&F(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!(r in t)||!I(e[r],t[r]))return!1;return!0}return!1}function re(e,t){return P(e,({newValue:n,abort:r})=>{t(e.value,n)&&r()})}var L=Symbol.for(`better-auth:focus-manager`),ie=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 ae(){return globalThis[L]||(globalThis[L]=new ie),globalThis[L]}var R=Symbol.for(`better-auth:online-manager`),oe=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 z(){return globalThis[R]||(globalThis[R]=new oe),globalThis[R]}var se={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*:/},B=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,V={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},ce=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function le(e){return e instanceof Date&&!isNaN(e.getTime())}function ue(e){let t=ce.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 le(f)?f:null}function H(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(),s=o.toLowerCase();if(s.length<=9&&s in V)return V[s];if(!B.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(se).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=ue(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function de(e,t={strict:!0}){return H(e,t)}var fe=()=>typeof window>`u`;function pe(e,t){return I(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}var me=(e,t,n,r)=>{let i=O({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>a(e)});re(i,pe);let 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){let t=i.get(),n=t.data!=null&&e.data!=null&&I(t.data,e.data)?t.data:e.data;i.set({data:n,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,s=!1,c=!1,l=()=>{if(o){c=!0;return}o=!0,a().finally(()=>{o=!1;let e=c&&s;c=!1,e&&l()})};return ne(i,()=>{if(fe())return;s=!0;let t=!1,n,r=e.map(e=>e.listen(()=>{t?a():(t=!0,clearTimeout(n),l())}));return n=setTimeout(()=>{t=!0,l()},0),()=>{s=!1;for(let e of r)e();clearTimeout(n)}}),i},he=()=>Math.floor(Date.now()/1e3),ge=5;function _e(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||z().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=he(),t();return}if(e?.event===`visibilitychange`){if(he()-c.lastSessionRequest<ge)return;c.lastSessionRequest=he(),t();return}t()}},d=e=>{x().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=x().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=ae().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=z().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=x().setup(),c.cleanupFocusSetup=ae().setup(),c.cleanupOnlineSetup=z().setup())},cleanup:()=>{c.isInitialized&&(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.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var ve=Object.create(null),U=e=>({}),W=new Proxy(ve,{get(e,t){return U()[t]??ve[t]},has(e,t){return t in U()||t in ve},set(e,t,n){let r=U(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=U(!0);return delete n[t],!0},ownKeys(){let e=U(!0);return Object.keys(e)}});W.NODE_ENV;function G(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 G(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return G(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return G(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return G(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return G(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return G(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return G(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});function ye(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}function be(){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 xe(e){let t=e.split(`
|
|
2
2
|
at `);return t.length<=1?e:(t.splice(1,1),t.join(`
|
|
3
|
-
at `))}function Se(e,t){class n extends e{#e;constructor(...e){if(be()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=xe(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 Ce={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};Se(class extends Error{constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:Ce[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 we=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},Te=47;function Ee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===Te;)t--;return t===e.length?e:e.slice(0,t)}function De(e){try{return(Ee(new URL(e).pathname)||`/`)!==`/`}catch{throw new we(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function Oe(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new we(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof we?t:new we(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function ke(e,t=`/api/auth`){if(Oe(e),De(e))return e;let n=Ee(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function Ae(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 je(e,t,n,r,i){if(e)return ke(e,t);if(r!==!1){let e=W.BETTER_AUTH_URL||W.NEXT_PUBLIC_BETTER_AUTH_URL||W.PUBLIC_BETTER_AUTH_URL||W.NUXT_PUBLIC_BETTER_AUTH_URL||W.NUXT_PUBLIC_AUTH_URL||(W.BASE_URL===`/`?void 0:W.BASE_URL);if(e)return ke(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&Ae(o,`proto`)&&Ae(a,`host`))try{return ke(`${o}://${a}`,t)}catch{}if(n){let e=Me(n.url);if(!e)throw new we(`Could not get origin from request. Please provide a valid base URL.`);return ke(e,t)}if(typeof window<`u`&&window.location)return ke(window.location.origin,t)}function Me(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var Ne=[`javascript:`,`data:`,`vbscript:`];function Pe(e){let t;try{t=new URL(e)}catch{return!0}return!Ne.includes(t.protocol)}var Fe={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&Pe(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},Ie=()=>typeof window>`u`;function Le(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Re(e){return!e||e.session===null&&e.user===null?null:e}function ze(e,t){return I(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function Be(e,t){let n=O(!1),r,i=e=>s(e),a=O({data:null,error:null,isPending:!0,isRefetching:!1,refetch:i});re(a,ze);let o=e=>{if(r!==e)return;let t=a.get();r=void 0,!(!t.isPending&&!t.isRefetching)&&a.set({...t,isPending:!1,isRefetching:!1,refetch:i})},s=async t=>{r?.abort();let n=new AbortController;r=n;let s=a.get();a.set({...s,isPending:s.data===null,isRefetching:!0,error:null,refetch:i});try{let r=await e(`/get-session`,{method:`GET`,query:t?.query,signal:n.signal});if(n.signal.aborted){o(n);return}let{data:s,error:c}=Le(r);if(s?.needsRefresh)try{let t=await e(`/get-session`,{method:`POST`,signal:n.signal});if(n.signal.aborted){o(n);return}({data:s,error:c}=Le(t))}catch{if(n.signal.aborted){o(n);return}}if(c){let e=a.get(),t=c?.status===401;a.set({data:t?null:e.data,error:c,isPending:!1,isRefetching:!1,refetch:i});return}let l=Re(s),u=a.get(),d=u.data!=null&&l!=null&&I(u.data,l)?u.data:l;a.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:i})}catch(e){if(n.signal.aborted){o(n);return}let t=a.get();a.set({data:t.data,error:e,isPending:!1,isRefetching:!1,refetch:i})}},c=()=>{};return ne(a,()=>{let e;Ie()||(e=setTimeout(()=>{s()},0));let i=_e({fetchSession:s,shouldPollSession:()=>a.get().data!=null,sessionSignal:n,options:t});return i.init(),c=i.broadcastSessionUpdate,()=>{e&&clearTimeout(e);let t=r;t?.abort(),t&&o(t),i.cleanup()}}),{session:a,$sessionSignal:n,broadcastSessionUpdate:e=>c(e)}}function Ve(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 He(e,t,n=`.`,r){if(!Ve(t))return He(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)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:Ve(a)&&Ve(i[t])?He(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function Ue(e){return(...t)=>t.reduce((t,n)=>He(t,n,``,e),{})}var We=Ue(),Ge=Object.defineProperty,Ke=Object.defineProperties,qe=Object.getOwnPropertyDescriptors,Je=Object.getOwnPropertySymbols,Ye=Object.prototype.hasOwnProperty,Xe=Object.prototype.propertyIsEnumerable,Ze=(e,t,n)=>t in e?Ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K=(e,t)=>{for(var n in t||={})Ye.call(t,n)&&Ze(e,n,t[n]);if(Je)for(var n of Je(t))Xe.call(t,n)&&Ze(e,n,t[n]);return e},q=(e,t)=>Ke(e,qe(t)),Qe=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)}},$e=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}},et=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}},tt=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 nt(e){if(typeof e==`number`)return new et({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new et(e);case`exponential`:return new tt(e);default:throw Error(`Invalid retry strategy`)}}var rt=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},it=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function at(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 it.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function ot(e){try{return JSON.parse(e),!0}catch{return!1}}function st(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 ct(e){try{return JSON.parse(e)}catch{return e}}function lt(e){return typeof e==`function`}function ut(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&<(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&<(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function dt(...e){let t={};for(let n of e)if(n)if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}return t}async function ft(e){let t=new Headers(dt(e?.headers,await rt(e)));if(!t.has(`content-type`)){let n=pt(e?.body);n&&t.set(`content-type`,n)}return t}function pt(e){return st(e)?`application/json`:null}function mt(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function ht(e,t){let{body:n}=e;return n?!st(n)||typeof n==`string`?n:mt(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function gt(e,t){if(t?.method)return t.method.toUpperCase();if(e.startsWith(`@`)){let n=e.split(`@`)[1]?.split(`/`)[0];return bt.includes(n)?n.toUpperCase():t?.body?`POST`:`GET`}return t?.body?`POST`:`GET`}function _t(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var vt=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function yt(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new vt(n.issues);return n.value}var bt=[`get`,`post`,`put`,`patch`,`delete`],xt=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,``)),e.startsWith(`/`)&&e.charAt(1)===`@`&&(e=e.substring(1));let i=r.schema[e];if(i){let e=n?.headers;if(i.headers&&!n?.disableValidation){let t={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((e,n)=>{t[n.toLowerCase()]=e});else if(typeof n.headers==`object`)for(let[e,r]of Object.entries(n.headers))r!=null&&(t[e.toLowerCase()]=r)}let r=await yt(i.headers,t),a={};for(let[e,t]of Object.entries(r))a[e.toLowerCase()]=t;e=a}let r=q(K({},n),{method:i.method,output:i.output,headers:e});return n?.disableValidation||(r=q(K({},r),{body:i.input?await yt(i.input,n?.body):n?.body,params:i.params?await yt(i.params,n?.params):n?.params,query:i.query?await yt(i.query,n?.query):n?.query})),{url:t,options:r}}}return{url:t,options:n}}}),St=e=>{async function t(t,n){let r=q(K(K({},e),n),{headers:dt(e?.headers,n?.headers),plugins:[...e?.plugins||[],xt(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Et(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 Et(t,r)}return t},Ct=e=>e===`.`||e===`..`;function wt(e,t){let n=e;for(let[e,r]of t)n=n.replace(e,r);if(Ct(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function Tt(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];bt.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)}let l=new Map;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];l.set(n,String(e))}}else for(let[e,t]of Object.entries(r))l.set(`:${e}`,String(t));o=o.split(`/`).map(e=>wt(e,l)).join(`/`),o=o.replace(/^\/+/,``);let u=c.toString();return u=u.length>0?`?${u}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${o}${u}`,a):`${a}${o}${u}`}var Et=async(e,t)=>{let{hooks:n,url:r,options:i}=await $e(e,t),a=ut(i),o=new AbortController,s=i.signal??o.signal,c=Tt(r,i),l=await ft(i),u=ht(i,l),d=gt(r,i),f=q(K({},i),{url:c,headers:l,body:u,method:d,signal:s});for(let e of n.onRequest)if(e){let t=await e(f);typeof t==`object`&&t&&Object.assign(f,t)}(`pipeTo`in f&&typeof f.pipeTo==`function`||typeof t?.body?.pipe==`function`)&&(`duplex`in f||(f.duplex=`half`));let{clearTimeout:p}=_t(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(q(K({},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=at(m),r={data:null,response:m,request:f};if(e===`json`||e===`text`){let e=await m.text();r.data=await(f.jsonParser??ct)(e)}else r.data=await m[e]();f?.output&&f.output&&!f.disableValidation&&(r.data=await yt(f.output,r.data));for(let e of n.onSuccess)e&&await e(q(K({},r),{response:t?.hookOptions?.cloneResponse?m.clone():m}));return t?.throw?r.data:{data:r.data,error:null}}let g=t?.jsonParser??ct,_=await m.text(),v=ot(_),y=v?await g(_):null,b={response:m,responseText:_,request:f,error:q(K({},y),{status:m.status,statusText:m.statusText})};for(let e of n.onError)e&&await e(q(K({},b),{response:t?.hookOptions?.cloneResponse?m.clone():m}));if(t?.retry){let r=nt(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 Et(e,q(K({},t),{retryAttempt:i+1}))}}if(t?.throw)throw new Qe(m.status,m.statusText,v?y:_);return{data:null,error:q(K({},y),{status:m.status,statusText:m.statusText})}},Dt=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{}}},Ot=(e,t)=>{let n=`credentials`in Request.prototype,r=je(e?.baseURL,e?.basePath,void 0,t)??Dt(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=St({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?de(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Fe],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=Be(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=We(t.getActions?.(d,b,e)??{},g));return{get baseURL(){return r},pluginsActions:g,pluginsAtoms:_,pluginPathMethods:v,atomListeners:y,$fetch:d,$store:b}};function kt(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function At(e){return e.charAt(0).toUpperCase()+e.slice(1)}var jt=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,Mt=/['\u2019]/g;function Nt(e){return e.replace(Mt,``).match(jt)??[]}function Pt(e){return Nt(e).map(e=>e.toLowerCase()).join(`-`)}function Ft(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 It(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`||kt(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(Pt).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=Ft(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 Lt(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,$fetch:i,atomListeners:a,$store:o}=Ot(e),s={};for(let[e,t]of Object.entries(r))s[`use${At(e)}`]=t;return It({...n,...s,$fetch:i,$store:o},i,t,r,a)}function Rt(e){return{success:!1,error:`You are not allowed to access resource: ${e}`}}function zt(e){return{success:!1,error:`unauthorized to access resource "${e}"`}}function Bt(e){return e===`OR`?`OR`:`AND`}function Vt(e){return Array.isArray(e)}function Ht(e){if(Vt(e))return{actions:e,connector:`AND`};if(!e||typeof e!=`object`)throw new we(`Invalid access control request`);let{actions:t,connector:n}=e;return Vt(t)?{actions:t,connector:Bt(n)}:{actions:[],connector:Bt(n)}}function Ut(e,t){return typeof t==`string`&&e.includes(t)}function Wt(e,{actions:t,connector:n}){return t.length===0?!1:n===`OR`?t.some(t=>Ut(e,t)):t.every(t=>Ut(e,t))}function Gt(e){return{authorize(t,n=`AND`){let r=!1;for(let[i,a]of Object.entries(t)){let t=e[i];if(!t){if(n===`AND`)return Rt(i);continue}let o=Wt(t,Ht(a));if(o&&(r=!0),o&&n===`OR`)return{success:!0};if(!o&&n===`AND`)return zt(i)}return r?{success:!0}:{success:!1,error:`Not authorized`}},statements:e}}function Kt(e){return{newRole(e){return Gt(e)},statements:e}}var qt=ye({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`,EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION:`Email verification required to view or list invitations for the session email`,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`,INVALID_TEAM_ID:`Team id contains a reserved character`}),Jt=Kt({organization:[`update`,`delete`],member:[`create`,`update`,`delete`],invitation:[`create`,`cancel`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),Yt=Jt.newRole({organization:[`update`],invitation:[`create`,`cancel`],member:[`create`,`update`,`delete`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),Xt=Jt.newRole({organization:[`update`,`delete`],member:[`create`,`update`,`delete`],invitation:[`create`,`cancel`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),Zt=Jt.newRole({organization:[],member:[],invitation:[],team:[],ac:[`read`]}),Qt={admin:Yt,owner:Xt,member:Zt},$t=(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},en=e=>$t(e,e.options.roles||Qt),tn=e=>{let t=O(!1),n=O(!1),r=O(!1),i=O(!1),a={admin:Yt,member:Zt,owner:Xt,...e?.roles};return{id:`organization`,version:v,$InferServerPlugin:{},getActions:(t,n,r)=>({$Infer:{ActiveOrganization:{},Organization:{},Invitation:{},Member:{},Team:{}},organization:{checkRolePermission:t=>en({role:t.role,options:{ac:e?.ac,roles:a},permissions:t.permissions})}}),getAtoms:e=>{let a=me(t,`/organization/list`,e,{method:`GET`}),o=me([n],`/organization/get-full-organization`,e,()=>({method:`GET`})),s=me([n,r],`/organization/get-active-member`,e,{method:`GET`}),c=me([n,i],`/organization/get-active-member-role`,e,{method:`GET`});return{$listOrg:t,$activeOrgSignal:n,$activeMemberSignal:r,$activeMemberRoleSignal:i,activeOrganization:o,listOrganizations:a,activeMember:s,activeMemberRole:c}},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===`/sign-out`||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:qt}},nn=ye({OTP_NOT_ENABLED:`OTP not enabled`,OTP_HAS_EXPIRED:`OTP has expired`,TOTP_NOT_ENABLED:`TOTP not enabled`,TWO_FACTOR_NOT_ENABLED:`Two factor isn't enabled`,BACKUP_CODES_NOT_ENABLED:`Backup codes aren't enabled`,INVALID_BACKUP_CODE:`Invalid backup code`,INVALID_CODE:`Invalid code`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many attempts. Please request a new code.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many failed verification attempts. Your account is temporarily locked. Please try again later.`,INVALID_TWO_FACTOR_COOKIE:`Invalid two factor cookie`}),rn=e=>({id:`two-factor`,version:v,$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith(`/two-factor/`),signal:`$sessionSignal`}],pathMethods:{"/two-factor/disable":`POST`,"/two-factor/enable":`POST`,"/two-factor/send-otp":`POST`,"/two-factor/generate-backup-codes":`POST`,"/two-factor/get-totp-uri":`POST`,"/two-factor/verify-totp":`POST`,"/two-factor/verify-otp":`POST`,"/two-factor/verify-backup-code":`POST`},fetchPlugins:[{id:`two-factor`,name:`two-factor`,hooks:{async onSuccess(t){if(t.data?.twoFactorRedirect){if(e?.onTwoFactorRedirect){await e.onTwoFactorRedirect({twoFactorMethods:t.data.twoFactorMethods});return}e?.twoFactorPage&&typeof window<`u`&&Pe(e.twoFactorPage)&&(window.location.href=e.twoFactorPage)}}}}],$ERROR_CODES:nn}),an=`auth-session-token`,J={_memoryToken:null,get(){try{if(typeof localStorage<`u`)return localStorage.getItem(an)}catch{}return this._memoryToken},set(e){this._memoryToken=e;try{typeof localStorage<`u`&&localStorage.setItem(an,e)}catch{}},clear(){this._memoryToken=null;try{typeof localStorage<`u`&&localStorage.removeItem(an)}catch{}}};function on(e){let t=Error(e.message??`Auth request failed with status ${e.status}`);return e.code&&(t.code=e.code),t}function sn(e){try{let t=new URL(e);return{origin:t.origin,basePath:t.pathname.replace(/\/$/,``)}}catch{return{origin:cn()??`http://localhost`,basePath:e.replace(/\/$/,``)}}}function cn(){try{if(typeof window<`u`&&window.location?.origin)return window.location.origin}catch{}}function ln(){try{if(typeof document<`u`){let e=document.querySelector(`base`)?.getAttribute(`href`);if(e)return`${new URL(e,cn()??`http://localhost`).pathname.replace(/\/$/,``)}/reset-password`}}catch{}return`/reset-password`}function un(e){let t=e||globalThis.fetch.bind(globalThis);return async(e,n)=>{let r=new Headers(n?.headers),i=J.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&&J.set(o),a}}function dn(e){let{baseURL:t,fetchFn:n}=e,{origin:r,basePath:i}=sn(t),a=un(n),o=Lt({baseURL:r,basePath:i,disableDefaultFetchPlugins:!0,fetchOptions:{customFetchImpl:a},plugins:[tn(),rn()]});async function s(e,t){let n=await a(`${r}${i}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`},credentials:`include`,body:JSON.stringify(t)}),o=await n.json().catch(()=>({}));if(!n.ok){let e=Error(o?.message??`Auth request failed with status ${n.status}`);throw o?.code&&(e.code=o.code),e.status=n.status,e}return o??{}}async function c(e){let t=typeof AbortController<`u`?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),e):void 0;try{let e=`${r}${i}/config`,n=await a(e,{method:`GET`,headers:{"Content-Type":`application/json`},...t?{signal:t.signal}:{}});if(!n.ok)throw Error(`Failed to load auth config (status ${n.status})`);let o=await n.json();return o&&typeof o==`object`&&`data`in o&&o.data?o.data:o}finally{n!==void 0&&clearTimeout(n)}}let l=[500,1500,3500],u=null;async function d(){let e;for(let t=0;t<=l.length;t++)try{return await c(8e3)}catch(n){e=n,t<l.length&&await new Promise(e=>setTimeout(e,l[t]))}throw e instanceof Error?e:Error(String(e))}return{async signIn(e){let{data:t,error:n}=await o.signIn.email({email:e.email,password:e.password});if(n)throw on(n);let r=t;return r.session?.token&&J.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 on(n);let r=t,i=r.token??r.session?.token??null;i&&J.set(i);let a=r.session??null;return!a&&i&&(a={token:i}),{user:r.user,session:a,requiresVerification:i===null}},async sendVerificationEmail(e,t){let{error:n}=await o.sendVerificationEmail({email:e,callbackURL:t});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`)},async signOut(){let{error:e}=await o.signOut();if(J.clear(),e)throw Error(e.message??`Auth request failed with status ${e.status}`)},async getSession(){let e=null;try{let t=await o.getSession();t.error||(e=t.data)}catch{}if(e){let t=e;return t.session?.token&&J.set(t.session.token),{user:t.user,session:t.session}}if(J.get())try{let e=await(n||globalThis.fetch.bind(globalThis))(`${r}${i}/get-session`,{method:`GET`,credentials:`include`,headers:{"Content-Type":`application/json`}});if(e.ok){let t=await e.json().catch(()=>null);if(t?.user&&t?.session)return t.session.token?J.set(t.session.token):J.clear(),{user:t.user,session:t.session};J.clear()}}catch{}return null},async forgotPassword(e){let t=o,n=t.requestPasswordReset??t.forgetPassword;if(typeof n!=`function`)throw Error(`password reset is not available on this auth backend`);let{error:r}=await n({email:e,redirectTo:ln()});if(r)throw Error(r.message??`Auth request failed with status ${r.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 sendPhoneOtp(e){await s(`/phone-number/send-otp`,{phoneNumber:e})},async signInWithPhoneOtp(e,t){let n=await s(`/phone-number/verify`,{phoneNumber:e,code:t}),r=typeof n.token==`string`?n.token:void 0,i=n.user??null;if(!r||!i)throw Error(`No account is registered for this phone number.`);return J.set(r),{user:i,session:{token:r}}},async signInWithPhonePassword(e,t){let n=await s(`/sign-in/phone-number`,{phoneNumber:e,password:t}),r=typeof n.token==`string`?n.token:void 0,i=n.user??null;if(!r||!i)throw Error(`Invalid phone number or password.`);return J.set(r),{user:i,session:{token:r}}},async requestPhonePasswordReset(e){await s(`/phone-number/request-password-reset`,{phoneNumber:e})},async resetPasswordWithPhoneOtp(e,t,n){await s(`/phone-number/reset-password`,{phoneNumber:e,otp:t,newPassword:n})},async changePassword(e,t,n){let r=o.changePassword;if(typeof r!=`function`)throw Error(`change-password is not available on this auth backend`);let{error:i}=await r({currentPassword:e,newPassword:t,...n?.revokeOtherSessions==null?{}:{revokeOtherSessions:n.revokeOtherSessions}});if(i)throw Error(i.message??`Auth request failed with status ${i.status}`)},async enrollTotp(e){let t=o.twoFactor;if(!t||typeof t.enable!=`function`)throw Error(`two-factor enrollment is not available on this auth backend`);let{data:n,error:r}=await t.enable({password:e});if(r)throw Error(r.message??`Two-factor enable failed (${r.status??`?`})`);return{totpURI:n?.totpURI??``,backupCodes:n?.backupCodes??[]}},async verifyTotp(e){let t=o.twoFactor;if(!t||typeof t.verifyTotp!=`function`)throw Error(`two-factor verification is not available on this auth backend`);let{error:n}=await t.verifyTotp({code:e});if(n)throw Error(n.message??`Two-factor verification failed (${n.status??`?`})`)},async setInitialPassword(e){let t=`${r}${i}/set-initial-password`,n=await a(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({newPassword:e})});if(!n.ok){let e=`Set password failed with status ${n.status}`;try{let t=await n.json();t?.error?.message&&(e=t.error.message)}catch{}throw Error(e)}},async hasLocalPassword(){let e=`${r}${i}/list-accounts`;try{let t=await a(e,{method:`GET`,headers:{"Content-Type":`application/json`}});if(!t.ok)return!1;let n=await t.json();return(Array.isArray(n)?n:n&&`data`in n&&Array.isArray(n.data)?n.data:[]).some(e=>e?.providerId===`credential`)}catch{return!1}},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 describeDelegableScope(){try{let e=i.replace(/\/auth$/,`/security`),t=await a(`${r}${e}/my-delegable-scope`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(!t.ok)return null;let n=await t.json(),o=n&&typeof n==`object`&&`data`in n?n.data:n;return o&&typeof o==`object`&&Array.isArray(o.placeableBusinessUnitIds)?o:null}catch{return null}},async getConfig(){return u||=d().catch(e=>{throw u=null,e}),u},async signInWithProvider(e,t={}){let{type:n=`social`,callbackURL:r,errorCallbackURL:i}=t,a=e=>new Promise((t,n)=>{let r=setTimeout(()=>n(Error(`Sign-in timed out — the server did not respond. Please try again.`)),2e4);e.then(e=>{clearTimeout(r),t(e)},e=>{clearTimeout(r),n(e)})}),s=async()=>await a(o.signIn.social({provider:e,callbackURL:r,errorCallbackURL:i})),c;if(n===`oidc`){if(c=await s(),c.error){let t=o.signIn.oauth2,n=t?await a(t({providerId:e,callbackURL:r,errorCallbackURL:i})).catch(()=>null):null;n&&!n.error&&(c=n)}}else c=await s();let{data:l,error:u}=c;if(u)throw Error(u.message??`Auth request failed with status ${u.status}`);if(!l?.url)throw Error(`Sign-in with "${e}" did not return a redirect URL — please try again or contact your administrator.`);typeof window<`u`&&(window.location.href=l.url)},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 getActiveMember(){let e=o.organization?.getActiveMember;if(typeof e!=`function`)return null;let{data:t,error:n}=await e();return n||!t?null:t},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,...e.businessUnitId?{businessUnitId:e.businessUnitId}:{},...e.positions?.length?{positions:e.positions}:{}});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 fn=`auth-active-organization-id`,pn={_memoryValue:null,get(){try{if(typeof localStorage<`u`)return localStorage.getItem(fn)}catch{}return this._memoryValue},set(e){this._memoryValue=e;try{typeof localStorage<`u`&&localStorage.setItem(fn,e)}catch{}},clear(){this._memoryValue=null;try{typeof localStorage<`u`&&localStorage.removeItem(fn)}catch{}}};function mn(e){if(typeof window>`u`||!window.location)return!0;try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!0}}function hn(e){return async(t,n)=>{let r=new Headers(n?.headers),i=typeof t==`string`?t:t instanceof URL?t.href:t.url;if(e?.sameOriginOnly&&mn(i))return fetch(t,n);let a=/\/api\//i.test(i),o=J.get();o&&a&&r.set(`Authorization`,`Bearer ${o}`);let s=pn.get();if(s&&r.set(`X-Tenant-ID`,s),a&&!r.has(`Accept-Language`)&&typeof document<`u`){let e=document.documentElement.lang;e&&r.set(`Accept-Language`,e)}let c=await fetch(t,{...n,headers:r});if(a&&c.status===403)try{let e=g(c.status,await c.clone().json());e&&h.emit(e)}catch{}return c}}var Y=t();function gn({authUrl:e,client:t,onAuthStateChange:n,enabled:r=!0,previewMode:i,children:a}){let o=(0,p.useMemo)(()=>t??dn({baseURL:e}),[t,e]),[s,c]=(0,p.useState)(null),[l,u]=(0,p.useState)(null),[d,f]=(0,p.useState)(!0),[m,g]=(0,p.useState)(null),[v,y]=(0,p.useState)(null),[b,ee]=(0,p.useState)([]),[x,S]=(0,p.useState)(null),[C,w]=(0,p.useState)(null),[T,E]=(0,p.useState)(!1),D=i!=null,O=r&&!D?s!==null&&l!==null:!0;(0,p.useEffect)(()=>{if(D){let e=i.simulatedRole??`admin`,t=i.simulatedUserName??`Preview User`,n=i.expiresInSeconds??0;c({id:`preview-user`,email:`preview@preview.local`,name:t,role:e,roles:[e]}),u({token:`preview-token`,expiresAt:n>0?new Date(Date.now()+n*1e3):new Date(Date.now()+31536e6)}),f(!1);return}if(!r){c({id:`guest`,email:`guest@local`,name:`Guest User`,role:`admin`}),u({token:`guest-token`,expiresAt:new Date(Date.now()+31536e6)}),f(!1);return}let e=!1;async function t(){try{let t=await o.getSession();if(e)return;t&&(c(t.user),u(t.session))}catch(t){if(e)return;g(t instanceof Error?t:Error(String(t)))}finally{e||f(!1)}}return t(),()=>{e=!0}},[o,r,D,i]),(0,p.useEffect)(()=>{n?.({user:s,session:l,isAuthenticated:O,isLoading:d,error:m})},[s,l,O,d,m,n]);let k=(0,p.useCallback)(async(e,t)=>{f(!0),g(null);try{let n=await o.signIn({email:e,password:t});c(n.user),u(n.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{f(!1)}},[o]),A=(0,p.useCallback)(async(e,t,n)=>{f(!0),g(null);try{let r=await o.signUp({name:e,email:t,password:n});return r.requiresVerification?{requiresVerification:!0}:(c(r.user),u(r.session),{requiresVerification:!1})}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{f(!1)}},[o]),j=(0,p.useCallback)(async()=>{f(!0);try{await o.signOut(),c(null),u(null),g(null)}catch(e){g(e instanceof Error?e:Error(String(e)))}finally{f(!1)}},[o]),M=(0,p.useCallback)(async e=>{g(null);try{let t=await o.updateUser(e);c(t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),N=(0,p.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]),P=(0,p.useCallback)(async(e,t)=>{g(null);try{await o.sendVerificationEmail(e,t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),te=(0,p.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]),ne=(0,p.useCallback)(async e=>{g(null);try{await o.sendPhoneOtp(e)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),F=(0,p.useCallback)(async(e,t)=>{f(!0),g(null);try{let n=await o.signInWithPhoneOtp(e,t);c(n.user),u(n.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{f(!1)}},[o]),I=(0,p.useCallback)(async(e,t)=>{f(!0),g(null);try{let n=await o.signInWithPhonePassword(e,t);c(n.user),u(n.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{f(!1)}},[o]),re=(0,p.useCallback)(async e=>{g(null);try{await o.requestPhonePasswordReset(e)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),L=(0,p.useCallback)(async(e,t,n)=>{g(null);try{await o.resetPasswordWithPhoneOtp(e,t,n)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]);(0,p.useEffect)(()=>h.subscribe(e=>{y(t=>t??e)}),[]);let ie=(0,p.useCallback)(e=>o.enrollTotp(e),[o]),ae=(0,p.useCallback)(e=>o.verifyTotp(e),[o]),R=(0,p.useCallback)(async(e,t,n)=>{g(null);try{await o.changePassword(e,t,n)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),oe=(0,p.useCallback)(async e=>{g(null);try{await o.setInitialPassword(e)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),z=(0,p.useCallback)(()=>o.hasLocalPassword(),[o]),se=(0,p.useCallback)(()=>o.getConfig(),[o]),B=(0,p.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]),V=(0,p.useCallback)(async e=>{if(!(!r||D)){E(!0);try{let t=await o.listOrganizations();if(e?.())return t;if(ee(t),t.length>0&&!x){let n=null;try{n=await o.getActiveOrganization()}catch{n=null}if(!n&&t.length===1)try{n=await o.setActiveOrganization(t[0].id)}catch{n=null}n&&!e?.()&&(S(n),pn.set(n.id))}return t}catch(t){e?.()||console.warn(`[AuthProvider] Failed to load organizations:`,t)}finally{e?.()||E(!1)}}},[o,r,D,x]),ce=(0,p.useCallback)(async()=>{if(!r||D){let e=D?i?.simulatedRole??`admin`:`admin`;w({id:`preview-member`,organizationId:x?.id??`preview-org`,userId:`preview-user`,role:e});return}if(!x){w(null);return}try{let e=await o.getActiveMember();w(e)}catch(e){console.warn(`[AuthProvider] Failed to load active member:`,e),w(null)}},[o,r,D,i,x]);(0,p.useEffect)(()=>{ce()},[ce]),(0,p.useEffect)(()=>{if(!(s&&r&&!D))return;let e=!1;return V(()=>e),()=>{e=!0}},[s,r,D]);let le=(0,p.useCallback)(async e=>{g(null);try{let t=await o.setActiveOrganization(e);S(t),t?pn.set(t.id):pn.clear()}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),ue=(0,p.useCallback)(async e=>{g(null);try{let t=await o.createOrganization(e);return await V(),await le(t.id),t}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o,V,le]),H=(0,p.useCallback)(async(e,t)=>{let n=await o.updateOrganization(e,t);return await V(),x?.id===e&&S(n),n},[o,V,x]),de=(0,p.useCallback)(async e=>{await o.deleteOrganization(e),x?.id===e&&(S(null),pn.clear()),await V()},[o,x,V]),fe=(0,p.useCallback)(async e=>{await o.leaveOrganization(e),x?.id===e&&(S(null),pn.clear()),await V()},[o,x,V]),pe=(0,p.useCallback)(e=>o.getMembers(e),[o]),me=(0,p.useCallback)(e=>o.inviteMember(e),[o]),he=(0,p.useCallback)(()=>o.describeDelegableScope(),[o]),ge=(0,p.useCallback)(e=>o.removeMember(e),[o]),_e=(0,p.useCallback)(e=>o.updateMemberRole(e),[o]),ve=(0,p.useCallback)(e=>o.listInvitations(e),[o]),U=(0,p.useCallback)(e=>o.cancelInvitation(e),[o]),W=(0,p.useCallback)(e=>o.getInvitation(e),[o]),G=(0,p.useCallback)(async e=>{await o.acceptInvitation(e),await V()},[o,V]),ye=(0,p.useCallback)(e=>o.rejectInvitation(e),[o]),be=(0,p.useCallback)(()=>o.listUserInvitations(),[o]),xe=r&&!D,Se=(0,p.useMemo)(()=>({user:s,session:l,isAuthenticated:O,isAuthEnabled:xe,isLoading:d,error:m,isPreviewMode:D,previewMode:D?i:null,signIn:k,signUp:A,signOut:j,updateUser:M,forgotPassword:N,sendVerificationEmail:P,resetPassword:te,sendPhoneOtp:ne,signInWithPhoneOtp:F,signInWithPhonePassword:I,requestPhonePasswordReset:re,resetPasswordWithPhoneOtp:L,changePassword:R,remediationRequired:v,setRemediationRequired:y,enrollTotp:ie,verifyTotp:ae,setInitialPassword:oe,hasLocalPassword:z,getAuthConfig:se,signInWithProvider:B,organizations:b,activeOrganization:x,activeMember:C,isOrganizationsLoading:T,switchOrganization:le,createOrganization:ue,refreshOrganizations:V,updateOrganization:H,deleteOrganization:de,leaveOrganization:fe,getMembers:pe,inviteMember:me,describeDelegableScope:he,removeMember:ge,updateMemberRole:_e,listInvitations:ve,cancelInvitation:U,getInvitation:W,acceptInvitation:G,rejectInvitation:ye,listUserInvitations:be}),[s,l,O,xe,d,m,D,i,k,A,j,M,N,P,te,R,oe,z,se,B,ne,F,I,re,L,v,ie,ae,b,x,C,T,le,ue,V,H,de,fe,pe,me,he,ge,_e,ve,U,W,G,ye,be]);return(0,Y.jsx)(_.Provider,{value:Se,children:a})}function X(){return(0,p.useContext)(_)||{user:null,session:null,isAuthenticated:!1,isAuthEnabled:!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`)},sendVerificationEmail:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},resetPassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},sendPhoneOtp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},signInWithPhoneOtp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},signInWithPhonePassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},requestPhonePasswordReset:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},resetPasswordWithPhoneOtp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},changePassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},remediationRequired:null,setRemediationRequired:()=>{},enrollTotp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},verifyTotp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},setInitialPassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},hasLocalPassword:async()=>!1,getAuthConfig:async()=>({}),describeDelegableScope:async()=>null,signInWithProvider:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},organizations:[],activeOrganization:null,activeMember: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`)}}}var _n=new Set([`owner`,`admin`,`super_admin`,`superadmin`,`platform_admin`,`system_admin`,`org_owner`,`org_admin`]);function vn(e){return typeof e==`string`&&_n.has(e.toLowerCase())}function yn(){let{activeMember:e,user:t}=X();return!!(vn(e?.role)||vn(t?.role)||Array.isArray(t?.roles)&&t.roles.some(vn))}function bn({fallback:e=null,requiredRoles:t,loadingFallback:n,children:r}){let{isAuthenticated:i,isLoading:a,user:o}=X();if(a)return(0,Y.jsx)(Y.Fragment,{children:n??null});if(!i)return(0,Y.jsx)(Y.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,Y.jsx)(Y.Fragment,{children:e})}return(0,Y.jsx)(Y.Fragment,{children:r})}var Z=`flex h-11 w-full rounded-lg border border-input bg-background px-3.5 py-2 text-sm shadow-sm ring-offset-background transition-colors placeholder:text-muted-foreground hover:border-primary/40 focus-visible:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50`,xn=`inline-flex h-11 w-full items-center justify-center gap-2 rounded-lg bg-gradient-to-r from-primary to-primary/85 px-4 py-2 text-sm font-medium text-primary-foreground shadow-sm ring-offset-background transition-[box-shadow,background-color,transform] hover:shadow-md hover:from-primary hover:to-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 active:scale-[0.99] disabled:pointer-events-none disabled:opacity-60 motion-reduce:transition-none motion-reduce:active:transform-none`,Q=`text-sm font-medium leading-none text-foreground`;function $(){return(0,Y.jsxs)(`svg`,{className:`h-4 w-4 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,"aria-hidden":`true`,children:[(0,Y.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,Y.jsx)(`path`,{className:`opacity-90`,d:`M4 12a8 8 0 018-8`,stroke:`currentColor`,strokeWidth:`4`,strokeLinecap:`round`})]})}function Sn({className:e}){return(0,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e??`h-4 w-4 shrink-0`,"aria-hidden":`true`,children:[(0,Y.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,Y.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,Y.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]})}function Cn({className:e}){return(0,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e??`h-7 w-7`,"aria-hidden":`true`,children:[(0,Y.jsx)(`rect`,{x:`2`,y:`4`,width:`20`,height:`16`,rx:`2`}),(0,Y.jsx)(`path`,{d:`m22 6-10 7L2 6`})]})}function wn({icon:e,title:t,description:n}){return(0,Y.jsxs)(`div`,{className:`flex flex-col items-center space-y-3 text-center`,children:[e&&(0,Y.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary ring-1 ring-primary/15`,children:e}),(0,Y.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight text-foreground sm:text-[1.6rem]`,children:t}),n&&(0,Y.jsx)(`p`,{className:`text-sm leading-relaxed text-muted-foreground`,children:n})]})}function Tn({message:e}){return(0,Y.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive`,role:`alert`,children:[(0,Y.jsx)(Sn,{className:`mt-0.5 h-4 w-4 shrink-0`}),(0,Y.jsx)(`span`,{className:`leading-snug`,children:e})]})}var En={google:`Google`,github:`GitHub`,microsoft:`Microsoft`,apple:`Apple`,facebook:`Facebook`,twitter:`Twitter`,discord:`Discord`,gitlab:`GitLab`,linkedin:`LinkedIn`},Dn={google:(0,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Y.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,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:[(0,Y.jsx)(`path`,{fill:`#F25022`,d:`M2 2h9.5v9.5H2z`}),(0,Y.jsx)(`path`,{fill:`#7FBA00`,d:`M12.5 2H22v9.5h-9.5z`}),(0,Y.jsx)(`path`,{fill:`#00A4EF`,d:`M2 12.5h9.5V22H2z`}),(0,Y.jsx)(`path`,{fill:`#FFB900`,d:`M12.5 12.5H22V22h-9.5z`})]}),apple:(0,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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 On({id:e}){let t=Dn[e];return t?(0,Y.jsx)(`span`,{className:`mr-2 flex h-4 w-4 items-center justify-center`,children:t}):(0,Y.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 kn({mode:e=`sign-in`,callbackURL:t,errorCallbackURL:n,dividerText:r=`or continue with email`,onProvidersResolved:i}){let{getAuthConfig:a,signInWithProvider:o}=X(),[s,c]=(0,p.useState)([]),[l,u]=(0,p.useState)(!0),[d,f]=(0,p.useState)(null),[m,h]=(0,p.useState)(null);if((0,p.useEffect)(()=>{let e=!1;return Promise.resolve().then(()=>a()).then(t=>{if(e)return;let n=(t?.socialProviders??[]).filter(e=>e.enabled);c(n),i?.(n.length>0)}).catch(t=>{e||(console.warn(`[SocialSignInButtons] failed to load auth config`,t),i?.(!1))}).finally(()=>{e||u(!1)}),()=>{e=!0}},[a]),l||s.length===0)return null;let g=e===`sign-in`?`Continue with`:`Sign up with`,_=typeof window<`u`?window.location.href:void 0,v=async e=>{if(!m){f(null),h(e.id);try{await o(e.id,{callbackURL:t??_,errorCallbackURL:n??t??_,type:e.type??`social`})}catch(e){f(e instanceof Error?e.message:String(e)),h(null)}}};return(0,Y.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[d&&(0,Y.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:d}),s.map(e=>(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>v(e),disabled:m!==null,"aria-busy":m===e.id,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:[m===e.id?(0,Y.jsx)($,{}):(0,Y.jsx)(On,{id:e.id}),g,` `,En[e.id]??e.name]},e.id)),(0,Y.jsxs)(`div`,{className:`relative my-1`,children:[(0,Y.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,Y.jsx)(`span`,{className:`w-full border-t`})}),(0,Y.jsx)(`div`,{className:`relative flex justify-center text-xs uppercase`,children:(0,Y.jsx)(`span`,{className:`bg-background px-2 text-muted-foreground`,children:r})})]})]})}function An(e){let t=String(e??``).replace(/[\s\-().]/g,``);return/^\+?[0-9]{6,15}$/.test(t)?t:null}function jn(e){return typeof e!=`string`||e.includes(`@`)?!1:An(e)!==null}var Mn=({href:e,className:t,children:n})=>(0,Y.jsx)(`a`,{href:e,className:t,children:n}),Nn=()=>(0,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`h-6 w-6`,"aria-hidden":`true`,children:[(0,Y.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,Y.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]});function Pn({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`,icon:o,hideIcon:s=!1,linkComponent:c=Mn,labels:l={},errorMessages:u}){let{signIn:d,isLoading:f,getAuthConfig:m,sendPhoneOtp:h,signInWithPhoneOtp:g,signInWithPhonePassword:_}=X(),[v,y]=(0,p.useState)(``),[b,ee]=(0,p.useState)(``),[x,S]=(0,p.useState)(null),[C,w]=(0,p.useState)(!1),[T,E]=(0,p.useState)(!1),[D,O]=(0,p.useState)(`password`),[k,A]=(0,p.useState)(``),[j,M]=(0,p.useState)(``),[N,P]=(0,p.useState)(!1),[te,ne]=(0,p.useState)(!1),[F,I]=(0,p.useState)(0),[re,L]=(0,p.useState)(!1),[ie,ae]=(0,p.useState)(!1),[R,oe]=(0,p.useState)(!1),[z,se]=(0,p.useState)(!1),[B,V]=(0,p.useState)(!1),[ce,le]=(0,p.useState)(!0);(0,p.useEffect)(()=>{let e=!1;return Promise.resolve().then(()=>m()).then(t=>{e||(ae(t?.features?.sso===!0),w(t?.features?.phoneNumberOtp===!0),E(t?.features?.phoneNumber===!0),oe(t?.features?.ssoEnforced===!0||t?.emailPassword?.enabled===!1))}).catch(()=>{}).finally(()=>{e||le(!1)}),()=>{e=!0}},[m]);let ue=!R||z,H={emailLabel:l.emailLabel??`Email`,emailPlaceholder:l.emailPlaceholder??`name@example.com`,emailOrPhoneLabel:l.emailOrPhoneLabel??`Email or phone number`,emailOrPhonePlaceholder:l.emailOrPhonePlaceholder??`name@example.com or +1 555 000 0000`,passwordLabel:l.passwordLabel??`Password`,passwordPlaceholder:l.passwordPlaceholder??`Enter your password`,forgotPasswordText:l.forgotPasswordText??`Forgot password?`,submitButton:l.submitButton??`Sign In`,submittingButton:l.submittingButton??`Signing in…`,noAccountText:l.noAccountText??`Don't have an account?`,signUpText:l.signUpText??`Sign up`,orText:l.orText??`or`,ssoButton:l.ssoButton??`Sign in with SSO`,usePasswordText:l.usePasswordText??`Use a password instead`,backToSsoText:l.backToSsoText??`Back to single sign-on`,ssoOnlyDescription:l.ssoOnlyDescription??`Sign in with your organization's single sign-on`,phoneLabel:l.phoneLabel??`Phone number`,phonePlaceholder:l.phonePlaceholder??`+1 555 000 0000`,otpCodeLabel:l.otpCodeLabel??`Verification code`,otpCodePlaceholder:l.otpCodePlaceholder??`6-digit code`,sendOtpButton:l.sendOtpButton??`Get code`,resendOtpCountdownText:l.resendOtpCountdownText??`Resend in {seconds}s`,usePhoneOtpText:l.usePhoneOtpText??`Sign in with verification code`,usePasswordSignInText:l.usePasswordSignInText??`Sign in with password instead`};(0,p.useEffect)(()=>{if(F<=0)return;let e=setTimeout(()=>I(e=>e>1?e-1:0),1e3);return()=>clearTimeout(e)},[F]);let de=async n=>{n.preventDefault(),S(null);let r=v.trim();try{D===`phone-otp`?await g(k.trim(),j.trim()):T&&jn(r)?await _(An(r)??r,b):await d(r,b),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e)),r=n.code;S(r&&u?.[r]||n.message),t?.(n)}},fe=async()=>{if(!(!k.trim()||N||F>0)){S(null),P(!0);try{await h(k.trim()),ne(!0),I(60)}catch(e){let n=e instanceof Error?e:Error(String(e)),r=n.code;S(r&&u?.[r]||n.message),t?.(n)}finally{P(!1)}}},pe=e=>{O(e),S(null)};return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:s?void 0:o??(0,Y.jsx)(Nn,{}),title:i,description:R&&!z?H.ssoOnlyDescription:a}),(0,Y.jsx)(`div`,{className:`space-y-5`,children:ce?(0,Y.jsx)(`div`,{className:`flex justify-center py-10`,role:`status`,"aria-live":`polite`,"data-testid":`login-config-loading`,children:(0,Y.jsx)($,{})}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(kn,{mode:`sign-in`,onProvidersResolved:e=>L(e)}),ue?D===`phone-otp`?(0,Y.jsxs)(`form`,{onSubmit:de,className:`space-y-4`,children:[x&&(0,Y.jsx)(Tn,{message:x}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`login-phone`,className:Q,children:H.phoneLabel}),(0,Y.jsx)(`input`,{id:`login-phone`,type:`tel`,placeholder:H.phonePlaceholder,value:k,onChange:e=>A(e.target.value),required:!0,autoComplete:`tel`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`login-otp`,className:Q,children:H.otpCodeLabel}),(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{id:`login-otp`,type:`text`,inputMode:`numeric`,placeholder:H.otpCodePlaceholder,value:j,onChange:e=>M(e.target.value),required:!0,autoComplete:`one-time-code`,disabled:f,className:Z}),(0,Y.jsxs)(`button`,{type:`button`,onClick:fe,disabled:N||F>0||!k.trim()||f,className:`shrink-0 rounded-md border border-input bg-background px-3 py-2 text-sm font-medium transition-colors hover:bg-accent disabled:opacity-50`,children:[N&&(0,Y.jsx)($,{}),F>0?H.resendOtpCountdownText.replace(`{seconds}`,String(F)):H.sendOtpButton]})]})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:f||!te,className:xn,children:[f&&(0,Y.jsx)($,{}),f?H.submittingButton:H.submitButton]}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>pe(`password`),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.usePasswordSignInText})]}):(0,Y.jsxs)(`form`,{onSubmit:de,className:`space-y-4`,children:[x&&(0,Y.jsx)(Tn,{message:x}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`login-email`,className:Q,children:T?H.emailOrPhoneLabel:H.emailLabel}),(0,Y.jsx)(`input`,{id:`login-email`,type:T?`text`:`email`,inputMode:T?`text`:`email`,placeholder:T?H.emailOrPhonePlaceholder:H.emailPlaceholder,value:v,onChange:e=>y(e.target.value),required:!0,autoComplete:`username`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Y.jsx)(`label`,{htmlFor:`login-password`,className:Q,children:H.passwordLabel}),r&&(0,Y.jsx)(c,{href:r,className:`text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.forgotPasswordText})]}),(0,Y.jsx)(`input`,{id:`login-password`,type:`password`,placeholder:H.passwordPlaceholder,value:b,onChange:e=>ee(e.target.value),required:!0,autoComplete:`current-password`,disabled:f,className:Z})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:f,className:xn,children:[f&&(0,Y.jsx)($,{}),f?H.submittingButton:H.submitButton]}),ie&&(0,Y.jsxs)(`button`,{type:`button`,onClick:async()=>{if(B)return;S(null);let e=v.trim();if(jn(e)){S(`Enter your email address to sign in with SSO.`);return}V(!0);try{let t=window.location.pathname.replace(/\/login(?:\/.*)?$/,``),n=await fetch(`/api/v1/auth/sign-in/sso`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:e,callbackURL:t+`/home`}),credentials:`include`}),r=await n.json().catch(()=>({}));if(n.ok&&typeof r.url==`string`){window.location.href=r.url;return}S(r.message||`No SSO provider is configured for this email domain.`),V(!1)}catch(e){S(e instanceof Error?e.message:String(e)),V(!1)}},disabled:f||B,"aria-busy":B,className:`flex w-full items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent disabled:opacity-50`,children:[B&&(0,Y.jsx)($,{}),H.ssoButton]}),C&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>pe(`phone-otp`),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.usePhoneOtpText}),R&&z&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>se(!1),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.backToSsoText})]}):(0,Y.jsxs)(`div`,{className:`space-y-4`,children:[x&&(0,Y.jsx)(Tn,{message:x}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>se(!0),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.usePasswordText})]})]})}),n&&!R&&(0,Y.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[H.noAccountText,` `,(0,Y.jsx)(c,{href:n,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:H.signUpText})]})]})}var Fn=({href:e,className:t,children:n})=>(0,Y.jsx)(`a`,{href:e,className:t,children:n}),In=()=>(0,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`h-6 w-6`,"aria-hidden":`true`,children:[(0,Y.jsx)(`path`,{d:`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`}),(0,Y.jsx)(`circle`,{cx:`9`,cy:`7`,r:`4`}),(0,Y.jsx)(`line`,{x1:`19`,y1:`8`,x2:`19`,y2:`14`}),(0,Y.jsx)(`line`,{x1:`22`,y1:`11`,x2:`16`,y2:`11`})]});function Ln({onSuccess:e,onVerificationRequired:t,onError:n,loginUrl:r=`/login`,title:i=`Create an account`,description:a=`Enter your information to get started`,icon:o,hideIcon:s=!1,linkComponent:c=Fn,labels:l={},errorMessages:u}){let{signUp:d,isLoading:f}=X(),[m,h]=(0,p.useState)(``),[g,_]=(0,p.useState)(``),[v,y]=(0,p.useState)(``),[b,ee]=(0,p.useState)(``),[x,S]=(0,p.useState)(null),C={nameLabel:l.nameLabel??`Name`,namePlaceholder:l.namePlaceholder??`John Doe`,emailLabel:l.emailLabel??`Email`,emailPlaceholder:l.emailPlaceholder??`name@example.com`,passwordLabel:l.passwordLabel??`Password`,passwordPlaceholder:l.passwordPlaceholder??`Create a password (min. 8 characters)`,confirmPasswordLabel:l.confirmPasswordLabel??`Confirm Password`,confirmPasswordPlaceholder:l.confirmPasswordPlaceholder??`Confirm your password`,passwordMismatchError:l.passwordMismatchError??`Passwords do not match`,passwordTooShortError:l.passwordTooShortError??`Password must be at least 8 characters`,submitButton:l.submitButton??`Create Account`,submittingButton:l.submittingButton??`Creating account…`,hasAccountText:l.hasAccountText??`Already have an account?`,signInText:l.signInText??`Sign in`,orText:l.orText??`or`};return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:s?void 0:o??(0,Y.jsx)(In,{}),title:i,description:a}),(0,Y.jsxs)(`div`,{className:`space-y-5`,children:[(0,Y.jsx)(kn,{mode:`sign-up`}),(0,Y.jsxs)(`form`,{onSubmit:async r=>{if(r.preventDefault(),S(null),v!==b){S(C.passwordMismatchError);return}if(v.length<8){S(C.passwordTooShortError);return}let i=g.trim();try{if((await d(m,i,v))?.requiresVerification){t?.(i);return}e?.()}catch(e){let t=e instanceof Error?e:Error(String(e)),r=t.code;S(r&&u?.[r]||t.message),n?.(t)}},className:`space-y-4`,children:[x&&(0,Y.jsx)(Tn,{message:x}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`register-name`,className:Q,children:C.nameLabel}),(0,Y.jsx)(`input`,{id:`register-name`,type:`text`,placeholder:C.namePlaceholder,value:m,onChange:e=>h(e.target.value),required:!0,autoComplete:`name`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`register-email`,className:Q,children:C.emailLabel}),(0,Y.jsx)(`input`,{id:`register-email`,type:`email`,placeholder:C.emailPlaceholder,value:g,onChange:e=>_(e.target.value),required:!0,autoComplete:`email`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`register-password`,className:Q,children:C.passwordLabel}),(0,Y.jsx)(`input`,{id:`register-password`,type:`password`,placeholder:C.passwordPlaceholder,value:v,onChange:e=>y(e.target.value),required:!0,minLength:8,autoComplete:`new-password`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`register-confirm-password`,className:Q,children:C.confirmPasswordLabel}),(0,Y.jsx)(`input`,{id:`register-confirm-password`,type:`password`,placeholder:C.confirmPasswordPlaceholder,value:b,onChange:e=>ee(e.target.value),required:!0,minLength:8,autoComplete:`new-password`,disabled:f,className:Z})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:f,className:xn,children:[f&&(0,Y.jsx)($,{}),f?C.submittingButton:C.submitButton]})]})]}),r&&(0,Y.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[C.hasAccountText,` `,(0,Y.jsx)(c,{href:r,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:C.signInText})]})]})}var Rn=({href:e,className:t,children:n})=>(0,Y.jsx)(`a`,{href:e,className:t,children:n}),zn=()=>(0,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`h-6 w-6`,"aria-hidden":`true`,children:(0,Y.jsx)(`path`,{d:`M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4`})});function Bn({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`,icon:a,hideIcon:o=!1,linkComponent:s=Rn,labels:c={}}){let{forgotPassword:l,isLoading:u,getAuthConfig:d,requestPhonePasswordReset:f,resetPasswordWithPhoneOtp:m}=X(),[h,g]=(0,p.useState)(``),[_,v]=(0,p.useState)(null),[y,b]=(0,p.useState)(!1),[ee,x]=(0,p.useState)(!1),[S,C]=(0,p.useState)(`email`),[w,T]=(0,p.useState)(``),[E,D]=(0,p.useState)(``),[O,k]=(0,p.useState)(``),[A,j]=(0,p.useState)(!1),[M,N]=(0,p.useState)(!1),[P,te]=(0,p.useState)(0),[ne,F]=(0,p.useState)(!1),[I,re]=(0,p.useState)(!1);(0,p.useEffect)(()=>{let e=!1;return Promise.resolve().then(()=>d()).then(t=>{e||x(t?.features?.phoneNumberOtp===!0)}).catch(()=>{}),()=>{e=!0}},[d]),(0,p.useEffect)(()=>{if(P<=0)return;let e=setTimeout(()=>te(e=>e>1?e-1:0),1e3);return()=>clearTimeout(e)},[P]);let L={emailLabel:c.emailLabel??`Email`,emailPlaceholder:c.emailPlaceholder??`name@example.com`,submitButton:c.submitButton??`Send Reset Link`,submittingButton:c.submittingButton??`Sending…`,successTitle:c.successTitle??`Check your email`,successDescription:c.successDescription??`We've sent a password reset link to {{email}}. Please check your inbox.`,backToSignInText:c.backToSignInText??`Back to sign in`,rememberPasswordText:c.rememberPasswordText??`Remember your password?`,signInText:c.signInText??`Sign in`,phoneLabel:c.phoneLabel??`Phone number`,phonePlaceholder:c.phonePlaceholder??`+1 555 000 0000`,otpCodeLabel:c.otpCodeLabel??`Verification code`,otpCodePlaceholder:c.otpCodePlaceholder??`6-digit code`,sendOtpButton:c.sendOtpButton??`Get code`,resendOtpCountdownText:c.resendOtpCountdownText??`Resend in {seconds}s`,newPasswordLabel:c.newPasswordLabel??`New password`,newPasswordPlaceholder:c.newPasswordPlaceholder??`Enter a new password`,resetButton:c.resetButton??`Reset Password`,usePhoneResetText:c.usePhoneResetText??`Reset via SMS code`,useEmailResetText:c.useEmailResetText??`Reset via email instead`,phoneSuccessTitle:c.phoneSuccessTitle??`Password reset`,phoneSuccessDescription:c.phoneSuccessDescription??`Your password has been reset. You can now sign in with your new password.`},ie=async n=>{n.preventDefault(),v(null);try{await l(h.trim()),b(!0),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));v(n.message),t?.(n)}},ae=async()=>{if(!(!w.trim()||A||P>0)){v(null),j(!0);try{await f(w.trim()),N(!0),te(60)}catch(e){let n=e instanceof Error?e:Error(String(e));v(n.message),t?.(n)}finally{j(!1)}}},R=async n=>{n.preventDefault(),v(null),re(!0);try{await m(w.trim(),E.trim(),O),F(!0),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));v(n.message),t?.(n)}finally{re(!1)}},oe=e=>{C(e),v(null)};if(ne)return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:(0,Y.jsx)(`span`,{className:`flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-500/10 text-emerald-600 ring-1 ring-emerald-500/15 dark:text-emerald-400`,children:(0,Y.jsx)(Cn,{})}),title:L.phoneSuccessTitle,description:L.phoneSuccessDescription}),n&&(0,Y.jsx)(`p`,{className:`text-center text-sm text-muted-foreground`,children:(0,Y.jsxs)(s,{href:n,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:[`← `,L.backToSignInText]})})]});if(y){let e=L.successDescription.includes(`{{email}}`)?L.successDescription.replace(`{{email}}`,h):`${L.successDescription} ${h}`;return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:(0,Y.jsx)(`span`,{className:`flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-500/10 text-emerald-600 ring-1 ring-emerald-500/15 dark:text-emerald-400`,children:(0,Y.jsx)(Cn,{})}),title:L.successTitle,description:e}),n&&(0,Y.jsx)(`p`,{className:`text-center text-sm text-muted-foreground`,children:(0,Y.jsxs)(s,{href:n,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:[`← `,L.backToSignInText]})})]})}return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:o?void 0:a??(0,Y.jsx)(zn,{}),title:r,description:i}),S===`phone`?(0,Y.jsxs)(`form`,{onSubmit:R,className:`space-y-4`,children:[_&&(0,Y.jsx)(Tn,{message:_}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`forgot-phone`,className:Q,children:L.phoneLabel}),(0,Y.jsx)(`input`,{id:`forgot-phone`,type:`tel`,placeholder:L.phonePlaceholder,value:w,onChange:e=>T(e.target.value),required:!0,autoComplete:`tel`,disabled:I,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`forgot-otp`,className:Q,children:L.otpCodeLabel}),(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{id:`forgot-otp`,type:`text`,inputMode:`numeric`,placeholder:L.otpCodePlaceholder,value:E,onChange:e=>D(e.target.value),required:!0,autoComplete:`one-time-code`,disabled:I,className:Z}),(0,Y.jsxs)(`button`,{type:`button`,onClick:ae,disabled:A||P>0||!w.trim()||I,className:`shrink-0 rounded-md border border-input bg-background px-3 py-2 text-sm font-medium transition-colors hover:bg-accent disabled:opacity-50`,children:[A&&(0,Y.jsx)($,{}),P>0?L.resendOtpCountdownText.replace(`{seconds}`,String(P)):L.sendOtpButton]})]})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`forgot-new-password`,className:Q,children:L.newPasswordLabel}),(0,Y.jsx)(`input`,{id:`forgot-new-password`,type:`password`,placeholder:L.newPasswordPlaceholder,value:O,onChange:e=>k(e.target.value),required:!0,autoComplete:`new-password`,disabled:I,className:Z})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:I||!M,className:xn,children:[I&&(0,Y.jsx)($,{}),I?L.submittingButton:L.resetButton]}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>oe(`email`),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:L.useEmailResetText})]}):(0,Y.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[_&&(0,Y.jsx)(Tn,{message:_}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`forgot-email`,className:Q,children:L.emailLabel}),(0,Y.jsx)(`input`,{id:`forgot-email`,type:`email`,placeholder:L.emailPlaceholder,value:h,onChange:e=>g(e.target.value),required:!0,autoComplete:`email`,disabled:u,className:Z})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:u,className:xn,children:[u&&(0,Y.jsx)($,{}),u?L.submittingButton:L.submitButton]}),ee&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>oe(`phone`),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:L.usePhoneResetText})]}),n&&(0,Y.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[L.rememberPasswordText,` `,(0,Y.jsx)(s,{href:n,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:L.signInText})]})]})}function Vn(e){return e?e.name?e.name.split(` `).map(e=>e[0]).join(``).toUpperCase().slice(0,2):e.email?.[0]?.toUpperCase()??`?`:`?`}var Hn=[...i],Un={[a]:{key:`organization.roles.owner`,defaultValue:`Owner`},[o]:{key:`organization.roles.admin`,defaultValue:`Admin`},[s]:{key:`organization.roles.delegatedAdmin`,defaultValue:`Delegated Admin`},[r]:{key:`organization.roles.member`,defaultValue:`Member`}},Wn=0,Gn=1,Kn=2,qn=3;function Jn(e){if(typeof e!=`string`)return Wn;let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);if(t.length===0)return Wn;let n=Gn;for(let e of t)e===`owner`?n=Math.max(n,qn):e===`admin`&&(n=Math.max(n,Kn));return n}function Yn(e){let t=Jn(e);return t<Kn?[r]:Hn.filter(e=>Jn(e)<=t)}function Xn(e,t){let n=Jn(e);if(n<Kn)return[];let r=n>=qn;return!r&&Jn(t)>=qn?[]:Hn.filter(e=>e!==`owner`||r)}function Zn(e,t=`en`){let n=e instanceof Date?e:new Date(e),r=new Date,i=n.getTime()-r.getTime(),a=Math.round(i/1e3),o=Math.round(a/60),s=Math.round(o/60),c=Math.round(s/24),l=new Intl.RelativeTimeFormat(t,{numeric:`auto`});if(Math.abs(a)<60)return l.format(a,`second`);if(Math.abs(o)<60)return l.format(o,`minute`);if(Math.abs(s)<24)return l.format(s,`hour`);if(Math.abs(c)<30)return l.format(c,`day`);let u=Math.round(c/30);return Math.abs(u)<12?l.format(u,`month`):l.format(Math.round(c/365),`year`)}function Qn(e){if(!e)return!1;let t=e.objects;if(!t||typeof t!=`object`||Array.isArray(t))return!1;for(let e of Object.values(t))if(e&&typeof e==`object`&&!Array.isArray(e)&&`fields`in e)return!0;return!1}var $n=[`apps`,`messages`,`validationMessages`,`dashboards`,`globalActions`];function er(e){let t={},n={},r={},i=e.objects;if(i)for(let[e,a]of Object.entries(i)){if(!a||typeof a!=`object`)continue;let i={};a.label&&(i.label=a.label),a.pluralLabel&&(i.pluralLabel=a.pluralLabel),a.description&&(i.description=a.description);for(let[e,t]of Object.entries(a))e.startsWith(`_`)&&(i[e]=t);if(t[e]=i,a.fields&&typeof a.fields==`object`){let t=Object.entries(a.fields);for(let[i,a]of t)a?.label&&(n[e]||(n[e]={}),n[e][i]=a.label),a?.options&&typeof a.options==`object`&&Object.keys(a.options).length>0&&(r[e]||(r[e]={}),r[e][i]=a.options)}}let a={};Object.keys(t).length>0&&(a.objects=t),Object.keys(n).length>0&&(a.fields=n),Object.keys(r).length>0&&(a.fieldOptions=r);for(let t of $n)e[t]!==void 0&&(a[t]=e[t]);let o=new Set([`objects`,...$n]);for(let[t,n]of Object.entries(e))o.has(t)||(a[t]=n);return{app:a}}var tr=(0,p.createContext)(null);tr.displayName=`PermissionContext`;var nr=`/api/v1/auth/me/permissions`;function rr({endpoint:e=nr,fetcher:t,initialPermissions:n,loadingFallback:r=null,errorFallback:i,maxRetries:a=3,retryBaseDelayMs:o=500,children:s}){let[m,h]=(0,p.useState)(n??null),[g,_]=(0,p.useState)(null),[v,y]=(0,p.useState)(!n),b=(0,p.useCallback)(async n=>{let r=()=>!n?.cancelled;y(!0),_(null);let i=t??fetch,s=Math.max(0,a)+1;for(let t=0;t<s;t++)try{let t=await i(e,{credentials:`include`,headers:{Accept:`application/json`}});if(!t.ok)throw new l(t.status,f(t),`Permissions endpoint returned ${t.status}`);let n=await t.json();if(!r())return;h(n),y(!1);return}catch(e){let n=e instanceof Error?e:Error(String(e));if(!u(n)||t===s-1){if(!r())return;_(n),y(!1);return}let i=n instanceof l?n.retryAfterMs:void 0;if(await d(c(t,o,i)),!r())return}},[e,t,a,o]),ee=(0,p.useCallback)(()=>{b()},[b]);(0,p.useEffect)(()=>{if(n)return;let e={cancelled:!1};return b(e),()=>{e.cancelled=!0}},[b,n]);let x=(0,p.useCallback)((e,t,n)=>{if(!m)return!1;let r=(e??``).toLowerCase(),i=`${r}.${t}`,a=m.fields?.[i]??m.fields?.[`${e}.${t}`];if(a)return n===`read`?a.readable!==!1:a.editable!==!1;let o=m.objects?.[r]??m.objects?.[e]??m.objects?.[`*`];return o?n===`read`?o.allowRead!==!1:o.allowEdit!==!1:m.authenticated!==!0},[m]),S=(0,p.useCallback)((e,t)=>{if(!m)return{allowed:!1,reason:`permissions-loading`};let n=m.objects?.[e]??m.objects?.[`*`],r={read:`allowRead`,view:`allowRead`,create:`allowCreate`,update:`allowEdit`,edit:`allowEdit`,delete:`allowDelete`,import:`allowCreate`,export:`allowRead`}[t]??`allowRead`,i=n?n[r]!==!1:m.authenticated!==!0;return{allowed:i,reason:i?void 0:`denied-by-permission-set`}},[m]),C=(0,p.useCallback)(e=>{if(!m)return[];let t=`${e}.`,n=[];for(let[e,r]of Object.entries(m.fields??{})){if(!e.startsWith(t))continue;let i=e.slice(t.length);n.push({field:i,read:r.readable!==!1,write:r.editable!==!1})}return n},[m]),w=(0,p.useCallback)(()=>void 0,[]),T=(0,p.useCallback)(e=>{if(!m)return;let t=(e??``).toLowerCase(),n=(m.objects?.[t]??m.objects?.[e])?.apiOperations;return Array.isArray(n)?n:void 0},[m]),E=(0,p.useMemo)(()=>({check:S,checkField:x,getFieldPermissions:C,getRowFilter:w,getObjectApiOperations:T,roles:m?.roles??[],systemPermissions:m?.systemPermissions??[],hasCapabilities:e=>{let t=new Set(m?.systemPermissions??[]);return e.every(e=>t.has(e))},isLoaded:!v&&!g&&m!==null}),[S,x,C,w,T,m,v,g]);return v&&!m?(0,Y.jsx)(Y.Fragment,{children:r}):g&&!m?i?(0,Y.jsx)(Y.Fragment,{children:i(g,ee)}):(0,Y.jsx)(Y.Fragment,{children:r}):(0,Y.jsx)(tr.Provider,{value:E,children:s})}function ir(){let e=(0,p.useContext)(tr);return(0,p.useMemo)(()=>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,getObjectApiOperations:()=>void 0,roles:[],systemPermissions:[],hasCapabilities:()=>!0,isLoaded:!1,can:()=>!0,cannot:()=>!1},[e])}function ar(e){let{checkField:t,getFieldPermissions:n}=ir(),r=(0,p.useMemo)(()=>n(e),[n,e]);return(0,p.useMemo)(()=>({permissions:r,canRead:n=>t(e,n,`read`),canWrite:n=>t(e,n,`write`),readableFields:n=>n.filter(n=>t(e,n,`read`)),writableFields:n=>n.filter(n=>t(e,n,`write`))}),[r,t,e])}export{X as _,er as a,J as b,Xn as c,Bn as d,Ln as f,yn as g,bn as h,Qn as i,Yn as l,Tn as m,ir as n,Zn as o,Pn as p,rr as r,Un as s,ar as t,Vn as u,gn as v,hn as y};
|
|
3
|
+
at `))}function Se(e,t){class n extends e{#e;constructor(...e){if(be()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=xe(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 Ce={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};Se(class extends Error{constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:Ce[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 we=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},Te=47;function Ee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===Te;)t--;return t===e.length?e:e.slice(0,t)}function De(e){try{return(Ee(new URL(e).pathname)||`/`)!==`/`}catch{throw new we(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function Oe(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new we(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof we?t:new we(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function ke(e,t=`/api/auth`){if(Oe(e),De(e))return e;let n=Ee(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function Ae(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 je(e,t,n,r,i){if(e)return ke(e,t);if(r!==!1){let e=W.BETTER_AUTH_URL||W.NEXT_PUBLIC_BETTER_AUTH_URL||W.PUBLIC_BETTER_AUTH_URL||W.NUXT_PUBLIC_BETTER_AUTH_URL||W.NUXT_PUBLIC_AUTH_URL||(W.BASE_URL===`/`?void 0:W.BASE_URL);if(e)return ke(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&Ae(o,`proto`)&&Ae(a,`host`))try{return ke(`${o}://${a}`,t)}catch{}if(n){let e=Me(n.url);if(!e)throw new we(`Could not get origin from request. Please provide a valid base URL.`);return ke(e,t)}if(typeof window<`u`&&window.location)return ke(window.location.origin,t)}function Me(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var Ne=[`javascript:`,`data:`,`vbscript:`];function Pe(e){let t;try{t=new URL(e)}catch{return!0}return!Ne.includes(t.protocol)}var Fe={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&Pe(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},Ie=()=>typeof window>`u`;function Le(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Re(e){return!e||e.session===null&&e.user===null?null:e}function ze(e,t){return I(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function Be(e,t){let n=O(!1),r,i=e=>s(e),a=O({data:null,error:null,isPending:!0,isRefetching:!1,refetch:i});re(a,ze);let o=e=>{if(r!==e)return;let t=a.get();r=void 0,!(!t.isPending&&!t.isRefetching)&&a.set({...t,isPending:!1,isRefetching:!1,refetch:i})},s=async t=>{r?.abort();let n=new AbortController;r=n;let s=a.get();a.set({...s,isPending:s.data===null,isRefetching:!0,error:null,refetch:i});try{let r=await e(`/get-session`,{method:`GET`,query:t?.query,signal:n.signal});if(n.signal.aborted){o(n);return}let{data:s,error:c}=Le(r);if(s?.needsRefresh)try{let t=await e(`/get-session`,{method:`POST`,signal:n.signal});if(n.signal.aborted){o(n);return}({data:s,error:c}=Le(t))}catch{if(n.signal.aborted){o(n);return}}if(c){let e=a.get(),t=c?.status===401;a.set({data:t?null:e.data,error:c,isPending:!1,isRefetching:!1,refetch:i});return}let l=Re(s),u=a.get(),d=u.data!=null&&l!=null&&I(u.data,l)?u.data:l;a.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:i})}catch(e){if(n.signal.aborted){o(n);return}let t=a.get();a.set({data:t.data,error:e,isPending:!1,isRefetching:!1,refetch:i})}},c=()=>{};return ne(a,()=>{let e;Ie()||(e=setTimeout(()=>{s()},0));let i=_e({fetchSession:s,shouldPollSession:()=>a.get().data!=null,sessionSignal:n,options:t});return i.init(),c=i.broadcastSessionUpdate,()=>{e&&clearTimeout(e);let t=r;t?.abort(),t&&o(t),i.cleanup()}}),{session:a,$sessionSignal:n,broadcastSessionUpdate:e=>c(e)}}function Ve(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 He(e,t,n=`.`,r){if(!Ve(t))return He(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)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:Ve(a)&&Ve(i[t])?He(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function Ue(e){return(...t)=>t.reduce((t,n)=>He(t,n,``,e),{})}var We=Ue(),Ge=Object.defineProperty,Ke=Object.defineProperties,qe=Object.getOwnPropertyDescriptors,Je=Object.getOwnPropertySymbols,Ye=Object.prototype.hasOwnProperty,Xe=Object.prototype.propertyIsEnumerable,Ze=(e,t,n)=>t in e?Ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K=(e,t)=>{for(var n in t||={})Ye.call(t,n)&&Ze(e,n,t[n]);if(Je)for(var n of Je(t))Xe.call(t,n)&&Ze(e,n,t[n]);return e},q=(e,t)=>Ke(e,qe(t)),Qe=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)}},$e=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}},et=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}},tt=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 nt(e){if(typeof e==`number`)return new et({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new et(e);case`exponential`:return new tt(e);default:throw Error(`Invalid retry strategy`)}}var rt=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},it=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function at(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 it.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function ot(e){try{return JSON.parse(e),!0}catch{return!1}}function st(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 ct(e){try{return JSON.parse(e)}catch{return e}}function lt(e){return typeof e==`function`}function ut(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&<(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&<(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function dt(...e){let t={};for(let n of e)if(n)if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}return t}async function ft(e){let t=new Headers(dt(e?.headers,await rt(e)));if(!t.has(`content-type`)){let n=pt(e?.body);n&&t.set(`content-type`,n)}return t}function pt(e){return st(e)?`application/json`:null}function mt(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function ht(e,t){let{body:n}=e;return n?!st(n)||typeof n==`string`?n:mt(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function gt(e,t){if(t?.method)return t.method.toUpperCase();if(e.startsWith(`@`)){let n=e.split(`@`)[1]?.split(`/`)[0];return bt.includes(n)?n.toUpperCase():t?.body?`POST`:`GET`}return t?.body?`POST`:`GET`}function _t(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var vt=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function yt(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new vt(n.issues);return n.value}var bt=[`get`,`post`,`put`,`patch`,`delete`],xt=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,``)),e.startsWith(`/`)&&e.charAt(1)===`@`&&(e=e.substring(1));let i=r.schema[e];if(i){let e=n?.headers;if(i.headers&&!n?.disableValidation){let t={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((e,n)=>{t[n.toLowerCase()]=e});else if(typeof n.headers==`object`)for(let[e,r]of Object.entries(n.headers))r!=null&&(t[e.toLowerCase()]=r)}let r=await yt(i.headers,t),a={};for(let[e,t]of Object.entries(r))a[e.toLowerCase()]=t;e=a}let r=q(K({},n),{method:i.method,output:i.output,headers:e});return n?.disableValidation||(r=q(K({},r),{body:i.input?await yt(i.input,n?.body):n?.body,params:i.params?await yt(i.params,n?.params):n?.params,query:i.query?await yt(i.query,n?.query):n?.query})),{url:t,options:r}}}return{url:t,options:n}}}),St=e=>{async function t(t,n){let r=q(K(K({},e),n),{headers:dt(e?.headers,n?.headers),plugins:[...e?.plugins||[],xt(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Et(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 Et(t,r)}return t},Ct=e=>e===`.`||e===`..`;function wt(e,t){let n=e;for(let[e,r]of t)n=n.replace(e,r);if(Ct(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function Tt(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];bt.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)}let l=new Map;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];l.set(n,String(e))}}else for(let[e,t]of Object.entries(r))l.set(`:${e}`,String(t));o=o.split(`/`).map(e=>wt(e,l)).join(`/`),o=o.replace(/^\/+/,``);let u=c.toString();return u=u.length>0?`?${u}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${o}${u}`,a):`${a}${o}${u}`}var Et=async(e,t)=>{let{hooks:n,url:r,options:i}=await $e(e,t),a=ut(i),o=new AbortController,s=i.signal??o.signal,c=Tt(r,i),l=await ft(i),u=ht(i,l),d=gt(r,i),f=q(K({},i),{url:c,headers:l,body:u,method:d,signal:s});for(let e of n.onRequest)if(e){let t=await e(f);typeof t==`object`&&t&&Object.assign(f,t)}(`pipeTo`in f&&typeof f.pipeTo==`function`||typeof t?.body?.pipe==`function`)&&(`duplex`in f||(f.duplex=`half`));let{clearTimeout:p}=_t(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(q(K({},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=at(m),r={data:null,response:m,request:f};if(e===`json`||e===`text`){let e=await m.text();r.data=await(f.jsonParser??ct)(e)}else r.data=await m[e]();f?.output&&f.output&&!f.disableValidation&&(r.data=await yt(f.output,r.data));for(let e of n.onSuccess)e&&await e(q(K({},r),{response:t?.hookOptions?.cloneResponse?m.clone():m}));return t?.throw?r.data:{data:r.data,error:null}}let g=t?.jsonParser??ct,_=await m.text(),v=ot(_),y=v?await g(_):null,b={response:m,responseText:_,request:f,error:q(K({},y),{status:m.status,statusText:m.statusText})};for(let e of n.onError)e&&await e(q(K({},b),{response:t?.hookOptions?.cloneResponse?m.clone():m}));if(t?.retry){let r=nt(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 Et(e,q(K({},t),{retryAttempt:i+1}))}}if(t?.throw)throw new Qe(m.status,m.statusText,v?y:_);return{data:null,error:q(K({},y),{status:m.status,statusText:m.statusText})}},Dt=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{}}},Ot=(e,t)=>{let n=`credentials`in Request.prototype,r=je(e?.baseURL,e?.basePath,void 0,t)??Dt(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=St({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?de(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[Fe],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=Be(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=We(t.getActions?.(d,b,e)??{},g));return{get baseURL(){return r},pluginsActions:g,pluginsAtoms:_,pluginPathMethods:v,atomListeners:y,$fetch:d,$store:b}};function kt(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function At(e){return e.charAt(0).toUpperCase()+e.slice(1)}var jt=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,Mt=/['\u2019]/g;function Nt(e){return e.replace(Mt,``).match(jt)??[]}function Pt(e){return Nt(e).map(e=>e.toLowerCase()).join(`-`)}function Ft(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 It(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`||kt(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(Pt).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=Ft(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 Lt(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,$fetch:i,atomListeners:a,$store:o}=Ot(e),s={};for(let[e,t]of Object.entries(r))s[`use${At(e)}`]=t;return It({...n,...s,$fetch:i,$store:o},i,t,r,a)}function Rt(e){return{success:!1,error:`You are not allowed to access resource: ${e}`}}function zt(e){return{success:!1,error:`unauthorized to access resource "${e}"`}}function Bt(e){return e===`OR`?`OR`:`AND`}function Vt(e){return Array.isArray(e)}function Ht(e){if(Vt(e))return{actions:e,connector:`AND`};if(!e||typeof e!=`object`)throw new we(`Invalid access control request`);let{actions:t,connector:n}=e;return Vt(t)?{actions:t,connector:Bt(n)}:{actions:[],connector:Bt(n)}}function Ut(e,t){return typeof t==`string`&&e.includes(t)}function Wt(e,{actions:t,connector:n}){return t.length===0?!1:n===`OR`?t.some(t=>Ut(e,t)):t.every(t=>Ut(e,t))}function Gt(e){return{authorize(t,n=`AND`){let r=!1;for(let[i,a]of Object.entries(t)){let t=e[i];if(!t){if(n===`AND`)return Rt(i);continue}let o=Wt(t,Ht(a));if(o&&(r=!0),o&&n===`OR`)return{success:!0};if(!o&&n===`AND`)return zt(i)}return r?{success:!0}:{success:!1,error:`Not authorized`}},statements:e}}function Kt(e){return{newRole(e){return Gt(e)},statements:e}}var qt=ye({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`,EMAIL_VERIFICATION_REQUIRED_FOR_INVITATION:`Email verification required to view or list invitations for the session email`,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`,INVALID_TEAM_ID:`Team id contains a reserved character`}),Jt=Kt({organization:[`update`,`delete`],member:[`create`,`update`,`delete`],invitation:[`create`,`cancel`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),Yt=Jt.newRole({organization:[`update`],invitation:[`create`,`cancel`],member:[`create`,`update`,`delete`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),Xt=Jt.newRole({organization:[`update`,`delete`],member:[`create`,`update`,`delete`],invitation:[`create`,`cancel`],team:[`create`,`update`,`delete`],ac:[`create`,`read`,`update`,`delete`]}),Zt=Jt.newRole({organization:[],member:[],invitation:[],team:[],ac:[`read`]}),Qt={admin:Yt,owner:Xt,member:Zt},$t=(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},en=e=>$t(e,e.options.roles||Qt),tn=e=>{let t=O(!1),n=O(!1),r=O(!1),i=O(!1),a={admin:Yt,member:Zt,owner:Xt,...e?.roles};return{id:`organization`,version:v,$InferServerPlugin:{},getActions:(t,n,r)=>({$Infer:{ActiveOrganization:{},Organization:{},Invitation:{},Member:{},Team:{}},organization:{checkRolePermission:t=>en({role:t.role,options:{ac:e?.ac,roles:a},permissions:t.permissions})}}),getAtoms:e=>{let a=me(t,`/organization/list`,e,{method:`GET`}),o=me([n],`/organization/get-full-organization`,e,()=>({method:`GET`})),s=me([n,r],`/organization/get-active-member`,e,{method:`GET`}),c=me([n,i],`/organization/get-active-member-role`,e,{method:`GET`});return{$listOrg:t,$activeOrgSignal:n,$activeMemberSignal:r,$activeMemberRoleSignal:i,activeOrganization:o,listOrganizations:a,activeMember:s,activeMemberRole:c}},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===`/sign-out`||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:qt}},nn=ye({OTP_NOT_ENABLED:`OTP not enabled`,OTP_HAS_EXPIRED:`OTP has expired`,TOTP_NOT_ENABLED:`TOTP not enabled`,TWO_FACTOR_NOT_ENABLED:`Two factor isn't enabled`,BACKUP_CODES_NOT_ENABLED:`Backup codes aren't enabled`,INVALID_BACKUP_CODE:`Invalid backup code`,INVALID_CODE:`Invalid code`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many attempts. Please request a new code.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many failed verification attempts. Your account is temporarily locked. Please try again later.`,INVALID_TWO_FACTOR_COOKIE:`Invalid two factor cookie`}),rn=e=>({id:`two-factor`,version:v,$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith(`/two-factor/`),signal:`$sessionSignal`}],pathMethods:{"/two-factor/disable":`POST`,"/two-factor/enable":`POST`,"/two-factor/send-otp":`POST`,"/two-factor/generate-backup-codes":`POST`,"/two-factor/get-totp-uri":`POST`,"/two-factor/verify-totp":`POST`,"/two-factor/verify-otp":`POST`,"/two-factor/verify-backup-code":`POST`},fetchPlugins:[{id:`two-factor`,name:`two-factor`,hooks:{async onSuccess(t){if(t.data?.twoFactorRedirect){if(e?.onTwoFactorRedirect){await e.onTwoFactorRedirect({twoFactorMethods:t.data.twoFactorMethods});return}e?.twoFactorPage&&typeof window<`u`&&Pe(e.twoFactorPage)&&(window.location.href=e.twoFactorPage)}}}}],$ERROR_CODES:nn}),an=`auth-session-token`,J={_memoryToken:null,get(){try{if(typeof localStorage<`u`)return localStorage.getItem(an)}catch{}return this._memoryToken},set(e){this._memoryToken=e;try{typeof localStorage<`u`&&localStorage.setItem(an,e)}catch{}},clear(){this._memoryToken=null;try{typeof localStorage<`u`&&localStorage.removeItem(an)}catch{}}};function on(e){let t=Error(e.message??`Auth request failed with status ${e.status}`);return e.code&&(t.code=e.code),t}function sn(e){try{let t=new URL(e);return{origin:t.origin,basePath:t.pathname.replace(/\/$/,``)}}catch{return{origin:cn()??`http://localhost`,basePath:e.replace(/\/$/,``)}}}function cn(){try{if(typeof window<`u`&&window.location?.origin)return window.location.origin}catch{}}function ln(){try{if(typeof document<`u`){let e=document.querySelector(`base`)?.getAttribute(`href`);if(e)return`${new URL(e,cn()??`http://localhost`).pathname.replace(/\/$/,``)}/reset-password`}}catch{}return`/reset-password`}function un(e){let t=e||globalThis.fetch.bind(globalThis);return async(e,n)=>{let r=new Headers(n?.headers),i=J.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&&J.set(o),a}}function dn(e){let{baseURL:t,fetchFn:n}=e,{origin:r,basePath:i}=sn(t),a=un(n),o=Lt({baseURL:r,basePath:i,disableDefaultFetchPlugins:!0,fetchOptions:{customFetchImpl:a},plugins:[tn(),rn()]});async function s(e,t){let n=await a(`${r}${i}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`},credentials:`include`,body:JSON.stringify(t)}),o=await n.json().catch(()=>({}));if(!n.ok){let e=Error(o?.message??`Auth request failed with status ${n.status}`);throw o?.code&&(e.code=o.code),e.status=n.status,e}return o??{}}async function c(e){let t=typeof AbortController<`u`?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),e):void 0;try{let e=`${r}${i}/config`,n=await a(e,{method:`GET`,headers:{"Content-Type":`application/json`},...t?{signal:t.signal}:{}});if(!n.ok)throw Error(`Failed to load auth config (status ${n.status})`);let o=await n.json();return o&&typeof o==`object`&&`data`in o&&o.data?o.data:o}finally{n!==void 0&&clearTimeout(n)}}let l=[500,1500,3500],u=null;async function d(){let e;for(let t=0;t<=l.length;t++)try{return await c(8e3)}catch(n){e=n,t<l.length&&await new Promise(e=>setTimeout(e,l[t]))}throw e instanceof Error?e:Error(String(e))}return{async signIn(e){let{data:t,error:n}=await o.signIn.email({email:e.email,password:e.password});if(n)throw on(n);let r=t;return r.session?.token&&J.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 on(n);let r=t,i=r.token??r.session?.token??null;i&&J.set(i);let a=r.session??null;return!a&&i&&(a={token:i}),{user:r.user,session:a,requiresVerification:i===null}},async sendVerificationEmail(e,t){let{error:n}=await o.sendVerificationEmail({email:e,callbackURL:t});if(n)throw Error(n.message??`Auth request failed with status ${n.status}`)},async signOut(){let{error:e}=await o.signOut();if(J.clear(),e)throw Error(e.message??`Auth request failed with status ${e.status}`)},async getSession(){let e=null;try{let t=await o.getSession();t.error||(e=t.data)}catch{}if(e){let t=e;return t.session?.token&&J.set(t.session.token),{user:t.user,session:t.session}}if(J.get())try{let e=await(n||globalThis.fetch.bind(globalThis))(`${r}${i}/get-session`,{method:`GET`,credentials:`include`,headers:{"Content-Type":`application/json`}});if(e.ok){let t=await e.json().catch(()=>null);if(t?.user&&t?.session)return t.session.token?J.set(t.session.token):J.clear(),{user:t.user,session:t.session};J.clear()}}catch{}return null},async forgotPassword(e){let t=o,n=t.requestPasswordReset??t.forgetPassword;if(typeof n!=`function`)throw Error(`password reset is not available on this auth backend`);let{error:r}=await n({email:e,redirectTo:ln()});if(r)throw Error(r.message??`Auth request failed with status ${r.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 sendPhoneOtp(e){await s(`/phone-number/send-otp`,{phoneNumber:e})},async signInWithPhoneOtp(e,t){let n=await s(`/phone-number/verify`,{phoneNumber:e,code:t}),r=typeof n.token==`string`?n.token:void 0,i=n.user??null;if(!r||!i)throw Error(`No account is registered for this phone number.`);return J.set(r),{user:i,session:{token:r}}},async signInWithPhonePassword(e,t){let n=await s(`/sign-in/phone-number`,{phoneNumber:e,password:t}),r=typeof n.token==`string`?n.token:void 0,i=n.user??null;if(!r||!i)throw Error(`Invalid phone number or password.`);return J.set(r),{user:i,session:{token:r}}},async requestPhonePasswordReset(e){await s(`/phone-number/request-password-reset`,{phoneNumber:e})},async resetPasswordWithPhoneOtp(e,t,n){await s(`/phone-number/reset-password`,{phoneNumber:e,otp:t,newPassword:n})},async changePassword(e,t,n){let r=o.changePassword;if(typeof r!=`function`)throw Error(`change-password is not available on this auth backend`);let{error:i}=await r({currentPassword:e,newPassword:t,...n?.revokeOtherSessions==null?{}:{revokeOtherSessions:n.revokeOtherSessions}});if(i)throw Error(i.message??`Auth request failed with status ${i.status}`)},async enrollTotp(e){let t=o.twoFactor;if(!t||typeof t.enable!=`function`)throw Error(`two-factor enrollment is not available on this auth backend`);let{data:n,error:r}=await t.enable({password:e});if(r)throw Error(r.message??`Two-factor enable failed (${r.status??`?`})`);return{totpURI:n?.totpURI??``,backupCodes:n?.backupCodes??[]}},async verifyTotp(e){let t=o.twoFactor;if(!t||typeof t.verifyTotp!=`function`)throw Error(`two-factor verification is not available on this auth backend`);let{error:n}=await t.verifyTotp({code:e});if(n)throw Error(n.message??`Two-factor verification failed (${n.status??`?`})`)},async setInitialPassword(e){let t=`${r}${i}/set-initial-password`,n=await a(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({newPassword:e})});if(!n.ok){let e=`Set password failed with status ${n.status}`;try{let t=await n.json();t?.error?.message&&(e=t.error.message)}catch{}throw Error(e)}},async hasLocalPassword(){let e=`${r}${i}/list-accounts`;try{let t=await a(e,{method:`GET`,headers:{"Content-Type":`application/json`}});if(!t.ok)return!1;let n=await t.json();return(Array.isArray(n)?n:n&&`data`in n&&Array.isArray(n.data)?n.data:[]).some(e=>e?.providerId===`credential`)}catch{return!1}},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 describeDelegableScope(){try{let e=i.replace(/\/auth$/,`/security`),t=await a(`${r}${e}/my-delegable-scope`,{method:`GET`,headers:{"Content-Type":`application/json`}});if(!t.ok)return null;let n=await t.json(),o=n&&typeof n==`object`&&`data`in n?n.data:n;return o&&typeof o==`object`&&Array.isArray(o.placeableBusinessUnitIds)?o:null}catch{return null}},async getConfig(){return u||=d().catch(e=>{throw u=null,e}),u},async signInWithProvider(e,t={}){let{type:n=`social`,callbackURL:r,errorCallbackURL:i}=t,a=e=>new Promise((t,n)=>{let r=setTimeout(()=>n(Error(`Sign-in timed out — the server did not respond. Please try again.`)),2e4);e.then(e=>{clearTimeout(r),t(e)},e=>{clearTimeout(r),n(e)})}),s=async()=>await a(o.signIn.social({provider:e,callbackURL:r,errorCallbackURL:i})),c;if(n===`oidc`){if(c=await s(),c.error){let t=o.signIn.oauth2,n=t?await a(t({providerId:e,callbackURL:r,errorCallbackURL:i})).catch(()=>null):null;n&&!n.error&&(c=n)}}else c=await s();let{data:l,error:u}=c;if(u)throw Error(u.message??`Auth request failed with status ${u.status}`);if(!l?.url)throw Error(`Sign-in with "${e}" did not return a redirect URL — please try again or contact your administrator.`);typeof window<`u`&&(window.location.href=l.url)},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 getActiveMember(){let e=o.organization?.getActiveMember;if(typeof e!=`function`)return null;let{data:t,error:n}=await e();return n||!t?null:t},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,...e.businessUnitId?{businessUnitId:e.businessUnitId}:{},...e.positions?.length?{positions:e.positions}:{}});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 fn=`auth-active-organization-id`,pn={_memoryValue:null,get(){try{if(typeof localStorage<`u`)return localStorage.getItem(fn)}catch{}return this._memoryValue},set(e){this._memoryValue=e;try{typeof localStorage<`u`&&localStorage.setItem(fn,e)}catch{}},clear(){this._memoryValue=null;try{typeof localStorage<`u`&&localStorage.removeItem(fn)}catch{}}};function mn(e){if(typeof window>`u`||!window.location)return!0;try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!0}}function hn(e){return async(t,n)=>{let r=new Headers(n?.headers),i=typeof t==`string`?t:t instanceof URL?t.href:t.url;if(e?.sameOriginOnly&&mn(i))return fetch(t,n);let a=/\/api\//i.test(i),o=J.get();o&&a&&r.set(`Authorization`,`Bearer ${o}`);let s=pn.get();if(s&&r.set(`X-Tenant-ID`,s),a&&!r.has(`Accept-Language`)&&typeof document<`u`){let e=document.documentElement.lang;e&&r.set(`Accept-Language`,e)}let c=await fetch(t,{...n,headers:r});if(a&&c.status===403)try{let e=g(c.status,await c.clone().json());e&&h.emit(e)}catch{}return c}}var Y=t();function gn({authUrl:e,client:t,onAuthStateChange:n,enabled:r=!0,previewMode:i,children:a}){let o=(0,p.useMemo)(()=>t??dn({baseURL:e}),[t,e]),[s,c]=(0,p.useState)(null),[l,u]=(0,p.useState)(null),[d,f]=(0,p.useState)(!0),[m,g]=(0,p.useState)(null),[v,y]=(0,p.useState)(null),[b,ee]=(0,p.useState)([]),[x,S]=(0,p.useState)(null),[C,w]=(0,p.useState)(null),[T,E]=(0,p.useState)(!1),D=i!=null,O=r&&!D?s!==null&&l!==null:!0;(0,p.useEffect)(()=>{if(D){let e=i.simulatedRole??`admin`,t=i.simulatedUserName??`Preview User`,n=i.expiresInSeconds??0;c({id:`preview-user`,email:`preview@preview.local`,name:t,role:e,roles:[e]}),u({token:`preview-token`,expiresAt:n>0?new Date(Date.now()+n*1e3):new Date(Date.now()+31536e6)}),f(!1);return}if(!r){c({id:`guest`,email:`guest@local`,name:`Guest User`,role:`admin`}),u({token:`guest-token`,expiresAt:new Date(Date.now()+31536e6)}),f(!1);return}let e=!1;async function t(){try{let t=await o.getSession();if(e)return;t&&(c(t.user),u(t.session))}catch(t){if(e)return;g(t instanceof Error?t:Error(String(t)))}finally{e||f(!1)}}return t(),()=>{e=!0}},[o,r,D,i]),(0,p.useEffect)(()=>{n?.({user:s,session:l,isAuthenticated:O,isLoading:d,error:m})},[s,l,O,d,m,n]);let k=(0,p.useCallback)(async(e,t)=>{f(!0),g(null);try{let n=await o.signIn({email:e,password:t});c(n.user),u(n.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{f(!1)}},[o]),A=(0,p.useCallback)(async(e,t,n)=>{f(!0),g(null);try{let r=await o.signUp({name:e,email:t,password:n});return r.requiresVerification?{requiresVerification:!0}:(c(r.user),u(r.session),{requiresVerification:!1})}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{f(!1)}},[o]),j=(0,p.useCallback)(async()=>{f(!0);try{await o.signOut(),c(null),u(null),g(null)}catch(e){g(e instanceof Error?e:Error(String(e)))}finally{f(!1)}},[o]),M=(0,p.useCallback)(async e=>{g(null);try{let t=await o.updateUser(e);c(t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),N=(0,p.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]),P=(0,p.useCallback)(async(e,t)=>{g(null);try{await o.sendVerificationEmail(e,t)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),te=(0,p.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]),ne=(0,p.useCallback)(async e=>{g(null);try{await o.sendPhoneOtp(e)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),F=(0,p.useCallback)(async(e,t)=>{f(!0),g(null);try{let n=await o.signInWithPhoneOtp(e,t);c(n.user),u(n.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{f(!1)}},[o]),I=(0,p.useCallback)(async(e,t)=>{f(!0),g(null);try{let n=await o.signInWithPhonePassword(e,t);c(n.user),u(n.session)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}finally{f(!1)}},[o]),re=(0,p.useCallback)(async e=>{g(null);try{await o.requestPhonePasswordReset(e)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),L=(0,p.useCallback)(async(e,t,n)=>{g(null);try{await o.resetPasswordWithPhoneOtp(e,t,n)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]);(0,p.useEffect)(()=>h.subscribe(e=>{y(t=>t??e)}),[]);let ie=(0,p.useCallback)(e=>o.enrollTotp(e),[o]),ae=(0,p.useCallback)(e=>o.verifyTotp(e),[o]),R=(0,p.useCallback)(async(e,t,n)=>{g(null);try{await o.changePassword(e,t,n)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),oe=(0,p.useCallback)(async e=>{g(null);try{await o.setInitialPassword(e)}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),z=(0,p.useCallback)(()=>o.hasLocalPassword(),[o]),se=(0,p.useCallback)(()=>o.getConfig(),[o]),B=(0,p.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]),V=(0,p.useCallback)(async e=>{if(!(!r||D)){E(!0);try{let t=await o.listOrganizations();if(e?.())return t;if(ee(t),t.length>0&&!x){let n=null;try{n=await o.getActiveOrganization()}catch{n=null}if(!n&&t.length===1)try{n=await o.setActiveOrganization(t[0].id)}catch{n=null}n&&!e?.()&&(S(n),pn.set(n.id))}return t}catch(t){e?.()||console.warn(`[AuthProvider] Failed to load organizations:`,t)}finally{e?.()||E(!1)}}},[o,r,D,x]),ce=(0,p.useCallback)(async()=>{if(!r||D){let e=D?i?.simulatedRole??`admin`:`admin`;w({id:`preview-member`,organizationId:x?.id??`preview-org`,userId:`preview-user`,role:e});return}if(!x){w(null);return}try{let e=await o.getActiveMember();w(e)}catch(e){console.warn(`[AuthProvider] Failed to load active member:`,e),w(null)}},[o,r,D,i,x]);(0,p.useEffect)(()=>{ce()},[ce]),(0,p.useEffect)(()=>{if(!(s&&r&&!D))return;let e=!1;return V(()=>e),()=>{e=!0}},[s,r,D]);let le=(0,p.useCallback)(async e=>{g(null);try{let t=await o.setActiveOrganization(e);S(t),t?pn.set(t.id):pn.clear()}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o]),ue=(0,p.useCallback)(async e=>{g(null);try{let t=await o.createOrganization(e);return await V(),await le(t.id),t}catch(e){let t=e instanceof Error?e:Error(String(e));throw g(t),t}},[o,V,le]),H=(0,p.useCallback)(async(e,t)=>{let n=await o.updateOrganization(e,t);return await V(),x?.id===e&&S(n),n},[o,V,x]),de=(0,p.useCallback)(async e=>{await o.deleteOrganization(e),x?.id===e&&(S(null),pn.clear()),await V()},[o,x,V]),fe=(0,p.useCallback)(async e=>{await o.leaveOrganization(e),x?.id===e&&(S(null),pn.clear()),await V()},[o,x,V]),pe=(0,p.useCallback)(e=>o.getMembers(e),[o]),me=(0,p.useCallback)(e=>o.inviteMember(e),[o]),he=(0,p.useCallback)(()=>o.describeDelegableScope(),[o]),ge=(0,p.useCallback)(e=>o.removeMember(e),[o]),_e=(0,p.useCallback)(e=>o.updateMemberRole(e),[o]),ve=(0,p.useCallback)(e=>o.listInvitations(e),[o]),U=(0,p.useCallback)(e=>o.cancelInvitation(e),[o]),W=(0,p.useCallback)(e=>o.getInvitation(e),[o]),G=(0,p.useCallback)(async e=>{await o.acceptInvitation(e),await V()},[o,V]),ye=(0,p.useCallback)(e=>o.rejectInvitation(e),[o]),be=(0,p.useCallback)(()=>o.listUserInvitations(),[o]),xe=r&&!D,Se=(0,p.useMemo)(()=>({user:s,session:l,isAuthenticated:O,isAuthEnabled:xe,isLoading:d,error:m,isPreviewMode:D,previewMode:D?i:null,signIn:k,signUp:A,signOut:j,updateUser:M,forgotPassword:N,sendVerificationEmail:P,resetPassword:te,sendPhoneOtp:ne,signInWithPhoneOtp:F,signInWithPhonePassword:I,requestPhonePasswordReset:re,resetPasswordWithPhoneOtp:L,changePassword:R,remediationRequired:v,setRemediationRequired:y,enrollTotp:ie,verifyTotp:ae,setInitialPassword:oe,hasLocalPassword:z,getAuthConfig:se,signInWithProvider:B,organizations:b,activeOrganization:x,activeMember:C,isOrganizationsLoading:T,switchOrganization:le,createOrganization:ue,refreshOrganizations:V,updateOrganization:H,deleteOrganization:de,leaveOrganization:fe,getMembers:pe,inviteMember:me,describeDelegableScope:he,removeMember:ge,updateMemberRole:_e,listInvitations:ve,cancelInvitation:U,getInvitation:W,acceptInvitation:G,rejectInvitation:ye,listUserInvitations:be}),[s,l,O,xe,d,m,D,i,k,A,j,M,N,P,te,R,oe,z,se,B,ne,F,I,re,L,v,ie,ae,b,x,C,T,le,ue,V,H,de,fe,pe,me,he,ge,_e,ve,U,W,G,ye,be]);return(0,Y.jsx)(_.Provider,{value:Se,children:a})}function X(){return(0,p.useContext)(_)||{user:null,session:null,isAuthenticated:!1,isAuthEnabled:!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`)},sendVerificationEmail:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},resetPassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},sendPhoneOtp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},signInWithPhoneOtp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},signInWithPhonePassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},requestPhonePasswordReset:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},resetPasswordWithPhoneOtp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},changePassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},remediationRequired:null,setRemediationRequired:()=>{},enrollTotp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},verifyTotp:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},setInitialPassword:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},hasLocalPassword:async()=>!1,getAuthConfig:async()=>({}),describeDelegableScope:async()=>null,signInWithProvider:async()=>{throw Error(`useAuth must be used within an AuthProvider`)},organizations:[],activeOrganization:null,activeMember: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`)}}}var _n=new Set([`owner`,`admin`,`super_admin`,`superadmin`,`platform_admin`,`system_admin`,`org_owner`,`org_admin`]);function vn(e){return typeof e==`string`&&_n.has(e.toLowerCase())}function yn(){let{activeMember:e,user:t}=X();return!!(vn(e?.role)||vn(t?.role)||Array.isArray(t?.roles)&&t.roles.some(vn))}function bn({fallback:e=null,requiredRoles:t,loadingFallback:n,children:r}){let{isAuthenticated:i,isLoading:a,user:o}=X();if(a)return(0,Y.jsx)(Y.Fragment,{children:n??null});if(!i)return(0,Y.jsx)(Y.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,Y.jsx)(Y.Fragment,{children:e})}return(0,Y.jsx)(Y.Fragment,{children:r})}var Z=`flex h-11 w-full rounded-lg border border-input bg-background px-3.5 py-2 text-sm shadow-sm ring-offset-background transition-colors placeholder:text-muted-foreground hover:border-primary/40 focus-visible:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50`,xn=`inline-flex h-11 w-full items-center justify-center gap-2 rounded-lg bg-gradient-to-r from-primary to-primary/85 px-4 py-2 text-sm font-medium text-primary-foreground shadow-sm ring-offset-background transition-[box-shadow,background-color,transform] hover:shadow-md hover:from-primary hover:to-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 active:scale-[0.99] disabled:pointer-events-none disabled:opacity-60 motion-reduce:transition-none motion-reduce:active:transform-none`,Q=`text-sm font-medium leading-none text-foreground`;function $(){return(0,Y.jsxs)(`svg`,{className:`h-4 w-4 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,"aria-hidden":`true`,children:[(0,Y.jsx)(`circle`,{className:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`4`}),(0,Y.jsx)(`path`,{className:`opacity-90`,d:`M4 12a8 8 0 018-8`,stroke:`currentColor`,strokeWidth:`4`,strokeLinecap:`round`})]})}function Sn({className:e}){return(0,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e??`h-4 w-4 shrink-0`,"aria-hidden":`true`,children:[(0,Y.jsx)(`circle`,{cx:`12`,cy:`12`,r:`10`}),(0,Y.jsx)(`line`,{x1:`12`,y1:`8`,x2:`12`,y2:`12`}),(0,Y.jsx)(`line`,{x1:`12`,y1:`16`,x2:`12.01`,y2:`16`})]})}function Cn({className:e}){return(0,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e??`h-7 w-7`,"aria-hidden":`true`,children:[(0,Y.jsx)(`rect`,{x:`2`,y:`4`,width:`20`,height:`16`,rx:`2`}),(0,Y.jsx)(`path`,{d:`m22 6-10 7L2 6`})]})}function wn({icon:e,title:t,description:n}){return(0,Y.jsxs)(`div`,{className:`flex flex-col items-center space-y-3 text-center`,children:[e&&(0,Y.jsx)(`div`,{className:`flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary ring-1 ring-primary/15`,children:e}),(0,Y.jsx)(`h1`,{className:`text-2xl font-semibold tracking-tight text-foreground sm:text-[1.6rem]`,children:t}),n&&(0,Y.jsx)(`p`,{className:`text-sm leading-relaxed text-muted-foreground`,children:n})]})}function Tn({message:e}){return(0,Y.jsxs)(`div`,{className:`flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive`,role:`alert`,children:[(0,Y.jsx)(Sn,{className:`mt-0.5 h-4 w-4 shrink-0`}),(0,Y.jsx)(`span`,{className:`leading-snug`,children:e})]})}var En={google:`Google`,github:`GitHub`,microsoft:`Microsoft`,apple:`Apple`,facebook:`Facebook`,twitter:`Twitter`,discord:`Discord`,gitlab:`GitLab`,linkedin:`LinkedIn`},Dn={google:(0,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Y.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,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:[(0,Y.jsx)(`path`,{fill:`#F25022`,d:`M2 2h9.5v9.5H2z`}),(0,Y.jsx)(`path`,{fill:`#7FBA00`,d:`M12.5 2H22v9.5h-9.5z`}),(0,Y.jsx)(`path`,{fill:`#00A4EF`,d:`M2 12.5h9.5V22H2z`}),(0,Y.jsx)(`path`,{fill:`#FFB900`,d:`M12.5 12.5H22V22h-9.5z`})]}),apple:(0,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4 fill-current`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,className:`h-4 w-4`,"aria-hidden":`true`,children:(0,Y.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 On({id:e}){let t=Dn[e];return t?(0,Y.jsx)(`span`,{className:`mr-2 flex h-4 w-4 items-center justify-center`,children:t}):(0,Y.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 kn({mode:e=`sign-in`,callbackURL:t,errorCallbackURL:n,dividerText:r=`or continue with email`,onProvidersResolved:i}){let{getAuthConfig:a,signInWithProvider:o}=X(),[s,c]=(0,p.useState)([]),[l,u]=(0,p.useState)(!0),[d,f]=(0,p.useState)(null),[m,h]=(0,p.useState)(null);if((0,p.useEffect)(()=>{let e=!1;return Promise.resolve().then(()=>a()).then(t=>{if(e)return;let n=(t?.socialProviders??[]).filter(e=>e.enabled);c(n),i?.(n.length>0)}).catch(t=>{e||(console.warn(`[SocialSignInButtons] failed to load auth config`,t),i?.(!1))}).finally(()=>{e||u(!1)}),()=>{e=!0}},[a]),l||s.length===0)return null;let g=e===`sign-in`?`Continue with`:`Sign up with`,_=typeof window<`u`?window.location.href:void 0,v=async e=>{if(!m){f(null),h(e.id);try{await o(e.id,{callbackURL:t??_,errorCallbackURL:n??t??_,type:e.type??`social`})}catch(e){f(e instanceof Error?e.message:String(e)),h(null)}}};return(0,Y.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[d&&(0,Y.jsx)(`div`,{className:`rounded-md bg-destructive/15 p-3 text-sm text-destructive`,role:`alert`,children:d}),s.map(e=>(0,Y.jsxs)(`button`,{type:`button`,onClick:()=>v(e),disabled:m!==null,"aria-busy":m===e.id,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:[m===e.id?(0,Y.jsx)($,{}):(0,Y.jsx)(On,{id:e.id}),g,` `,En[e.id]??e.name]},e.id)),(0,Y.jsxs)(`div`,{className:`relative my-1`,children:[(0,Y.jsx)(`div`,{className:`absolute inset-0 flex items-center`,children:(0,Y.jsx)(`span`,{className:`w-full border-t`})}),(0,Y.jsx)(`div`,{className:`relative flex justify-center text-xs uppercase`,children:(0,Y.jsx)(`span`,{className:`bg-background px-2 text-muted-foreground`,children:r})})]})]})}function An(e){let t=String(e??``).replace(/[\s\-().]/g,``);return/^\+?[0-9]{6,15}$/.test(t)?t:null}function jn(e){return typeof e!=`string`||e.includes(`@`)?!1:An(e)!==null}var Mn=({href:e,className:t,children:n})=>(0,Y.jsx)(`a`,{href:e,className:t,children:n}),Nn=()=>(0,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`h-6 w-6`,"aria-hidden":`true`,children:[(0,Y.jsx)(`rect`,{x:`3`,y:`11`,width:`18`,height:`11`,rx:`2`}),(0,Y.jsx)(`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`})]});function Pn({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`,icon:o,hideIcon:s=!1,linkComponent:c=Mn,labels:l={},errorMessages:u}){let{signIn:d,isLoading:f,getAuthConfig:m,sendPhoneOtp:h,signInWithPhoneOtp:g,signInWithPhonePassword:_}=X(),[v,y]=(0,p.useState)(``),[b,ee]=(0,p.useState)(``),[x,S]=(0,p.useState)(null),[C,w]=(0,p.useState)(!1),[T,E]=(0,p.useState)(!1),[D,O]=(0,p.useState)(`password`),[k,A]=(0,p.useState)(``),[j,M]=(0,p.useState)(``),[N,P]=(0,p.useState)(!1),[te,ne]=(0,p.useState)(!1),[F,I]=(0,p.useState)(0),[re,L]=(0,p.useState)(!1),[ie,ae]=(0,p.useState)(!1),[R,oe]=(0,p.useState)(!1),[z,se]=(0,p.useState)(!1),[B,V]=(0,p.useState)(!1),[ce,le]=(0,p.useState)(!0);(0,p.useEffect)(()=>{let e=!1;return Promise.resolve().then(()=>m()).then(t=>{e||(ae(t?.features?.sso===!0),w(t?.features?.phoneNumberOtp===!0),E(t?.features?.phoneNumber===!0),oe(t?.features?.ssoEnforced===!0||t?.emailPassword?.enabled===!1))}).catch(()=>{}).finally(()=>{e||le(!1)}),()=>{e=!0}},[m]);let ue=!R||z,H={emailLabel:l.emailLabel??`Email`,emailPlaceholder:l.emailPlaceholder??`name@example.com`,emailOrPhoneLabel:l.emailOrPhoneLabel??`Email or phone number`,emailOrPhonePlaceholder:l.emailOrPhonePlaceholder??`name@example.com or +1 555 000 0000`,passwordLabel:l.passwordLabel??`Password`,passwordPlaceholder:l.passwordPlaceholder??`Enter your password`,forgotPasswordText:l.forgotPasswordText??`Forgot password?`,submitButton:l.submitButton??`Sign In`,submittingButton:l.submittingButton??`Signing in…`,noAccountText:l.noAccountText??`Don't have an account?`,signUpText:l.signUpText??`Sign up`,orText:l.orText??`or`,ssoButton:l.ssoButton??`Sign in with SSO`,usePasswordText:l.usePasswordText??`Use a password instead`,backToSsoText:l.backToSsoText??`Back to single sign-on`,ssoOnlyDescription:l.ssoOnlyDescription??`Sign in with your organization's single sign-on`,phoneLabel:l.phoneLabel??`Phone number`,phonePlaceholder:l.phonePlaceholder??`+1 555 000 0000`,otpCodeLabel:l.otpCodeLabel??`Verification code`,otpCodePlaceholder:l.otpCodePlaceholder??`6-digit code`,sendOtpButton:l.sendOtpButton??`Get code`,resendOtpCountdownText:l.resendOtpCountdownText??`Resend in {seconds}s`,usePhoneOtpText:l.usePhoneOtpText??`Sign in with verification code`,usePasswordSignInText:l.usePasswordSignInText??`Sign in with password instead`};(0,p.useEffect)(()=>{if(F<=0)return;let e=setTimeout(()=>I(e=>e>1?e-1:0),1e3);return()=>clearTimeout(e)},[F]);let de=async n=>{n.preventDefault(),S(null);let r=v.trim();try{D===`phone-otp`?await g(k.trim(),j.trim()):T&&jn(r)?await _(An(r)??r,b):await d(r,b),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e)),r=n.code;S(r&&u?.[r]||n.message),t?.(n)}},fe=async()=>{if(!(!k.trim()||N||F>0)){S(null),P(!0);try{await h(k.trim()),ne(!0),I(60)}catch(e){let n=e instanceof Error?e:Error(String(e)),r=n.code;S(r&&u?.[r]||n.message),t?.(n)}finally{P(!1)}}},pe=e=>{O(e),S(null)};return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:s?void 0:o??(0,Y.jsx)(Nn,{}),title:i,description:R&&!z?H.ssoOnlyDescription:a}),(0,Y.jsx)(`div`,{className:`space-y-5`,children:ce?(0,Y.jsx)(`div`,{className:`flex justify-center py-10`,role:`status`,"aria-live":`polite`,"data-testid":`login-config-loading`,children:(0,Y.jsx)($,{})}):(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)(kn,{mode:`sign-in`,onProvidersResolved:e=>L(e)}),ue?D===`phone-otp`?(0,Y.jsxs)(`form`,{onSubmit:de,className:`space-y-4`,children:[x&&(0,Y.jsx)(Tn,{message:x}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`login-phone`,className:Q,children:H.phoneLabel}),(0,Y.jsx)(`input`,{id:`login-phone`,type:`tel`,placeholder:H.phonePlaceholder,value:k,onChange:e=>A(e.target.value),required:!0,autoComplete:`tel`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`login-otp`,className:Q,children:H.otpCodeLabel}),(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{id:`login-otp`,type:`text`,inputMode:`numeric`,placeholder:H.otpCodePlaceholder,value:j,onChange:e=>M(e.target.value),required:!0,autoComplete:`one-time-code`,disabled:f,className:Z}),(0,Y.jsxs)(`button`,{type:`button`,onClick:fe,disabled:N||F>0||!k.trim()||f,className:`shrink-0 rounded-md border border-input bg-background px-3 py-2 text-sm font-medium transition-colors hover:bg-accent disabled:opacity-50`,children:[N&&(0,Y.jsx)($,{}),F>0?H.resendOtpCountdownText.replace(`{seconds}`,String(F)):H.sendOtpButton]})]})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:f||!te,className:xn,children:[f&&(0,Y.jsx)($,{}),f?H.submittingButton:H.submitButton]}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>pe(`password`),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.usePasswordSignInText})]}):(0,Y.jsxs)(`form`,{onSubmit:de,className:`space-y-4`,children:[x&&(0,Y.jsx)(Tn,{message:x}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`login-email`,className:Q,children:T?H.emailOrPhoneLabel:H.emailLabel}),(0,Y.jsx)(`input`,{id:`login-email`,type:T?`text`:`email`,inputMode:T?`text`:`email`,placeholder:T?H.emailOrPhonePlaceholder:H.emailPlaceholder,value:v,onChange:e=>y(e.target.value),required:!0,autoComplete:`username`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,Y.jsx)(`label`,{htmlFor:`login-password`,className:Q,children:H.passwordLabel}),r&&(0,Y.jsx)(c,{href:r,className:`text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.forgotPasswordText})]}),(0,Y.jsx)(`input`,{id:`login-password`,type:`password`,placeholder:H.passwordPlaceholder,value:b,onChange:e=>ee(e.target.value),required:!0,autoComplete:`current-password`,disabled:f,className:Z})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:f,className:xn,children:[f&&(0,Y.jsx)($,{}),f?H.submittingButton:H.submitButton]}),ie&&(0,Y.jsxs)(`button`,{type:`button`,onClick:async()=>{if(B)return;S(null);let e=v.trim();if(jn(e)){S(`Enter your email address to sign in with SSO.`);return}V(!0);try{let t=window.location.pathname.replace(/\/login(?:\/.*)?$/,``),n=await fetch(`/api/v1/auth/sign-in/sso`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:e,callbackURL:t+`/home`}),credentials:`include`}),r=await n.json().catch(()=>({}));if(n.ok&&typeof r.url==`string`){window.location.href=r.url;return}S(r.message||`No SSO provider is configured for this email domain.`),V(!1)}catch(e){S(e instanceof Error?e.message:String(e)),V(!1)}},disabled:f||B,"aria-busy":B,className:`flex w-full items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent disabled:opacity-50`,children:[B&&(0,Y.jsx)($,{}),H.ssoButton]}),C&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>pe(`phone-otp`),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.usePhoneOtpText}),R&&z&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>se(!1),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.backToSsoText})]}):(0,Y.jsxs)(`div`,{className:`space-y-4`,children:[x&&(0,Y.jsx)(Tn,{message:x}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>se(!0),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:H.usePasswordText})]})]})}),n&&!R&&(0,Y.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[H.noAccountText,` `,(0,Y.jsx)(c,{href:n,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:H.signUpText})]})]})}var Fn=({href:e,className:t,children:n})=>(0,Y.jsx)(`a`,{href:e,className:t,children:n}),In=()=>(0,Y.jsxs)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`h-6 w-6`,"aria-hidden":`true`,children:[(0,Y.jsx)(`path`,{d:`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`}),(0,Y.jsx)(`circle`,{cx:`9`,cy:`7`,r:`4`}),(0,Y.jsx)(`line`,{x1:`19`,y1:`8`,x2:`19`,y2:`14`}),(0,Y.jsx)(`line`,{x1:`22`,y1:`11`,x2:`16`,y2:`11`})]});function Ln({onSuccess:e,onVerificationRequired:t,onError:n,loginUrl:r=`/login`,title:i=`Create an account`,description:a=`Enter your information to get started`,icon:o,hideIcon:s=!1,linkComponent:c=Fn,labels:l={},errorMessages:u}){let{signUp:d,isLoading:f}=X(),[m,h]=(0,p.useState)(``),[g,_]=(0,p.useState)(``),[v,y]=(0,p.useState)(``),[b,ee]=(0,p.useState)(``),[x,S]=(0,p.useState)(null),C={nameLabel:l.nameLabel??`Name`,namePlaceholder:l.namePlaceholder??`John Doe`,emailLabel:l.emailLabel??`Email`,emailPlaceholder:l.emailPlaceholder??`name@example.com`,passwordLabel:l.passwordLabel??`Password`,passwordPlaceholder:l.passwordPlaceholder??`Create a password (min. 8 characters)`,confirmPasswordLabel:l.confirmPasswordLabel??`Confirm Password`,confirmPasswordPlaceholder:l.confirmPasswordPlaceholder??`Confirm your password`,passwordMismatchError:l.passwordMismatchError??`Passwords do not match`,passwordTooShortError:l.passwordTooShortError??`Password must be at least 8 characters`,submitButton:l.submitButton??`Create Account`,submittingButton:l.submittingButton??`Creating account…`,hasAccountText:l.hasAccountText??`Already have an account?`,signInText:l.signInText??`Sign in`,orText:l.orText??`or`};return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:s?void 0:o??(0,Y.jsx)(In,{}),title:i,description:a}),(0,Y.jsxs)(`div`,{className:`space-y-5`,children:[(0,Y.jsx)(kn,{mode:`sign-up`}),(0,Y.jsxs)(`form`,{onSubmit:async r=>{if(r.preventDefault(),S(null),v!==b){S(C.passwordMismatchError);return}if(v.length<8){S(C.passwordTooShortError);return}let i=g.trim();try{if((await d(m,i,v))?.requiresVerification){t?.(i);return}e?.()}catch(e){let t=e instanceof Error?e:Error(String(e)),r=t.code;S(r&&u?.[r]||t.message),n?.(t)}},className:`space-y-4`,children:[x&&(0,Y.jsx)(Tn,{message:x}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`register-name`,className:Q,children:C.nameLabel}),(0,Y.jsx)(`input`,{id:`register-name`,type:`text`,placeholder:C.namePlaceholder,value:m,onChange:e=>h(e.target.value),required:!0,autoComplete:`name`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`register-email`,className:Q,children:C.emailLabel}),(0,Y.jsx)(`input`,{id:`register-email`,type:`email`,placeholder:C.emailPlaceholder,value:g,onChange:e=>_(e.target.value),required:!0,autoComplete:`email`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`register-password`,className:Q,children:C.passwordLabel}),(0,Y.jsx)(`input`,{id:`register-password`,type:`password`,placeholder:C.passwordPlaceholder,value:v,onChange:e=>y(e.target.value),required:!0,minLength:8,autoComplete:`new-password`,disabled:f,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`register-confirm-password`,className:Q,children:C.confirmPasswordLabel}),(0,Y.jsx)(`input`,{id:`register-confirm-password`,type:`password`,placeholder:C.confirmPasswordPlaceholder,value:b,onChange:e=>ee(e.target.value),required:!0,minLength:8,autoComplete:`new-password`,disabled:f,className:Z})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:f,className:xn,children:[f&&(0,Y.jsx)($,{}),f?C.submittingButton:C.submitButton]})]})]}),r&&(0,Y.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[C.hasAccountText,` `,(0,Y.jsx)(c,{href:r,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:C.signInText})]})]})}var Rn=({href:e,className:t,children:n})=>(0,Y.jsx)(`a`,{href:e,className:t,children:n}),zn=()=>(0,Y.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.75`,strokeLinecap:`round`,strokeLinejoin:`round`,className:`h-6 w-6`,"aria-hidden":`true`,children:(0,Y.jsx)(`path`,{d:`M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4`})});function Bn({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`,icon:a,hideIcon:o=!1,linkComponent:s=Rn,labels:c={}}){let{forgotPassword:l,isLoading:u,getAuthConfig:d,requestPhonePasswordReset:f,resetPasswordWithPhoneOtp:m}=X(),[h,g]=(0,p.useState)(``),[_,v]=(0,p.useState)(null),[y,b]=(0,p.useState)(!1),[ee,x]=(0,p.useState)(!1),[S,C]=(0,p.useState)(`email`),[w,T]=(0,p.useState)(``),[E,D]=(0,p.useState)(``),[O,k]=(0,p.useState)(``),[A,j]=(0,p.useState)(!1),[M,N]=(0,p.useState)(!1),[P,te]=(0,p.useState)(0),[ne,F]=(0,p.useState)(!1),[I,re]=(0,p.useState)(!1);(0,p.useEffect)(()=>{let e=!1;return Promise.resolve().then(()=>d()).then(t=>{e||x(t?.features?.phoneNumberOtp===!0)}).catch(()=>{}),()=>{e=!0}},[d]),(0,p.useEffect)(()=>{if(P<=0)return;let e=setTimeout(()=>te(e=>e>1?e-1:0),1e3);return()=>clearTimeout(e)},[P]);let L={emailLabel:c.emailLabel??`Email`,emailPlaceholder:c.emailPlaceholder??`name@example.com`,submitButton:c.submitButton??`Send Reset Link`,submittingButton:c.submittingButton??`Sending…`,successTitle:c.successTitle??`Check your email`,successDescription:c.successDescription??`We've sent a password reset link to {{email}}. Please check your inbox.`,backToSignInText:c.backToSignInText??`Back to sign in`,rememberPasswordText:c.rememberPasswordText??`Remember your password?`,signInText:c.signInText??`Sign in`,phoneLabel:c.phoneLabel??`Phone number`,phonePlaceholder:c.phonePlaceholder??`+1 555 000 0000`,otpCodeLabel:c.otpCodeLabel??`Verification code`,otpCodePlaceholder:c.otpCodePlaceholder??`6-digit code`,sendOtpButton:c.sendOtpButton??`Get code`,resendOtpCountdownText:c.resendOtpCountdownText??`Resend in {seconds}s`,newPasswordLabel:c.newPasswordLabel??`New password`,newPasswordPlaceholder:c.newPasswordPlaceholder??`Enter a new password`,resetButton:c.resetButton??`Reset Password`,usePhoneResetText:c.usePhoneResetText??`Reset via SMS code`,useEmailResetText:c.useEmailResetText??`Reset via email instead`,phoneSuccessTitle:c.phoneSuccessTitle??`Password reset`,phoneSuccessDescription:c.phoneSuccessDescription??`Your password has been reset. You can now sign in with your new password.`},ie=async n=>{n.preventDefault(),v(null);try{await l(h.trim()),b(!0),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));v(n.message),t?.(n)}},ae=async()=>{if(!(!w.trim()||A||P>0)){v(null),j(!0);try{await f(w.trim()),N(!0),te(60)}catch(e){let n=e instanceof Error?e:Error(String(e));v(n.message),t?.(n)}finally{j(!1)}}},R=async n=>{n.preventDefault(),v(null),re(!0);try{await m(w.trim(),E.trim(),O),F(!0),e?.()}catch(e){let n=e instanceof Error?e:Error(String(e));v(n.message),t?.(n)}finally{re(!1)}},oe=e=>{C(e),v(null)};if(ne)return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:(0,Y.jsx)(`span`,{className:`flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-500/10 text-emerald-600 ring-1 ring-emerald-500/15 dark:text-emerald-400`,children:(0,Y.jsx)(Cn,{})}),title:L.phoneSuccessTitle,description:L.phoneSuccessDescription}),n&&(0,Y.jsx)(`p`,{className:`text-center text-sm text-muted-foreground`,children:(0,Y.jsxs)(s,{href:n,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:[`← `,L.backToSignInText]})})]});if(y){let e=L.successDescription.includes(`{{email}}`)?L.successDescription.replace(`{{email}}`,h):`${L.successDescription} ${h}`;return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:(0,Y.jsx)(`span`,{className:`flex h-12 w-12 items-center justify-center rounded-2xl bg-emerald-500/10 text-emerald-600 ring-1 ring-emerald-500/15 dark:text-emerald-400`,children:(0,Y.jsx)(Cn,{})}),title:L.successTitle,description:e}),n&&(0,Y.jsx)(`p`,{className:`text-center text-sm text-muted-foreground`,children:(0,Y.jsxs)(s,{href:n,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:[`← `,L.backToSignInText]})})]})}return(0,Y.jsxs)(`div`,{className:`mx-auto flex w-full flex-col justify-center space-y-7 sm:w-[400px]`,children:[(0,Y.jsx)(wn,{icon:o?void 0:a??(0,Y.jsx)(zn,{}),title:r,description:i}),S===`phone`?(0,Y.jsxs)(`form`,{onSubmit:R,className:`space-y-4`,children:[_&&(0,Y.jsx)(Tn,{message:_}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`forgot-phone`,className:Q,children:L.phoneLabel}),(0,Y.jsx)(`input`,{id:`forgot-phone`,type:`tel`,placeholder:L.phonePlaceholder,value:w,onChange:e=>T(e.target.value),required:!0,autoComplete:`tel`,disabled:I,className:Z})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`forgot-otp`,className:Q,children:L.otpCodeLabel}),(0,Y.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Y.jsx)(`input`,{id:`forgot-otp`,type:`text`,inputMode:`numeric`,placeholder:L.otpCodePlaceholder,value:E,onChange:e=>D(e.target.value),required:!0,autoComplete:`one-time-code`,disabled:I,className:Z}),(0,Y.jsxs)(`button`,{type:`button`,onClick:ae,disabled:A||P>0||!w.trim()||I,className:`shrink-0 rounded-md border border-input bg-background px-3 py-2 text-sm font-medium transition-colors hover:bg-accent disabled:opacity-50`,children:[A&&(0,Y.jsx)($,{}),P>0?L.resendOtpCountdownText.replace(`{seconds}`,String(P)):L.sendOtpButton]})]})]}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`forgot-new-password`,className:Q,children:L.newPasswordLabel}),(0,Y.jsx)(`input`,{id:`forgot-new-password`,type:`password`,placeholder:L.newPasswordPlaceholder,value:O,onChange:e=>k(e.target.value),required:!0,autoComplete:`new-password`,disabled:I,className:Z})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:I||!M,className:xn,children:[I&&(0,Y.jsx)($,{}),I?L.submittingButton:L.resetButton]}),(0,Y.jsx)(`button`,{type:`button`,onClick:()=>oe(`email`),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:L.useEmailResetText})]}):(0,Y.jsxs)(`form`,{onSubmit:ie,className:`space-y-4`,children:[_&&(0,Y.jsx)(Tn,{message:_}),(0,Y.jsxs)(`div`,{className:`space-y-2`,children:[(0,Y.jsx)(`label`,{htmlFor:`forgot-email`,className:Q,children:L.emailLabel}),(0,Y.jsx)(`input`,{id:`forgot-email`,type:`email`,placeholder:L.emailPlaceholder,value:h,onChange:e=>g(e.target.value),required:!0,autoComplete:`email`,disabled:u,className:Z})]}),(0,Y.jsxs)(`button`,{type:`submit`,disabled:u,className:xn,children:[u&&(0,Y.jsx)($,{}),u?L.submittingButton:L.submitButton]}),ee&&(0,Y.jsx)(`button`,{type:`button`,onClick:()=>oe(`phone`),className:`w-full text-center text-xs text-muted-foreground underline-offset-4 transition-colors hover:text-primary hover:underline`,children:L.usePhoneResetText})]}),n&&(0,Y.jsxs)(`p`,{className:`px-8 text-center text-sm text-muted-foreground`,children:[L.rememberPasswordText,` `,(0,Y.jsx)(s,{href:n,className:`font-medium text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:underline`,children:L.signInText})]})]})}function Vn(e){return e?e.name?e.name.split(` `).map(e=>e[0]).join(``).toUpperCase().slice(0,2):e.email?.[0]?.toUpperCase()??`?`:`?`}var Hn=[...o],Un={[i]:{key:`organization.roles.owner`,defaultValue:`Owner`},[r]:{key:`organization.roles.admin`,defaultValue:`Admin`},[a]:{key:`organization.roles.delegatedAdmin`,defaultValue:`Delegated Admin`},[s]:{key:`organization.roles.member`,defaultValue:`Member`}},Wn=0,Gn=1,Kn=2,qn=3;function Jn(e){if(typeof e!=`string`)return Wn;let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);if(t.length===0)return Wn;let n=Gn;for(let e of t)e===`owner`?n=Math.max(n,qn):e===`admin`&&(n=Math.max(n,Kn));return n}function Yn(e){let t=Jn(e);return t<Kn?[s]:Hn.filter(e=>Jn(e)<=t)}function Xn(e,t){let n=Jn(e);if(n<Kn)return[];let r=n>=qn;return!r&&Jn(t)>=qn?[]:Hn.filter(e=>e!==`owner`||r)}function Zn(e,t=`en`){let n=e instanceof Date?e:new Date(e),r=new Date,i=n.getTime()-r.getTime(),a=Math.round(i/1e3),o=Math.round(a/60),s=Math.round(o/60),c=Math.round(s/24),l=new Intl.RelativeTimeFormat(t,{numeric:`auto`});if(Math.abs(a)<60)return l.format(a,`second`);if(Math.abs(o)<60)return l.format(o,`minute`);if(Math.abs(s)<24)return l.format(s,`hour`);if(Math.abs(c)<30)return l.format(c,`day`);let u=Math.round(c/30);return Math.abs(u)<12?l.format(u,`month`):l.format(Math.round(c/365),`year`)}function Qn(e){if(!e)return!1;let t=e.objects;if(!t||typeof t!=`object`||Array.isArray(t))return!1;for(let e of Object.values(t))if(e&&typeof e==`object`&&!Array.isArray(e)&&`fields`in e)return!0;return!1}var $n=[`apps`,`messages`,`validationMessages`,`dashboards`,`globalActions`];function er(e){let t={},n={},r={},i=e.objects;if(i)for(let[e,a]of Object.entries(i)){if(!a||typeof a!=`object`)continue;let i={};a.label&&(i.label=a.label),a.pluralLabel&&(i.pluralLabel=a.pluralLabel),a.description&&(i.description=a.description);for(let[e,t]of Object.entries(a))e.startsWith(`_`)&&(i[e]=t);if(t[e]=i,a.fields&&typeof a.fields==`object`){let t=Object.entries(a.fields);for(let[i,a]of t)a?.label&&(n[e]||(n[e]={}),n[e][i]=a.label),a?.options&&typeof a.options==`object`&&Object.keys(a.options).length>0&&(r[e]||(r[e]={}),r[e][i]=a.options)}}let a={};Object.keys(t).length>0&&(a.objects=t),Object.keys(n).length>0&&(a.fields=n),Object.keys(r).length>0&&(a.fieldOptions=r);for(let t of $n)e[t]!==void 0&&(a[t]=e[t]);let o=new Set([`objects`,...$n]);for(let[t,n]of Object.entries(e))o.has(t)||(a[t]=n);return{app:a}}var tr=(0,p.createContext)(null);tr.displayName=`PermissionContext`;var nr=`/api/v1/auth/me/permissions`;function rr({endpoint:e=nr,fetcher:t,initialPermissions:n,loadingFallback:r=null,errorFallback:i,maxRetries:a=3,retryBaseDelayMs:o=500,children:s}){let[m,h]=(0,p.useState)(n??null),[g,_]=(0,p.useState)(null),[v,y]=(0,p.useState)(!n),b=(0,p.useCallback)(async n=>{let r=()=>!n?.cancelled;y(!0),_(null);let i=t??fetch,s=Math.max(0,a)+1;for(let t=0;t<s;t++)try{let t=await i(e,{credentials:`include`,headers:{Accept:`application/json`}});if(!t.ok)throw new c(t.status,l(t),`Permissions endpoint returned ${t.status}`);let n=await t.json();if(!r())return;h(n),y(!1);return}catch(e){let n=e instanceof Error?e:Error(String(e));if(!f(n)||t===s-1){if(!r())return;_(n),y(!1);return}let i=n instanceof c?n.retryAfterMs:void 0;if(await u(d(t,o,i)),!r())return}},[e,t,a,o]),ee=(0,p.useCallback)(()=>{b()},[b]);(0,p.useEffect)(()=>{if(n)return;let e={cancelled:!1};return b(e),()=>{e.cancelled=!0}},[b,n]);let x=(0,p.useCallback)((e,t,n)=>{if(!m)return!1;let r=(e??``).toLowerCase(),i=`${r}.${t}`,a=m.fields?.[i]??m.fields?.[`${e}.${t}`];if(a)return n===`read`?a.readable!==!1:a.editable!==!1;let o=m.objects?.[r]??m.objects?.[e]??m.objects?.[`*`];return o?n===`read`?o.allowRead!==!1:o.allowEdit!==!1:m.authenticated!==!0},[m]),S=(0,p.useCallback)((e,t)=>{if(!m)return{allowed:!1,reason:`permissions-loading`};let n=m.objects?.[e]??m.objects?.[`*`],r={read:`allowRead`,view:`allowRead`,create:`allowCreate`,update:`allowEdit`,edit:`allowEdit`,delete:`allowDelete`,import:`allowCreate`,export:`allowRead`}[t]??`allowRead`,i=n?n[r]!==!1:m.authenticated!==!0;return{allowed:i,reason:i?void 0:`denied-by-permission-set`}},[m]),C=(0,p.useCallback)(e=>{if(!m)return[];let t=`${e}.`,n=[];for(let[e,r]of Object.entries(m.fields??{})){if(!e.startsWith(t))continue;let i=e.slice(t.length);n.push({field:i,read:r.readable!==!1,write:r.editable!==!1})}return n},[m]),w=(0,p.useCallback)(()=>void 0,[]),T=(0,p.useCallback)(e=>{if(!m)return;let t=(e??``).toLowerCase(),n=(m.objects?.[t]??m.objects?.[e])?.apiOperations;return Array.isArray(n)?n:void 0},[m]),E=(0,p.useMemo)(()=>({check:S,checkField:x,getFieldPermissions:C,getRowFilter:w,getObjectApiOperations:T,roles:m?.roles??[],systemPermissions:m?.systemPermissions??[],hasCapabilities:e=>{let t=new Set(m?.systemPermissions??[]);return e.every(e=>t.has(e))},isLoaded:!v&&!g&&m!==null}),[S,x,C,w,T,m,v,g]);return v&&!m?(0,Y.jsx)(Y.Fragment,{children:r}):g&&!m?i?(0,Y.jsx)(Y.Fragment,{children:i(g,ee)}):(0,Y.jsx)(Y.Fragment,{children:r}):(0,Y.jsx)(tr.Provider,{value:E,children:s})}function ir(){let e=(0,p.useContext)(tr);return(0,p.useMemo)(()=>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,getObjectApiOperations:()=>void 0,roles:[],systemPermissions:[],hasCapabilities:()=>!0,isLoaded:!1,can:()=>!0,cannot:()=>!1},[e])}function ar(e){let{checkField:t,getFieldPermissions:n}=ir(),r=(0,p.useMemo)(()=>n(e),[n,e]);return(0,p.useMemo)(()=>({permissions:r,canRead:n=>t(e,n,`read`),canWrite:n=>t(e,n,`write`),readableFields:n=>n.filter(n=>t(e,n,`read`)),writableFields:n=>n.filter(n=>t(e,n,`write`))}),[r,t,e])}export{X as _,er as a,J as b,Xn as c,Bn as d,Ln as f,yn as g,bn as h,Qn as i,Yn as l,Tn as m,ir as n,Zn as o,Pn as p,rr as r,Un as s,ar as t,Vn as u,gn as v,hn as y};
|