@skylabs-digital/react-identity-access 2.27.0 → 2.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.js +350 -337
- package/dist/index.es.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/services/SessionManager.d.ts +2 -0
- package/dist/services/SessionManager.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),a=require("react"),ie=require("react-router-dom");class ne{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async executeRequest(e,t,n,i){const o=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,l=(i==null?void 0:i.timeout)||this.timeout;let d={"Content-Type":"application/json",...i==null?void 0:i.headers};if(!(i!=null&&i.skipAuth)&&this.sessionManager){const f=await this.sessionManager.getValidAccessToken();d={...d,Authorization:`Bearer ${f}`}}const m=new AbortController,y=setTimeout(()=>m.abort(),l);try{const f=await fetch(o,{method:e,headers:d,body:n?JSON.stringify(n):void 0,signal:m.signal});if(clearTimeout(y),!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);const L=f.headers.get("content-type");return!L||!L.includes("application/json")?{}:await f.json()}catch(f){throw clearTimeout(y),f instanceof Error&&f.name==="AbortError"?new Error(`Request timeout after ${l}ms`):f}}async get(e,t){return this.executeRequest("GET",e,void 0,t)}async post(e,t,n){return this.executeRequest("POST",e,t,n)}async put(e,t,n){return this.executeRequest("PUT",e,t,n)}async delete(e,t){return this.executeRequest("DELETE",e,void 0,t)}}class Ae{constructor(e,t){this.httpService=e,this.sessionManager=t}async createApp(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/apps/",e,{headers:t})).data}async getApps(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/apps/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{apps:o.data,meta:o.meta}}async getAppById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}`,{headers:t})).data}async updateApp(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:n})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:n})).data}async updateSettingsSchema(e,t,n){const i=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:n},{headers:i})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const Pe=a.createContext(null);function mt({config:s,children:e}){const t=a.useMemo(()=>{var g,v,k;return{enabled:((g=s.cache)==null?void 0:g.enabled)??!0,ttl:((v=s.cache)==null?void 0:v.ttl)??3e5,storageKey:((k=s.cache)==null?void 0:k.storageKey)??`app_cache_${s.appId}`}},[s.cache,s.appId]),[n,i]=a.useState(()=>{if(!t.enabled)return null;try{const g=localStorage.getItem(t.storageKey);if(!g)return null;const v=JSON.parse(g);return Date.now()-v.timestamp<t.ttl&&v.appId===s.appId?v.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[o,l]=a.useState(!n),[d,m]=a.useState(null),y=a.useMemo(()=>{const g=()=>{f()};return{appId:s.appId,baseUrl:s.baseUrl,appInfo:n,isAppLoading:o,appError:d,retryApp:g}},[s,n,o,d]),f=a.useCallback(async(g=!1)=>{if(!(!g&&t.enabled&&n))try{l(!0),m(null);const v=new ne(s.baseUrl),M=await new Ae(v,{}).getPublicAppInfo(s.appId);if(i(M),t.enabled)try{const E={data:M,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(E))}catch(E){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Failed to cache app info:",E)}}catch(v){const k=v instanceof Error?v:new Error("Failed to load app information");m(k),i(null)}finally{l(!1)}},[s.baseUrl,s.appId,t,n]),L=a.useCallback(async()=>{if(!(!t.enabled||!n))try{const g=localStorage.getItem(t.storageKey);if(!g)return;const v=JSON.parse(g);if(Date.now()-v.timestamp>t.ttl*.5){const M=new ne(s.baseUrl),A=await new Ae(M,{}).getPublicAppInfo(s.appId);i(A);const u={data:A,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(u))}}catch(g){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Background app refresh failed:",g)}},[s,t,n]);return a.useEffect(()=>{n?L():f()},[]),r.jsx(Pe.Provider,{value:y,children:e})}function me(){const s=a.useContext(Pe);if(!s)throw new Error("useApp must be used within an AppProvider");return s}function Re(){return a.useContext(Pe)}const yt=me;class ee extends Error{constructor(e,t){const n={token_expired:"Refresh token has expired",token_invalid:"Refresh token is invalid",user_inactive:"User account is inactive"};super(t||n[e]),this.name="SessionExpiredError",this.reason=e}}class ze extends Error{constructor(e){super(`Token refresh timed out after ${e}ms`),this.name="TokenRefreshTimeoutError",this.timeoutMs=e}}class Ve extends Error{constructor(e,t){super(`Token refresh failed after ${e} attempts: ${(t==null?void 0:t.message)||"Unknown error"}`),this.name="TokenRefreshError",this.attempts=e,this.lastError=t}}const re=class re{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.proactiveTimerId=null,this.backgroundRetryTimerId=null,this.isDestroyed=!1,this.sessionGeneration=0,e.tenantSlug!==void 0?this.storageKey=e.tenantSlug?`auth_tokens_${e.tenantSlug}`:"auth_tokens":this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.onSessionExpired=e.onSessionExpired,this.baseUrl=e.baseUrl||"",this.proactiveRefreshMargin=e.proactiveRefreshMargin??6e4,this.refreshQueueTimeout=e.refreshQueueTimeout??1e4,this.maxRefreshRetries=e.maxRefreshRetries??3,this.retryBackoffBase=e.retryBackoffBase??1e3,this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey),this.scheduleProactiveRefresh()}static getInstance(e={}){const t=re.resolveStorageKey(e),n=re.instances.get(t);if(n)return n.updateConfig(e),n;const i=new re(e);return re.instances.set(t,i),i}static resetAllInstances(){for(const e of re.instances.values())e.destroy();re.instances.clear()}static resolveStorageKey(e){return e.storageKey?e.storageKey:e.tenantSlug!==void 0&&e.tenantSlug?`auth_tokens_${e.tenantSlug}`:"auth_tokens"}updateConfig(e){e.onSessionExpired!==void 0&&(this.onSessionExpired=e.onSessionExpired),e.onRefreshFailed!==void 0&&(this.onRefreshFailed=e.onRefreshFailed),e.baseUrl&&(this.baseUrl=e.baseUrl)}createTokenStorage(e){return{get:()=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(e,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(e)}catch{}}}}static extractJwtExpiry(e){try{const t=e.split(".");if(t.length!==3)return;const n=JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof n.exp=="number"?n.exp*1e3:void 0}catch{return}}setTokens(e){const t=e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)||re.extractJwtExpiry(e.accessToken),n={...e,expiresAt:t},i=this.tokenStorage.get()||{};this.tokenStorage.set({...i,...n}),this.scheduleProactiveRefresh()}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:n,expiresIn:i,tokenType:o}=this.tokenStorage.get()||{};if(!e)return null;const l=n||re.extractJwtExpiry(e);return{accessToken:e,refreshToken:t,expiresAt:l,expiresIn:i,tokenType:o}}clearTokens(){this.tokenStorage.clear()}isTokenExpired(e){const t=e||this.getTokens();return t!=null&&t.expiresAt?Date.now()>=t.expiresAt:!1}shouldRefreshToken(e){const t=e||this.getTokens();return!(t!=null&&t.expiresAt)||!this.autoRefresh?!1:Date.now()>=t.expiresAt-this.refreshThreshold}getAccessToken(){const e=this.getTokens();return(e==null?void 0:e.accessToken)||null}scheduleProactiveRefresh(){if(this.cancelProactiveTimer(),!this.autoRefresh||this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.expiresAt)||!e.refreshToken)return;const n=e.expiresAt-this.proactiveRefreshMargin-Date.now();if(n<=0){this.backgroundRefresh();return}this.proactiveTimerId=setTimeout(()=>{this.backgroundRefresh()},n)}cancelProactiveTimer(){this.proactiveTimerId!==null&&(clearTimeout(this.proactiveTimerId),this.proactiveTimerId=null),this.backgroundRetryTimerId!==null&&(clearTimeout(this.backgroundRetryTimerId),this.backgroundRetryTimerId=null)}backgroundRefresh(){if(this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.refreshToken)||this.refreshPromise)return;const t=this.sessionGeneration;this.startRefreshAndResolveQueue(e.refreshToken).then(()=>{}).catch(n=>{n instanceof ee||this.sessionGeneration===t&&(process.env.NODE_ENV==="development"&&console.warn("[SessionManager] Background refresh failed, retrying in 30s:",n.message),this.backgroundRetryTimerId=setTimeout(()=>{this.backgroundRefresh()},3e4))})}async waitForPendingRefresh(){if(!this.refreshPromise)return!1;try{return await this.refreshPromise,!0}catch{return!1}}async getValidAccessToken(){const e=this.getTokens();if(!(e!=null&&e.accessToken)){const t=new ee("token_invalid","No tokens available");throw this.handleSessionExpired(t),t}if(!this.shouldRefreshToken(e)&&!this.isTokenExpired(e))return e.accessToken;if(!e.refreshToken){const t=new ee("token_invalid","No refresh token available");throw this.handleSessionExpired(t),t}return this.refreshPromise?this.enqueueForToken():this.startRefreshAndResolveQueue(e.refreshToken)}async getAuthHeaders(){try{return{Authorization:`Bearer ${await this.getValidAccessToken()}`}}catch(e){return e instanceof ee&&this.onRefreshFailed&&this.onRefreshFailed(),{}}}enqueueForToken(){return new Promise((e,t)=>{const n=setTimeout(()=>{const i=this.refreshQueue.findIndex(o=>o.timeoutId===n);i!==-1&&this.refreshQueue.splice(i,1),t(new ze(this.refreshQueueTimeout))},this.refreshQueueTimeout);this.refreshQueue.push({resolve:e,reject:t,timeoutId:n})})}async startRefreshAndResolveQueue(e){this.refreshPromise=this.executeRefreshWithRetry(e);try{await this.refreshPromise;const t=this.getTokens(),n=(t==null?void 0:t.accessToken)||"";return this.resolveQueue(n),n}catch(t){const n=t instanceof Error?t:new Error("Token refresh failed");throw n instanceof ee?(this.rejectQueue(n),this.handleSessionExpired(n)):this.rejectQueue(n),n}finally{this.refreshPromise=null}}resolveQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const n of t)clearTimeout(n.timeoutId),n.resolve(e)}rejectQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const n of t)clearTimeout(n.timeoutId),n.reject(e)}async executeRefreshWithRetry(e){let t;const n=this.sessionGeneration;for(let i=0;i<=this.maxRefreshRetries;i++){if(this.sessionGeneration!==n)throw new ee("token_invalid","Session cleared during refresh");try{await this.performTokenRefresh(e,n);return}catch(o){const l=o instanceof Error?o:new Error(String(o));if(l instanceof ee)throw l;if(t=l,i<this.maxRefreshRetries){const d=this.retryBackoffBase*Math.pow(2,i);await this.sleep(d)}}}throw new Ve(this.maxRefreshRetries+1,t)}async performTokenRefresh(e,t){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const n=`${this.baseUrl}/auth/refresh`;let i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})})}catch(l){throw l instanceof Error?l:new Error("Network error during token refresh")}if(!i.ok){let l="";try{const d=await i.json();l=(d.message||d.error||"").toLowerCase()}catch{l=i.statusText.toLowerCase()}throw i.status===401?l.includes("expired")?new ee("token_expired"):l.includes("invalid")?new ee("token_invalid"):new ee("token_invalid",`Unauthorized: ${l}`):i.status===400?l.includes("inactive")?new ee("user_inactive"):l.includes("expired")||l.includes("invalid")?new ee("token_invalid",l):new Error(`Token refresh failed (400): ${l}`):new Error(`Token refresh failed: ${i.status} ${l}`)}if(this.sessionGeneration!==t)throw new ee("token_invalid","Session cleared during refresh");const o=await i.json();this.setTokens({accessToken:o.accessToken,refreshToken:o.refreshToken||e,expiresIn:o.expiresIn})}handleSessionExpired(e){this.cancelProactiveTimer(),this.clearSession(),this.onSessionExpired?this.onSessionExpired(e):this.onRefreshFailed&&this.onRefreshFailed()}setUser(e){const t=this.tokenStorage.get()||{};this.tokenStorage.set({...t,user:e})}getUser(){const e=this.tokenStorage.get();return(e==null?void 0:e.user)||null}clearUser(){const e=this.tokenStorage.get()||{};delete e.user,this.tokenStorage.set(e)}clearSession(){this.sessionGeneration++,this.cancelProactiveTimer(),this.clearTokens();const e=new ee("token_invalid","Session cleared");this.rejectQueue(e)}destroy(){this.isDestroyed=!0,re.instances.delete(this.storageKey),this.cancelProactiveTimer();const e=new ee("token_invalid","SessionManager destroyed");this.rejectQueue(e)}getTokenPayload(){try{const e=this.getTokens();if(!(e!=null&&e.accessToken))return null;const t=e.accessToken.split(".");if(t.length!==3)return null;const n=t[1],i=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(i)}catch{return null}}getUserId(){const e=this.getTokenPayload();if(e!=null&&e.userId)return e.userId;const t=this.getUser();return(t==null?void 0:t.id)||null}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}sleep(e){return new Promise(t=>setTimeout(t,e))}};re.instances=new Map;let he=re;const ve=new Map;class We{constructor(e){this.httpService=e}async login(e){return await this.httpService.post("/auth/login",e)}async signup(e){return await this.httpService.post("/auth/signup",e)}async signupTenantAdmin(e){return await this.httpService.post("/auth/signup/tenant-admin",e)}async refreshToken(e){return await this.httpService.post("/auth/refresh",e)}async switchTenant(e){return await this.httpService.post("/auth/switch-tenant",e)}async getUserTenants(e){return await this.httpService.get("/auth/tenants",{headers:e})}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async sendMagicLink(e){return await this.httpService.post("/auth/magic-link/send",e)}async verifyMagicLink(e){const t=e.token,n=ve.get(t);if(n)return n;const i=this.httpService.post("/auth/magic-link/verify",e).finally(()=>{ve.delete(t)});return ve.set(t,i),i}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e,t){await this.httpService.post("/auth/change-password",e,{headers:t})}}class je{constructor(e,t){this.httpService=e,this.sessionManager=t}async createRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/roles/",e,{headers:t})).data}async getRoleById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/roles/${e}`,{headers:t})).data}async updateRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:n})).data}async deleteRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/roles/${e}`,{headers:t})}async getRolesByApp(e,t){const n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const i=`/roles/app/${e}${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i);return{roles:o.data,meta:o.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:n})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:n})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders(),i=new URLSearchParams;t!=null&&t.page&&i.append("page",t.page.toString()),t!=null&&t.limit&&i.append("limit",t.limit.toString()),t!=null&&t.sortBy&&i.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&i.append("sortOrder",t.sortOrder);const o=`/roles/user/${e}${i.toString()?`?${i.toString()}`:""}`,l=await this.httpService.get(o,{headers:n});return{roles:l.data,meta:l.meta}}}class Ge{constructor(e,t){this.httpService=e,this.sessionManager=t}async createUser(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/users/",e,{headers:t})).data}async getUsers(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/users/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{users:o.data,meta:o.meta}}async getUserById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/users/${e}`,{headers:t})).data}async updateUser(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:n})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class pe{constructor(e,t,n){this.httpService=e,this.appId=t,this.sessionManager=n}async createTenant(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/tenants/",e,{headers:t})).data}async getTenants(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/tenants/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{tenants:o.data,meta:o.meta}}async getTenantById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/tenants/${e}`,{headers:t})).data}async updateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:n})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:n})).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`)).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`)).data}async updateTenantSettings(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:n})).data}}function wt(s,e){if(s==="localhost"||s.startsWith("127.")||s.startsWith("192.168."))return null;if(e){const i=e.toLowerCase(),o=s.toLowerCase();if(o===i||o===`www.${i}`)return null;if(o.endsWith(`.${i}`)){const l=o.slice(0,-(i.length+1));return l==="www"?null:l}return null}const n=s.split(".");return n.length>=3&&n[0]!=="www"?n[0]:null}function xt(s,e="tenant",t){const i=new URLSearchParams(s).get(e);return i?(t&&t.setItem("tenant",i),i):t?t.getItem("tenant"):null}function bt(s,e,t){const{tenantMode:n,baseDomain:i,selectorParam:o,fixedTenantSlug:l}=s;return n==="fixed"?l||null:n==="subdomain"?wt(e.hostname,i):n==="selector"?xt(e.search,o,t):null}function St(s,e,t){if(t)return`${s}.${t}`;const n=e.split(".");return n.length===2?`${s}.${e}`:n.length>=3?(n[0]=s,n.join(".")):null}const ue="_auth";function He(s){const e=JSON.stringify(s);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vt(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";const t=atob(e),n=JSON.parse(t);return typeof n.accessToken=="string"&&typeof n.refreshToken=="string"&&typeof n.expiresIn=="number"?n:null}catch{return null}}function Tt(){if(typeof window>"u")return null;const e=new URLSearchParams(window.location.search).get(ue);return e?vt(e):null}function kt(){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.delete(ue),window.history.replaceState({},"",s.toString())}const Ee=a.createContext(null);function At({config:s,children:e}){const{baseUrl:t,appInfo:n,appId:i}=me(),o=a.useCallback(()=>typeof window>"u"?null:bt({tenantMode:s.tenantMode||"selector",baseDomain:s.baseDomain,selectorParam:s.selectorParam,fixedTenantSlug:s.fixedTenantSlug},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[s.tenantMode,s.baseDomain,s.selectorParam,s.fixedTenantSlug]),[l,d]=a.useState(()=>o()),m=a.useMemo(()=>{var p,N,x;return{enabled:((p=s.cache)==null?void 0:p.enabled)??!0,ttl:((N=s.cache)==null?void 0:N.ttl)??5*60*1e3,storageKey:((x=s.cache)==null?void 0:x.storageKey)??`tenant_cache_${l||"default"}`}},[s.cache,l]),[y,f]=a.useState(()=>{if(s.initialTenant)return s.initialTenant;if(!m.enabled||!l)return null;try{const p=localStorage.getItem(m.storageKey);if(!p)return null;const N=JSON.parse(p);return Date.now()-N.timestamp<m.ttl&&N.tenantSlug===l?N.data:(localStorage.removeItem(m.storageKey),null)}catch{return null}}),[L,g]=a.useState(!y&&!s.initialTenant),[v,k]=a.useState(null),[M,E]=a.useState(null),[A,u]=a.useState(!1),[b,I]=a.useState(null);a.useEffect(()=>{if(s.tenantMode==="fixed")return;const p=o();d(p)},[o,s.tenantMode]);const D=(n==null?void 0:n.settingsSchema)||null,w=a.useCallback(async(p,N=!1)=>{if(!(!N&&m.enabled&&y&&y.domain===p))try{g(!0),k(null);const x=new ne(t),S=await new pe(x,i).getPublicTenantInfo(p);if(f(S),m.enabled)try{const P={data:S,timestamp:Date.now(),tenantSlug:p};localStorage.setItem(m.storageKey,JSON.stringify(P))}catch(P){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Failed to cache tenant info:",P)}}catch(x){const h=x instanceof Error?x:new Error("Failed to load tenant information");k(h),f(null)}finally{g(!1)}},[t,i,m,y]),j=a.useCallback(async()=>{if(!(!m.enabled||!y||!l))try{const p=localStorage.getItem(m.storageKey);if(!p)return;const N=JSON.parse(p);if(Date.now()-N.timestamp>m.ttl*.5){const h=new ne(t),P=await new pe(h,i).getPublicTenantInfo(l);f(P);const W={data:P,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(m.storageKey,JSON.stringify(W))}}catch(p){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Background tenant refresh failed:",p)}},[t,i,m,y,l]),T=a.useCallback(async()=>{if(y!=null&&y.id)try{u(!0),I(null);const p=new ne(t),x=await new pe(p,y.appId).getTenantSettings(y.id);E(x)}catch(p){const N=p instanceof Error?p:new Error("Failed to load tenant settings");I(N),E(null)}finally{u(!1)}},[t,y]),R=a.useCallback(()=>{T()},[T]),c=a.useCallback(p=>{if(!D)return{isValid:!0,errors:[]};const N=[];try{return D.properties&&Object.entries(D.properties).forEach(([x,h])=>{var P;const S=p[x];if((P=D.required)!=null&&P.includes(x)&&S==null){N.push(`Field '${x}' is required`);return}if(S!=null){if(h.type){const W=h.type,V=typeof S;W==="string"&&V!=="string"?N.push(`Field '${x}' must be a string`):(W==="number"||W==="integer")&&V!=="number"?N.push(`Field '${x}' must be a number`):W==="boolean"&&V!=="boolean"?N.push(`Field '${x}' must be a boolean`):W==="array"&&!Array.isArray(S)&&N.push(`Field '${x}' must be an array`)}h.minLength!==void 0&&typeof S=="string"&&S.length<h.minLength&&N.push(`Field '${x}' must be at least ${h.minLength} characters long`),h.maxLength!==void 0&&typeof S=="string"&&S.length>h.maxLength&&N.push(`Field '${x}' must be no more than ${h.maxLength} characters long`),h.minimum!==void 0&&typeof S=="number"&&S<h.minimum&&N.push(`Field '${x}' must be at least ${h.minimum}`),h.maximum!==void 0&&typeof S=="number"&&S>h.maximum&&N.push(`Field '${x}' must be no more than ${h.maximum}`),h.pattern&&typeof S=="string"&&(new RegExp(h.pattern).test(S)||N.push(`Field '${x}' does not match the required pattern`)),h.enum&&!h.enum.includes(S)&&N.push(`Field '${x}' must be one of: ${h.enum.join(", ")}`)}}),{isValid:N.length===0,errors:N}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[D]);a.useEffect(()=>{!s.initialTenant&&l?y?j():w(l):!s.initialTenant&&!l&&(f(null),k(null),g(!1))},[s.initialTenant,l,y,w,j]),a.useEffect(()=>{y!=null&&y.id?T():(E(null),I(null),u(!1))},[y==null?void 0:y.id,T]);const O=a.useCallback((p,N)=>{const{mode:x="reload",tokens:h,redirectPath:S}=N||{},P=s.tenantMode||"selector";if(P==="fixed"){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] switchTenant is a no-op in fixed mode. Tenant is always:",s.fixedTenantSlug),S&&(window.location.href=S);return}if(localStorage.setItem("tenant",p),P==="subdomain"){const W=window.location.hostname,V=St(p,W,s.baseDomain);if(!V){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",W);return}const K=S||window.location.pathname,_=new URL(`${window.location.protocol}//${V}${K}`);new URLSearchParams(window.location.search).forEach((q,$)=>{$!==ue&&_.searchParams.set($,q)}),h&&_.searchParams.set(ue,He(h)),window.location.href=_.toString()}else if(P==="selector"){const W=S||window.location.pathname,V=new URLSearchParams(window.location.search);if(V.set(s.selectorParam||"tenant",p),V.delete(ue),h&&V.set(ue,He(h)),x==="reload"){const K=`${W}?${V.toString()}${window.location.hash}`;window.location.href=K}else{const K=`${W}?${V.toString()}${window.location.hash}`;window.history.pushState({},"",K),d(p),w(p)}}},[s.tenantMode,s.selectorParam,s.baseDomain,w]),F=a.useMemo(()=>({tenant:y,tenantSlug:l,isTenantLoading:L,tenantError:v,retryTenant:()=>{l&&w(l)},settings:M,settingsSchema:D,isSettingsLoading:A,settingsError:b,refreshSettings:R,switchTenant:O,validateSettings:c}),[y,l,L,v,M,D,A,b,R,O,c]);return r.jsx(Ee.Provider,{value:F,children:e})}function fe(){const s=a.useContext(Ee);if(!s)throw new Error("useTenant must be used within a TenantProvider");return s}function le(){return a.useContext(Ee)}const jt=fe;function Pt(){const{settings:s,settingsSchema:e,isSettingsLoading:t,settingsError:n,validateSettings:i}=fe();return{settings:s,settingsSchema:e,isLoading:t,error:n,validateSettings:i}}function Me(){const{tenant:s,tenantSlug:e,isTenantLoading:t,tenantError:n,retryTenant:i}=fe();return{tenant:s,tenantSlug:e,isLoading:t,error:n,retry:i}}const Ie=a.createContext(null);function Rt({config:s={},children:e}){const t=Re(),n=le(),i=(t==null?void 0:t.baseUrl)??s.baseUrl??"",o=(t==null?void 0:t.appId)??s.appId,l=(n==null?void 0:n.tenant)??null,d=(n==null?void 0:n.tenantSlug)??null,m=(n==null?void 0:n.switchTenant)??(()=>{});if(!i)throw new Error("[AuthProvider] baseUrl is required. Provide it via AppProvider or AuthConfig.baseUrl.");const[y,f]=a.useState(s.initialRoles||[]),[L,g]=a.useState(!s.initialRoles),[v,k]=a.useState(null),[M,E]=a.useState(!1),[A,u]=a.useState(null),[b,I]=a.useState(()=>{try{const C=localStorage.getItem("userTenants");return C?JSON.parse(C):[]}catch{return[]}}),[D,w]=a.useState(!1),j=a.useRef({done:!1,urlTokens:null});j.current.done||(j.current.done=!0,j.current.urlTokens=Tt());const[T,R]=a.useState(()=>j.current.urlTokens!==null),c=a.useMemo(()=>{const C=he.getInstance({tenantSlug:d,baseUrl:i,refreshQueueTimeout:s.refreshQueueTimeout,proactiveRefreshMargin:s.proactiveRefreshMargin,onSessionExpired:se=>{k(null),u(null),I([]),w(!1);try{localStorage.removeItem("userTenants")}catch{}s.onSessionExpired?s.onSessionExpired(se):s.onRefreshFailed&&s.onRefreshFailed()}});return j.current.urlTokens&&C.setTokens({accessToken:j.current.urlTokens.accessToken,refreshToken:j.current.urlTokens.refreshToken,expiresIn:j.current.urlTokens.expiresIn}),C},[d,i,s.refreshQueueTimeout,s.proactiveRefreshMargin]),[O,F]=a.useState(()=>{if(j.current.urlTokens)return!1;const C=c.getTokens();return C?c.hasValidSession()||!!C.refreshToken:!1}),p=j.current.done&&!T&&!O,N=a.useMemo(()=>{const C=new ne(i);return C.setSessionManager(c),C},[i,c]),x=a.useMemo(()=>new We(new ne(i)),[i]),h=a.useMemo(()=>new Ge(N,c),[N,c]),S=a.useMemo(()=>new je(new ne(i)),[i]),P=a.useMemo(()=>v||c.getUser(),[v,c]),W=a.useMemo(()=>P!=null&&P.roleId&&y.find(C=>C.id===P.roleId)||null,[P,y]),V=a.useMemo(()=>(W==null?void 0:W.permissions)||[],[W]),K=a.useMemo(()=>c.hasValidSession()&&v!==null,[c,v]),_=a.useRef(async()=>{}),B=a.useMemo(()=>{const C=async(U=!1)=>{try{if(!c.hasValidSession()||!U&&v)return;const H=c.getUserId();if(!H){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] No userId available in token or storage");return}E(!0),u(null);const Z=await h.getUserById(H);k(Z),c.setUser(Z)}catch(H){const Z=H instanceof Error?H:new Error("Failed to load user data");u(Z),process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data:",Z)}finally{E(!1)}},se=async()=>{await C()},ce=async U=>{var Ue;const{username:H,password:Z,tenantSlug:z,redirectPath:Q}=U;let J=l==null?void 0:l.id,Y=d,X=c;z&&(J=(await new pe(N,o).getPublicTenantInfo(z)).id,Y=z);const G=await x.login({username:H,password:Z,appId:o,tenantId:J}),ge=z&&z!==d;if(ge&&(X=new he({tenantSlug:Y,baseUrl:i})),X.setTokens({accessToken:G.accessToken,refreshToken:G.refreshToken,expiresIn:G.expiresIn}),G.user){X.setUser(G.user),k(G.user);try{await C()}catch(ye){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after login:",ye)}}if(G.tenants&&G.tenants.length>0){I(G.tenants);try{localStorage.setItem("userTenants",JSON.stringify(G.tenants))}catch{}}const be=((Ue=G.user)==null?void 0:Ue.tenantId)!==null;w(be);const Se={accessToken:G.accessToken,refreshToken:G.refreshToken,expiresIn:G.expiresIn};if(ge&&Y)return m(Y,{tokens:Se,redirectPath:Q}),G;if(Q&&Q!==window.location.pathname)return m(Y||d||"",{tokens:Se,redirectPath:Q}),G;if(!be&&G.tenants&&G.tenants.length>0){const ye=U.autoSwitch!==!1&&s.autoSwitchSingleTenant!==!1;if(G.tenants.length===1&&ye){const $e=G.tenants[0];return m($e.subdomain,{tokens:Se,redirectPath:Q}),G}else G.tenants.length>1&&s.onTenantSelectionRequired&&s.onTenantSelectionRequired(G.tenants)}return G},de=async U=>{const{email:H,phoneNumber:Z,name:z,password:Q,lastName:J,tenantId:Y}=U;if(!H&&!Z)throw new Error("Either email or phoneNumber is required");if(!z||!Q)throw new Error("Name and password are required");const X=Y??(l==null?void 0:l.id);return await x.signup({email:H,phoneNumber:Z,name:z,password:Q,tenantId:X,lastName:J,appId:o})},nt=async U=>{const{email:H,phoneNumber:Z,name:z,password:Q,tenantName:J,lastName:Y}=U;if(!H&&!Z)throw new Error("Either email or phoneNumber is required");if(!z||!Q||!J)throw new Error("Name, password, and tenantName are required");return await x.signupTenantAdmin({email:H,phoneNumber:Z,name:z,password:Q,tenantName:J,appId:o,lastName:Y})},st=async U=>{const{currentPassword:H,newPassword:Z}=U,z=await c.getAuthHeaders();await x.changePassword({currentPassword:H,newPassword:Z},z)},it=async U=>{const{email:H,tenantId:Z}=U,z=Z??(l==null?void 0:l.id);if(!z)throw new Error("tenantId is required for password reset");await x.requestPasswordReset({email:H,tenantId:z})},ot=async U=>{const{token:H,newPassword:Z}=U;await x.confirmPasswordReset({token:H,newPassword:Z})},at=async U=>{const{email:H,frontendUrl:Z,name:z,lastName:Q,tenantId:J}=U,Y=J??(l==null?void 0:l.id);if(!Y)throw new Error("tenantId is required for magic link authentication");return await x.sendMagicLink({email:H,tenantId:Y,frontendUrl:Z,name:z,lastName:Q,appId:o})},lt=async U=>{const{token:H,email:Z,tenantSlug:z}=U;let Q=l==null?void 0:l.id,J=d,Y=c;z&&(Q=(await new pe(N,o).getPublicTenantInfo(z)).id,J=z);const X=await x.verifyMagicLink({token:H,email:Z,appId:o,tenantId:Q}),G=z&&z!==d;if(G&&(Y=new he({tenantSlug:J,baseUrl:i})),Y.setTokens({accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}),X.user){Y.setUser(X.user),k(X.user);try{await C()}catch(ge){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after magic link:",ge)}}return G&&J&&J!==d&&m(J,{tokens:{accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}}),X},ct=async()=>{const U=c.getTokens();if(!(U!=null&&U.refreshToken))throw new Error("No refresh token available");const H=await x.refreshToken({refreshToken:U.refreshToken});c.setTokens({accessToken:H.accessToken,refreshToken:H.refreshToken||U.refreshToken,expiresIn:H.expiresIn})},dt=()=>{c.clearSession(),k(null),u(null),I([]),w(!1);try{localStorage.removeItem("userTenants")}catch{}},ut=U=>{c.setTokens(U)},ht=()=>c.hasValidSession(),pt=()=>{c.clearSession(),k(null),u(null)},ft=async()=>{if(o)try{g(!0);const{roles:U}=await S.getRolesByApp(o);f(U)}catch(U){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",U)}finally{g(!1)}},gt=async()=>{await ft()},xe=U=>{if(!V||V.length===0)return!1;if(typeof U=="string")return V.includes(U);const H=`${U.resource}.${U.action}`;return V.includes(H)};return{isAuthenticated:K,sessionManager:c,authenticatedHttpService:N,login:ce,signup:de,signupTenantAdmin:nt,sendMagicLink:at,verifyMagicLink:lt,changePassword:st,requestPasswordReset:it,confirmPasswordReset:ot,refreshToken:ct,logout:dt,setTokens:ut,hasValidSession:ht,clearSession:pt,currentUser:v,isUserLoading:M,userError:A,loadUserData:C,refreshUser:se,isAuthInitializing:!p,isAuthReady:p,userRole:W,userPermissions:V,availableRoles:y,rolesLoading:L,hasPermission:xe,hasAnyPermission:U=>U.some(H=>xe(H)),hasAllPermissions:U=>U.every(H=>xe(H)),getUserPermissionStrings:()=>V||[],refreshRoles:gt,userTenants:b,hasTenantContext:D,switchToTenant:async(U,H)=>{const{redirectPath:Z}=H||{},z=c.getTokens();if(!(z!=null&&z.refreshToken))throw new Error("No refresh token available for tenant switch");const Q=await x.switchTenant({refreshToken:z.refreshToken,tenantId:U});c.setTokens({accessToken:Q.accessToken,refreshToken:z.refreshToken,expiresIn:Q.expiresIn}),k(Q.user),c.setUser(Q.user),w(!0);const J=b.find(Y=>Y.id===U);J&&m(J.subdomain,{tokens:{accessToken:Q.accessToken,refreshToken:z.refreshToken,expiresIn:Q.expiresIn},redirectPath:Z})},refreshUserTenants:async()=>{const U=await c.getAuthHeaders(),H=await x.getUserTenants(U);I(H);try{localStorage.setItem("userTenants",JSON.stringify(H))}catch{}return H}}},[K,c,N,x,h,S,o,l,d,m,y,v,M,A,b,D,p,W,V]);_.current=B.loadUserData,a.useEffect(()=>{!s.initialRoles&&o&&(async()=>{try{g(!0);const se=new ne(i),ce=new je(se),{roles:de}=await ce.getRolesByApp(o);f(de)}catch(se){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",se)}finally{g(!1)}})()},[o,i,s.initialRoles]);const[q,$]=a.useState(!1);return a.useEffect(()=>{q||($(!0),j.current.urlTokens&&(kt(),R(!0),B.loadUserData().catch(C=>{process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data after URL tokens:",C)}).finally(()=>{R(!1)})))},[B,q]),a.useEffect(()=>{let C=!1;return(async()=>{var de;if(!c.hasValidSession()&&((de=c.getTokens())!=null&&de.refreshToken)&&await c.waitForPendingRefresh(),C)return;const ce=c.getUser();ce&&c.hasValidSession()&&k(ce),F(!1)})(),()=>{C=!0}},[c]),a.useEffect(()=>{q&&(j.current.urlTokens||(!v&&!M&&!A&&c.hasValidSession()?_.current().catch(()=>{}).finally(()=>{F(!1)}):F(!1)))},[v,M,A,c,q]),r.jsx(Ie.Provider,{value:B,children:e})}function ae(){const s=a.useContext(Ie);if(!s)throw new Error("useAuth must be used within an AuthProvider");return s}function Le(){return a.useContext(Ie)}class Ze{constructor(e,t){this.httpService=e,this.sessionManager=t}async createFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/feature-flags/",e,{headers:t})).data}async getFeatureFlags(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/feature-flags/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{featureFlags:o.data,meta:o.meta}}async getFeatureFlagById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/feature-flags/${e}`,{headers:t})).data}async updateFeatureFlag(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:n})).data}async deleteFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/feature-flags/${e}`,{headers:t})}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",e),n.append("appId",t);const i=`/tenant-feature-flags${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(i,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,n){if(!e||!t||!n)throw new Error("Flag Key, Tenant ID and App ID are required");const i=new URLSearchParams;i.append("tenantId",t),i.append("appId",n);const o=`/tenant-feature-flags/${e}${i.toString()?`?${i.toString()}`:""}`;return(await this.httpService.get(o,{headers:{"X-Tenant-ID":t}})).data}}const Fe=a.createContext(null);function Et({config:s={},children:e}){const t=Re(),n=le(),i=(t==null?void 0:t.baseUrl)??"",o=(t==null?void 0:t.appId)??"",l=(n==null?void 0:n.tenant)??null,[d,m]=a.useState([]),[y,f]=a.useState(!1),[L,g]=a.useState(null),[v,k]=a.useState(!1),M=a.useMemo(()=>{const u=new ne(i);return new Ze(u)},[i]),E=async()=>{if(!(l!=null&&l.id)){m([]);return}f(!0),g(null);try{const u=await M.getTenantFeatureFlags(l.id,o);m(u)}catch(u){const b=u instanceof Error?u.message:"Failed to fetch feature flags";g(b),s.onError&&s.onError(u instanceof Error?u:new Error(b))}finally{f(!1)}};a.useEffect(()=>{if(!i||!o)return;E().finally(()=>k(!0));const u=s.refreshInterval||5*60*1e3,b=setInterval(E,u);return()=>clearInterval(b)},[l==null?void 0:l.id,i,o,s.refreshInterval]);const A=a.useMemo(()=>{const u=j=>{const T=d.find(R=>R.key===j);return(T==null?void 0:T.value)===!0},b=j=>d.find(T=>T.key===j),I=j=>{const T=d.find(R=>R.key===j);return T?T.value?"enabled":"disabled":"not_found"},D=async()=>{await E()},w=!!(i&&o)&&(v||!(l!=null&&l.id));return{featureFlags:d,loading:y,error:L,isReady:w,isEnabled:u,getFlag:b,getFlagState:I,refresh:D}},[d,y,L,i,o,l==null?void 0:l.id,v]);return r.jsx(Fe.Provider,{value:A,children:e})}function Qe(){const s=a.useContext(Fe);if(!s)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return s}function Ke(){return a.useContext(Fe)}class Je{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscription(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscriptions/",e,{headers:t})).data}async getSubscriptionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscriptions/subscriptions/${e}`,{headers:t})).data}async updateSubscription(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:n})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:n})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`)).data}async processPayment(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:n})).data}}const Ne=a.createContext(void 0);function Mt({config:s={},children:e}){const t=Re(),n=le(),i=(t==null?void 0:t.baseUrl)??"",o=(n==null?void 0:n.tenant)??null,[l,d]=a.useState(null),[m,y]=a.useState(!1),[f,L]=a.useState(null),[g,v]=a.useState(!1),k=a.useMemo(()=>{const A=new ne(i);return new Je(A)},[i]),M=async()=>{if(!(o!=null&&o.id)){d(null);return}y(!0),L(null);try{const A=await k.getTenantSubscriptionFeatures(o.id);d(A)}catch(A){const u=A instanceof Error?A.message:"Failed to fetch subscription";L(u),s.onError&&s.onError(A instanceof Error?A:new Error(u))}finally{y(!1)}};a.useEffect(()=>{if(!i||(M().finally(()=>v(!0)),!s.refreshInterval))return;const A=s.refreshInterval||10*60*1e3,u=setInterval(M,A);return()=>clearInterval(u)},[o==null?void 0:o.id,i,s.refreshInterval]);const E=a.useMemo(()=>{const A=(l==null?void 0:l.features)||[],u=T=>{const R=A.find(c=>c.key===T);return R?R.type==="BOOLEAN"||R.type==="boolean"?R.value===!0:!!R.value:!1},b=T=>A.find(R=>R.key===T),I=(T,R)=>{const c=A.find(O=>O.key===T);return c?c.value:R},D=T=>!l||!l.isActive?!1:T.includes(l.planId),w=async()=>{await M()},j=!!i&&(g||!(o!=null&&o.id));return{subscription:l,features:A,loading:m,error:f,isReady:j,isFeatureEnabled:u,getFeature:b,getFeatureValue:I,hasAllowedPlan:D,refresh:w}},[l,m,f,i,o==null?void 0:o.id,g]);return r.jsx(Ne.Provider,{value:E,children:e})}function Ye(){const s=a.useContext(Ne);if(s===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return s}function Xe(){return a.useContext(Ne)??null}var te=(s=>(s.SUPERUSER="SUPERUSER",s.TENANT_ADMIN="TENANT_ADMIN",s.USER="USER",s))(te||{});const we={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},De={landing:{tenant:"forbidden",auth:"optional"},publicOnly:{tenant:"forbidden",auth:"forbidden"},login:{tenant:"required",auth:"forbidden"},guest:{auth:"forbidden"},authenticated:{auth:"required"},tenant:{tenant:"required"},tenantOpen:{tenant:"required",auth:"optional"},tenantAuth:{tenant:"required",auth:"required"},user:{tenant:"required",auth:"required",userType:te.USER},admin:{tenant:"required",auth:"required",userType:te.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Ce=a.createContext(null);function It({config:s={},children:e}){const t=a.useMemo(()=>{const n={...we,...s.zoneRoots},i={...De,...s.presets};return{zoneRoots:n,presets:i,loadingFallback:s.loadingFallback??null,accessDeniedFallback:s.accessDeniedFallback??null,onAccessDenied:s.onAccessDenied,returnToParam:s.returnToParam??"returnTo",returnToStorage:s.returnToStorage??"url"}},[s]);return r.jsx(Ce.Provider,{value:t,children:e})}function Lt(){const s=a.useContext(Ce);if(!s)throw new Error("useRouting must be used within a RoutingProvider");return s}function et(){const s=a.useContext(Ce);return s||{zoneRoots:we,presets:De,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"}}const Be=()=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),r.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),r.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),r.jsx("button",{style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},onClick:()=>window.location.href="/login",children:"Sign In"})]}),Oe=({userType:s,minUserType:e,missingPermissions:t})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#fff3cd",border:"1px solid #ffeaa7",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),r.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&s?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",r.jsx("strong",{children:s})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:"You don't have the required permissions to view this content."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]}),Ft=(s,e)=>{const t={[te.USER]:1,[te.TENANT_ADMIN]:2,[te.SUPERUSER]:3};return t[s]>=t[e]};function Nt({children:s,fallback:e,minUserType:t,requiredPermissions:n,requireAllPermissions:i=!1}){const{hasValidSession:o,sessionManager:l,hasPermission:d,hasAnyPermission:m,hasAllPermissions:y}=ae();if(!o())return r.jsx(r.Fragment,{children:e||r.jsx(Be,{})});const f=l.getUser();if(!f)return r.jsx(r.Fragment,{children:e||r.jsx(Be,{})});if(t&&!Ft(f.userType,t))return r.jsx(Oe,{userType:f.userType,minUserType:t});if(n&&n.length>0&&!(i?y(n):m(n))){const g=n.filter(v=>!d(v)).map(v=>typeof v=="string"?v:v.name);return r.jsx(Oe,{missingPermissions:g})}return r.jsx(r.Fragment,{children:s})}const Dt=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})}),qe=({userType:s,requiredUserType:e,missingPermissions:t})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&s?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current user type: ",r.jsx("strong",{children:s})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]})}),Ct=(s,e)=>s===e;function Ut({children:s,redirectTo:e="/login",requiredUserType:t,requiredPermissions:n,requireAllPermissions:i=!1,fallback:o}){const{hasValidSession:l,sessionManager:d,hasPermission:m,hasAnyPermission:y,hasAllPermissions:f}=ae(),L=ie.useLocation();if(a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] ProtectedRoute is deprecated. Use AuthenticatedZone or AdminZone from ZoneRoute instead.")},[]),!l())return o?r.jsx(r.Fragment,{children:o}):r.jsxs(r.Fragment,{children:[r.jsx(Dt,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:L.pathname},replace:!0})]});const g=d.getUser();if(!g)return r.jsx(ie.Navigate,{to:e,state:{from:L.pathname},replace:!0});if(t&&!Ct(g.userType,t))return r.jsx(qe,{userType:g.userType,requiredUserType:t});if(n&&n.length>0&&!(i?f(n):y(n))){const k=n.filter(M=>!m(M)).map(M=>typeof M=="string"?M:M.name);return r.jsx(qe,{missingPermissions:k})}return r.jsx(r.Fragment,{children:s})}const $t=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Ht({children:s,redirectTo:e="/",fallback:t}){const{tenant:n,isLoading:i,error:o}=Me(),l=ie.useLocation();return a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] TenantRoute is deprecated. Use TenantZone from ZoneRoute instead.")},[]),i||o?null:n?r.jsx(r.Fragment,{children:s}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx($t,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const Bt=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Ot({children:s,redirectTo:e="/dashboard",fallback:t}){const{tenant:n,isLoading:i,error:o}=Me(),l=ie.useLocation();return a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] LandingRoute is deprecated. Use PublicZone from ZoneRoute instead.")},[]),i||o?null:n?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Bt,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:s})}function qt(s,e){return e?s?Array.isArray(e)?e.includes(s):s===e:!1:!0}function _e(s,e){return!s||s==="optional"?"skip":s==="required"?e?"pass":"fail":s==="forbidden"?e?"fail":"pass":"skip"}function _t(s,e){return _e(s.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":_e(s.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":s.userType&&e.isAuthenticated&&!qt(e.userType,s.userType)?"wrong_user_type":s.permissions&&s.permissions.length>0&&!(s.requireAllPermissions!==!1?o=>o.every(l=>e.permissions.includes(l)):o=>o.some(l=>e.permissions.includes(l)))(s.permissions)?"missing_permissions":null}function zt(s,e){return s.hasTenant?s.isAuthenticated?s.userType===te.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:s.isAuthenticated?s.userType===te.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function Vt(s,e,t,n,i){if(!e||i!=="url")return s;const o=typeof e=="string"?e:t,l=s.includes("?")?"&":"?";return`${s}${l}${n}=${encodeURIComponent(o)}`}function Wt(s,e,t){if(!s||t==="url")return;const n=typeof s=="string"?s:e,i="zone_return_to";t==="session"?sessionStorage.setItem(i,n):t==="local"&&localStorage.setItem(i,n)}const oe=({children:s,preset:e,tenant:t,auth:n,userType:i,requiredPermissions:o,requireAllPermissions:l=!0,returnTo:d,onAccessDenied:m,redirectTo:y,loadingFallback:f,accessDeniedFallback:L})=>{const g=ie.useLocation(),{isAuthenticated:v,isAuthInitializing:k,currentUser:M,userPermissions:E}=ae(),{tenant:A,isTenantLoading:u}=fe(),b=et(),I=a.useMemo(()=>{if(e)return b.presets[e]},[e,b.presets]),D=a.useMemo(()=>({tenant:t??(I==null?void 0:I.tenant),auth:n??(I==null?void 0:I.auth),userType:i??(I==null?void 0:I.userType),permissions:o??(I==null?void 0:I.requiredPermissions),requireAllPermissions:l}),[t,n,i,o,I,l]),w=a.useMemo(()=>({hasTenant:!!A,isAuthenticated:v,userType:M==null?void 0:M.userType,permissions:E,isLoading:k||u}),[A,v,M==null?void 0:M.userType,E,k,u]),j=a.useMemo(()=>w.isLoading?null:_t(D,w),[D,w]),T=a.useMemo(()=>j?y||zt(w,b.zoneRoots):null,[j,y,w,b.zoneRoots]),R=a.useMemo(()=>!j||!T?null:{type:j,required:{tenant:D.tenant,auth:D.auth,userType:D.userType,permissions:D.permissions},current:{hasTenant:w.hasTenant,isAuthenticated:w.isAuthenticated,userType:w.userType,permissions:w.permissions},redirectTo:T},[j,T,D,w]);if(a.useEffect(()=>{R&&(m?m(R):b.onAccessDenied&&b.onAccessDenied(R))},[R,m,b]),a.useEffect(()=>{R&&d&&Wt(d,g.pathname+g.search,b.returnToStorage)},[R,d,g.pathname,g.search,b.returnToStorage]),w.isLoading)return r.jsx(r.Fragment,{children:f??b.loadingFallback??null});if(R&&T){const c=L??b.accessDeniedFallback;if(c)return r.jsx(r.Fragment,{children:c});const O=Vt(T,d,g.pathname+g.search,b.returnToParam,b.returnToStorage);return r.jsx(ie.Navigate,{to:O,replace:!0})}return r.jsx(r.Fragment,{children:s})},Gt=s=>r.jsx(oe,{tenant:"required",...s}),Zt=s=>r.jsx(oe,{tenant:"forbidden",...s}),Qt=s=>r.jsx(oe,{auth:"required",...s}),Kt=s=>r.jsx(oe,{auth:"forbidden",...s}),Jt=s=>r.jsx(oe,{auth:"required",userType:te.TENANT_ADMIN,...s}),Yt=s=>r.jsx(oe,{auth:"required",userType:te.USER,...s}),Xt=s=>r.jsx(oe,{tenant:"optional",auth:"optional",...s}),er=s=>r.jsx(oe,{tenant:"required",auth:"required",...s}),tr=s=>r.jsx(oe,{tenant:"required",auth:"optional",...s}),rr=s=>r.jsx(oe,{tenant:"required",auth:"forbidden",...s}),nr=()=>r.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[r.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),r.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function sr({children:s,fallback:e=r.jsx(nr,{}),allowedPlans:t,requiredFeature:n}){const{subscription:i,hasAllowedPlan:o,isFeatureEnabled:l,loading:d}=Ye();return d?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):i?i.isActive?t&&t.length>0&&!o(t)?r.jsx(r.Fragment,{children:e}):n&&!l(n)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:s}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const ir=({flagName:s})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"15px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",fontFamily:"system-ui, sans-serif",color:"#6c757d"},children:[r.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),r.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),r.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',s,'" is disabled']})]});function or({name:s,children:e,fallback:t}){const{isEnabled:n,loading:i}=Qe();return i?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):n(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(ir,{flagName:s})})}const ar=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),lr=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),cr={showPassword:r.jsx(ar,{}),hidePassword:r.jsx(lr,{})},dr={title:"Sign In",usernameLabel:"Email or Phone",usernamePlaceholder:"Enter your email or phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",submitButton:"Sign In",forgotPasswordLink:"Forgot your password?",signupLink:"Sign up here",signupText:"Don't have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Invalid credentials",loadingText:"Signing in...",tenantNotFoundError:"Tenant not found",dividerBullet:"•",showPasswordAriaLabel:"Show password",hidePasswordAriaLabel:"Hide password"},ur={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},inputContainer:{position:"relative",display:"flex",alignItems:"center"},passwordToggle:{position:"absolute",right:"0.75rem",background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"#6b7280",display:"flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",borderRadius:"4px",transition:"background-color 0.15s ease-in-out"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},inputWithIcon:{paddingRight:"2.5rem"}};function hr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onForgotPassword:o,onSignupClick:l,onMagicLinkClick:d,showForgotPassword:m=!0,showSignupLink:y=!0,showMagicLinkOption:f=!0,className:L}){const[g,v]=a.useState(""),[k,M]=a.useState(""),[E,A]=a.useState(!1),[u,b]=a.useState(!1),[I,D]=a.useState(""),[w,j]=a.useState({}),{login:T}=ae(),R={...dr,...s},c={...ur,...e},O={...cr,...t},F=()=>{const h={};return g.trim()||(h.username=!0),k.trim()||(h.password=!0),j(h),Object.keys(h).length===0},p=async h=>{if(h.preventDefault(),!!F()){b(!0),D("");try{const S=await T({username:g,password:k});n==null||n(S)}catch(S){const P=S.message||R.errorMessage;D(P),i==null||i(P)}finally{b(!1)}}},N=h=>({...c.input,...w[h]?c.inputError:{}}),x=()=>({...c.button,...u?c.buttonLoading:{},...!g||!k||u?c.buttonDisabled:{}});return r.jsxs("div",{className:L,style:c.container,children:[r.jsx("h2",{style:c.title,children:R.title}),r.jsxs("form",{onSubmit:p,style:c.form,children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:R.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:g,onChange:h=>{v(h.target.value),w.username&&j(S=>({...S,username:!1}))},placeholder:R.usernamePlaceholder,style:N("username"),disabled:u})]}),r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:R.passwordLabel}),r.jsxs("div",{style:c.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:E?"text":"password",value:k,onChange:h=>{M(h.target.value),w.password&&j(S=>({...S,password:!1}))},placeholder:R.passwordPlaceholder,style:{...N("password"),...c.inputWithIcon},disabled:u}),r.jsx("button",{type:"button",onClick:()=>A(!E),style:c.passwordToggle,disabled:u,"aria-label":E?R.hidePasswordAriaLabel:R.showPasswordAriaLabel,children:E?O.hidePassword:O.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!g||!k||u,style:x(),children:u?R.loadingText:R.submitButton}),I&&r.jsx("div",{style:c.errorText,children:I})]}),(m||y||f)&&r.jsxs("div",{style:c.linkContainer,children:[f&&r.jsxs("div",{children:[r.jsxs("span",{style:c.divider,children:[R.magicLinkText," "]}),r.jsx("a",{onClick:d,style:c.link,children:R.magicLinkLink})]}),f&&(m||y)&&r.jsx("div",{style:c.divider,children:R.dividerBullet}),m&&r.jsx("a",{onClick:o,style:c.link,children:R.forgotPasswordLink}),m&&y&&r.jsx("div",{style:c.divider,children:R.dividerBullet}),y&&r.jsxs("div",{children:[r.jsxs("span",{style:c.divider,children:[R.signupText," "]}),r.jsx("a",{onClick:l,style:c.link,children:R.signupLink})]})]})]})}const pr={title:"Create Account",nameLabel:"First Name",namePlaceholder:"Enter your first name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",emailLabel:"Email",emailPlaceholder:"Enter your email",phoneNumberLabel:"Phone Number",phoneNumberPlaceholder:"Enter your phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm your password",tenantNameLabel:"Organization Name",tenantNamePlaceholder:"Enter your organization name",submitButton:"Create Account",loginLink:"Sign in here",loginText:"Already have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Failed to create account",loadingText:"Creating account...",passwordMismatchError:"Passwords do not match",isAdminLabel:"Create new organization",isAdminDescription:"Check this if you want to create a new organization",contactMethodHint:"At least one contact method (email or phone) is required",tenantNotFoundError:"Tenant not found",dividerBullet:"•"},fr={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},checkbox:{marginRight:"0.5rem"},checkboxContainer:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0"},checkboxLabel:{fontSize:"0.875rem",color:"#374151",lineHeight:"1.4"},button:{padding:"0.75rem 1rem",backgroundColor:"#10b981",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},hintText:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"}};function gr({copy:s={},styles:e={},signupType:t="user",onSuccess:n,onError:i,onLoginClick:o,onMagicLinkClick:l,showLoginLink:d=!0,showMagicLinkOption:m=!0,className:y}){var q;const[f,L]=a.useState(""),[g,v]=a.useState(""),[k,M]=a.useState(""),[E,A]=a.useState(""),[u,b]=a.useState(""),[I,D]=a.useState(""),[w,j]=a.useState(""),[T,R]=a.useState(!1),[c,O]=a.useState(""),[F,p]=a.useState({}),{signup:N,signupTenantAdmin:x}=ae(),h=((q=le())==null?void 0:q.tenant)??null,S={...pr,...s},P={...fr,...e},W=()=>{const $={};return f.trim()||($.name=!0),!k.trim()&&!E.trim()&&($.email=!0,$.phoneNumber=!0),u.trim()||($.password=!0),I.trim()||($.confirmPassword=!0),t==="tenant"&&!w.trim()&&($.tenantName=!0),p($),Object.keys($).length===0},V=async $=>{if($.preventDefault(),!!W()){if(u!==I){O(S.passwordMismatchError),p({confirmPassword:!0});return}if(t==="user"&&!(h!=null&&h.id)){O(S.tenantNotFoundError);return}R(!0),O("");try{let C;t==="tenant"?C=await x({email:k||void 0,phoneNumber:E||void 0,name:f,password:u,tenantName:w,lastName:g||void 0}):C=await N({email:k||void 0,phoneNumber:E||void 0,name:f,password:u,tenantId:h.id,lastName:g||void 0}),n==null||n(C)}catch(C){const se=C.message||S.errorMessage;O(se),i==null||i(se)}finally{R(!1)}}},K=$=>({...P.input,...F[$]?P.inputError:{}}),_=()=>({...P.button,...T?P.buttonLoading:{},...!f||!k&&!E||!u||!I||T||t==="tenant"&&!w?P.buttonDisabled:{}}),B=f&&(k||E)&&u&&I&&(t==="user"||w);return r.jsxs("div",{className:y,style:P.container,children:[r.jsx("h2",{style:P.title,children:S.title}),r.jsxs("form",{onSubmit:V,style:P.form,children:[r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:f,onChange:$=>{L($.target.value),F.name&&p(C=>({...C,name:!1}))},placeholder:S.namePlaceholder,style:K("name"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:g,onChange:$=>v($.target.value),placeholder:S.lastNamePlaceholder,style:P.input,disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:k,onChange:$=>{M($.target.value),F.email&&p(C=>({...C,email:!1,phoneNumber:!1}))},placeholder:S.emailPlaceholder,style:K("email"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:E,onChange:$=>{A($.target.value),F.phoneNumber&&p(C=>({...C,email:!1,phoneNumber:!1}))},placeholder:S.phoneNumberPlaceholder,style:K("phoneNumber"),disabled:T})]}),r.jsx("div",{style:P.hintText,children:S.contactMethodHint}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:u,onChange:$=>{b($.target.value),F.password&&p(C=>({...C,password:!1}))},placeholder:S.passwordPlaceholder,style:K("password"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:I,onChange:$=>{D($.target.value),F.confirmPassword&&p(C=>({...C,confirmPassword:!1})),c===S.passwordMismatchError&&O("")},placeholder:S.confirmPasswordPlaceholder,style:K("confirmPassword"),disabled:T})]}),t==="tenant"&&r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:w,onChange:$=>{j($.target.value),F.tenantName&&p(C=>({...C,tenantName:!1}))},placeholder:S.tenantNamePlaceholder,style:K("tenantName"),disabled:T})]}),r.jsx("button",{type:"submit",disabled:!B||T,style:_(),children:T?S.loadingText:S.submitButton}),c&&r.jsx("div",{style:P.errorText,children:c})]}),(d||m)&&r.jsxs("div",{style:P.linkContainer,children:[m&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[S.magicLinkText," "]}),r.jsx("a",{onClick:l,style:P.link,children:S.magicLinkLink})]}),m&&d&&r.jsx("div",{style:P.divider,children:S.dividerBullet}),d&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[S.loginText," "]}),r.jsx("a",{onClick:o,style:P.link,children:S.loginLink})]})]})]})}const mr={title:"Sign In with Magic Link",emailLabel:"Email",emailPlaceholder:"Enter your email",nameLabel:"Name",namePlaceholder:"Enter your name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",submitButton:"Send Magic Link",loginLink:"Sign in with password",signupLink:"Sign up with password",loginText:"Already have an account?",signupText:"Prefer traditional signup?",successMessage:"Magic link sent! Check your email and click the link to sign in.",errorMessage:"Failed to send magic link. Please try again.",loadingText:"Sending magic link...",verifyingText:"Verifying magic link...",verifyingDescription:"Please wait while we verify your magic link...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you.",showNameToggle:"New user? Add your name",hideNameToggle:"Existing user? Hide name fields",tenantNotFoundError:"Tenant not found",missingTenantOrEmailError:"Missing tenant or email",dividerBullet:"•"},yr={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1rem",color:"#333333"},description:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",marginBottom:"1.5rem",lineHeight:"1.5"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem",padding:"0.75rem",backgroundColor:"#f0fdf4",borderRadius:"6px",border:"1px solid #bbf7d0"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},verifyingContainer:{textAlign:"center",padding:"2rem"},verifyingText:{fontSize:"1rem",color:"#6b7280"},toggleContainer:{textAlign:"center",marginTop:"0.5rem"},toggleLink:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"}};function wr({copy:s={},styles:e={},onSuccess:t,onError:n,onLoginClick:i,onSignupClick:o,showTraditionalLinks:l=!0,className:d,verifyToken:m,frontendUrl:y}){var _;const[f,L]=a.useState(""),[g,v]=a.useState(""),[k,M]=a.useState(""),[E,A]=a.useState(!1),[u,b]=a.useState(!1),[I,D]=a.useState(""),[w,j]=a.useState(""),[T,R]=a.useState({}),[c,O]=a.useState(!1),{sendMagicLink:F,verifyMagicLink:p}=ae(),N=((_=le())==null?void 0:_.tenant)??null,x={...mr,...s},h={...yr,...e};a.useEffect(()=>{m&&S(m)},[m]);const S=async B=>{if(!N||!f){D(x.missingTenantOrEmailError);return}b(!0),D("");try{const q=await p({token:B,email:f});t==null||t(q)}catch(q){const $=q.message||"Failed to verify magic link";D($),n==null||n($)}finally{b(!1)}},P=()=>{const B={};return f.trim()||(B.email=!0),c&&!g.trim()&&(B.name=!0),R(B),Object.keys(B).length===0},W=async B=>{if(B.preventDefault(),!!P()){if(!(N!=null&&N.id)){D(x.tenantNotFoundError);return}A(!0),D(""),j("");try{const q=y||(typeof window<"u"?window.location.origin:""),$=await F({email:f,tenantId:N.id,frontendUrl:q,name:c?g:void 0,lastName:c?k:void 0});j(x.successMessage),t==null||t($)}catch(q){const $=q.message||x.errorMessage;D($),n==null||n($)}finally{A(!1)}}},V=B=>({...h.input,...T[B]?h.inputError:{}}),K=()=>({...h.button,...E||u?h.buttonLoading:{},...!f||E||u?h.buttonDisabled:{}});return u?r.jsxs("div",{className:d,style:h.container,children:[r.jsx("h2",{style:h.title,children:x.verifyingText}),r.jsx("div",{style:h.verifyingContainer,children:r.jsx("div",{style:h.verifyingText,children:x.verifyingDescription})})]}):r.jsxs("div",{className:d,style:h.container,children:[r.jsx("h2",{style:h.title,children:x.title}),r.jsx("p",{style:h.description,children:x.description}),r.jsxs("form",{onSubmit:W,style:h.form,children:[r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:x.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:f,onChange:B=>{L(B.target.value),T.email&&R(q=>({...q,email:!1}))},placeholder:x.emailPlaceholder,style:V("email"),disabled:E||u})]}),!c&&r.jsx("div",{style:h.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>O(!0),style:h.toggleLink,children:x.showNameToggle})}),c&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:x.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:g,onChange:B=>{v(B.target.value),T.name&&R(q=>({...q,name:!1}))},placeholder:x.namePlaceholder,style:V("name"),disabled:E||u})]}),r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:x.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:k,onChange:B=>M(B.target.value),placeholder:x.lastNamePlaceholder,style:h.input,disabled:E||u})]}),r.jsx("div",{style:h.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>{O(!1),v(""),M("")},style:h.toggleLink,children:x.hideNameToggle})})]}),r.jsx("button",{type:"submit",disabled:!f||E||u,style:K(),children:E?x.loadingText:x.submitButton}),I&&r.jsx("div",{style:h.errorText,children:I}),w&&r.jsx("div",{style:h.successText,children:w})]}),l&&r.jsxs("div",{style:h.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:h.divider,children:[x.loginText," "]}),r.jsx("a",{onClick:i,style:h.link,children:x.loginLink})]}),r.jsx("div",{style:h.divider,children:x.dividerBullet}),r.jsxs("div",{children:[r.jsxs("span",{style:h.divider,children:[x.signupText," "]}),r.jsx("a",{onClick:o,style:h.link,children:x.signupLink})]})]})]})}const xr={title:"Verifying Magic Link",verifyingMessage:"Please wait while we verify your magic link...",successMessage:"Magic link verified successfully! You are now logged in.",errorMessage:"Failed to verify magic link. The link may be expired or invalid.",redirectingMessage:"Redirecting you to the dashboard...",retryButton:"Try Again",backToLoginButton:"Back to Login",missingParamsError:"Missing required parameters: token or email"},tt={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},card:{backgroundColor:"transparent",padding:"0",borderRadius:"0",boxShadow:"none",maxWidth:"100%",width:"100%",textAlign:"center"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},message:{fontSize:"1rem",color:"#6b7280",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},successMessage:{fontSize:"1rem",color:"#059669",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},errorMessage:{fontSize:"0.875rem",color:"#ef4444",textAlign:"center",marginBottom:"1rem",lineHeight:"1.5"},spinner:{display:"inline-block",width:"20px",height:"20px",border:"2px solid #e5e7eb",borderTop:"2px solid #3b82f6",borderRadius:"50%",animation:"spin 1s linear infinite",marginRight:"0.5rem"},buttonContainer:{display:"flex",gap:"0.75rem",justifyContent:"center",flexWrap:"wrap",marginTop:"1rem"},retryButton:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out"},backButton:{padding:"0.75rem 1rem",backgroundColor:"#f3f4f6",color:"#374151",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"all 0.15s ease-in-out"},retryButtonHover:{backgroundColor:"#2563eb"},backButtonHover:{backgroundColor:"#e5e7eb"}},br=()=>r.jsx("div",{style:tt.spinner}),Sr=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),vr=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),r.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),Tr={loading:r.jsx(br,{}),success:r.jsx(Sr,{}),error:r.jsx(vr,{})};function kr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onRetry:o,onBackToLogin:l,className:d,token:m,email:y,appId:f,tenantSlug:L,autoRedirectDelay:g=3e3}){const[v,k]=a.useState("verifying"),[M,E]=a.useState(""),{verifyMagicLink:A}=ae(),u={...xr,...s},b={...tt,...e},I={...Tr,...t},D=()=>{if(typeof window>"u")return{};const c=new URLSearchParams(window.location.search);return{token:m||c.get("token")||"",email:y||c.get("email")||"",appId:f||c.get("appId")||"",tenantSlug:L||c.get("tenantSlug")||void 0}},w=async()=>{k("verifying"),E("");try{const c=D();if(!c.token||!c.email)throw new Error(u.missingParamsError);const O=await A({token:c.token,email:c.email,tenantSlug:c.tenantSlug});k("success"),n==null||n(O),g>0&&setTimeout(()=>{k("redirecting")},g)}catch(c){const O=c.message||u.errorMessage;E(O),k("error"),i==null||i(O)}},j=()=>{o==null||o(),w()},T=()=>{l==null||l()};a.useEffect(()=>{w()},[]);const R=()=>{switch(v){case"verifying":return r.jsxs("div",{style:b.message,children:[I.loading,u.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[I.success,r.jsx("div",{style:b.successMessage,children:u.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[I.loading,r.jsx("div",{style:b.message,children:u.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[I.error,r.jsx("div",{style:b.errorMessage,children:M||u.errorMessage}),r.jsxs("div",{style:b.buttonContainer,children:[r.jsx("button",{onClick:j,style:b.retryButton,onMouseOver:c=>{Object.assign(c.currentTarget.style,b.retryButtonHover)},onMouseOut:c=>{const O=b.retryButton||{};Object.keys(b.retryButtonHover||{}).forEach(F=>{c.currentTarget.style[F]=O[F]??""})},children:u.retryButton}),r.jsx("button",{onClick:T,style:b.backButton,onMouseOver:c=>{Object.assign(c.currentTarget.style,b.backButtonHover)},onMouseOut:c=>{const O=b.backButton||{};Object.keys(b.backButtonHover||{}).forEach(F=>{c.currentTarget.style[F]=O[F]??""})},children:u.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:b.container,className:d,children:[r.jsx("style",{children:`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),a=require("react"),ie=require("react-router-dom");class ne{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async executeRequest(e,t,n,i){const o=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,l=(i==null?void 0:i.timeout)||this.timeout;let d={"Content-Type":"application/json",...i==null?void 0:i.headers};if(!(i!=null&&i.skipAuth)&&this.sessionManager){const f=await this.sessionManager.getValidAccessToken();d={...d,Authorization:`Bearer ${f}`}}const m=new AbortController,y=setTimeout(()=>m.abort(),l);try{const f=await fetch(o,{method:e,headers:d,body:n?JSON.stringify(n):void 0,signal:m.signal});if(clearTimeout(y),!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);const F=f.headers.get("content-type");return!F||!F.includes("application/json")?{}:await f.json()}catch(f){throw clearTimeout(y),f instanceof Error&&f.name==="AbortError"?new Error(`Request timeout after ${l}ms`):f}}async get(e,t){return this.executeRequest("GET",e,void 0,t)}async post(e,t,n){return this.executeRequest("POST",e,t,n)}async put(e,t,n){return this.executeRequest("PUT",e,t,n)}async delete(e,t){return this.executeRequest("DELETE",e,void 0,t)}}class Ae{constructor(e,t){this.httpService=e,this.sessionManager=t}async createApp(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/apps/",e,{headers:t})).data}async getApps(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/apps/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{apps:o.data,meta:o.meta}}async getAppById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}`,{headers:t})).data}async updateApp(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:n})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:n})).data}async updateSettingsSchema(e,t,n){const i=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:n},{headers:i})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const Pe=a.createContext(null);function mt({config:s,children:e}){const t=a.useMemo(()=>{var g,v,k;return{enabled:((g=s.cache)==null?void 0:g.enabled)??!0,ttl:((v=s.cache)==null?void 0:v.ttl)??3e5,storageKey:((k=s.cache)==null?void 0:k.storageKey)??`app_cache_${s.appId}`}},[s.cache,s.appId]),[n,i]=a.useState(()=>{if(!t.enabled)return null;try{const g=localStorage.getItem(t.storageKey);if(!g)return null;const v=JSON.parse(g);return Date.now()-v.timestamp<t.ttl&&v.appId===s.appId?v.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[o,l]=a.useState(!n),[d,m]=a.useState(null),y=a.useMemo(()=>{const g=()=>{f()};return{appId:s.appId,baseUrl:s.baseUrl,appInfo:n,isAppLoading:o,appError:d,retryApp:g}},[s,n,o,d]),f=a.useCallback(async(g=!1)=>{if(!(!g&&t.enabled&&n))try{l(!0),m(null);const v=new ne(s.baseUrl),M=await new Ae(v,{}).getPublicAppInfo(s.appId);if(i(M),t.enabled)try{const E={data:M,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(E))}catch(E){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Failed to cache app info:",E)}}catch(v){const k=v instanceof Error?v:new Error("Failed to load app information");m(k),i(null)}finally{l(!1)}},[s.baseUrl,s.appId,t,n]),F=a.useCallback(async()=>{if(!(!t.enabled||!n))try{const g=localStorage.getItem(t.storageKey);if(!g)return;const v=JSON.parse(g);if(Date.now()-v.timestamp>t.ttl*.5){const M=new ne(s.baseUrl),A=await new Ae(M,{}).getPublicAppInfo(s.appId);i(A);const u={data:A,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(u))}}catch(g){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Background app refresh failed:",g)}},[s,t,n]);return a.useEffect(()=>{n?F():f()},[]),r.jsx(Pe.Provider,{value:y,children:e})}function me(){const s=a.useContext(Pe);if(!s)throw new Error("useApp must be used within an AppProvider");return s}function Re(){return a.useContext(Pe)}const yt=me;class ee extends Error{constructor(e,t){const n={token_expired:"Refresh token has expired",token_invalid:"Refresh token is invalid",user_inactive:"User account is inactive"};super(t||n[e]),this.name="SessionExpiredError",this.reason=e}}class ze extends Error{constructor(e){super(`Token refresh timed out after ${e}ms`),this.name="TokenRefreshTimeoutError",this.timeoutMs=e}}class Ve extends Error{constructor(e,t){super(`Token refresh failed after ${e} attempts: ${(t==null?void 0:t.message)||"Unknown error"}`),this.name="TokenRefreshError",this.attempts=e,this.lastError=t}}const te=class te{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],this.proactiveTimerId=null,this.backgroundRetryTimerId=null,this.isDestroyed=!1,this.sessionGeneration=0,this.consecutiveBackgroundFailures=0,e.tenantSlug!==void 0?this.storageKey=e.tenantSlug?`auth_tokens_${e.tenantSlug}`:"auth_tokens":this.storageKey=e.storageKey||"auth_tokens",this.autoRefresh=e.autoRefresh??!0,this.refreshThreshold=e.refreshThreshold||3e5,this.onRefreshFailed=e.onRefreshFailed,this.onSessionExpired=e.onSessionExpired,this.baseUrl=e.baseUrl||"",this.proactiveRefreshMargin=e.proactiveRefreshMargin??6e4,this.refreshQueueTimeout=e.refreshQueueTimeout??1e4,this.maxRefreshRetries=e.maxRefreshRetries??3,this.retryBackoffBase=e.retryBackoffBase??1e3,this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey),this.scheduleProactiveRefresh()}static getInstance(e={}){const t=te.resolveStorageKey(e),n=te.instances.get(t);if(n)return n.updateConfig(e),n;const i=new te(e);return te.instances.set(t,i),i}static resetAllInstances(){for(const e of te.instances.values())e.destroy();te.instances.clear()}static resolveStorageKey(e){return e.storageKey?e.storageKey:e.tenantSlug!==void 0&&e.tenantSlug?`auth_tokens_${e.tenantSlug}`:"auth_tokens"}updateConfig(e){e.onSessionExpired!==void 0&&(this.onSessionExpired=e.onSessionExpired),e.onRefreshFailed!==void 0&&(this.onRefreshFailed=e.onRefreshFailed),e.baseUrl&&(this.baseUrl=e.baseUrl)}createTokenStorage(e){return{get:()=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},set:t=>{try{localStorage.setItem(e,JSON.stringify(t))}catch{}},clear:()=>{try{localStorage.removeItem(e)}catch{}}}}static extractJwtExpiry(e){try{const t=e.split(".");if(t.length!==3)return;const n=JSON.parse(atob(t[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof n.exp=="number"?n.exp*1e3:void 0}catch{return}}setTokens(e){const t=e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)||te.extractJwtExpiry(e.accessToken),n={...e,expiresAt:t},i=this.tokenStorage.get()||{};this.tokenStorage.set({...i,...n}),this.scheduleProactiveRefresh()}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:n,expiresIn:i,tokenType:o}=this.tokenStorage.get()||{};if(!e)return null;const l=n||te.extractJwtExpiry(e);return{accessToken:e,refreshToken:t,expiresAt:l,expiresIn:i,tokenType:o}}clearTokens(){this.tokenStorage.clear()}isTokenExpired(e){const t=e||this.getTokens();return t!=null&&t.expiresAt?Date.now()>=t.expiresAt:!1}shouldRefreshToken(e){const t=e||this.getTokens();return!(t!=null&&t.expiresAt)||!this.autoRefresh?!1:Date.now()>=t.expiresAt-this.refreshThreshold}getAccessToken(){const e=this.getTokens();return(e==null?void 0:e.accessToken)||null}scheduleProactiveRefresh(){if(this.cancelProactiveTimer(),!this.autoRefresh||this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.expiresAt)||!e.refreshToken)return;const n=e.expiresAt-this.proactiveRefreshMargin-Date.now();if(n<=0){this.backgroundRefresh();return}this.proactiveTimerId=setTimeout(()=>{this.backgroundRefresh()},n)}cancelProactiveTimer(){this.proactiveTimerId!==null&&(clearTimeout(this.proactiveTimerId),this.proactiveTimerId=null),this.backgroundRetryTimerId!==null&&(clearTimeout(this.backgroundRetryTimerId),this.backgroundRetryTimerId=null)}backgroundRefresh(){if(this.isDestroyed)return;const e=this.getTokens();if(!(e!=null&&e.refreshToken)||this.refreshPromise)return;const t=this.sessionGeneration;this.startRefreshAndResolveQueue(e.refreshToken).then(()=>{this.consecutiveBackgroundFailures=0}).catch(n=>{if(!(n instanceof ee)){if(this.sessionGeneration===t){if(this.consecutiveBackgroundFailures++,this.consecutiveBackgroundFailures>=te.MAX_BACKGROUND_FAILURES){process.env.NODE_ENV==="development"&&console.error(`[SessionManager] Background refresh failed ${this.consecutiveBackgroundFailures} consecutive times — expiring session`),this.consecutiveBackgroundFailures=0,this.handleSessionExpired(new ee("token_invalid","Background refresh failed repeatedly"));return}process.env.NODE_ENV==="development"&&console.warn("[SessionManager] Background refresh failed, retrying in 30s:",n.message),this.backgroundRetryTimerId=setTimeout(()=>{this.backgroundRefresh()},3e4)}}})}async waitForPendingRefresh(){if(!this.refreshPromise)return!1;try{return await this.refreshPromise,!0}catch{return!1}}async getValidAccessToken(){const e=this.getTokens();if(!(e!=null&&e.accessToken)){const t=new ee("token_invalid","No tokens available");throw this.handleSessionExpired(t),t}if(!this.shouldRefreshToken(e)&&!this.isTokenExpired(e))return e.accessToken;if(!e.refreshToken){const t=new ee("token_invalid","No refresh token available");throw this.handleSessionExpired(t),t}return this.refreshPromise?this.enqueueForToken():this.startRefreshAndResolveQueue(e.refreshToken)}async getAuthHeaders(){try{return{Authorization:`Bearer ${await this.getValidAccessToken()}`}}catch(e){return e instanceof ee&&this.onRefreshFailed&&this.onRefreshFailed(),{}}}enqueueForToken(){return new Promise((e,t)=>{const n=setTimeout(()=>{const i=this.refreshQueue.findIndex(o=>o.timeoutId===n);i!==-1&&this.refreshQueue.splice(i,1),t(new ze(this.refreshQueueTimeout))},this.refreshQueueTimeout);this.refreshQueue.push({resolve:e,reject:t,timeoutId:n})})}async startRefreshAndResolveQueue(e){this.refreshPromise=this.executeRefreshWithRetry(e);try{await this.refreshPromise;const t=this.getTokens(),n=(t==null?void 0:t.accessToken)||"";return this.resolveQueue(n),n}catch(t){const n=t instanceof Error?t:new Error("Token refresh failed");throw n instanceof ee?(this.rejectQueue(n),this.handleSessionExpired(n)):this.rejectQueue(n),n}finally{this.refreshPromise=null}}resolveQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const n of t)clearTimeout(n.timeoutId),n.resolve(e)}rejectQueue(e){const t=[...this.refreshQueue];this.refreshQueue=[];for(const n of t)clearTimeout(n.timeoutId),n.reject(e)}async executeRefreshWithRetry(e){let t;const n=this.sessionGeneration;for(let i=0;i<=this.maxRefreshRetries;i++){if(this.sessionGeneration!==n)throw new ee("token_invalid","Session cleared during refresh");try{await this.performTokenRefresh(e,n);return}catch(o){const l=o instanceof Error?o:new Error(String(o));if(l instanceof ee)throw l;if(t=l,i<this.maxRefreshRetries){const d=this.retryBackoffBase*Math.pow(2,i);await this.sleep(d)}}}throw new Ve(this.maxRefreshRetries+1,t)}async performTokenRefresh(e,t){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const n=`${this.baseUrl}/auth/refresh`;let i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})})}catch(l){throw l instanceof Error?l:new Error("Network error during token refresh")}if(!i.ok){let l="";try{const d=await i.json();l=(d.message||d.error||"").toLowerCase()}catch{l=i.statusText.toLowerCase()}throw i.status===401?l.includes("expired")?new ee("token_expired"):l.includes("invalid")?new ee("token_invalid"):new ee("token_invalid",`Unauthorized: ${l}`):i.status===400?l.includes("inactive")?new ee("user_inactive"):l.includes("expired")||l.includes("invalid")?new ee("token_invalid",l):l.includes("reuse")||l.includes("revoked")?new ee("token_invalid",l):new Error(`Token refresh failed (400): ${l}`):new Error(`Token refresh failed: ${i.status} ${l}`)}if(this.sessionGeneration!==t)throw new ee("token_invalid","Session cleared during refresh");const o=await i.json();this.setTokens({accessToken:o.accessToken,refreshToken:o.refreshToken||e,expiresIn:o.expiresIn})}handleSessionExpired(e){this.cancelProactiveTimer(),this.clearSession(),this.onSessionExpired?this.onSessionExpired(e):this.onRefreshFailed&&this.onRefreshFailed()}setUser(e){const t=this.tokenStorage.get()||{};this.tokenStorage.set({...t,user:e})}getUser(){const e=this.tokenStorage.get();return(e==null?void 0:e.user)||null}clearUser(){const e=this.tokenStorage.get()||{};delete e.user,this.tokenStorage.set(e)}clearSession(){this.sessionGeneration++,this.cancelProactiveTimer(),this.clearTokens();const e=new ee("token_invalid","Session cleared");this.rejectQueue(e)}destroy(){this.isDestroyed=!0,te.instances.delete(this.storageKey),this.cancelProactiveTimer();const e=new ee("token_invalid","SessionManager destroyed");this.rejectQueue(e)}getTokenPayload(){try{const e=this.getTokens();if(!(e!=null&&e.accessToken))return null;const t=e.accessToken.split(".");if(t.length!==3)return null;const n=t[1],i=atob(n.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(i)}catch{return null}}getUserId(){const e=this.getTokenPayload();if(e!=null&&e.userId)return e.userId;const t=this.getUser();return(t==null?void 0:t.id)||null}hasValidSession(){const e=this.getTokens();return e!==null&&!this.isTokenExpired(e)}sleep(e){return new Promise(t=>setTimeout(t,e))}};te.instances=new Map,te.MAX_BACKGROUND_FAILURES=3;let he=te;const ve=new Map;class We{constructor(e){this.httpService=e}async login(e){return await this.httpService.post("/auth/login",e)}async signup(e){return await this.httpService.post("/auth/signup",e)}async signupTenantAdmin(e){return await this.httpService.post("/auth/signup/tenant-admin",e)}async refreshToken(e){return await this.httpService.post("/auth/refresh",e)}async switchTenant(e){return await this.httpService.post("/auth/switch-tenant",e)}async getUserTenants(e){return await this.httpService.get("/auth/tenants",{headers:e})}async requestPasswordReset(e){await this.httpService.post("/auth/password-reset/request",e)}async sendMagicLink(e){return await this.httpService.post("/auth/magic-link/send",e)}async verifyMagicLink(e){const t=e.token,n=ve.get(t);if(n)return n;const i=this.httpService.post("/auth/magic-link/verify",e).finally(()=>{ve.delete(t)});return ve.set(t,i),i}async confirmPasswordReset(e){await this.httpService.post("/auth/password-reset/confirm",e)}async changePassword(e,t){await this.httpService.post("/auth/change-password",e,{headers:t})}}class je{constructor(e,t){this.httpService=e,this.sessionManager=t}async createRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/roles/",e,{headers:t})).data}async getRoleById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/roles/${e}`,{headers:t})).data}async updateRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:n})).data}async deleteRole(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/roles/${e}`,{headers:t})}async getRolesByApp(e,t){const n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const i=`/roles/app/${e}${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i);return{roles:o.data,meta:o.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:n})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:n})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders(),i=new URLSearchParams;t!=null&&t.page&&i.append("page",t.page.toString()),t!=null&&t.limit&&i.append("limit",t.limit.toString()),t!=null&&t.sortBy&&i.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&i.append("sortOrder",t.sortOrder);const o=`/roles/user/${e}${i.toString()?`?${i.toString()}`:""}`,l=await this.httpService.get(o,{headers:n});return{roles:l.data,meta:l.meta}}}class Ge{constructor(e,t){this.httpService=e,this.sessionManager=t}async createUser(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/users/",e,{headers:t})).data}async getUsers(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/users/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{users:o.data,meta:o.meta}}async getUserById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/users/${e}`,{headers:t})).data}async updateUser(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:n})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class pe{constructor(e,t,n){this.httpService=e,this.appId=t,this.sessionManager=n}async createTenant(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/tenants/",e,{headers:t})).data}async getTenants(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/tenants/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{tenants:o.data,meta:o.meta}}async getTenantById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/tenants/${e}`,{headers:t})).data}async updateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:n})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:n})).data}async getPublicTenantInfo(e){return(await this.httpService.get(`/tenants/${this.appId}/${e}/public`)).data}async getTenantSettings(e){return(await this.httpService.get(`/tenants/${e}/settings`)).data}async updateTenantSettings(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:n})).data}}function wt(s,e){if(s==="localhost"||s.startsWith("127.")||s.startsWith("192.168."))return null;if(e){const i=e.toLowerCase(),o=s.toLowerCase();if(o===i||o===`www.${i}`)return null;if(o.endsWith(`.${i}`)){const l=o.slice(0,-(i.length+1));return l==="www"?null:l}return null}const n=s.split(".");return n.length>=3&&n[0]!=="www"?n[0]:null}function xt(s,e="tenant",t){const i=new URLSearchParams(s).get(e);return i?(t&&t.setItem("tenant",i),i):t?t.getItem("tenant"):null}function bt(s,e,t){const{tenantMode:n,baseDomain:i,selectorParam:o,fixedTenantSlug:l}=s;return n==="fixed"?l||null:n==="subdomain"?wt(e.hostname,i):n==="selector"?xt(e.search,o,t):null}function St(s,e,t){if(t)return`${s}.${t}`;const n=e.split(".");return n.length===2?`${s}.${e}`:n.length>=3?(n[0]=s,n.join(".")):null}const ue="_auth";function $e(s){const e=JSON.stringify(s);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vt(s){try{let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";const t=atob(e),n=JSON.parse(t);return typeof n.accessToken=="string"&&typeof n.refreshToken=="string"&&typeof n.expiresIn=="number"?n:null}catch{return null}}function Tt(){if(typeof window>"u")return null;const e=new URLSearchParams(window.location.search).get(ue);return e?vt(e):null}function kt(){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.delete(ue),window.history.replaceState({},"",s.toString())}const Ee=a.createContext(null);function At({config:s,children:e}){const{baseUrl:t,appInfo:n,appId:i}=me(),o=a.useCallback(()=>typeof window>"u"?null:bt({tenantMode:s.tenantMode||"selector",baseDomain:s.baseDomain,selectorParam:s.selectorParam,fixedTenantSlug:s.fixedTenantSlug},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[s.tenantMode,s.baseDomain,s.selectorParam,s.fixedTenantSlug]),[l,d]=a.useState(()=>o()),m=a.useMemo(()=>{var p,N,x;return{enabled:((p=s.cache)==null?void 0:p.enabled)??!0,ttl:((N=s.cache)==null?void 0:N.ttl)??5*60*1e3,storageKey:((x=s.cache)==null?void 0:x.storageKey)??`tenant_cache_${l||"default"}`}},[s.cache,l]),[y,f]=a.useState(()=>{if(s.initialTenant)return s.initialTenant;if(!m.enabled||!l)return null;try{const p=localStorage.getItem(m.storageKey);if(!p)return null;const N=JSON.parse(p);return Date.now()-N.timestamp<m.ttl&&N.tenantSlug===l?N.data:(localStorage.removeItem(m.storageKey),null)}catch{return null}}),[F,g]=a.useState(!y&&!s.initialTenant),[v,k]=a.useState(null),[M,E]=a.useState(null),[A,u]=a.useState(!1),[b,I]=a.useState(null);a.useEffect(()=>{if(s.tenantMode==="fixed")return;const p=o();d(p)},[o,s.tenantMode]);const D=(n==null?void 0:n.settingsSchema)||null,w=a.useCallback(async(p,N=!1)=>{if(!(!N&&m.enabled&&y&&y.domain===p))try{g(!0),k(null);const x=new ne(t),S=await new pe(x,i).getPublicTenantInfo(p);if(f(S),m.enabled)try{const P={data:S,timestamp:Date.now(),tenantSlug:p};localStorage.setItem(m.storageKey,JSON.stringify(P))}catch(P){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Failed to cache tenant info:",P)}}catch(x){const h=x instanceof Error?x:new Error("Failed to load tenant information");k(h),f(null)}finally{g(!1)}},[t,i,m,y]),j=a.useCallback(async()=>{if(!(!m.enabled||!y||!l))try{const p=localStorage.getItem(m.storageKey);if(!p)return;const N=JSON.parse(p);if(Date.now()-N.timestamp>m.ttl*.5){const h=new ne(t),P=await new pe(h,i).getPublicTenantInfo(l);f(P);const W={data:P,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(m.storageKey,JSON.stringify(W))}}catch(p){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Background tenant refresh failed:",p)}},[t,i,m,y,l]),T=a.useCallback(async()=>{if(y!=null&&y.id)try{u(!0),I(null);const p=new ne(t),x=await new pe(p,y.appId).getTenantSettings(y.id);E(x)}catch(p){const N=p instanceof Error?p:new Error("Failed to load tenant settings");I(N),E(null)}finally{u(!1)}},[t,y]),R=a.useCallback(()=>{T()},[T]),c=a.useCallback(p=>{if(!D)return{isValid:!0,errors:[]};const N=[];try{return D.properties&&Object.entries(D.properties).forEach(([x,h])=>{var P;const S=p[x];if((P=D.required)!=null&&P.includes(x)&&S==null){N.push(`Field '${x}' is required`);return}if(S!=null){if(h.type){const W=h.type,V=typeof S;W==="string"&&V!=="string"?N.push(`Field '${x}' must be a string`):(W==="number"||W==="integer")&&V!=="number"?N.push(`Field '${x}' must be a number`):W==="boolean"&&V!=="boolean"?N.push(`Field '${x}' must be a boolean`):W==="array"&&!Array.isArray(S)&&N.push(`Field '${x}' must be an array`)}h.minLength!==void 0&&typeof S=="string"&&S.length<h.minLength&&N.push(`Field '${x}' must be at least ${h.minLength} characters long`),h.maxLength!==void 0&&typeof S=="string"&&S.length>h.maxLength&&N.push(`Field '${x}' must be no more than ${h.maxLength} characters long`),h.minimum!==void 0&&typeof S=="number"&&S<h.minimum&&N.push(`Field '${x}' must be at least ${h.minimum}`),h.maximum!==void 0&&typeof S=="number"&&S>h.maximum&&N.push(`Field '${x}' must be no more than ${h.maximum}`),h.pattern&&typeof S=="string"&&(new RegExp(h.pattern).test(S)||N.push(`Field '${x}' does not match the required pattern`)),h.enum&&!h.enum.includes(S)&&N.push(`Field '${x}' must be one of: ${h.enum.join(", ")}`)}}),{isValid:N.length===0,errors:N}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[D]);a.useEffect(()=>{!s.initialTenant&&l?y?j():w(l):!s.initialTenant&&!l&&(f(null),k(null),g(!1))},[s.initialTenant,l,y,w,j]),a.useEffect(()=>{y!=null&&y.id?T():(E(null),I(null),u(!1))},[y==null?void 0:y.id,T]);const O=a.useCallback((p,N)=>{const{mode:x="reload",tokens:h,redirectPath:S}=N||{},P=s.tenantMode||"selector";if(P==="fixed"){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] switchTenant is a no-op in fixed mode. Tenant is always:",s.fixedTenantSlug),S&&(window.location.href=S);return}if(localStorage.setItem("tenant",p),P==="subdomain"){const W=window.location.hostname,V=St(p,W,s.baseDomain);if(!V){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",W);return}const Q=S||window.location.pathname,_=new URL(`${window.location.protocol}//${V}${Q}`);new URLSearchParams(window.location.search).forEach((q,B)=>{B!==ue&&_.searchParams.set(B,q)}),h&&_.searchParams.set(ue,$e(h)),window.location.href=_.toString()}else if(P==="selector"){const W=S||window.location.pathname,V=new URLSearchParams(window.location.search);if(V.set(s.selectorParam||"tenant",p),V.delete(ue),h&&V.set(ue,$e(h)),x==="reload"){const Q=`${W}?${V.toString()}${window.location.hash}`;window.location.href=Q}else{const Q=`${W}?${V.toString()}${window.location.hash}`;window.history.pushState({},"",Q),d(p),w(p)}}},[s.tenantMode,s.selectorParam,s.baseDomain,w]),L=a.useMemo(()=>({tenant:y,tenantSlug:l,isTenantLoading:F,tenantError:v,retryTenant:()=>{l&&w(l)},settings:M,settingsSchema:D,isSettingsLoading:A,settingsError:b,refreshSettings:R,switchTenant:O,validateSettings:c}),[y,l,F,v,M,D,A,b,R,O,c]);return r.jsx(Ee.Provider,{value:L,children:e})}function fe(){const s=a.useContext(Ee);if(!s)throw new Error("useTenant must be used within a TenantProvider");return s}function le(){return a.useContext(Ee)}const jt=fe;function Pt(){const{settings:s,settingsSchema:e,isSettingsLoading:t,settingsError:n,validateSettings:i}=fe();return{settings:s,settingsSchema:e,isLoading:t,error:n,validateSettings:i}}function Me(){const{tenant:s,tenantSlug:e,isTenantLoading:t,tenantError:n,retryTenant:i}=fe();return{tenant:s,tenantSlug:e,isLoading:t,error:n,retry:i}}const Ie=a.createContext(null);function Rt({config:s={},children:e}){const t=Re(),n=le(),i=(t==null?void 0:t.baseUrl)??s.baseUrl??"",o=(t==null?void 0:t.appId)??s.appId,l=(n==null?void 0:n.tenant)??null,d=(n==null?void 0:n.tenantSlug)??null,m=(n==null?void 0:n.switchTenant)??(()=>{});if(!i)throw new Error("[AuthProvider] baseUrl is required. Provide it via AppProvider or AuthConfig.baseUrl.");const[y,f]=a.useState(s.initialRoles||[]),[F,g]=a.useState(!s.initialRoles),[v,k]=a.useState(null),[M,E]=a.useState(!1),[A,u]=a.useState(null),[b,I]=a.useState(()=>{try{const C=localStorage.getItem("userTenants");return C?JSON.parse(C):[]}catch{return[]}}),[D,w]=a.useState(!1),j=a.useRef({done:!1,urlTokens:null});j.current.done||(j.current.done=!0,j.current.urlTokens=Tt());const[T,R]=a.useState(()=>j.current.urlTokens!==null),c=a.useMemo(()=>{const C=he.getInstance({tenantSlug:d,baseUrl:i,refreshQueueTimeout:s.refreshQueueTimeout,proactiveRefreshMargin:s.proactiveRefreshMargin,onSessionExpired:se=>{k(null),u(null),I([]),w(!1);try{localStorage.removeItem("userTenants")}catch{}s.onSessionExpired?s.onSessionExpired(se):s.onRefreshFailed&&s.onRefreshFailed()}});return j.current.urlTokens&&C.setTokens({accessToken:j.current.urlTokens.accessToken,refreshToken:j.current.urlTokens.refreshToken,expiresIn:j.current.urlTokens.expiresIn}),C},[d,i,s.refreshQueueTimeout,s.proactiveRefreshMargin]),[O,L]=a.useState(()=>{if(j.current.urlTokens)return!1;const C=c.getTokens();return C?c.hasValidSession()||!!C.refreshToken:!1}),p=j.current.done&&!T&&!O,N=a.useMemo(()=>{const C=new ne(i);return C.setSessionManager(c),C},[i,c]),x=a.useMemo(()=>new We(new ne(i)),[i]),h=a.useMemo(()=>new Ge(N,c),[N,c]),S=a.useMemo(()=>new je(new ne(i)),[i]),P=a.useMemo(()=>v||c.getUser(),[v,c]),W=a.useMemo(()=>P!=null&&P.roleId&&y.find(C=>C.id===P.roleId)||null,[P,y]),V=a.useMemo(()=>(W==null?void 0:W.permissions)||[],[W]),Q=a.useMemo(()=>c.hasValidSession()&&v!==null,[c,v]),_=a.useRef(async()=>{}),H=a.useMemo(()=>{const C=async(U=!1)=>{try{if(!c.hasValidSession()||!U&&v)return;const $=c.getUserId();if(!$){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] No userId available in token or storage");return}E(!0),u(null);const Z=await h.getUserById($);k(Z),c.setUser(Z)}catch($){const Z=$ instanceof Error?$:new Error("Failed to load user data");u(Z),process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data:",Z)}finally{E(!1)}},se=async()=>{await C()},ce=async U=>{var Ue;const{username:$,password:Z,tenantSlug:z,redirectPath:K}=U;let J=l==null?void 0:l.id,Y=d,X=c;z&&(J=(await new pe(N,o).getPublicTenantInfo(z)).id,Y=z);const G=await x.login({username:$,password:Z,appId:o,tenantId:J}),ge=z&&z!==d;if(ge&&(X=new he({tenantSlug:Y,baseUrl:i})),X.setTokens({accessToken:G.accessToken,refreshToken:G.refreshToken,expiresIn:G.expiresIn}),G.user){X.setUser(G.user),k(G.user);try{await C()}catch(ye){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after login:",ye)}}if(G.tenants&&G.tenants.length>0){I(G.tenants);try{localStorage.setItem("userTenants",JSON.stringify(G.tenants))}catch{}}const be=((Ue=G.user)==null?void 0:Ue.tenantId)!==null;w(be);const Se={accessToken:G.accessToken,refreshToken:G.refreshToken,expiresIn:G.expiresIn};if(ge&&Y)return m(Y,{tokens:Se,redirectPath:K}),G;if(K&&K!==window.location.pathname)return m(Y||d||"",{tokens:Se,redirectPath:K}),G;if(!be&&G.tenants&&G.tenants.length>0){const ye=U.autoSwitch!==!1&&s.autoSwitchSingleTenant!==!1;if(G.tenants.length===1&&ye){const Be=G.tenants[0];return m(Be.subdomain,{tokens:Se,redirectPath:K}),G}else G.tenants.length>1&&s.onTenantSelectionRequired&&s.onTenantSelectionRequired(G.tenants)}return G},de=async U=>{const{email:$,phoneNumber:Z,name:z,password:K,lastName:J,tenantId:Y}=U;if(!$&&!Z)throw new Error("Either email or phoneNumber is required");if(!z||!K)throw new Error("Name and password are required");const X=Y??(l==null?void 0:l.id);return await x.signup({email:$,phoneNumber:Z,name:z,password:K,tenantId:X,lastName:J,appId:o})},nt=async U=>{const{email:$,phoneNumber:Z,name:z,password:K,tenantName:J,lastName:Y}=U;if(!$&&!Z)throw new Error("Either email or phoneNumber is required");if(!z||!K||!J)throw new Error("Name, password, and tenantName are required");return await x.signupTenantAdmin({email:$,phoneNumber:Z,name:z,password:K,tenantName:J,appId:o,lastName:Y})},st=async U=>{const{currentPassword:$,newPassword:Z}=U,z=await c.getAuthHeaders();await x.changePassword({currentPassword:$,newPassword:Z},z)},it=async U=>{const{email:$,tenantId:Z}=U,z=Z??(l==null?void 0:l.id);if(!z)throw new Error("tenantId is required for password reset");await x.requestPasswordReset({email:$,tenantId:z})},ot=async U=>{const{token:$,newPassword:Z}=U;await x.confirmPasswordReset({token:$,newPassword:Z})},at=async U=>{const{email:$,frontendUrl:Z,name:z,lastName:K,tenantId:J}=U,Y=J??(l==null?void 0:l.id);if(!Y)throw new Error("tenantId is required for magic link authentication");return await x.sendMagicLink({email:$,tenantId:Y,frontendUrl:Z,name:z,lastName:K,appId:o})},lt=async U=>{const{token:$,email:Z,tenantSlug:z}=U;let K=l==null?void 0:l.id,J=d,Y=c;z&&(K=(await new pe(N,o).getPublicTenantInfo(z)).id,J=z);const X=await x.verifyMagicLink({token:$,email:Z,appId:o,tenantId:K}),G=z&&z!==d;if(G&&(Y=new he({tenantSlug:J,baseUrl:i})),Y.setTokens({accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}),X.user){Y.setUser(X.user),k(X.user);try{await C()}catch(ge){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after magic link:",ge)}}return G&&J&&J!==d&&m(J,{tokens:{accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}}),X},ct=async()=>{const U=c.getTokens();if(!(U!=null&&U.refreshToken))throw new Error("No refresh token available");const $=await x.refreshToken({refreshToken:U.refreshToken});c.setTokens({accessToken:$.accessToken,refreshToken:$.refreshToken||U.refreshToken,expiresIn:$.expiresIn})},dt=()=>{c.clearSession(),k(null),u(null),I([]),w(!1);try{localStorage.removeItem("userTenants")}catch{}},ut=U=>{c.setTokens(U)},ht=()=>c.hasValidSession(),pt=()=>{c.clearSession(),k(null),u(null)},ft=async()=>{if(o)try{g(!0);const{roles:U}=await S.getRolesByApp(o);f(U)}catch(U){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",U)}finally{g(!1)}},gt=async()=>{await ft()},xe=U=>{if(!V||V.length===0)return!1;if(typeof U=="string")return V.includes(U);const $=`${U.resource}.${U.action}`;return V.includes($)};return{isAuthenticated:Q,sessionManager:c,authenticatedHttpService:N,login:ce,signup:de,signupTenantAdmin:nt,sendMagicLink:at,verifyMagicLink:lt,changePassword:st,requestPasswordReset:it,confirmPasswordReset:ot,refreshToken:ct,logout:dt,setTokens:ut,hasValidSession:ht,clearSession:pt,currentUser:v,isUserLoading:M,userError:A,loadUserData:C,refreshUser:se,isAuthInitializing:!p,isAuthReady:p,userRole:W,userPermissions:V,availableRoles:y,rolesLoading:F,hasPermission:xe,hasAnyPermission:U=>U.some($=>xe($)),hasAllPermissions:U=>U.every($=>xe($)),getUserPermissionStrings:()=>V||[],refreshRoles:gt,userTenants:b,hasTenantContext:D,switchToTenant:async(U,$)=>{const{redirectPath:Z}=$||{},z=c.getTokens();if(!(z!=null&&z.refreshToken))throw new Error("No refresh token available for tenant switch");const K=await x.switchTenant({refreshToken:z.refreshToken,tenantId:U});c.setTokens({accessToken:K.accessToken,refreshToken:z.refreshToken,expiresIn:K.expiresIn}),k(K.user),c.setUser(K.user),w(!0);const J=b.find(Y=>Y.id===U);J&&m(J.subdomain,{tokens:{accessToken:K.accessToken,refreshToken:z.refreshToken,expiresIn:K.expiresIn},redirectPath:Z})},refreshUserTenants:async()=>{const U=await c.getAuthHeaders(),$=await x.getUserTenants(U);I($);try{localStorage.setItem("userTenants",JSON.stringify($))}catch{}return $}}},[Q,c,N,x,h,S,o,l,d,m,y,v,M,A,b,D,p,W,V]);_.current=H.loadUserData,a.useEffect(()=>{!s.initialRoles&&o&&(async()=>{try{g(!0);const se=new ne(i),ce=new je(se),{roles:de}=await ce.getRolesByApp(o);f(de)}catch(se){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",se)}finally{g(!1)}})()},[o,i,s.initialRoles]);const[q,B]=a.useState(!1);return a.useEffect(()=>{q||(B(!0),j.current.urlTokens&&(kt(),R(!0),H.loadUserData().catch(C=>{process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data after URL tokens:",C)}).finally(()=>{R(!1)})))},[H,q]),a.useEffect(()=>{let C=!1;return(async()=>{var de;if(!c.hasValidSession()&&((de=c.getTokens())!=null&&de.refreshToken)&&await c.waitForPendingRefresh(),C)return;const ce=c.getUser();ce&&c.hasValidSession()&&k(ce),L(!1)})(),()=>{C=!0}},[c]),a.useEffect(()=>{q&&(j.current.urlTokens||(!v&&!M&&!A&&c.hasValidSession()?_.current().catch(()=>{}).finally(()=>{L(!1)}):L(!1)))},[v,M,A,c,q]),r.jsx(Ie.Provider,{value:H,children:e})}function ae(){const s=a.useContext(Ie);if(!s)throw new Error("useAuth must be used within an AuthProvider");return s}function Fe(){return a.useContext(Ie)}class Ze{constructor(e,t){this.httpService=e,this.sessionManager=t}async createFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/feature-flags/",e,{headers:t})).data}async getFeatureFlags(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/feature-flags/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{featureFlags:o.data,meta:o.meta}}async getFeatureFlagById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/feature-flags/${e}`,{headers:t})).data}async updateFeatureFlag(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:n})).data}async deleteFeatureFlag(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/feature-flags/${e}`,{headers:t})}async getTenantFeatureFlags(e,t){if(!e||!t)throw new Error("Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",e),n.append("appId",t);const i=`/tenant-feature-flags${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(i,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,n){if(!e||!t||!n)throw new Error("Flag Key, Tenant ID and App ID are required");const i=new URLSearchParams;i.append("tenantId",t),i.append("appId",n);const o=`/tenant-feature-flags/${e}${i.toString()?`?${i.toString()}`:""}`;return(await this.httpService.get(o,{headers:{"X-Tenant-ID":t}})).data}}const Le=a.createContext(null);function Et({config:s={},children:e}){const t=Re(),n=le(),i=(t==null?void 0:t.baseUrl)??"",o=(t==null?void 0:t.appId)??"",l=(n==null?void 0:n.tenant)??null,[d,m]=a.useState([]),[y,f]=a.useState(!1),[F,g]=a.useState(null),[v,k]=a.useState(!1),M=a.useMemo(()=>{const u=new ne(i);return new Ze(u)},[i]),E=async()=>{if(!(l!=null&&l.id)){m([]);return}f(!0),g(null);try{const u=await M.getTenantFeatureFlags(l.id,o);m(u)}catch(u){const b=u instanceof Error?u.message:"Failed to fetch feature flags";g(b),s.onError&&s.onError(u instanceof Error?u:new Error(b))}finally{f(!1)}};a.useEffect(()=>{if(!i||!o)return;E().finally(()=>k(!0));const u=s.refreshInterval||5*60*1e3,b=setInterval(E,u);return()=>clearInterval(b)},[l==null?void 0:l.id,i,o,s.refreshInterval]);const A=a.useMemo(()=>{const u=j=>{const T=d.find(R=>R.key===j);return(T==null?void 0:T.value)===!0},b=j=>d.find(T=>T.key===j),I=j=>{const T=d.find(R=>R.key===j);return T?T.value?"enabled":"disabled":"not_found"},D=async()=>{await E()},w=!!(i&&o)&&(v||!(l!=null&&l.id));return{featureFlags:d,loading:y,error:F,isReady:w,isEnabled:u,getFlag:b,getFlagState:I,refresh:D}},[d,y,F,i,o,l==null?void 0:l.id,v]);return r.jsx(Le.Provider,{value:A,children:e})}function Ke(){const s=a.useContext(Le);if(!s)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return s}function Qe(){return a.useContext(Le)}class Je{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscription(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscriptions/",e,{headers:t})).data}async getSubscriptionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscriptions/subscriptions/${e}`,{headers:t})).data}async updateSubscription(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:n})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:n})).data}async getTenantSubscriptionFeatures(e){return(await this.httpService.get(`/subscriptions/tenants/${e}/subscription-features`)).data}async processPayment(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:n})).data}}const Ne=a.createContext(void 0);function Mt({config:s={},children:e}){const t=Re(),n=le(),i=(t==null?void 0:t.baseUrl)??"",o=(n==null?void 0:n.tenant)??null,[l,d]=a.useState(null),[m,y]=a.useState(!1),[f,F]=a.useState(null),[g,v]=a.useState(!1),k=a.useMemo(()=>{const A=new ne(i);return new Je(A)},[i]),M=async()=>{if(!(o!=null&&o.id)){d(null);return}y(!0),F(null);try{const A=await k.getTenantSubscriptionFeatures(o.id);d(A)}catch(A){const u=A instanceof Error?A.message:"Failed to fetch subscription";F(u),s.onError&&s.onError(A instanceof Error?A:new Error(u))}finally{y(!1)}};a.useEffect(()=>{if(!i||(M().finally(()=>v(!0)),!s.refreshInterval))return;const A=s.refreshInterval||10*60*1e3,u=setInterval(M,A);return()=>clearInterval(u)},[o==null?void 0:o.id,i,s.refreshInterval]);const E=a.useMemo(()=>{const A=(l==null?void 0:l.features)||[],u=T=>{const R=A.find(c=>c.key===T);return R?R.type==="BOOLEAN"||R.type==="boolean"?R.value===!0:!!R.value:!1},b=T=>A.find(R=>R.key===T),I=(T,R)=>{const c=A.find(O=>O.key===T);return c?c.value:R},D=T=>!l||!l.isActive?!1:T.includes(l.planId),w=async()=>{await M()},j=!!i&&(g||!(o!=null&&o.id));return{subscription:l,features:A,loading:m,error:f,isReady:j,isFeatureEnabled:u,getFeature:b,getFeatureValue:I,hasAllowedPlan:D,refresh:w}},[l,m,f,i,o==null?void 0:o.id,g]);return r.jsx(Ne.Provider,{value:E,children:e})}function Ye(){const s=a.useContext(Ne);if(s===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return s}function Xe(){return a.useContext(Ne)??null}var re=(s=>(s.SUPERUSER="SUPERUSER",s.TENANT_ADMIN="TENANT_ADMIN",s.USER="USER",s))(re||{});const we={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},De={landing:{tenant:"forbidden",auth:"optional"},publicOnly:{tenant:"forbidden",auth:"forbidden"},login:{tenant:"required",auth:"forbidden"},guest:{auth:"forbidden"},authenticated:{auth:"required"},tenant:{tenant:"required"},tenantOpen:{tenant:"required",auth:"optional"},tenantAuth:{tenant:"required",auth:"required"},user:{tenant:"required",auth:"required",userType:re.USER},admin:{tenant:"required",auth:"required",userType:re.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Ce=a.createContext(null);function It({config:s={},children:e}){const t=a.useMemo(()=>{const n={...we,...s.zoneRoots},i={...De,...s.presets};return{zoneRoots:n,presets:i,loadingFallback:s.loadingFallback??null,accessDeniedFallback:s.accessDeniedFallback??null,onAccessDenied:s.onAccessDenied,returnToParam:s.returnToParam??"returnTo",returnToStorage:s.returnToStorage??"url"}},[s]);return r.jsx(Ce.Provider,{value:t,children:e})}function Ft(){const s=a.useContext(Ce);if(!s)throw new Error("useRouting must be used within a RoutingProvider");return s}function et(){const s=a.useContext(Ce);return s||{zoneRoots:we,presets:De,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"}}const He=()=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"🔒"}),r.jsx("h3",{style:{color:"#495057",marginBottom:"10px"},children:"Access Required"}),r.jsx("p",{style:{color:"#6c757d",fontSize:"14px",marginBottom:"15px"},children:"You need to be signed in to view this content."}),r.jsx("button",{style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},onClick:()=>window.location.href="/login",children:"Sign In"})]}),Oe=({userType:s,minUserType:e,missingPermissions:t})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"20px",backgroundColor:"#fff3cd",border:"1px solid #ffeaa7",borderRadius:"6px",textAlign:"center",margin:"20px 0"},children:[r.jsx("div",{style:{fontSize:"2rem",marginBottom:"10px"},children:"⚠️"}),r.jsx("h3",{style:{color:"#856404",marginBottom:"10px"},children:"Insufficient Permissions"}),e&&s?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:["This content requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Your current access level: ",r.jsx("strong",{children:s})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#856404",fontSize:"14px",marginBottom:"10px"},children:"You don't have the required permissions to view this content."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#6c757d",fontSize:"12px"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]}),Lt=(s,e)=>{const t={[re.USER]:1,[re.TENANT_ADMIN]:2,[re.SUPERUSER]:3};return t[s]>=t[e]};function Nt({children:s,fallback:e,minUserType:t,requiredPermissions:n,requireAllPermissions:i=!1}){const{hasValidSession:o,sessionManager:l,hasPermission:d,hasAnyPermission:m,hasAllPermissions:y}=ae();if(!o())return r.jsx(r.Fragment,{children:e||r.jsx(He,{})});const f=l.getUser();if(!f)return r.jsx(r.Fragment,{children:e||r.jsx(He,{})});if(t&&!Lt(f.userType,t))return r.jsx(Oe,{userType:f.userType,minUserType:t});if(n&&n.length>0&&!(i?y(n):m(n))){const g=n.filter(v=>!d(v)).map(v=>typeof v=="string"?v:v.name);return r.jsx(Oe,{missingPermissions:g})}return r.jsx(r.Fragment,{children:s})}const Dt=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🔒"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Access Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You need to be signed in to access this page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})}),qe=({userType:s,requiredUserType:e,missingPermissions:t})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"⚠️"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Insufficient Permissions"}),e&&s?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current user type: ",r.jsx("strong",{children:s})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:"You don't have the required permissions to access this page."}),t&&t.length>0&&r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Required permissions: ",r.jsx("strong",{children:t.join(", ")})]})]})]})}),Ct=(s,e)=>s===e;function Ut({children:s,redirectTo:e="/login",requiredUserType:t,requiredPermissions:n,requireAllPermissions:i=!1,fallback:o}){const{hasValidSession:l,sessionManager:d,hasPermission:m,hasAnyPermission:y,hasAllPermissions:f}=ae(),F=ie.useLocation();if(a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] ProtectedRoute is deprecated. Use AuthenticatedZone or AdminZone from ZoneRoute instead.")},[]),!l())return o?r.jsx(r.Fragment,{children:o}):r.jsxs(r.Fragment,{children:[r.jsx(Dt,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:F.pathname},replace:!0})]});const g=d.getUser();if(!g)return r.jsx(ie.Navigate,{to:e,state:{from:F.pathname},replace:!0});if(t&&!Ct(g.userType,t))return r.jsx(qe,{userType:g.userType,requiredUserType:t});if(n&&n.length>0&&!(i?f(n):y(n))){const k=n.filter(M=>!m(M)).map(M=>typeof M=="string"?M:M.name);return r.jsx(qe,{missingPermissions:k})}return r.jsx(r.Fragment,{children:s})}const Bt=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🏢"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Required"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"This page requires a tenant context to access."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function $t({children:s,redirectTo:e="/",fallback:t}){const{tenant:n,isLoading:i,error:o}=Me(),l=ie.useLocation();return a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] TenantRoute is deprecated. Use TenantZone from ZoneRoute instead.")},[]),i||o?null:n?r.jsx(r.Fragment,{children:s}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Bt,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const Ht=({redirectPath:s})=>r.jsx("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",padding:"2rem",backgroundColor:"#f9fafb",textAlign:"center"},children:r.jsxs("div",{style:{backgroundColor:"#ffffff",padding:"2rem",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)",maxWidth:"400px"},children:[r.jsx("div",{style:{fontSize:"3rem",marginBottom:"1rem"},children:"🚀"}),r.jsx("h2",{style:{color:"#374151",marginBottom:"1rem"},children:"Tenant Detected"}),r.jsx("p",{style:{color:"#6b7280",marginBottom:"1.5rem"},children:"You are accessing a tenant-specific context. Redirecting to the appropriate page."}),r.jsxs("p",{style:{fontSize:"0.875rem",color:"#9ca3af"},children:["Redirecting to ",s,"..."]})]})});function Ot({children:s,redirectTo:e="/dashboard",fallback:t}){const{tenant:n,isLoading:i,error:o}=Me(),l=ie.useLocation();return a.useEffect(()=>{process.env.NODE_ENV==="development"&&console.warn("[react-identity-access] LandingRoute is deprecated. Use PublicZone from ZoneRoute instead.")},[]),i||o?null:n?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(Ht,{redirectPath:e}),r.jsx(ie.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:s})}function qt(s,e){return e?s?Array.isArray(e)?e.includes(s):s===e:!1:!0}function _e(s,e){return!s||s==="optional"?"skip":s==="required"?e?"pass":"fail":s==="forbidden"?e?"fail":"pass":"skip"}function _t(s,e){return _e(s.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":_e(s.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":s.userType&&e.isAuthenticated&&!qt(e.userType,s.userType)?"wrong_user_type":s.permissions&&s.permissions.length>0&&!(s.requireAllPermissions!==!1?o=>o.every(l=>e.permissions.includes(l)):o=>o.some(l=>e.permissions.includes(l)))(s.permissions)?"missing_permissions":null}function zt(s,e){return s.hasTenant?s.isAuthenticated?s.userType===re.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:s.isAuthenticated?s.userType===re.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function Vt(s,e,t,n,i){if(!e||i!=="url")return s;const o=typeof e=="string"?e:t,l=s.includes("?")?"&":"?";return`${s}${l}${n}=${encodeURIComponent(o)}`}function Wt(s,e,t){if(!s||t==="url")return;const n=typeof s=="string"?s:e,i="zone_return_to";t==="session"?sessionStorage.setItem(i,n):t==="local"&&localStorage.setItem(i,n)}const oe=({children:s,preset:e,tenant:t,auth:n,userType:i,requiredPermissions:o,requireAllPermissions:l=!0,returnTo:d,onAccessDenied:m,redirectTo:y,loadingFallback:f,accessDeniedFallback:F})=>{const g=ie.useLocation(),{isAuthenticated:v,isAuthInitializing:k,currentUser:M,userPermissions:E}=ae(),{tenant:A,isTenantLoading:u}=fe(),b=et(),I=a.useMemo(()=>{if(e)return b.presets[e]},[e,b.presets]),D=a.useMemo(()=>({tenant:t??(I==null?void 0:I.tenant),auth:n??(I==null?void 0:I.auth),userType:i??(I==null?void 0:I.userType),permissions:o??(I==null?void 0:I.requiredPermissions),requireAllPermissions:l}),[t,n,i,o,I,l]),w=a.useMemo(()=>({hasTenant:!!A,isAuthenticated:v,userType:M==null?void 0:M.userType,permissions:E,isLoading:k||u}),[A,v,M==null?void 0:M.userType,E,k,u]),j=a.useMemo(()=>w.isLoading?null:_t(D,w),[D,w]),T=a.useMemo(()=>j?y||zt(w,b.zoneRoots):null,[j,y,w,b.zoneRoots]),R=a.useMemo(()=>!j||!T?null:{type:j,required:{tenant:D.tenant,auth:D.auth,userType:D.userType,permissions:D.permissions},current:{hasTenant:w.hasTenant,isAuthenticated:w.isAuthenticated,userType:w.userType,permissions:w.permissions},redirectTo:T},[j,T,D,w]);if(a.useEffect(()=>{R&&(m?m(R):b.onAccessDenied&&b.onAccessDenied(R))},[R,m,b]),a.useEffect(()=>{R&&d&&Wt(d,g.pathname+g.search,b.returnToStorage)},[R,d,g.pathname,g.search,b.returnToStorage]),w.isLoading)return r.jsx(r.Fragment,{children:f??b.loadingFallback??null});if(R&&T){const c=F??b.accessDeniedFallback;if(c)return r.jsx(r.Fragment,{children:c});const O=Vt(T,d,g.pathname+g.search,b.returnToParam,b.returnToStorage);return r.jsx(ie.Navigate,{to:O,replace:!0})}return r.jsx(r.Fragment,{children:s})},Gt=s=>r.jsx(oe,{tenant:"required",...s}),Zt=s=>r.jsx(oe,{tenant:"forbidden",...s}),Kt=s=>r.jsx(oe,{auth:"required",...s}),Qt=s=>r.jsx(oe,{auth:"forbidden",...s}),Jt=s=>r.jsx(oe,{auth:"required",userType:re.TENANT_ADMIN,...s}),Yt=s=>r.jsx(oe,{auth:"required",userType:re.USER,...s}),Xt=s=>r.jsx(oe,{tenant:"optional",auth:"optional",...s}),er=s=>r.jsx(oe,{tenant:"required",auth:"required",...s}),tr=s=>r.jsx(oe,{tenant:"required",auth:"optional",...s}),rr=s=>r.jsx(oe,{tenant:"required",auth:"forbidden",...s}),nr=()=>r.jsxs("div",{style:{padding:"2rem",textAlign:"center",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626"},children:[r.jsx("h3",{style:{margin:"0 0 1rem 0"},children:"🔒 Subscription Required"}),r.jsx("p",{style:{margin:0},children:"This feature requires a higher subscription plan. Please upgrade your plan to access this content."})]});function sr({children:s,fallback:e=r.jsx(nr,{}),allowedPlans:t,requiredFeature:n}){const{subscription:i,hasAllowedPlan:o,isFeatureEnabled:l,loading:d}=Ye();return d?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):i?i.isActive?t&&t.length>0&&!o(t)?r.jsx(r.Fragment,{children:e}):n&&!l(n)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:s}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const ir=({flagName:s})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",padding:"15px",backgroundColor:"#f8f9fa",border:"1px solid #dee2e6",borderRadius:"6px",textAlign:"center",fontFamily:"system-ui, sans-serif",color:"#6c757d"},children:[r.jsx("div",{style:{fontSize:"24px",marginBottom:"8px"},children:"🚧"}),r.jsx("div",{style:{fontSize:"14px",fontWeight:"500",marginBottom:"4px"},children:"Feature Not Available"}),r.jsxs("div",{style:{fontSize:"12px",opacity:.7},children:['Feature flag "',s,'" is disabled']})]});function or({name:s,children:e,fallback:t}){const{isEnabled:n,loading:i}=Ke();return i?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):n(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(ir,{flagName:s})})}const ar=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),lr=()=>r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[r.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]}),cr={showPassword:r.jsx(ar,{}),hidePassword:r.jsx(lr,{})},dr={title:"Sign In",usernameLabel:"Email or Phone",usernamePlaceholder:"Enter your email or phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",submitButton:"Sign In",forgotPasswordLink:"Forgot your password?",signupLink:"Sign up here",signupText:"Don't have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Invalid credentials",loadingText:"Signing in...",tenantNotFoundError:"Tenant not found",dividerBullet:"•",showPasswordAriaLabel:"Show password",hidePasswordAriaLabel:"Hide password"},ur={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},inputContainer:{position:"relative",display:"flex",alignItems:"center"},passwordToggle:{position:"absolute",right:"0.75rem",background:"none",border:"none",cursor:"pointer",padding:"0.25rem",color:"#6b7280",display:"flex",alignItems:"center",justifyContent:"center",width:"24px",height:"24px",borderRadius:"4px",transition:"background-color 0.15s ease-in-out"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},inputWithIcon:{paddingRight:"2.5rem"}};function hr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onForgotPassword:o,onSignupClick:l,onMagicLinkClick:d,showForgotPassword:m=!0,showSignupLink:y=!0,showMagicLinkOption:f=!0,className:F}){const[g,v]=a.useState(""),[k,M]=a.useState(""),[E,A]=a.useState(!1),[u,b]=a.useState(!1),[I,D]=a.useState(""),[w,j]=a.useState({}),{login:T}=ae(),R={...dr,...s},c={...ur,...e},O={...cr,...t},L=()=>{const h={};return g.trim()||(h.username=!0),k.trim()||(h.password=!0),j(h),Object.keys(h).length===0},p=async h=>{if(h.preventDefault(),!!L()){b(!0),D("");try{const S=await T({username:g,password:k});n==null||n(S)}catch(S){const P=S.message||R.errorMessage;D(P),i==null||i(P)}finally{b(!1)}}},N=h=>({...c.input,...w[h]?c.inputError:{}}),x=()=>({...c.button,...u?c.buttonLoading:{},...!g||!k||u?c.buttonDisabled:{}});return r.jsxs("div",{className:F,style:c.container,children:[r.jsx("h2",{style:c.title,children:R.title}),r.jsxs("form",{onSubmit:p,style:c.form,children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:R.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:g,onChange:h=>{v(h.target.value),w.username&&j(S=>({...S,username:!1}))},placeholder:R.usernamePlaceholder,style:N("username"),disabled:u})]}),r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:R.passwordLabel}),r.jsxs("div",{style:c.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:E?"text":"password",value:k,onChange:h=>{M(h.target.value),w.password&&j(S=>({...S,password:!1}))},placeholder:R.passwordPlaceholder,style:{...N("password"),...c.inputWithIcon},disabled:u}),r.jsx("button",{type:"button",onClick:()=>A(!E),style:c.passwordToggle,disabled:u,"aria-label":E?R.hidePasswordAriaLabel:R.showPasswordAriaLabel,children:E?O.hidePassword:O.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!g||!k||u,style:x(),children:u?R.loadingText:R.submitButton}),I&&r.jsx("div",{style:c.errorText,children:I})]}),(m||y||f)&&r.jsxs("div",{style:c.linkContainer,children:[f&&r.jsxs("div",{children:[r.jsxs("span",{style:c.divider,children:[R.magicLinkText," "]}),r.jsx("a",{onClick:d,style:c.link,children:R.magicLinkLink})]}),f&&(m||y)&&r.jsx("div",{style:c.divider,children:R.dividerBullet}),m&&r.jsx("a",{onClick:o,style:c.link,children:R.forgotPasswordLink}),m&&y&&r.jsx("div",{style:c.divider,children:R.dividerBullet}),y&&r.jsxs("div",{children:[r.jsxs("span",{style:c.divider,children:[R.signupText," "]}),r.jsx("a",{onClick:l,style:c.link,children:R.signupLink})]})]})]})}const pr={title:"Create Account",nameLabel:"First Name",namePlaceholder:"Enter your first name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",emailLabel:"Email",emailPlaceholder:"Enter your email",phoneNumberLabel:"Phone Number",phoneNumberPlaceholder:"Enter your phone number",passwordLabel:"Password",passwordPlaceholder:"Enter your password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm your password",tenantNameLabel:"Organization Name",tenantNamePlaceholder:"Enter your organization name",submitButton:"Create Account",loginLink:"Sign in here",loginText:"Already have an account?",magicLinkText:"Prefer passwordless?",magicLinkLink:"Use Magic Link",errorMessage:"Failed to create account",loadingText:"Creating account...",passwordMismatchError:"Passwords do not match",isAdminLabel:"Create new organization",isAdminDescription:"Check this if you want to create a new organization",contactMethodHint:"At least one contact method (email or phone) is required",tenantNotFoundError:"Tenant not found",dividerBullet:"•"},fr={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},checkbox:{marginRight:"0.5rem"},checkboxContainer:{display:"flex",alignItems:"flex-start",gap:"0.5rem",padding:"0.5rem 0"},checkboxLabel:{fontSize:"0.875rem",color:"#374151",lineHeight:"1.4"},button:{padding:"0.75rem 1rem",backgroundColor:"#10b981",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},hintText:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"}};function gr({copy:s={},styles:e={},signupType:t="user",onSuccess:n,onError:i,onLoginClick:o,onMagicLinkClick:l,showLoginLink:d=!0,showMagicLinkOption:m=!0,className:y}){var q;const[f,F]=a.useState(""),[g,v]=a.useState(""),[k,M]=a.useState(""),[E,A]=a.useState(""),[u,b]=a.useState(""),[I,D]=a.useState(""),[w,j]=a.useState(""),[T,R]=a.useState(!1),[c,O]=a.useState(""),[L,p]=a.useState({}),{signup:N,signupTenantAdmin:x}=ae(),h=((q=le())==null?void 0:q.tenant)??null,S={...pr,...s},P={...fr,...e},W=()=>{const B={};return f.trim()||(B.name=!0),!k.trim()&&!E.trim()&&(B.email=!0,B.phoneNumber=!0),u.trim()||(B.password=!0),I.trim()||(B.confirmPassword=!0),t==="tenant"&&!w.trim()&&(B.tenantName=!0),p(B),Object.keys(B).length===0},V=async B=>{if(B.preventDefault(),!!W()){if(u!==I){O(S.passwordMismatchError),p({confirmPassword:!0});return}if(t==="user"&&!(h!=null&&h.id)){O(S.tenantNotFoundError);return}R(!0),O("");try{let C;t==="tenant"?C=await x({email:k||void 0,phoneNumber:E||void 0,name:f,password:u,tenantName:w,lastName:g||void 0}):C=await N({email:k||void 0,phoneNumber:E||void 0,name:f,password:u,tenantId:h.id,lastName:g||void 0}),n==null||n(C)}catch(C){const se=C.message||S.errorMessage;O(se),i==null||i(se)}finally{R(!1)}}},Q=B=>({...P.input,...L[B]?P.inputError:{}}),_=()=>({...P.button,...T?P.buttonLoading:{},...!f||!k&&!E||!u||!I||T||t==="tenant"&&!w?P.buttonDisabled:{}}),H=f&&(k||E)&&u&&I&&(t==="user"||w);return r.jsxs("div",{className:y,style:P.container,children:[r.jsx("h2",{style:P.title,children:S.title}),r.jsxs("form",{onSubmit:V,style:P.form,children:[r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:f,onChange:B=>{F(B.target.value),L.name&&p(C=>({...C,name:!1}))},placeholder:S.namePlaceholder,style:Q("name"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:g,onChange:B=>v(B.target.value),placeholder:S.lastNamePlaceholder,style:P.input,disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:k,onChange:B=>{M(B.target.value),L.email&&p(C=>({...C,email:!1,phoneNumber:!1}))},placeholder:S.emailPlaceholder,style:Q("email"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:E,onChange:B=>{A(B.target.value),L.phoneNumber&&p(C=>({...C,email:!1,phoneNumber:!1}))},placeholder:S.phoneNumberPlaceholder,style:Q("phoneNumber"),disabled:T})]}),r.jsx("div",{style:P.hintText,children:S.contactMethodHint}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:u,onChange:B=>{b(B.target.value),L.password&&p(C=>({...C,password:!1}))},placeholder:S.passwordPlaceholder,style:Q("password"),disabled:T})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:I,onChange:B=>{D(B.target.value),L.confirmPassword&&p(C=>({...C,confirmPassword:!1})),c===S.passwordMismatchError&&O("")},placeholder:S.confirmPasswordPlaceholder,style:Q("confirmPassword"),disabled:T})]}),t==="tenant"&&r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:S.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:w,onChange:B=>{j(B.target.value),L.tenantName&&p(C=>({...C,tenantName:!1}))},placeholder:S.tenantNamePlaceholder,style:Q("tenantName"),disabled:T})]}),r.jsx("button",{type:"submit",disabled:!H||T,style:_(),children:T?S.loadingText:S.submitButton}),c&&r.jsx("div",{style:P.errorText,children:c})]}),(d||m)&&r.jsxs("div",{style:P.linkContainer,children:[m&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[S.magicLinkText," "]}),r.jsx("a",{onClick:l,style:P.link,children:S.magicLinkLink})]}),m&&d&&r.jsx("div",{style:P.divider,children:S.dividerBullet}),d&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[S.loginText," "]}),r.jsx("a",{onClick:o,style:P.link,children:S.loginLink})]})]})]})}const mr={title:"Sign In with Magic Link",emailLabel:"Email",emailPlaceholder:"Enter your email",nameLabel:"Name",namePlaceholder:"Enter your name",lastNameLabel:"Last Name",lastNamePlaceholder:"Enter your last name",submitButton:"Send Magic Link",loginLink:"Sign in with password",signupLink:"Sign up with password",loginText:"Already have an account?",signupText:"Prefer traditional signup?",successMessage:"Magic link sent! Check your email and click the link to sign in.",errorMessage:"Failed to send magic link. Please try again.",loadingText:"Sending magic link...",verifyingText:"Verifying magic link...",verifyingDescription:"Please wait while we verify your magic link...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you.",showNameToggle:"New user? Add your name",hideNameToggle:"Existing user? Hide name fields",tenantNotFoundError:"Tenant not found",missingTenantOrEmailError:"Missing tenant or email",dividerBullet:"•"},yr={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1rem",color:"#333333"},description:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",marginBottom:"1.5rem",lineHeight:"1.5"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none",width:"100%"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem",padding:"0.75rem",backgroundColor:"#f0fdf4",borderRadius:"6px",border:"1px solid #bbf7d0"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},divider:{margin:"0.5rem 0",color:"#6b7280",fontSize:"0.875rem"},verifyingContainer:{textAlign:"center",padding:"2rem"},verifyingText:{fontSize:"1rem",color:"#6b7280"},toggleContainer:{textAlign:"center",marginTop:"0.5rem"},toggleLink:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"}};function wr({copy:s={},styles:e={},onSuccess:t,onError:n,onLoginClick:i,onSignupClick:o,showTraditionalLinks:l=!0,className:d,verifyToken:m,frontendUrl:y}){var _;const[f,F]=a.useState(""),[g,v]=a.useState(""),[k,M]=a.useState(""),[E,A]=a.useState(!1),[u,b]=a.useState(!1),[I,D]=a.useState(""),[w,j]=a.useState(""),[T,R]=a.useState({}),[c,O]=a.useState(!1),{sendMagicLink:L,verifyMagicLink:p}=ae(),N=((_=le())==null?void 0:_.tenant)??null,x={...mr,...s},h={...yr,...e};a.useEffect(()=>{m&&S(m)},[m]);const S=async H=>{if(!N||!f){D(x.missingTenantOrEmailError);return}b(!0),D("");try{const q=await p({token:H,email:f});t==null||t(q)}catch(q){const B=q.message||"Failed to verify magic link";D(B),n==null||n(B)}finally{b(!1)}},P=()=>{const H={};return f.trim()||(H.email=!0),c&&!g.trim()&&(H.name=!0),R(H),Object.keys(H).length===0},W=async H=>{if(H.preventDefault(),!!P()){if(!(N!=null&&N.id)){D(x.tenantNotFoundError);return}A(!0),D(""),j("");try{const q=y||(typeof window<"u"?window.location.origin:""),B=await L({email:f,tenantId:N.id,frontendUrl:q,name:c?g:void 0,lastName:c?k:void 0});j(x.successMessage),t==null||t(B)}catch(q){const B=q.message||x.errorMessage;D(B),n==null||n(B)}finally{A(!1)}}},V=H=>({...h.input,...T[H]?h.inputError:{}}),Q=()=>({...h.button,...E||u?h.buttonLoading:{},...!f||E||u?h.buttonDisabled:{}});return u?r.jsxs("div",{className:d,style:h.container,children:[r.jsx("h2",{style:h.title,children:x.verifyingText}),r.jsx("div",{style:h.verifyingContainer,children:r.jsx("div",{style:h.verifyingText,children:x.verifyingDescription})})]}):r.jsxs("div",{className:d,style:h.container,children:[r.jsx("h2",{style:h.title,children:x.title}),r.jsx("p",{style:h.description,children:x.description}),r.jsxs("form",{onSubmit:W,style:h.form,children:[r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:x.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:f,onChange:H=>{F(H.target.value),T.email&&R(q=>({...q,email:!1}))},placeholder:x.emailPlaceholder,style:V("email"),disabled:E||u})]}),!c&&r.jsx("div",{style:h.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>O(!0),style:h.toggleLink,children:x.showNameToggle})}),c&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:x.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:g,onChange:H=>{v(H.target.value),T.name&&R(q=>({...q,name:!1}))},placeholder:x.namePlaceholder,style:V("name"),disabled:E||u})]}),r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:x.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:k,onChange:H=>M(H.target.value),placeholder:x.lastNamePlaceholder,style:h.input,disabled:E||u})]}),r.jsx("div",{style:h.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>{O(!1),v(""),M("")},style:h.toggleLink,children:x.hideNameToggle})})]}),r.jsx("button",{type:"submit",disabled:!f||E||u,style:Q(),children:E?x.loadingText:x.submitButton}),I&&r.jsx("div",{style:h.errorText,children:I}),w&&r.jsx("div",{style:h.successText,children:w})]}),l&&r.jsxs("div",{style:h.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:h.divider,children:[x.loginText," "]}),r.jsx("a",{onClick:i,style:h.link,children:x.loginLink})]}),r.jsx("div",{style:h.divider,children:x.dividerBullet}),r.jsxs("div",{children:[r.jsxs("span",{style:h.divider,children:[x.signupText," "]}),r.jsx("a",{onClick:o,style:h.link,children:x.signupLink})]})]})]})}const xr={title:"Verifying Magic Link",verifyingMessage:"Please wait while we verify your magic link...",successMessage:"Magic link verified successfully! You are now logged in.",errorMessage:"Failed to verify magic link. The link may be expired or invalid.",redirectingMessage:"Redirecting you to the dashboard...",retryButton:"Try Again",backToLoginButton:"Back to Login",missingParamsError:"Missing required parameters: token or email"},tt={container:{maxWidth:"400px",width:"100%",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},card:{backgroundColor:"transparent",padding:"0",borderRadius:"0",boxShadow:"none",maxWidth:"100%",width:"100%",textAlign:"center"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"1.5rem",color:"#333333"},message:{fontSize:"1rem",color:"#6b7280",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},successMessage:{fontSize:"1rem",color:"#059669",marginBottom:"1.5rem",lineHeight:"1.5",textAlign:"center"},errorMessage:{fontSize:"0.875rem",color:"#ef4444",textAlign:"center",marginBottom:"1rem",lineHeight:"1.5"},spinner:{display:"inline-block",width:"20px",height:"20px",border:"2px solid #e5e7eb",borderTop:"2px solid #3b82f6",borderRadius:"50%",animation:"spin 1s linear infinite",marginRight:"0.5rem"},buttonContainer:{display:"flex",gap:"0.75rem",justifyContent:"center",flexWrap:"wrap",marginTop:"1rem"},retryButton:{padding:"0.75rem 1rem",backgroundColor:"#3b82f6",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out"},backButton:{padding:"0.75rem 1rem",backgroundColor:"#f3f4f6",color:"#374151",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"all 0.15s ease-in-out"},retryButtonHover:{backgroundColor:"#2563eb"},backButtonHover:{backgroundColor:"#e5e7eb"}},br=()=>r.jsx("div",{style:tt.spinner}),Sr=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#059669",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),vr=()=>r.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{margin:"0 auto 1rem auto",display:"block"},children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),r.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),Tr={loading:r.jsx(br,{}),success:r.jsx(Sr,{}),error:r.jsx(vr,{})};function kr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onRetry:o,onBackToLogin:l,className:d,token:m,email:y,appId:f,tenantSlug:F,autoRedirectDelay:g=3e3}){const[v,k]=a.useState("verifying"),[M,E]=a.useState(""),{verifyMagicLink:A}=ae(),u={...xr,...s},b={...tt,...e},I={...Tr,...t},D=()=>{if(typeof window>"u")return{};const c=new URLSearchParams(window.location.search);return{token:m||c.get("token")||"",email:y||c.get("email")||"",appId:f||c.get("appId")||"",tenantSlug:F||c.get("tenantSlug")||void 0}},w=async()=>{k("verifying"),E("");try{const c=D();if(!c.token||!c.email)throw new Error(u.missingParamsError);const O=await A({token:c.token,email:c.email,tenantSlug:c.tenantSlug});k("success"),n==null||n(O),g>0&&setTimeout(()=>{k("redirecting")},g)}catch(c){const O=c.message||u.errorMessage;E(O),k("error"),i==null||i(O)}},j=()=>{o==null||o(),w()},T=()=>{l==null||l()};a.useEffect(()=>{w()},[]);const R=()=>{switch(v){case"verifying":return r.jsxs("div",{style:b.message,children:[I.loading,u.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[I.success,r.jsx("div",{style:b.successMessage,children:u.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[I.loading,r.jsx("div",{style:b.message,children:u.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[I.error,r.jsx("div",{style:b.errorMessage,children:M||u.errorMessage}),r.jsxs("div",{style:b.buttonContainer,children:[r.jsx("button",{onClick:j,style:b.retryButton,onMouseOver:c=>{Object.assign(c.currentTarget.style,b.retryButtonHover)},onMouseOut:c=>{const O=b.retryButton||{};Object.keys(b.retryButtonHover||{}).forEach(L=>{c.currentTarget.style[L]=O[L]??""})},children:u.retryButton}),r.jsx("button",{onClick:T,style:b.backButton,onMouseOver:c=>{Object.assign(c.currentTarget.style,b.backButtonHover)},onMouseOut:c=>{const O=b.backButton||{};Object.keys(b.backButtonHover||{}).forEach(L=>{c.currentTarget.style[L]=O[L]??""})},children:u.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:b.container,className:d,children:[r.jsx("style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`}),r.jsx("h1",{style:b.title,children:u.title}),R()]})}const Ar={title:"Reset Password",subtitle:"Enter your email address and we'll send you a link to reset your password.",emailLabel:"Email",emailPlaceholder:"Enter your email",submitButton:"Send Reset Link",backToLoginLink:"Back to Sign In",successMessage:"Password reset link sent! Check your email.",errorMessage:"Failed to send reset link",loadingText:"Sending...",resetTitle:"Set New Password",resetSubtitle:"Enter your reset token and new password.",tokenLabel:"Reset Token",tokenPlaceholder:"Enter reset token from email",newPasswordLabel:"New Password",newPasswordPlaceholder:"Enter new password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm new password",resetSubmitButton:"Reset Password",resetLoadingText:"Resetting...",resetSuccessMessage:"Password reset successfully!",passwordMismatchError:"Passwords do not match",requestNewLinkLink:"Request New Link",haveTokenLink:"I have a token",tenantNotFoundError:"Tenant not found",dividerBullet:"•"},jr={container:{maxWidth:"400px",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"0.5rem",color:"#333333"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#f59e0b",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},modeSwitchDivider:{margin:"0 0.5rem",color:"#6b7280"}};function Pr({copy:s={},styles:e={},mode:t="request",token:n="",onSuccess:i,onError:o,onBackToLogin:l,onModeChange:d,className:m}){var K;const[y,f]=a.useState(""),[L,g]=a.useState(n),[v,k]=a.useState(""),[M,E]=a.useState(""),[A,u]=a.useState(!1),[b,I]=a.useState(""),[D,w]=a.useState(""),[j,T]=a.useState({}),{requestPasswordReset:R,confirmPasswordReset:c}=ae(),O=((K=le())==null?void 0:K.tenant)??null,F={...Ar,...s},p={...jr,...e},N=()=>{const _={};return y.trim()||(_.email=!0),T(_),Object.keys(_).length===0},x=()=>{const _={};return L.trim()||(_.token=!0),v.trim()||(_.newPassword=!0),M.trim()||(_.confirmPassword=!0),T(_),Object.keys(_).length===0},h=async _=>{if(_.preventDefault(),!!N()){if(!(O!=null&&O.id)){I(F.tenantNotFoundError);return}u(!0),I(""),w("");try{await R({email:y,tenantId:O.id}),w(F.successMessage),i==null||i()}catch(B){const q=B.message||F.errorMessage;I(q),o==null||o(q)}finally{u(!1)}}},S=async _=>{if(_.preventDefault(),!!x()){if(v!==M){I(F.passwordMismatchError),T({confirmPassword:!0});return}u(!0),I(""),w("");try{await c({token:L,newPassword:v}),w(F.resetSuccessMessage),i==null||i()}catch(B){const q=B.message||F.errorMessage;I(q),o==null||o(q)}finally{u(!1)}}},P=_=>({...p.input,...j[_]?p.inputError:{}}),W=()=>({...p.button,...A?p.buttonLoading:{}});if(t==="reset"){const _=L&&v&&M;return r.jsxs("div",{className:m,style:p.container,children:[r.jsx("h2",{style:p.title,children:F.resetTitle}),r.jsx("p",{style:p.subtitle,children:F.resetSubtitle}),r.jsxs("form",{onSubmit:S,style:p.form,children:[r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:F.tokenLabel}),r.jsx("input",{type:"text",value:L,onChange:B=>{g(B.target.value),j.token&&T(q=>({...q,token:!1}))},placeholder:F.tokenPlaceholder,style:P("token"),disabled:A})]}),r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:F.newPasswordLabel}),r.jsx("input",{type:"password",value:v,onChange:B=>{k(B.target.value),j.newPassword&&T(q=>({...q,newPassword:!1}))},placeholder:F.newPasswordPlaceholder,style:P("newPassword"),disabled:A})]}),r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:F.confirmPasswordLabel}),r.jsx("input",{type:"password",value:M,onChange:B=>{E(B.target.value),j.confirmPassword&&T(q=>({...q,confirmPassword:!1})),b===F.passwordMismatchError&&I("")},placeholder:F.confirmPasswordPlaceholder,style:P("confirmPassword"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!_||A,style:{...W(),...!_||A?p.buttonDisabled:{}},children:A?F.resetLoadingText:F.resetSubmitButton}),b&&r.jsx("div",{style:p.errorText,children:b}),D&&r.jsx("div",{style:p.successText,children:D})]}),r.jsxs("div",{style:p.linkContainer,children:[r.jsx("a",{onClick:l,style:p.link,children:F.backToLoginLink}),d&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:p.modeSwitchDivider,children:F.dividerBullet}),r.jsx("a",{onClick:()=>d("request"),style:p.link,children:F.requestNewLinkLink})]})]})]})}const V=y;return r.jsxs("div",{className:m,style:p.container,children:[r.jsx("h2",{style:p.title,children:F.title}),r.jsx("p",{style:p.subtitle,children:F.subtitle}),r.jsxs("form",{onSubmit:h,style:p.form,children:[r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:F.emailLabel}),r.jsx("input",{type:"email",value:y,onChange:_=>{f(_.target.value),j.email&&T(B=>({...B,email:!1}))},placeholder:F.emailPlaceholder,style:P("email"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!V||A,style:{...W(),...!V||A?p.buttonDisabled:{}},children:A?F.loadingText:F.submitButton}),b&&r.jsx("div",{style:p.errorText,children:b}),D&&r.jsx("div",{style:p.successText,children:D})]}),r.jsxs("div",{style:p.linkContainer,children:[r.jsx("a",{onClick:l,style:p.link,children:F.backToLoginLink}),d&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:p.modeSwitchDivider,children:F.dividerBullet}),r.jsx("a",{onClick:()=>d("reset"),style:p.link,children:F.haveTokenLink})]})]})]})}const Rr=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),Er=({error:s,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:s.message||"Unable to load application"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Mr({children:s,loadingFallback:e,errorFallback:t,requireTenant:n=!0}){const{isAppLoading:i,appError:o,retryApp:l}=me(),d=le(),m=Le(),y=Ke(),f=Xe(),L=(d==null?void 0:d.isTenantLoading)??!1,g=(d==null?void 0:d.tenantError)??null,v=(d==null?void 0:d.tenantSlug)??null,k=(d==null?void 0:d.retryTenant)??(()=>{}),M=(m==null?void 0:m.isAuthReady)??!0,E=(y==null?void 0:y.isReady)??!0,A=(f==null?void 0:f.isReady)??!0,u=n&&d&&v,w=i||u&&L||m&&!M||y&&!E||f&&!A,j=o||(u?g:null),T=()=>{o&&l(),g&&d&&k()};if(w)return r.jsx(r.Fragment,{children:e||r.jsx(Rr,{})});if(j){const R=typeof t=="function"?t(j,T):t||r.jsx(Er,{error:j,retry:T});return r.jsx(r.Fragment,{children:R})}return r.jsx(r.Fragment,{children:s})}function Ir(s=!0){const{isAppLoading:e,appError:t,retryApp:n,appInfo:i}=me(),o=le(),l=Le(),d=Ke(),m=Xe(),y=(o==null?void 0:o.isTenantLoading)??!1,f=(o==null?void 0:o.tenantError)??null,L=(o==null?void 0:o.tenant)??null,g=(o==null?void 0:o.tenantSlug)??null,v=(o==null?void 0:o.retryTenant)??(()=>{}),k=(l==null?void 0:l.isAuthReady)??!0,M=(d==null?void 0:d.isReady)??!0,E=(m==null?void 0:m.isReady)??!0,A=s&&o&&g,D=e||A&&y||l&&!k||d&&!M||m&&!E,w=t||(A?f:null);return{isLoading:D,error:w,isReady:!D&&!w&&i!==null&&(!A||L!==null),retry:()=>{t&&n(),f&&o&&v()},app:{isLoading:e,error:t,data:i},tenant:o?{isLoading:y,error:f,data:L}:null,auth:l?{isReady:k}:null,featureFlags:d?{isReady:M}:null,subscription:m?{isReady:E}:null}}const Lr={wrapper:{position:"relative"},button:{cursor:"pointer",opacity:1},buttonDisabled:{cursor:"not-allowed",opacity:.6},dropdown:{position:"absolute",top:"100%",left:0,right:0,zIndex:1e3,backgroundColor:"white",border:"1px solid #ccc",borderRadius:4,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",maxHeight:300,overflowY:"auto"},item:{padding:"8px 12px",cursor:"pointer",backgroundColor:"transparent"},itemSelected:{backgroundColor:"#f0f0f0"},itemHover:{backgroundColor:"#f5f5f5"},itemRole:{opacity:.7,marginLeft:8},arrow:{marginLeft:8}};function Fr({tenants:s,currentTenantId:e,onSelect:t,styles:n={},className:i="",dropdownClassName:o="",itemClassName:l="",renderItem:d,placeholder:m="Select tenant",disabled:y=!1,showCurrentTenant:f=!0}){var D;const L={...Lr,...n},g=Le(),[v,k]=a.useState(!1),M=a.useRef(null),E=s??(g==null?void 0:g.userTenants)??[],A=e??((D=g==null?void 0:g.currentUser)==null?void 0:D.tenantId)??null,u=async w=>{k(!1),t?t(w):g!=null&&g.switchToTenant&&await g.switchToTenant(w)};a.useEffect(()=>{const w=j=>{M.current&&!M.current.contains(j.target)&&k(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]);const b=E.find(w=>w.id===A);if(E.length===0)return null;if(E.length===1&&f)return r.jsx("div",{className:i,children:r.jsx("span",{children:E[0].name})});const I=(w,j)=>r.jsxs("span",{style:{fontWeight:j?"bold":"normal"},children:[w.name,w.role&&r.jsxs("span",{style:L.itemRole,children:["(",w.role,")"]})]});return r.jsxs("div",{ref:M,className:i,style:L.wrapper,children:[r.jsxs("button",{type:"button",onClick:()=>!y&&k(!v),disabled:y,style:{...L.button,...y?L.buttonDisabled:{}},children:[b?b.name:m,r.jsx("span",{style:L.arrow,children:v?"▲":"▼"})]}),v&&r.jsx("div",{className:o,style:L.dropdown,children:E.map(w=>{const j=w.id===A;return r.jsx("div",{className:l,onClick:()=>u(w.id),style:{...L.item,...j?L.itemSelected:{}},onMouseEnter:T=>{j||Object.assign(T.currentTarget.style,L.itemHover)},onMouseLeave:T=>{if(!j){const R=L.item||{};Object.keys(L.itemHover||{}).forEach(c=>{T.currentTarget.style[c]=R[c]??""})}},children:d?d(w,j):I(w,j)},w.id)})})]})}class Nr{constructor(e,t){this.httpService=e,this.sessionManager=t}async createPermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/permissions/",e,{headers:t})).data}async getPermissions(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/permissions/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{permissions:o.data,meta:o.meta}}async getPermissionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/permissions/${e}`,{headers:t})).data}async updatePermission(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:n})).data}async deletePermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/permissions/${e}`,{headers:t})}async getAppPermissions(e,t){const n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const i=`/permissions/apps/${e}${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i);return{permissions:o.data,meta:o.meta}}}class Dr{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscription-plans/",e,{headers:t})).data}async getSubscriptionPlans(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder),e!=null&&e.appId&&n.append("appId",e.appId);const i=`/subscription-plans/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{plans:o.data,meta:o.meta}}async getSubscriptionPlanById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscription-plans/${e}`,{headers:t})).data}async updateSubscriptionPlan(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:n})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class Cr{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class Ur{static toDate(e){return new Date(e)}static toISOString(e){return e.toISOString()}static transformPaginationMeta(e){return{total:e.total||0,page:e.page||1,limit:e.limit||100,totalPages:e.totalPages||1,hasNext:e.hasNext||!1,hasPrev:e.hasPrev||!1}}static transformUser(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.lastName?`${e.name} ${e.lastName}`:e.name,isActiveUser:e.isActive}}static transformRole(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),permissionCount:((t=e.permissions)==null?void 0:t.length)||0}}static transformTenant(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.name,hasCustomDomain:!!e.domain}}static transformSubscription(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),startDate:this.toDate(e.startDate),endDate:e.endDate?this.toDate(e.endDate):null,isActive:e.status==="ACTIVE",isExpired:e.endDate?new Date(e.endDate)<new Date:!1}}static transformApp(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isAdminLevel:e.securityLevel==="ADMIN",hasDefaultPlan:!!e.defaultSubscriptionPlanId}}static transformFeatureFlag(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isEnabled:e.isActive}}static transformPermission(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),fullName:`${e.resource}:${e.action}`,isSystemLevel:!e.appId}}static transformSubscriptionPlan(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayPrice:`${e.currency} ${e.price}`,isMonthly:e.billingCycle==="MONTHLY",featureCount:((t=e.features)==null?void 0:t.length)||0}}static transformError(e){var t;return{code:((t=e.error)==null?void 0:t.code)||"UNKNOWN_ERROR",message:e.message||"An unexpected error occurred",type:e.type||"SYSTEM",isAuthError:e.type==="AUTH",isValidationError:e.type==="VALIDATION"}}static transformQueryParams(e){const t=new URLSearchParams;return Object.entries(e).forEach(([n,i])=>{i!=null&&i!==""&&t.append(n,String(i))}),t}}const rt="returnTo",Te="zone_return_to",ke="zone_return_to";function $r(s={}){const{zoneRoots:e={},returnToParam:t=rt,returnToStorage:n="url"}=s,i=ie.useNavigate(),[o,l]=ie.useSearchParams(),{isAuthenticated:d,currentUser:m}=ae(),{tenant:y}=fe(),f=a.useMemo(()=>({...we,...e}),[e]),L=!!y,g=m==null?void 0:m.userType,v=a.useMemo(()=>{switch(n){case"url":return o.get(t);case"session":return sessionStorage.getItem(Te);case"local":return localStorage.getItem(ke);default:return null}},[n,o,t]),k=a.useCallback(()=>{switch(n){case"url":{const u=new URLSearchParams(o);u.delete(t),l(u,{replace:!0});break}case"session":sessionStorage.removeItem(Te);break;case"local":localStorage.removeItem(ke);break}},[n,o,t,l]),M=a.useCallback(u=>{switch(n){case"url":{const b=new URLSearchParams(o);b.set(t,u),l(b,{replace:!0});break}case"session":sessionStorage.setItem(Te,u);break;case"local":localStorage.setItem(ke,u);break}},[n,o,t,l]),E=a.useCallback(u=>{const b=f[u]||f.default;i(b)},[i,f]),A=a.useCallback(()=>L?d?g===te.TENANT_ADMIN?f.tenantAdmin:f.tenantUser:f.tenantGuest:d?g===te.TENANT_ADMIN?f.publicAdmin:f.publicUser:f.publicGuest,[L,d,g,f]);return{returnToUrl:v,clearReturnTo:k,setReturnTo:M,navigateToZone:E,getSmartRedirect:A}}function Hr(s,e,t=rt,n="url"){if(!e||n!=="url")return s;const i=new URL(s,window.location.origin);return i.searchParams.set(t,e),i.pathname+i.search}exports.AdminZone=Jt;exports.ApiMappers=Ur;exports.AppApiService=Ae;exports.AppLoader=Mr;exports.AppProvider=mt;exports.AuthApiService=We;exports.AuthProvider=Rt;exports.AuthenticatedZone=Qt;exports.DEFAULT_ZONE_PRESETS=De;exports.DEFAULT_ZONE_ROOTS=we;exports.FeatureFlag=or;exports.FeatureFlagApiService=Ze;exports.FeatureFlagProvider=Et;exports.GuestZone=Kt;exports.HealthApiService=Cr;exports.HttpService=ne;exports.LandingRoute=Ot;exports.LoginForm=hr;exports.MagicLinkForm=wr;exports.MagicLinkVerify=kr;exports.OpenZone=Xt;exports.PasswordRecoveryForm=Pr;exports.PermissionApiService=Nr;exports.Protected=Nt;exports.ProtectedRoute=Ut;exports.PublicZone=Zt;exports.RoleApiService=je;exports.RoutingProvider=It;exports.SessionExpiredError=ee;exports.SessionManager=he;exports.SignupForm=gr;exports.SubscriptionApiService=Je;exports.SubscriptionGuard=sr;exports.SubscriptionPlanApiService=Dr;exports.SubscriptionProvider=Mt;exports.TenantApiService=pe;exports.TenantAuthenticatedZone=er;exports.TenantGuestZone=rr;exports.TenantOpenZone=tr;exports.TenantProvider=At;exports.TenantRoute=Ht;exports.TenantSelector=Fr;exports.TenantZone=Gt;exports.TokenRefreshError=Ve;exports.TokenRefreshTimeoutError=ze;exports.UserApiService=Ge;exports.UserType=te;exports.UserZone=Yt;exports.ZoneRoute=oe;exports.buildRedirectUrl=Hr;exports.useApi=yt;exports.useApp=me;exports.useAppLoaderState=Ir;exports.useAuth=ae;exports.useFeatureFlags=Qe;exports.useRouting=Lt;exports.useRoutingOptional=et;exports.useSettings=Pt;exports.useSubscription=Ye;exports.useTenant=fe;exports.useTenantInfo=Me;exports.useTenantOptional=le;exports.useTenantSettings=jt;exports.useZoneNavigation=$r;
|
|
6
|
+
`}),r.jsx("h1",{style:b.title,children:u.title}),R()]})}const Ar={title:"Reset Password",subtitle:"Enter your email address and we'll send you a link to reset your password.",emailLabel:"Email",emailPlaceholder:"Enter your email",submitButton:"Send Reset Link",backToLoginLink:"Back to Sign In",successMessage:"Password reset link sent! Check your email.",errorMessage:"Failed to send reset link",loadingText:"Sending...",resetTitle:"Set New Password",resetSubtitle:"Enter your reset token and new password.",tokenLabel:"Reset Token",tokenPlaceholder:"Enter reset token from email",newPasswordLabel:"New Password",newPasswordPlaceholder:"Enter new password",confirmPasswordLabel:"Confirm Password",confirmPasswordPlaceholder:"Confirm new password",resetSubmitButton:"Reset Password",resetLoadingText:"Resetting...",resetSuccessMessage:"Password reset successfully!",passwordMismatchError:"Passwords do not match",requestNewLinkLink:"Request New Link",haveTokenLink:"I have a token",tenantNotFoundError:"Tenant not found",dividerBullet:"•"},jr={container:{maxWidth:"400px",margin:"0 auto",padding:"2rem",backgroundColor:"#ffffff",borderRadius:"8px",boxShadow:"0 2px 10px rgba(0, 0, 0, 0.1)"},title:{fontSize:"1.5rem",fontWeight:"bold",textAlign:"center",marginBottom:"0.5rem",color:"#333333"},subtitle:{fontSize:"0.875rem",textAlign:"center",marginBottom:"1.5rem",color:"#6b7280",lineHeight:"1.4"},form:{display:"flex",flexDirection:"column",gap:"1rem"},fieldGroup:{display:"flex",flexDirection:"column",gap:"0.5rem"},label:{fontSize:"0.875rem",fontWeight:"500",color:"#374151"},input:{padding:"0.75rem",border:"1px solid #d1d5db",borderRadius:"6px",fontSize:"1rem",transition:"border-color 0.15s ease-in-out",outline:"none"},inputError:{borderColor:"#ef4444",boxShadow:"0 0 0 3px rgba(239, 68, 68, 0.1)"},button:{padding:"0.75rem 1rem",backgroundColor:"#f59e0b",color:"white",border:"none",borderRadius:"6px",fontSize:"1rem",fontWeight:"500",cursor:"pointer",transition:"background-color 0.15s ease-in-out",marginTop:"0.5rem"},buttonDisabled:{backgroundColor:"#9ca3af",cursor:"not-allowed"},buttonLoading:{backgroundColor:"#6b7280"},errorText:{color:"#ef4444",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},successText:{color:"#10b981",fontSize:"0.875rem",textAlign:"center",marginTop:"0.5rem"},linkContainer:{textAlign:"center",marginTop:"1rem"},link:{color:"#3b82f6",textDecoration:"none",fontSize:"0.875rem",cursor:"pointer"},modeSwitchDivider:{margin:"0 0.5rem",color:"#6b7280"}};function Pr({copy:s={},styles:e={},mode:t="request",token:n="",onSuccess:i,onError:o,onBackToLogin:l,onModeChange:d,className:m}){var Q;const[y,f]=a.useState(""),[F,g]=a.useState(n),[v,k]=a.useState(""),[M,E]=a.useState(""),[A,u]=a.useState(!1),[b,I]=a.useState(""),[D,w]=a.useState(""),[j,T]=a.useState({}),{requestPasswordReset:R,confirmPasswordReset:c}=ae(),O=((Q=le())==null?void 0:Q.tenant)??null,L={...Ar,...s},p={...jr,...e},N=()=>{const _={};return y.trim()||(_.email=!0),T(_),Object.keys(_).length===0},x=()=>{const _={};return F.trim()||(_.token=!0),v.trim()||(_.newPassword=!0),M.trim()||(_.confirmPassword=!0),T(_),Object.keys(_).length===0},h=async _=>{if(_.preventDefault(),!!N()){if(!(O!=null&&O.id)){I(L.tenantNotFoundError);return}u(!0),I(""),w("");try{await R({email:y,tenantId:O.id}),w(L.successMessage),i==null||i()}catch(H){const q=H.message||L.errorMessage;I(q),o==null||o(q)}finally{u(!1)}}},S=async _=>{if(_.preventDefault(),!!x()){if(v!==M){I(L.passwordMismatchError),T({confirmPassword:!0});return}u(!0),I(""),w("");try{await c({token:F,newPassword:v}),w(L.resetSuccessMessage),i==null||i()}catch(H){const q=H.message||L.errorMessage;I(q),o==null||o(q)}finally{u(!1)}}},P=_=>({...p.input,...j[_]?p.inputError:{}}),W=()=>({...p.button,...A?p.buttonLoading:{}});if(t==="reset"){const _=F&&v&&M;return r.jsxs("div",{className:m,style:p.container,children:[r.jsx("h2",{style:p.title,children:L.resetTitle}),r.jsx("p",{style:p.subtitle,children:L.resetSubtitle}),r.jsxs("form",{onSubmit:S,style:p.form,children:[r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:L.tokenLabel}),r.jsx("input",{type:"text",value:F,onChange:H=>{g(H.target.value),j.token&&T(q=>({...q,token:!1}))},placeholder:L.tokenPlaceholder,style:P("token"),disabled:A})]}),r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:L.newPasswordLabel}),r.jsx("input",{type:"password",value:v,onChange:H=>{k(H.target.value),j.newPassword&&T(q=>({...q,newPassword:!1}))},placeholder:L.newPasswordPlaceholder,style:P("newPassword"),disabled:A})]}),r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:L.confirmPasswordLabel}),r.jsx("input",{type:"password",value:M,onChange:H=>{E(H.target.value),j.confirmPassword&&T(q=>({...q,confirmPassword:!1})),b===L.passwordMismatchError&&I("")},placeholder:L.confirmPasswordPlaceholder,style:P("confirmPassword"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!_||A,style:{...W(),...!_||A?p.buttonDisabled:{}},children:A?L.resetLoadingText:L.resetSubmitButton}),b&&r.jsx("div",{style:p.errorText,children:b}),D&&r.jsx("div",{style:p.successText,children:D})]}),r.jsxs("div",{style:p.linkContainer,children:[r.jsx("a",{onClick:l,style:p.link,children:L.backToLoginLink}),d&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:p.modeSwitchDivider,children:L.dividerBullet}),r.jsx("a",{onClick:()=>d("request"),style:p.link,children:L.requestNewLinkLink})]})]})]})}const V=y;return r.jsxs("div",{className:m,style:p.container,children:[r.jsx("h2",{style:p.title,children:L.title}),r.jsx("p",{style:p.subtitle,children:L.subtitle}),r.jsxs("form",{onSubmit:h,style:p.form,children:[r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:L.emailLabel}),r.jsx("input",{type:"email",value:y,onChange:_=>{f(_.target.value),j.email&&T(H=>({...H,email:!1}))},placeholder:L.emailPlaceholder,style:P("email"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!V||A,style:{...W(),...!V||A?p.buttonDisabled:{}},children:A?L.loadingText:L.submitButton}),b&&r.jsx("div",{style:p.errorText,children:b}),D&&r.jsx("div",{style:p.successText,children:D})]}),r.jsxs("div",{style:p.linkContainer,children:[r.jsx("a",{onClick:l,style:p.link,children:L.backToLoginLink}),d&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:p.modeSwitchDivider,children:L.dividerBullet}),r.jsx("a",{onClick:()=>d("reset"),style:p.link,children:L.haveTokenLink})]})]})]})}const Rr=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),Er=({error:s,retry:e})=>r.jsxs("div",{style:{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif",textAlign:"center",padding:"20px"},children:[r.jsx("h2",{style:{color:"#dc3545",marginBottom:"16px"},children:"Error"}),r.jsx("p",{style:{color:"#6c757d",marginBottom:"24px"},children:s.message||"Unable to load application"}),r.jsx("button",{onClick:e,style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Retry"})]});function Mr({children:s,loadingFallback:e,errorFallback:t,requireTenant:n=!0}){const{isAppLoading:i,appError:o,retryApp:l}=me(),d=le(),m=Fe(),y=Qe(),f=Xe(),F=(d==null?void 0:d.isTenantLoading)??!1,g=(d==null?void 0:d.tenantError)??null,v=(d==null?void 0:d.tenantSlug)??null,k=(d==null?void 0:d.retryTenant)??(()=>{}),M=(m==null?void 0:m.isAuthReady)??!0,E=(y==null?void 0:y.isReady)??!0,A=(f==null?void 0:f.isReady)??!0,u=n&&d&&v,w=i||u&&F||m&&!M||y&&!E||f&&!A,j=o||(u?g:null),T=()=>{o&&l(),g&&d&&k()};if(w)return r.jsx(r.Fragment,{children:e||r.jsx(Rr,{})});if(j){const R=typeof t=="function"?t(j,T):t||r.jsx(Er,{error:j,retry:T});return r.jsx(r.Fragment,{children:R})}return r.jsx(r.Fragment,{children:s})}function Ir(s=!0){const{isAppLoading:e,appError:t,retryApp:n,appInfo:i}=me(),o=le(),l=Fe(),d=Qe(),m=Xe(),y=(o==null?void 0:o.isTenantLoading)??!1,f=(o==null?void 0:o.tenantError)??null,F=(o==null?void 0:o.tenant)??null,g=(o==null?void 0:o.tenantSlug)??null,v=(o==null?void 0:o.retryTenant)??(()=>{}),k=(l==null?void 0:l.isAuthReady)??!0,M=(d==null?void 0:d.isReady)??!0,E=(m==null?void 0:m.isReady)??!0,A=s&&o&&g,D=e||A&&y||l&&!k||d&&!M||m&&!E,w=t||(A?f:null);return{isLoading:D,error:w,isReady:!D&&!w&&i!==null&&(!A||F!==null),retry:()=>{t&&n(),f&&o&&v()},app:{isLoading:e,error:t,data:i},tenant:o?{isLoading:y,error:f,data:F}:null,auth:l?{isReady:k}:null,featureFlags:d?{isReady:M}:null,subscription:m?{isReady:E}:null}}const Fr={wrapper:{position:"relative"},button:{cursor:"pointer",opacity:1},buttonDisabled:{cursor:"not-allowed",opacity:.6},dropdown:{position:"absolute",top:"100%",left:0,right:0,zIndex:1e3,backgroundColor:"white",border:"1px solid #ccc",borderRadius:4,boxShadow:"0 2px 8px rgba(0,0,0,0.15)",maxHeight:300,overflowY:"auto"},item:{padding:"8px 12px",cursor:"pointer",backgroundColor:"transparent"},itemSelected:{backgroundColor:"#f0f0f0"},itemHover:{backgroundColor:"#f5f5f5"},itemRole:{opacity:.7,marginLeft:8},arrow:{marginLeft:8}};function Lr({tenants:s,currentTenantId:e,onSelect:t,styles:n={},className:i="",dropdownClassName:o="",itemClassName:l="",renderItem:d,placeholder:m="Select tenant",disabled:y=!1,showCurrentTenant:f=!0}){var D;const F={...Fr,...n},g=Fe(),[v,k]=a.useState(!1),M=a.useRef(null),E=s??(g==null?void 0:g.userTenants)??[],A=e??((D=g==null?void 0:g.currentUser)==null?void 0:D.tenantId)??null,u=async w=>{k(!1),t?t(w):g!=null&&g.switchToTenant&&await g.switchToTenant(w)};a.useEffect(()=>{const w=j=>{M.current&&!M.current.contains(j.target)&&k(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]);const b=E.find(w=>w.id===A);if(E.length===0)return null;if(E.length===1&&f)return r.jsx("div",{className:i,children:r.jsx("span",{children:E[0].name})});const I=(w,j)=>r.jsxs("span",{style:{fontWeight:j?"bold":"normal"},children:[w.name,w.role&&r.jsxs("span",{style:F.itemRole,children:["(",w.role,")"]})]});return r.jsxs("div",{ref:M,className:i,style:F.wrapper,children:[r.jsxs("button",{type:"button",onClick:()=>!y&&k(!v),disabled:y,style:{...F.button,...y?F.buttonDisabled:{}},children:[b?b.name:m,r.jsx("span",{style:F.arrow,children:v?"▲":"▼"})]}),v&&r.jsx("div",{className:o,style:F.dropdown,children:E.map(w=>{const j=w.id===A;return r.jsx("div",{className:l,onClick:()=>u(w.id),style:{...F.item,...j?F.itemSelected:{}},onMouseEnter:T=>{j||Object.assign(T.currentTarget.style,F.itemHover)},onMouseLeave:T=>{if(!j){const R=F.item||{};Object.keys(F.itemHover||{}).forEach(c=>{T.currentTarget.style[c]=R[c]??""})}},children:d?d(w,j):I(w,j)},w.id)})})]})}class Nr{constructor(e,t){this.httpService=e,this.sessionManager=t}async createPermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/permissions/",e,{headers:t})).data}async getPermissions(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder);const i=`/permissions/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{permissions:o.data,meta:o.meta}}async getPermissionById(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/permissions/${e}`,{headers:t})).data}async updatePermission(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:n})).data}async deletePermission(e){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/permissions/${e}`,{headers:t})}async getAppPermissions(e,t){const n=new URLSearchParams;t!=null&&t.page&&n.append("page",t.page.toString()),t!=null&&t.limit&&n.append("limit",t.limit.toString()),t!=null&&t.sortBy&&n.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&n.append("sortOrder",t.sortOrder);const i=`/permissions/apps/${e}${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i);return{permissions:o.data,meta:o.meta}}}class Dr{constructor(e,t){this.httpService=e,this.sessionManager=t}async createSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.post("/subscription-plans/",e,{headers:t})).data}async getSubscriptionPlans(e){const t=await this.sessionManager.getAuthHeaders(),n=new URLSearchParams;e!=null&&e.page&&n.append("page",e.page.toString()),e!=null&&e.limit&&n.append("limit",e.limit.toString()),e!=null&&e.sortBy&&n.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&n.append("sortOrder",e.sortOrder),e!=null&&e.appId&&n.append("appId",e.appId);const i=`/subscription-plans/${n.toString()?`?${n.toString()}`:""}`,o=await this.httpService.get(i,{headers:t});return{plans:o.data,meta:o.meta}}async getSubscriptionPlanById(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/subscription-plans/${e}`,{headers:t})).data}async updateSubscriptionPlan(e,t){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:n})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class Cr{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class Ur{static toDate(e){return new Date(e)}static toISOString(e){return e.toISOString()}static transformPaginationMeta(e){return{total:e.total||0,page:e.page||1,limit:e.limit||100,totalPages:e.totalPages||1,hasNext:e.hasNext||!1,hasPrev:e.hasPrev||!1}}static transformUser(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.lastName?`${e.name} ${e.lastName}`:e.name,isActiveUser:e.isActive}}static transformRole(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),permissionCount:((t=e.permissions)==null?void 0:t.length)||0}}static transformTenant(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayName:e.name,hasCustomDomain:!!e.domain}}static transformSubscription(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),startDate:this.toDate(e.startDate),endDate:e.endDate?this.toDate(e.endDate):null,isActive:e.status==="ACTIVE",isExpired:e.endDate?new Date(e.endDate)<new Date:!1}}static transformApp(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isAdminLevel:e.securityLevel==="ADMIN",hasDefaultPlan:!!e.defaultSubscriptionPlanId}}static transformFeatureFlag(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),isEnabled:e.isActive}}static transformPermission(e){return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),fullName:`${e.resource}:${e.action}`,isSystemLevel:!e.appId}}static transformSubscriptionPlan(e){var t;return{...e,createdAt:this.toDate(e.createdAt),updatedAt:this.toDate(e.updatedAt),displayPrice:`${e.currency} ${e.price}`,isMonthly:e.billingCycle==="MONTHLY",featureCount:((t=e.features)==null?void 0:t.length)||0}}static transformError(e){var t;return{code:((t=e.error)==null?void 0:t.code)||"UNKNOWN_ERROR",message:e.message||"An unexpected error occurred",type:e.type||"SYSTEM",isAuthError:e.type==="AUTH",isValidationError:e.type==="VALIDATION"}}static transformQueryParams(e){const t=new URLSearchParams;return Object.entries(e).forEach(([n,i])=>{i!=null&&i!==""&&t.append(n,String(i))}),t}}const rt="returnTo",Te="zone_return_to",ke="zone_return_to";function Br(s={}){const{zoneRoots:e={},returnToParam:t=rt,returnToStorage:n="url"}=s,i=ie.useNavigate(),[o,l]=ie.useSearchParams(),{isAuthenticated:d,currentUser:m}=ae(),{tenant:y}=fe(),f=a.useMemo(()=>({...we,...e}),[e]),F=!!y,g=m==null?void 0:m.userType,v=a.useMemo(()=>{switch(n){case"url":return o.get(t);case"session":return sessionStorage.getItem(Te);case"local":return localStorage.getItem(ke);default:return null}},[n,o,t]),k=a.useCallback(()=>{switch(n){case"url":{const u=new URLSearchParams(o);u.delete(t),l(u,{replace:!0});break}case"session":sessionStorage.removeItem(Te);break;case"local":localStorage.removeItem(ke);break}},[n,o,t,l]),M=a.useCallback(u=>{switch(n){case"url":{const b=new URLSearchParams(o);b.set(t,u),l(b,{replace:!0});break}case"session":sessionStorage.setItem(Te,u);break;case"local":localStorage.setItem(ke,u);break}},[n,o,t,l]),E=a.useCallback(u=>{const b=f[u]||f.default;i(b)},[i,f]),A=a.useCallback(()=>F?d?g===re.TENANT_ADMIN?f.tenantAdmin:f.tenantUser:f.tenantGuest:d?g===re.TENANT_ADMIN?f.publicAdmin:f.publicUser:f.publicGuest,[F,d,g,f]);return{returnToUrl:v,clearReturnTo:k,setReturnTo:M,navigateToZone:E,getSmartRedirect:A}}function $r(s,e,t=rt,n="url"){if(!e||n!=="url")return s;const i=new URL(s,window.location.origin);return i.searchParams.set(t,e),i.pathname+i.search}exports.AdminZone=Jt;exports.ApiMappers=Ur;exports.AppApiService=Ae;exports.AppLoader=Mr;exports.AppProvider=mt;exports.AuthApiService=We;exports.AuthProvider=Rt;exports.AuthenticatedZone=Kt;exports.DEFAULT_ZONE_PRESETS=De;exports.DEFAULT_ZONE_ROOTS=we;exports.FeatureFlag=or;exports.FeatureFlagApiService=Ze;exports.FeatureFlagProvider=Et;exports.GuestZone=Qt;exports.HealthApiService=Cr;exports.HttpService=ne;exports.LandingRoute=Ot;exports.LoginForm=hr;exports.MagicLinkForm=wr;exports.MagicLinkVerify=kr;exports.OpenZone=Xt;exports.PasswordRecoveryForm=Pr;exports.PermissionApiService=Nr;exports.Protected=Nt;exports.ProtectedRoute=Ut;exports.PublicZone=Zt;exports.RoleApiService=je;exports.RoutingProvider=It;exports.SessionExpiredError=ee;exports.SessionManager=he;exports.SignupForm=gr;exports.SubscriptionApiService=Je;exports.SubscriptionGuard=sr;exports.SubscriptionPlanApiService=Dr;exports.SubscriptionProvider=Mt;exports.TenantApiService=pe;exports.TenantAuthenticatedZone=er;exports.TenantGuestZone=rr;exports.TenantOpenZone=tr;exports.TenantProvider=At;exports.TenantRoute=$t;exports.TenantSelector=Lr;exports.TenantZone=Gt;exports.TokenRefreshError=Ve;exports.TokenRefreshTimeoutError=ze;exports.UserApiService=Ge;exports.UserType=re;exports.UserZone=Yt;exports.ZoneRoute=oe;exports.buildRedirectUrl=$r;exports.useApi=yt;exports.useApp=me;exports.useAppLoaderState=Ir;exports.useAuth=ae;exports.useFeatureFlags=Ke;exports.useRouting=Ft;exports.useRoutingOptional=et;exports.useSettings=Pt;exports.useSubscription=Ye;exports.useTenant=fe;exports.useTenantInfo=Me;exports.useTenantOptional=le;exports.useTenantSettings=jt;exports.useZoneNavigation=Br;
|
|
7
7
|
//# sourceMappingURL=index.js.map
|