@skylabs-digital/react-identity-access 2.26.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/components/LoginForm.d.ts.map +1 -1
- package/dist/index.es.js +1374 -1353
- package/dist/index.es.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/providers/AuthProvider.d.ts +2 -0
- package/dist/providers/AuthProvider.d.ts.map +1 -1
- package/dist/services/AuthApiService.d.ts.map +1 -1
- package/dist/services/SessionManager.d.ts +2 -0
- package/dist/services/SessionManager.d.ts.map +1 -1
- package/dist/services/TenantApiService.d.ts +2 -2
- package/dist/services/TenantApiService.d.ts.map +1 -1
- package/dist/types/api.d.ts +2 -2
- package/dist/types/api.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"),ne=require("react-router-dom");class re{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 p={"Content-Type":"application/json",...i==null?void 0:i.headers};if(!(i!=null&&i.skipAuth)&&this.sessionManager){const f=await this.sessionManager.getValidAccessToken();p={...p,Authorization:`Bearer ${f}`}}const w=new AbortController,y=setTimeout(()=>w.abort(),l);try{const f=await fetch(o,{method:e,headers:p,body:n?JSON.stringify(n):void 0,signal:w.signal});if(clearTimeout(y),!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);const T=f.headers.get("content-type");return!T||!T.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 Te{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 Ae=a.createContext(null);function pt({config:s,children:e}){const t=a.useMemo(()=>{var h,j,I;return{enabled:((h=s.cache)==null?void 0:h.enabled)??!0,ttl:((j=s.cache)==null?void 0:j.ttl)??3e5,storageKey:((I=s.cache)==null?void 0:I.storageKey)??`app_cache_${s.appId}`}},[s.cache,s.appId]),[n,i]=a.useState(()=>{if(!t.enabled)return null;try{const h=localStorage.getItem(t.storageKey);if(!h)return null;const j=JSON.parse(h);return Date.now()-j.timestamp<t.ttl&&j.appId===s.appId?j.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[o,l]=a.useState(!n),[p,w]=a.useState(null),y=a.useMemo(()=>{const h=()=>{f()};return{appId:s.appId,baseUrl:s.baseUrl,appInfo:n,isAppLoading:o,appError:p,retryApp:h}},[s,n,o,p]),f=a.useCallback(async(h=!1)=>{if(!(!h&&t.enabled&&n))try{l(!0),w(null);const j=new re(s.baseUrl),L=await new Te(j,{}).getPublicAppInfo(s.appId);if(i(L),t.enabled)try{const P={data:L,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(P))}catch(P){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Failed to cache app info:",P)}}catch(j){const I=j instanceof Error?j:new Error("Failed to load app information");w(I),i(null)}finally{l(!1)}},[s.baseUrl,s.appId,t,n]),T=a.useCallback(async()=>{if(!(!t.enabled||!n))try{const h=localStorage.getItem(t.storageKey);if(!h)return;const j=JSON.parse(h);if(Date.now()-j.timestamp>t.ttl*.5){const L=new re(s.baseUrl),A=await new Te(L,{}).getPublicAppInfo(s.appId);i(A);const u={data:A,timestamp:Date.now(),appId:s.appId};localStorage.setItem(t.storageKey,JSON.stringify(u))}}catch(h){process.env.NODE_ENV==="development"&&console.warn("[AppProvider] Background app refresh failed:",h)}},[s,t,n]);return a.useEffect(()=>{n?T():f()},[]),r.jsx(Ae.Provider,{value:y,children:e})}function pe(){const s=a.useContext(Ae);if(!s)throw new Error("useApp must be used within an AppProvider");return s}function Be(){return a.useContext(Ae)}const ft=pe;class X 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 Oe extends Error{constructor(e){super(`Token refresh timed out after ${e}ms`),this.name="TokenRefreshTimeoutError",this.timeoutMs=e}}class qe 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,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(()=>{}).catch(n=>{n instanceof X||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 X("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 X("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 X&&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 Oe(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 X?(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 X("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 X)throw l;if(t=l,i<this.maxRefreshRetries){const p=this.retryBackoffBase*Math.pow(2,i);await this.sleep(p)}}}throw new qe(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 p=await i.json();l=(p.message||p.error||"").toLowerCase()}catch{l=i.statusText.toLowerCase()}throw i.status===401?l.includes("expired")?new X("token_expired"):l.includes("invalid")?new X("token_invalid"):new X("token_invalid",`Unauthorized: ${l}`):i.status===400?l.includes("inactive")?new X("user_inactive"):l.includes("expired")||l.includes("invalid")?new X("token_invalid",l):new Error(`Token refresh failed (400): ${l}`):new Error(`Token refresh failed: ${i.status} ${l}`)}if(this.sessionGeneration!==t)throw new X("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 X("token_invalid","Session cleared");this.rejectQueue(e)}destroy(){this.isDestroyed=!0,te.instances.delete(this.storageKey),this.cancelProactiveTimer();const e=new X("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;let ue=te;class _e{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){return await this.httpService.post("/auth/magic-link/verify",e)}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 ke{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 ze{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 he{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 gt(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 mt(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 yt(s,e,t){const{tenantMode:n,baseDomain:i,selectorParam:o,fixedTenantSlug:l}=s;return n==="fixed"?l||null:n==="subdomain"?gt(e.hostname,i):n==="selector"?mt(e.search,o,t):null}function wt(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 de="_auth";function De(s){const e=JSON.stringify(s);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xt(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 bt(){if(typeof window>"u")return null;const e=new URLSearchParams(window.location.search).get(de);return e?xt(e):null}function St(){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.delete(de),window.history.replaceState({},"",s.toString())}const je=a.createContext(null);function vt({config:s,children:e}){const{baseUrl:t,appInfo:n,appId:i}=pe(),o=a.useCallback(()=>typeof window>"u"?null:yt({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,p]=a.useState(()=>o()),w=a.useMemo(()=>{var d,U,R;return{enabled:((d=s.cache)==null?void 0:d.enabled)??!0,ttl:((U=s.cache)==null?void 0:U.ttl)??5*60*1e3,storageKey:((R=s.cache)==null?void 0:R.storageKey)??`tenant_cache_${l||"default"}`}},[s.cache,l]),[y,f]=a.useState(()=>{if(s.initialTenant)return s.initialTenant;if(!w.enabled||!l)return null;try{const d=localStorage.getItem(w.storageKey);if(!d)return null;const U=JSON.parse(d);return Date.now()-U.timestamp<w.ttl&&U.tenantSlug===l?U.data:(localStorage.removeItem(w.storageKey),null)}catch{return null}}),[T,h]=a.useState(!y&&!s.initialTenant),[j,I]=a.useState(null),[L,P]=a.useState(null),[A,u]=a.useState(!1),[S,N]=a.useState(null);a.useEffect(()=>{if(s.tenantMode==="fixed")return;const d=o();p(d)},[o,s.tenantMode]);const E=(n==null?void 0:n.settingsSchema)||null,v=a.useCallback(async(d,U=!1)=>{if(!(!U&&w.enabled&&y&&y.domain===d))try{h(!0),I(null);const R=new re(t),m=await new he(R,i).getPublicTenantInfo(d);if(f(m),w.enabled)try{const b={data:m,timestamp:Date.now(),tenantSlug:d};localStorage.setItem(w.storageKey,JSON.stringify(b))}catch(b){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Failed to cache tenant info:",b)}}catch(R){const g=R instanceof Error?R:new Error("Failed to load tenant information");I(g),f(null)}finally{h(!1)}},[t,i,w,y]),D=a.useCallback(async()=>{if(!(!w.enabled||!y||!l))try{const d=localStorage.getItem(w.storageKey);if(!d)return;const U=JSON.parse(d);if(Date.now()-U.timestamp>w.ttl*.5){const g=new re(t),b=await new he(g,i).getPublicTenantInfo(l);f(b);const W={data:b,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(w.storageKey,JSON.stringify(W))}}catch(d){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Background tenant refresh failed:",d)}},[t,i,w,y,l]),c=a.useCallback(async()=>{if(y!=null&&y.id)try{u(!0),N(null);const d=new re(t),R=await new he(d,y.appId).getTenantSettings(y.id);P(R)}catch(d){const U=d instanceof Error?d:new Error("Failed to load tenant settings");N(U),P(null)}finally{u(!1)}},[t,y]),C=a.useCallback(()=>{c()},[c]),x=a.useCallback(d=>{if(!E)return{isValid:!0,errors:[]};const U=[];try{return E.properties&&Object.entries(E.properties).forEach(([R,g])=>{var b;const m=d[R];if((b=E.required)!=null&&b.includes(R)&&m==null){U.push(`Field '${R}' is required`);return}if(m!=null){if(g.type){const W=g.type,Z=typeof m;W==="string"&&Z!=="string"?U.push(`Field '${R}' must be a string`):(W==="number"||W==="integer")&&Z!=="number"?U.push(`Field '${R}' must be a number`):W==="boolean"&&Z!=="boolean"?U.push(`Field '${R}' must be a boolean`):W==="array"&&!Array.isArray(m)&&U.push(`Field '${R}' must be an array`)}g.minLength!==void 0&&typeof m=="string"&&m.length<g.minLength&&U.push(`Field '${R}' must be at least ${g.minLength} characters long`),g.maxLength!==void 0&&typeof m=="string"&&m.length>g.maxLength&&U.push(`Field '${R}' must be no more than ${g.maxLength} characters long`),g.minimum!==void 0&&typeof m=="number"&&m<g.minimum&&U.push(`Field '${R}' must be at least ${g.minimum}`),g.maximum!==void 0&&typeof m=="number"&&m>g.maximum&&U.push(`Field '${R}' must be no more than ${g.maximum}`),g.pattern&&typeof m=="string"&&(new RegExp(g.pattern).test(m)||U.push(`Field '${R}' does not match the required pattern`)),g.enum&&!g.enum.includes(m)&&U.push(`Field '${R}' must be one of: ${g.enum.join(", ")}`)}}),{isValid:U.length===0,errors:U}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[E]);a.useEffect(()=>{!s.initialTenant&&l?y?D():v(l):!s.initialTenant&&!l&&(f(null),I(null),h(!1))},[s.initialTenant,l,y,v,D]),a.useEffect(()=>{y!=null&&y.id?c():(P(null),N(null),u(!1))},[y==null?void 0:y.id,c]);const M=a.useCallback((d,U)=>{const{mode:R="reload",tokens:g,redirectPath:m}=U||{},b=s.tenantMode||"selector";if(b==="fixed"){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] switchTenant is a no-op in fixed mode. Tenant is always:",s.fixedTenantSlug),m&&(window.location.href=m);return}if(localStorage.setItem("tenant",d),b==="subdomain"){const W=window.location.hostname,Z=wt(d,W,s.baseDomain);if(!Z){process.env.NODE_ENV==="development"&&console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",W);return}const H=m||window.location.pathname,B=new URL(`${window.location.protocol}//${Z}${H}`);new URLSearchParams(window.location.search).forEach((k,_)=>{_!==de&&B.searchParams.set(_,k)}),g&&B.searchParams.set(de,De(g)),window.location.href=B.toString()}else if(b==="selector"){const W=m||window.location.pathname,Z=new URLSearchParams(window.location.search);if(Z.set(s.selectorParam||"tenant",d),Z.delete(de),g&&Z.set(de,De(g)),R==="reload"){const H=`${W}?${Z.toString()}${window.location.hash}`;window.location.href=H}else{const H=`${W}?${Z.toString()}${window.location.hash}`;window.history.pushState({},"",H),p(d),v(d)}}},[s.tenantMode,s.selectorParam,s.baseDomain,v]),F=a.useMemo(()=>({tenant:y,tenantSlug:l,isTenantLoading:T,tenantError:j,retryTenant:()=>{l&&v(l)},settings:L,settingsSchema:E,isSettingsLoading:A,settingsError:S,refreshSettings:C,switchTenant:M,validateSettings:x}),[y,l,T,j,L,E,A,S,C,M,x]);return r.jsx(je.Provider,{value:F,children:e})}function ae(){const s=a.useContext(je);if(!s)throw new Error("useTenant must be used within a TenantProvider");return s}function ge(){return a.useContext(je)}const Tt=ae;function kt(){const{settings:s,settingsSchema:e,isSettingsLoading:t,settingsError:n,validateSettings:i}=ae();return{settings:s,settingsSchema:e,isLoading:t,error:n,validateSettings:i}}function le(){const{tenant:s,tenantSlug:e,isTenantLoading:t,tenantError:n,retryTenant:i}=ae();return{tenant:s,tenantSlug:e,isLoading:t,error:n,retry:i}}const Pe=a.createContext(null);function At({config:s={},children:e}){const{appId:t,baseUrl:n}=pe(),{tenant:i,tenantSlug:o,switchTenant:l}=ae(),[p,w]=a.useState(s.initialRoles||[]),[y,f]=a.useState(!s.initialRoles),[T,h]=a.useState(null),[j,I]=a.useState(!1),[L,P]=a.useState(null),[A,u]=a.useState(()=>{try{const k=localStorage.getItem("userTenants");return k?JSON.parse(k):[]}catch{return[]}}),[S,N]=a.useState(!1),E=a.useRef({done:!1,urlTokens:null});E.current.done||(E.current.done=!0,E.current.urlTokens=bt());const[v,D]=a.useState(()=>E.current.urlTokens!==null),c=a.useMemo(()=>{const k=ue.getInstance({tenantSlug:o,baseUrl:n,refreshQueueTimeout:s.refreshQueueTimeout,proactiveRefreshMargin:s.proactiveRefreshMargin,onSessionExpired:_=>{h(null),P(null),u([]),N(!1);try{localStorage.removeItem("userTenants")}catch{}s.onSessionExpired?s.onSessionExpired(_):s.onRefreshFailed&&s.onRefreshFailed()}});return E.current.urlTokens&&k.setTokens({accessToken:E.current.urlTokens.accessToken,refreshToken:E.current.urlTokens.refreshToken,expiresIn:E.current.urlTokens.expiresIn}),k},[o,n,s.refreshQueueTimeout,s.proactiveRefreshMargin]),[C,x]=a.useState(()=>{if(E.current.urlTokens)return!1;const k=c.getTokens();return k?c.hasValidSession()||!!k.refreshToken:!1}),M=E.current.done&&!v&&!C,F=a.useMemo(()=>{const k=new re(n);return k.setSessionManager(c),k},[n,c]),d=a.useMemo(()=>new _e(new re(n)),[n]),U=a.useMemo(()=>new ze(F,c),[F,c]),R=a.useMemo(()=>new ke(new re(n)),[n]),g=a.useMemo(()=>T||c.getUser(),[T,c]),m=a.useMemo(()=>g!=null&&g.roleId&&p.find(k=>k.id===g.roleId)||null,[g,p]),b=a.useMemo(()=>(m==null?void 0:m.permissions)||[],[m]),W=a.useMemo(()=>c.hasValidSession()&&T!==null,[c,T]),Z=a.useRef(async()=>{}),H=a.useMemo(()=>{const k=async($=!1)=>{try{if(!c.hasValidSession()||!$&&T)return;const O=c.getUserId();if(!O){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] No userId available in token or storage");return}I(!0),P(null);const G=await U.getUserById(O);h(G),c.setUser(G)}catch(O){const G=O instanceof Error?O:new Error("Failed to load user data");P(G),process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data:",G)}finally{I(!1)}},_=async()=>{await k()},oe=async $=>{var Fe;const{username:O,password:G,tenantSlug:q,redirectPath:Q}=$;let K=i==null?void 0:i.id,J=o,Y=c;q&&(K=(await new he(F,t).getPublicTenantInfo(q)).id,J=q);const V=await d.login({username:O,password:G,appId:t,tenantId:K}),fe=q&&q!==o;if(fe&&(Y=new ue({tenantSlug:J,baseUrl:n})),Y.setTokens({accessToken:V.accessToken,refreshToken:V.refreshToken,expiresIn:V.expiresIn}),V.user){Y.setUser(V.user),h(V.user);try{await k()}catch(me){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after login:",me)}}if(V.tenants&&V.tenants.length>0){u(V.tenants);try{localStorage.setItem("userTenants",JSON.stringify(V.tenants))}catch{}}const xe=((Fe=V.user)==null?void 0:Fe.tenantId)!==null;N(xe);const be={accessToken:V.accessToken,refreshToken:V.refreshToken,expiresIn:V.expiresIn};if(fe&&J)return l(J,{tokens:be,redirectPath:Q}),V;if(Q&&Q!==window.location.pathname)return l(J||o||"",{tokens:be,redirectPath:Q}),V;if(!xe&&V.tenants&&V.tenants.length>0){const me=$.autoSwitch!==!1&&s.autoSwitchSingleTenant!==!1;if(V.tenants.length===1&&me){const Ne=V.tenants[0];return l(Ne.subdomain,{tokens:be,redirectPath:Q}),V}else V.tenants.length>1&&s.onTenantSelectionRequired&&s.onTenantSelectionRequired(V.tenants)}return V},ce=async $=>{const{email:O,phoneNumber:G,name:q,password:Q,lastName:K,tenantId:J}=$;if(!O&&!G)throw new Error("Either email or phoneNumber is required");if(!q||!Q)throw new Error("Name and password are required");const Y=J??(i==null?void 0:i.id);return await d.signup({email:O,phoneNumber:G,name:q,password:Q,tenantId:Y,lastName:K,appId:t})},et=async $=>{const{email:O,phoneNumber:G,name:q,password:Q,tenantName:K,lastName:J}=$;if(!O&&!G)throw new Error("Either email or phoneNumber is required");if(!q||!Q||!K)throw new Error("Name, password, and tenantName are required");return await d.signupTenantAdmin({email:O,phoneNumber:G,name:q,password:Q,tenantName:K,appId:t,lastName:J})},tt=async $=>{const{currentPassword:O,newPassword:G}=$,q=await c.getAuthHeaders();await d.changePassword({currentPassword:O,newPassword:G},q)},rt=async $=>{const{email:O,tenantId:G}=$,q=G??(i==null?void 0:i.id);if(!q)throw new Error("tenantId is required for password reset");await d.requestPasswordReset({email:O,tenantId:q})},nt=async $=>{const{token:O,newPassword:G}=$;await d.confirmPasswordReset({token:O,newPassword:G})},st=async $=>{const{email:O,frontendUrl:G,name:q,lastName:Q,tenantId:K}=$,J=K??(i==null?void 0:i.id);if(!J)throw new Error("tenantId is required for magic link authentication");return await d.sendMagicLink({email:O,tenantId:J,frontendUrl:G,name:q,lastName:Q,appId:t})},it=async $=>{const{token:O,email:G,tenantSlug:q}=$;let Q=i==null?void 0:i.id,K=o,J=c;q&&(Q=(await new he(F,t).getPublicTenantInfo(q)).id,K=q);const Y=await d.verifyMagicLink({token:O,email:G,appId:t,tenantId:Q}),V=q&&q!==o;if(V&&(J=new ue({tenantSlug:K,baseUrl:n})),J.setTokens({accessToken:Y.accessToken,refreshToken:Y.refreshToken,expiresIn:Y.expiresIn}),Y.user){J.setUser(Y.user),h(Y.user);try{await k()}catch(fe){process.env.NODE_ENV==="development"&&console.warn("[AuthProvider] Failed to load complete user data after magic link:",fe)}}return V&&K&&K!==o&&l(K,{tokens:{accessToken:Y.accessToken,refreshToken:Y.refreshToken,expiresIn:Y.expiresIn}}),Y},ot=async()=>{const $=c.getTokens();if(!($!=null&&$.refreshToken))throw new Error("No refresh token available");const O=await d.refreshToken({refreshToken:$.refreshToken});c.setTokens({accessToken:O.accessToken,refreshToken:O.refreshToken||$.refreshToken,expiresIn:O.expiresIn})},at=()=>{c.clearSession(),h(null),P(null),u([]),N(!1);try{localStorage.removeItem("userTenants")}catch{}},lt=$=>{c.setTokens($)},ct=()=>c.hasValidSession(),dt=()=>{c.clearSession(),h(null),P(null)},ut=async()=>{if(t)try{f(!0);const{roles:$}=await R.getRolesByApp(t);w($)}catch($){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",$)}finally{f(!1)}},ht=async()=>{await ut()},we=$=>{if(!b||b.length===0)return!1;if(typeof $=="string")return b.includes($);const O=`${$.resource}.${$.action}`;return b.includes(O)};return{isAuthenticated:W,sessionManager:c,authenticatedHttpService:F,login:oe,signup:ce,signupTenantAdmin:et,sendMagicLink:st,verifyMagicLink:it,changePassword:tt,requestPasswordReset:rt,confirmPasswordReset:nt,refreshToken:ot,logout:at,setTokens:lt,hasValidSession:ct,clearSession:dt,currentUser:T,isUserLoading:j,userError:L,loadUserData:k,refreshUser:_,isAuthInitializing:!M,isAuthReady:M,userRole:m,userPermissions:b,availableRoles:p,rolesLoading:y,hasPermission:we,hasAnyPermission:$=>$.some(O=>we(O)),hasAllPermissions:$=>$.every(O=>we(O)),getUserPermissionStrings:()=>b||[],refreshRoles:ht,userTenants:A,hasTenantContext:S,switchToTenant:async($,O)=>{const{redirectPath:G}=O||{},q=c.getTokens();if(!(q!=null&&q.refreshToken))throw new Error("No refresh token available for tenant switch");const Q=await d.switchTenant({refreshToken:q.refreshToken,tenantId:$});c.setTokens({accessToken:Q.accessToken,refreshToken:q.refreshToken,expiresIn:Q.expiresIn}),h(Q.user),c.setUser(Q.user),N(!0);const K=A.find(J=>J.id===$);K&&l(K.subdomain,{tokens:{accessToken:Q.accessToken,refreshToken:q.refreshToken,expiresIn:Q.expiresIn},redirectPath:G})},refreshUserTenants:async()=>{const $=await c.getAuthHeaders(),O=await d.getUserTenants($);u(O);try{localStorage.setItem("userTenants",JSON.stringify(O))}catch{}return O}}},[W,c,F,d,U,R,t,i,o,l,p,T,j,L,A,S,M,m,b]);Z.current=H.loadUserData,a.useEffect(()=>{!s.initialRoles&&t&&(async()=>{try{f(!0);const _=new re(n),oe=new ke(_),{roles:ce}=await oe.getRolesByApp(t);w(ce)}catch(_){process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to fetch roles:",_)}finally{f(!1)}})()},[t,n,s.initialRoles]);const[B,z]=a.useState(!1);return a.useEffect(()=>{B||(z(!0),E.current.urlTokens&&(St(),D(!0),H.loadUserData().catch(k=>{process.env.NODE_ENV==="development"&&console.error("[AuthProvider] Failed to load user data after URL tokens:",k)}).finally(()=>{D(!1)})))},[H,B]),a.useEffect(()=>{let k=!1;return(async()=>{var ce;if(!c.hasValidSession()&&((ce=c.getTokens())!=null&&ce.refreshToken)&&await c.waitForPendingRefresh(),k)return;const oe=c.getUser();oe&&c.hasValidSession()&&h(oe),x(!1)})(),()=>{k=!0}},[c]),a.useEffect(()=>{B&&(E.current.urlTokens||(!T&&!j&&!L&&c.hasValidSession()?Z.current().catch(()=>{}).finally(()=>{x(!1)}):x(!1)))},[T,j,L,c,B]),r.jsx(Pe.Provider,{value:H,children:e})}function ie(){const s=a.useContext(Pe);if(!s)throw new Error("useAuth must be used within an AuthProvider");return s}function Re(){return a.useContext(Pe)}class Ve{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 Ee=a.createContext(null);function jt({config:s={},children:e}){const t=Be(),n=ge(),i=(t==null?void 0:t.baseUrl)??"",o=(t==null?void 0:t.appId)??"",l=(n==null?void 0:n.tenant)??null,[p,w]=a.useState([]),[y,f]=a.useState(!1),[T,h]=a.useState(null),[j,I]=a.useState(!1),L=a.useMemo(()=>{const u=new re(i);return new Ve(u)},[i]),P=async()=>{if(!(l!=null&&l.id)){w([]);return}f(!0),h(null);try{const u=await L.getTenantFeatureFlags(l.id,o);w(u)}catch(u){const S=u instanceof Error?u.message:"Failed to fetch feature flags";h(S),s.onError&&s.onError(u instanceof Error?u:new Error(S))}finally{f(!1)}};a.useEffect(()=>{if(!i||!o)return;P().finally(()=>I(!0));const u=s.refreshInterval||5*60*1e3,S=setInterval(P,u);return()=>clearInterval(S)},[l==null?void 0:l.id,i,o,s.refreshInterval]);const A=a.useMemo(()=>{const u=D=>{const c=p.find(C=>C.key===D);return(c==null?void 0:c.value)===!0},S=D=>p.find(c=>c.key===D),N=D=>{const c=p.find(C=>C.key===D);return c?c.value?"enabled":"disabled":"not_found"},E=async()=>{await P()},v=!!(i&&o)&&(j||!(l!=null&&l.id));return{featureFlags:p,loading:y,error:T,isReady:v,isEnabled:u,getFlag:S,getFlagState:N,refresh:E}},[p,y,T,i,o,l==null?void 0:l.id,j]);return r.jsx(Ee.Provider,{value:A,children:e})}function We(){const s=a.useContext(Ee);if(!s)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return s}function Ge(){return a.useContext(Ee)}class Ze{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 Me=a.createContext(void 0);function Pt({config:s={},children:e}){const t=Be(),n=ge(),i=(t==null?void 0:t.baseUrl)??"",o=(n==null?void 0:n.tenant)??null,[l,p]=a.useState(null),[w,y]=a.useState(!1),[f,T]=a.useState(null),[h,j]=a.useState(!1),I=a.useMemo(()=>{const A=new re(i);return new Ze(A)},[i]),L=async()=>{if(!(o!=null&&o.id)){p(null);return}y(!0),T(null);try{const A=await I.getTenantSubscriptionFeatures(o.id);p(A)}catch(A){const u=A instanceof Error?A.message:"Failed to fetch subscription";T(u),s.onError&&s.onError(A instanceof Error?A:new Error(u))}finally{y(!1)}};a.useEffect(()=>{if(!i||(L().finally(()=>j(!0)),!s.refreshInterval))return;const A=s.refreshInterval||10*60*1e3,u=setInterval(L,A);return()=>clearInterval(u)},[o==null?void 0:o.id,i,s.refreshInterval]);const P=a.useMemo(()=>{const A=(l==null?void 0:l.features)||[],u=c=>{const C=A.find(x=>x.key===c);return C?C.type==="BOOLEAN"||C.type==="boolean"?C.value===!0:!!C.value:!1},S=c=>A.find(C=>C.key===c),N=(c,C)=>{const x=A.find(M=>M.key===c);return x?x.value:C},E=c=>!l||!l.isActive?!1:c.includes(l.planId),v=async()=>{await L()},D=!!i&&(h||!(o!=null&&o.id));return{subscription:l,features:A,loading:w,error:f,isReady:D,isFeatureEnabled:u,getFeature:S,getFeatureValue:N,hasAllowedPlan:E,refresh:v}},[l,w,f,i,o==null?void 0:o.id,h]);return r.jsx(Me.Provider,{value:P,children:e})}function Qe(){const s=a.useContext(Me);if(s===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return s}function Ke(){return a.useContext(Me)??null}var ee=(s=>(s.SUPERUSER="SUPERUSER",s.TENANT_ADMIN="TENANT_ADMIN",s.USER="USER",s))(ee||{});const ye={publicGuest:"/",publicUser:"/account",publicAdmin:"/admin",tenantGuest:"/login",tenantUser:"/dashboard",tenantAdmin:"/admin/dashboard",default:"/"},Ie={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:ee.USER},admin:{tenant:"required",auth:"required",userType:ee.TENANT_ADMIN},open:{tenant:"optional",auth:"optional"}},Le=a.createContext(null);function Rt({config:s={},children:e}){const t=a.useMemo(()=>{const n={...ye,...s.zoneRoots},i={...Ie,...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(Le.Provider,{value:t,children:e})}function Et(){const s=a.useContext(Le);if(!s)throw new Error("useRouting must be used within a RoutingProvider");return s}function Je(){const s=a.useContext(Le);return s||{zoneRoots:ye,presets:Ie,loadingFallback:null,accessDeniedFallback:null,onAccessDenied:void 0,returnToParam:"returnTo",returnToStorage:"url"}}const Ce=()=>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"})]}),Ue=({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(", ")})]})]})]}),Mt=(s,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[s]>=t[e]};function It({children:s,fallback:e,minUserType:t,requiredPermissions:n,requireAllPermissions:i=!1}){const{hasValidSession:o,sessionManager:l,hasPermission:p,hasAnyPermission:w,hasAllPermissions:y}=ie();if(!o())return r.jsx(r.Fragment,{children:e||r.jsx(Ce,{})});const f=l.getUser();if(!f)return r.jsx(r.Fragment,{children:e||r.jsx(Ce,{})});if(t&&!Mt(f.userType,t))return r.jsx(Ue,{userType:f.userType,minUserType:t});if(n&&n.length>0&&!(i?y(n):w(n))){const h=n.filter(j=>!p(j)).map(j=>typeof j=="string"?j:j.name);return r.jsx(Ue,{missingPermissions:h})}return r.jsx(r.Fragment,{children:s})}const Lt=({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,"..."]})]})}),$e=({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(", ")})]})]})]})}),Ft=(s,e)=>s===e;function Nt({children:s,redirectTo:e="/login",requiredUserType:t,requiredPermissions:n,requireAllPermissions:i=!1,fallback:o}){const{hasValidSession:l,sessionManager:p,hasPermission:w,hasAnyPermission:y,hasAllPermissions:f}=ie(),T=ne.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(Lt,{redirectPath:e}),r.jsx(ne.Navigate,{to:e,state:{from:T.pathname},replace:!0})]});const h=p.getUser();if(!h)return r.jsx(ne.Navigate,{to:e,state:{from:T.pathname},replace:!0});if(t&&!Ft(h.userType,t))return r.jsx($e,{userType:h.userType,requiredUserType:t});if(n&&n.length>0&&!(i?f(n):y(n))){const I=n.filter(L=>!w(L)).map(L=>typeof L=="string"?L:L.name);return r.jsx($e,{missingPermissions:I})}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:"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 Ct({children:s,redirectTo:e="/",fallback:t}){const{tenant:n,isLoading:i,error:o}=le(),l=ne.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(Dt,{redirectPath:e}),r.jsx(ne.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const Ut=({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 $t({children:s,redirectTo:e="/dashboard",fallback:t}){const{tenant:n,isLoading:i,error:o}=le(),l=ne.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(Ut,{redirectPath:e}),r.jsx(ne.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:s})}function Ht(s,e){return e?s?Array.isArray(e)?e.includes(s):s===e:!1:!0}function He(s,e){return!s||s==="optional"?"skip":s==="required"?e?"pass":"fail":s==="forbidden"?e?"fail":"pass":"skip"}function Bt(s,e){return He(s.tenant,e.hasTenant)==="fail"?e.hasTenant?"has_tenant":"no_tenant":He(s.auth,e.isAuthenticated)==="fail"?e.isAuthenticated?"already_authenticated":"not_authenticated":s.userType&&e.isAuthenticated&&!Ht(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 Ot(s,e){return s.hasTenant?s.isAuthenticated?s.userType===ee.TENANT_ADMIN?e.tenantAdmin:e.tenantUser:e.tenantGuest:s.isAuthenticated?s.userType===ee.TENANT_ADMIN?e.publicAdmin:e.publicUser:e.publicGuest}function qt(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 _t(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 se=({children:s,preset:e,tenant:t,auth:n,userType:i,requiredPermissions:o,requireAllPermissions:l=!0,returnTo:p,onAccessDenied:w,redirectTo:y,loadingFallback:f,accessDeniedFallback:T})=>{const h=ne.useLocation(),{isAuthenticated:j,isAuthInitializing:I,currentUser:L,userPermissions:P}=ie(),{tenant:A,isTenantLoading:u}=ae(),S=Je(),N=a.useMemo(()=>{if(e)return S.presets[e]},[e,S.presets]),E=a.useMemo(()=>({tenant:t??(N==null?void 0:N.tenant),auth:n??(N==null?void 0:N.auth),userType:i??(N==null?void 0:N.userType),permissions:o??(N==null?void 0:N.requiredPermissions),requireAllPermissions:l}),[t,n,i,o,N,l]),v=a.useMemo(()=>({hasTenant:!!A,isAuthenticated:j,userType:L==null?void 0:L.userType,permissions:P,isLoading:I||u}),[A,j,L==null?void 0:L.userType,P,I,u]),D=a.useMemo(()=>v.isLoading?null:Bt(E,v),[E,v]),c=a.useMemo(()=>D?y||Ot(v,S.zoneRoots):null,[D,y,v,S.zoneRoots]),C=a.useMemo(()=>!D||!c?null:{type:D,required:{tenant:E.tenant,auth:E.auth,userType:E.userType,permissions:E.permissions},current:{hasTenant:v.hasTenant,isAuthenticated:v.isAuthenticated,userType:v.userType,permissions:v.permissions},redirectTo:c},[D,c,E,v]);if(a.useEffect(()=>{C&&(w?w(C):S.onAccessDenied&&S.onAccessDenied(C))},[C,w,S]),a.useEffect(()=>{C&&p&&_t(p,h.pathname+h.search,S.returnToStorage)},[C,p,h.pathname,h.search,S.returnToStorage]),v.isLoading)return r.jsx(r.Fragment,{children:f??S.loadingFallback??null});if(C&&c){const x=T??S.accessDeniedFallback;if(x)return r.jsx(r.Fragment,{children:x});const M=qt(c,p,h.pathname+h.search,S.returnToParam,S.returnToStorage);return r.jsx(ne.Navigate,{to:M,replace:!0})}return r.jsx(r.Fragment,{children:s})},zt=s=>r.jsx(se,{tenant:"required",...s}),Vt=s=>r.jsx(se,{tenant:"forbidden",...s}),Wt=s=>r.jsx(se,{auth:"required",...s}),Gt=s=>r.jsx(se,{auth:"forbidden",...s}),Zt=s=>r.jsx(se,{auth:"required",userType:ee.TENANT_ADMIN,...s}),Qt=s=>r.jsx(se,{auth:"required",userType:ee.USER,...s}),Kt=s=>r.jsx(se,{tenant:"optional",auth:"optional",...s}),Jt=s=>r.jsx(se,{tenant:"required",auth:"required",...s}),Yt=s=>r.jsx(se,{tenant:"required",auth:"optional",...s}),Xt=s=>r.jsx(se,{tenant:"required",auth:"forbidden",...s}),er=()=>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 tr({children:s,fallback:e=r.jsx(er,{}),allowedPlans:t,requiredFeature:n}){const{subscription:i,hasAllowedPlan:o,isFeatureEnabled:l,loading:p}=Qe();return p?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 rr=({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 nr({name:s,children:e,fallback:t}){const{isEnabled:n,loading:i}=We();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(rr,{flagName:s})})}const sr=()=>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"})]}),ir=()=>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"})]}),or={showPassword:r.jsx(sr,{}),hidePassword:r.jsx(ir,{})},ar={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"},lr={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 cr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onForgotPassword:o,onSignupClick:l,onMagicLinkClick:p,showForgotPassword:w=!0,showSignupLink:y=!0,showMagicLinkOption:f=!0,className:T}){const[h,j]=a.useState(""),[I,L]=a.useState(""),[P,A]=a.useState(!1),[u,S]=a.useState(!1),[N,E]=a.useState(""),[v,D]=a.useState({}),{login:c}=ie(),{tenant:C}=le(),x={...ar,...s},M={...lr,...e},F={...or,...t},d=()=>{const m={};return h.trim()||(m.username=!0),I.trim()||(m.password=!0),D(m),Object.keys(m).length===0},U=async m=>{if(m.preventDefault(),!!d()){if(!(C!=null&&C.id)){E(x.tenantNotFoundError);return}S(!0),E("");try{const b=await c({username:h,password:I});n==null||n(b)}catch(b){const W=b.message||x.errorMessage;E(W),i==null||i(W)}finally{S(!1)}}},R=m=>({...M.input,...v[m]?M.inputError:{}}),g=()=>({...M.button,...u?M.buttonLoading:{},...!h||!I||u?M.buttonDisabled:{}});return r.jsxs("div",{className:T,style:M.container,children:[r.jsx("h2",{style:M.title,children:x.title}),r.jsxs("form",{onSubmit:U,style:M.form,children:[r.jsxs("div",{style:M.fieldGroup,children:[r.jsx("label",{style:M.label,children:x.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:h,onChange:m=>{j(m.target.value),v.username&&D(b=>({...b,username:!1}))},placeholder:x.usernamePlaceholder,style:R("username"),disabled:u})]}),r.jsxs("div",{style:M.fieldGroup,children:[r.jsx("label",{style:M.label,children:x.passwordLabel}),r.jsxs("div",{style:M.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:P?"text":"password",value:I,onChange:m=>{L(m.target.value),v.password&&D(b=>({...b,password:!1}))},placeholder:x.passwordPlaceholder,style:{...R("password"),...M.inputWithIcon},disabled:u}),r.jsx("button",{type:"button",onClick:()=>A(!P),style:M.passwordToggle,disabled:u,"aria-label":P?x.hidePasswordAriaLabel:x.showPasswordAriaLabel,children:P?F.hidePassword:F.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!h||!I||u,style:g(),children:u?x.loadingText:x.submitButton}),N&&r.jsx("div",{style:M.errorText,children:N})]}),(w||y||f)&&r.jsxs("div",{style:M.linkContainer,children:[f&&r.jsxs("div",{children:[r.jsxs("span",{style:M.divider,children:[x.magicLinkText," "]}),r.jsx("a",{onClick:p,style:M.link,children:x.magicLinkLink})]}),f&&(w||y)&&r.jsx("div",{style:M.divider,children:x.dividerBullet}),w&&r.jsx("a",{onClick:o,style:M.link,children:x.forgotPasswordLink}),w&&y&&r.jsx("div",{style:M.divider,children:x.dividerBullet}),y&&r.jsxs("div",{children:[r.jsxs("span",{style:M.divider,children:[x.signupText," "]}),r.jsx("a",{onClick:l,style:M.link,children:x.signupLink})]})]})]})}const dr={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:"•"},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"},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 hr({copy:s={},styles:e={},signupType:t="user",onSuccess:n,onError:i,onLoginClick:o,onMagicLinkClick:l,showLoginLink:p=!0,showMagicLinkOption:w=!0,className:y}){const[f,T]=a.useState(""),[h,j]=a.useState(""),[I,L]=a.useState(""),[P,A]=a.useState(""),[u,S]=a.useState(""),[N,E]=a.useState(""),[v,D]=a.useState(""),[c,C]=a.useState(!1),[x,M]=a.useState(""),[F,d]=a.useState({}),{signup:U,signupTenantAdmin:R}=ie(),{tenant:g}=le(),m={...dr,...s},b={...ur,...e},W=()=>{const k={};return f.trim()||(k.name=!0),!I.trim()&&!P.trim()&&(k.email=!0,k.phoneNumber=!0),u.trim()||(k.password=!0),N.trim()||(k.confirmPassword=!0),t==="tenant"&&!v.trim()&&(k.tenantName=!0),d(k),Object.keys(k).length===0},Z=async k=>{if(k.preventDefault(),!!W()){if(u!==N){M(m.passwordMismatchError),d({confirmPassword:!0});return}if(t==="user"&&!(g!=null&&g.id)){M(m.tenantNotFoundError);return}C(!0),M("");try{let _;t==="tenant"?_=await R({email:I||void 0,phoneNumber:P||void 0,name:f,password:u,tenantName:v,lastName:h||void 0}):_=await U({email:I||void 0,phoneNumber:P||void 0,name:f,password:u,tenantId:g.id,lastName:h||void 0}),n==null||n(_)}catch(_){const oe=_.message||m.errorMessage;M(oe),i==null||i(oe)}finally{C(!1)}}},H=k=>({...b.input,...F[k]?b.inputError:{}}),B=()=>({...b.button,...c?b.buttonLoading:{},...!f||!I&&!P||!u||!N||c||t==="tenant"&&!v?b.buttonDisabled:{}}),z=f&&(I||P)&&u&&N&&(t==="user"||v);return r.jsxs("div",{className:y,style:b.container,children:[r.jsx("h2",{style:b.title,children:m.title}),r.jsxs("form",{onSubmit:Z,style:b.form,children:[r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:m.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:f,onChange:k=>{T(k.target.value),F.name&&d(_=>({..._,name:!1}))},placeholder:m.namePlaceholder,style:H("name"),disabled:c})]}),r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:m.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:h,onChange:k=>j(k.target.value),placeholder:m.lastNamePlaceholder,style:b.input,disabled:c})]}),r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:m.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:I,onChange:k=>{L(k.target.value),F.email&&d(_=>({..._,email:!1,phoneNumber:!1}))},placeholder:m.emailPlaceholder,style:H("email"),disabled:c})]}),r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:m.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:P,onChange:k=>{A(k.target.value),F.phoneNumber&&d(_=>({..._,email:!1,phoneNumber:!1}))},placeholder:m.phoneNumberPlaceholder,style:H("phoneNumber"),disabled:c})]}),r.jsx("div",{style:b.hintText,children:m.contactMethodHint}),r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:m.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:u,onChange:k=>{S(k.target.value),F.password&&d(_=>({..._,password:!1}))},placeholder:m.passwordPlaceholder,style:H("password"),disabled:c})]}),r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:m.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:N,onChange:k=>{E(k.target.value),F.confirmPassword&&d(_=>({..._,confirmPassword:!1})),x===m.passwordMismatchError&&M("")},placeholder:m.confirmPasswordPlaceholder,style:H("confirmPassword"),disabled:c})]}),t==="tenant"&&r.jsxs("div",{style:b.fieldGroup,children:[r.jsx("label",{style:b.label,children:m.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:v,onChange:k=>{D(k.target.value),F.tenantName&&d(_=>({..._,tenantName:!1}))},placeholder:m.tenantNamePlaceholder,style:H("tenantName"),disabled:c})]}),r.jsx("button",{type:"submit",disabled:!z||c,style:B(),children:c?m.loadingText:m.submitButton}),x&&r.jsx("div",{style:b.errorText,children:x})]}),(p||w)&&r.jsxs("div",{style:b.linkContainer,children:[w&&r.jsxs("div",{children:[r.jsxs("span",{style:b.divider,children:[m.magicLinkText," "]}),r.jsx("a",{onClick:l,style:b.link,children:m.magicLinkLink})]}),w&&p&&r.jsx("div",{style:b.divider,children:m.dividerBullet}),p&&r.jsxs("div",{children:[r.jsxs("span",{style:b.divider,children:[m.loginText," "]}),r.jsx("a",{onClick:o,style:b.link,children:m.loginLink})]})]})]})}const pr={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:"•"},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:"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 gr({copy:s={},styles:e={},onSuccess:t,onError:n,onLoginClick:i,onSignupClick:o,showTraditionalLinks:l=!0,className:p,verifyToken:w,frontendUrl:y}){const[f,T]=a.useState(""),[h,j]=a.useState(""),[I,L]=a.useState(""),[P,A]=a.useState(!1),[u,S]=a.useState(!1),[N,E]=a.useState(""),[v,D]=a.useState(""),[c,C]=a.useState({}),[x,M]=a.useState(!1),{sendMagicLink:F,verifyMagicLink:d}=ie(),{tenant:U}=le(),R={...pr,...s},g={...fr,...e};a.useEffect(()=>{w&&m(w)},[w]);const m=async B=>{if(!U||!f){E(R.missingTenantOrEmailError);return}S(!0),E("");try{const z=await d({token:B,email:f});t==null||t(z)}catch(z){const k=z.message||"Failed to verify magic link";E(k),n==null||n(k)}finally{S(!1)}},b=()=>{const B={};return f.trim()||(B.email=!0),x&&!h.trim()&&(B.name=!0),C(B),Object.keys(B).length===0},W=async B=>{if(B.preventDefault(),!!b()){if(!(U!=null&&U.id)){E(R.tenantNotFoundError);return}A(!0),E(""),D("");try{const z=y||(typeof window<"u"?window.location.origin:""),k=await F({email:f,tenantId:U.id,frontendUrl:z,name:x?h:void 0,lastName:x?I:void 0});D(R.successMessage),t==null||t(k)}catch(z){const k=z.message||R.errorMessage;E(k),n==null||n(k)}finally{A(!1)}}},Z=B=>({...g.input,...c[B]?g.inputError:{}}),H=()=>({...g.button,...P||u?g.buttonLoading:{},...!f||P||u?g.buttonDisabled:{}});return u?r.jsxs("div",{className:p,style:g.container,children:[r.jsx("h2",{style:g.title,children:R.verifyingText}),r.jsx("div",{style:g.verifyingContainer,children:r.jsx("div",{style:g.verifyingText,children:R.verifyingDescription})})]}):r.jsxs("div",{className:p,style:g.container,children:[r.jsx("h2",{style:g.title,children:R.title}),r.jsx("p",{style:g.description,children:R.description}),r.jsxs("form",{onSubmit:W,style:g.form,children:[r.jsxs("div",{style:g.fieldGroup,children:[r.jsx("label",{style:g.label,children:R.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:f,onChange:B=>{T(B.target.value),c.email&&C(z=>({...z,email:!1}))},placeholder:R.emailPlaceholder,style:Z("email"),disabled:P||u})]}),!x&&r.jsx("div",{style:g.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>M(!0),style:g.toggleLink,children:R.showNameToggle})}),x&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:g.fieldGroup,children:[r.jsx("label",{style:g.label,children:R.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:h,onChange:B=>{j(B.target.value),c.name&&C(z=>({...z,name:!1}))},placeholder:R.namePlaceholder,style:Z("name"),disabled:P||u})]}),r.jsxs("div",{style:g.fieldGroup,children:[r.jsx("label",{style:g.label,children:R.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:I,onChange:B=>L(B.target.value),placeholder:R.lastNamePlaceholder,style:g.input,disabled:P||u})]}),r.jsx("div",{style:g.toggleContainer,children:r.jsx("button",{type:"button",onClick:()=>{M(!1),j(""),L("")},style:g.toggleLink,children:R.hideNameToggle})})]}),r.jsx("button",{type:"submit",disabled:!f||P||u,style:H(),children:P?R.loadingText:R.submitButton}),N&&r.jsx("div",{style:g.errorText,children:N}),v&&r.jsx("div",{style:g.successText,children:v})]}),l&&r.jsxs("div",{style:g.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:g.divider,children:[R.loginText," "]}),r.jsx("a",{onClick:i,style:g.link,children:R.loginLink})]}),r.jsx("div",{style:g.divider,children:R.dividerBullet}),r.jsxs("div",{children:[r.jsxs("span",{style:g.divider,children:[R.signupText," "]}),r.jsx("a",{onClick:o,style:g.link,children:R.signupLink})]})]})]})}const mr={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"},Ye={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"}},yr=()=>r.jsx("div",{style:Ye.spinner}),wr=()=>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"})]}),xr=()=>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"})]}),br={loading:r.jsx(yr,{}),success:r.jsx(wr,{}),error:r.jsx(xr,{})};function Sr({copy:s={},styles:e={},icons:t={},onSuccess:n,onError:i,onRetry:o,onBackToLogin:l,className:p,token:w,email:y,appId:f,tenantSlug:T,autoRedirectDelay:h=3e3}){const[j,I]=a.useState("verifying"),[L,P]=a.useState(""),{verifyMagicLink:A}=ie(),u={...mr,...s},S={...Ye,...e},N={...br,...t},E=()=>{if(typeof window>"u")return{};const x=new URLSearchParams(window.location.search);return{token:w||x.get("token")||"",email:y||x.get("email")||"",appId:f||x.get("appId")||"",tenantSlug:T||x.get("tenantSlug")||void 0}},v=async()=>{I("verifying"),P("");try{const x=E();if(!x.token||!x.email)throw new Error(u.missingParamsError);const M=await A({token:x.token,email:x.email,tenantSlug:x.tenantSlug});I("success"),n==null||n(M),h>0&&setTimeout(()=>{I("redirecting")},h)}catch(x){const M=x.message||u.errorMessage;P(M),I("error"),i==null||i(M)}},D=()=>{o==null||o(),v()},c=()=>{l==null||l()};a.useEffect(()=>{v()},[]);const C=()=>{switch(j){case"verifying":return r.jsxs("div",{style:S.message,children:[N.loading,u.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[N.success,r.jsx("div",{style:S.successMessage,children:u.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[N.loading,r.jsx("div",{style:S.message,children:u.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[N.error,r.jsx("div",{style:S.errorMessage,children:L||u.errorMessage}),r.jsxs("div",{style:S.buttonContainer,children:[r.jsx("button",{onClick:D,style:S.retryButton,onMouseOver:x=>{Object.assign(x.currentTarget.style,S.retryButtonHover)},onMouseOut:x=>{const M=S.retryButton||{};Object.keys(S.retryButtonHover||{}).forEach(F=>{x.currentTarget.style[F]=M[F]??""})},children:u.retryButton}),r.jsx("button",{onClick:c,style:S.backButton,onMouseOver:x=>{Object.assign(x.currentTarget.style,S.backButtonHover)},onMouseOut:x=>{const M=S.backButton||{};Object.keys(S.backButtonHover||{}).forEach(F=>{x.currentTarget.style[F]=M[F]??""})},children:u.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:S.container,className:p,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:S.title,children:u.title}),C()]})}const vr={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:"•"},Tr={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 kr({copy:s={},styles:e={},mode:t="request",token:n="",onSuccess:i,onError:o,onBackToLogin:l,onModeChange:p,className:w}){const[y,f]=a.useState(""),[T,h]=a.useState(n),[j,I]=a.useState(""),[L,P]=a.useState(""),[A,u]=a.useState(!1),[S,N]=a.useState(""),[E,v]=a.useState(""),[D,c]=a.useState({}),{requestPasswordReset:C,confirmPasswordReset:x}=ie(),{tenant:M}=le(),F={...vr,...s},d={...Tr,...e},U=()=>{const H={};return y.trim()||(H.email=!0),c(H),Object.keys(H).length===0},R=()=>{const H={};return T.trim()||(H.token=!0),j.trim()||(H.newPassword=!0),L.trim()||(H.confirmPassword=!0),c(H),Object.keys(H).length===0},g=async H=>{if(H.preventDefault(),!!U()){if(!(M!=null&&M.id)){N(F.tenantNotFoundError);return}u(!0),N(""),v("");try{await C({email:y,tenantId:M.id}),v(F.successMessage),i==null||i()}catch(B){const z=B.message||F.errorMessage;N(z),o==null||o(z)}finally{u(!1)}}},m=async H=>{if(H.preventDefault(),!!R()){if(j!==L){N(F.passwordMismatchError),c({confirmPassword:!0});return}u(!0),N(""),v("");try{await x({token:T,newPassword:j}),v(F.resetSuccessMessage),i==null||i()}catch(B){const z=B.message||F.errorMessage;N(z),o==null||o(z)}finally{u(!1)}}},b=H=>({...d.input,...D[H]?d.inputError:{}}),W=()=>({...d.button,...A?d.buttonLoading:{}});if(t==="reset"){const H=T&&j&&L;return r.jsxs("div",{className:w,style:d.container,children:[r.jsx("h2",{style:d.title,children:F.resetTitle}),r.jsx("p",{style:d.subtitle,children:F.resetSubtitle}),r.jsxs("form",{onSubmit:m,style:d.form,children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:F.tokenLabel}),r.jsx("input",{type:"text",value:T,onChange:B=>{h(B.target.value),D.token&&c(z=>({...z,token:!1}))},placeholder:F.tokenPlaceholder,style:b("token"),disabled:A})]}),r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:F.newPasswordLabel}),r.jsx("input",{type:"password",value:j,onChange:B=>{I(B.target.value),D.newPassword&&c(z=>({...z,newPassword:!1}))},placeholder:F.newPasswordPlaceholder,style:b("newPassword"),disabled:A})]}),r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:F.confirmPasswordLabel}),r.jsx("input",{type:"password",value:L,onChange:B=>{P(B.target.value),D.confirmPassword&&c(z=>({...z,confirmPassword:!1})),S===F.passwordMismatchError&&N("")},placeholder:F.confirmPasswordPlaceholder,style:b("confirmPassword"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!H||A,style:{...W(),...!H||A?d.buttonDisabled:{}},children:A?F.resetLoadingText:F.resetSubmitButton}),S&&r.jsx("div",{style:d.errorText,children:S}),E&&r.jsx("div",{style:d.successText,children:E})]}),r.jsxs("div",{style:d.linkContainer,children:[r.jsx("a",{onClick:l,style:d.link,children:F.backToLoginLink}),p&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:d.modeSwitchDivider,children:F.dividerBullet}),r.jsx("a",{onClick:()=>p("request"),style:d.link,children:F.requestNewLinkLink})]})]})]})}const Z=y;return r.jsxs("div",{className:w,style:d.container,children:[r.jsx("h2",{style:d.title,children:F.title}),r.jsx("p",{style:d.subtitle,children:F.subtitle}),r.jsxs("form",{onSubmit:g,style:d.form,children:[r.jsxs("div",{style:d.fieldGroup,children:[r.jsx("label",{style:d.label,children:F.emailLabel}),r.jsx("input",{type:"email",value:y,onChange:H=>{f(H.target.value),D.email&&c(B=>({...B,email:!1}))},placeholder:F.emailPlaceholder,style:b("email"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!Z||A,style:{...W(),...!Z||A?d.buttonDisabled:{}},children:A?F.loadingText:F.submitButton}),S&&r.jsx("div",{style:d.errorText,children:S}),E&&r.jsx("div",{style:d.successText,children:E})]}),r.jsxs("div",{style:d.linkContainer,children:[r.jsx("a",{onClick:l,style:d.link,children:F.backToLoginLink}),p&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:d.modeSwitchDivider,children:F.dividerBullet}),r.jsx("a",{onClick:()=>p("reset"),style:d.link,children:F.haveTokenLink})]})]})]})}const Ar=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),jr=({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 Pr({children:s,loadingFallback:e,errorFallback:t,requireTenant:n=!0}){const{isAppLoading:i,appError:o,retryApp:l}=pe(),p=ge(),w=Re(),y=Ge(),f=Ke(),T=(p==null?void 0:p.isTenantLoading)??!1,h=(p==null?void 0:p.tenantError)??null,j=(p==null?void 0:p.tenantSlug)??null,I=(p==null?void 0:p.retryTenant)??(()=>{}),L=(w==null?void 0:w.isAuthReady)??!0,P=(y==null?void 0:y.isReady)??!0,A=(f==null?void 0:f.isReady)??!0,u=n&&p&&j,v=i||u&&T||w&&!L||y&&!P||f&&!A,D=o||(u?h:null),c=()=>{o&&l(),h&&p&&I()};if(v)return r.jsx(r.Fragment,{children:e||r.jsx(Ar,{})});if(D){const C=typeof t=="function"?t(D,c):t||r.jsx(jr,{error:D,retry:c});return r.jsx(r.Fragment,{children:C})}return r.jsx(r.Fragment,{children:s})}function Rr(s=!0){const{isAppLoading:e,appError:t,retryApp:n,appInfo:i}=pe(),o=ge(),l=Re(),p=Ge(),w=Ke(),y=(o==null?void 0:o.isTenantLoading)??!1,f=(o==null?void 0:o.tenantError)??null,T=(o==null?void 0:o.tenant)??null,h=(o==null?void 0:o.tenantSlug)??null,j=(o==null?void 0:o.retryTenant)??(()=>{}),I=(l==null?void 0:l.isAuthReady)??!0,L=(p==null?void 0:p.isReady)??!0,P=(w==null?void 0:w.isReady)??!0,A=s&&o&&h,E=e||A&&y||l&&!I||p&&!L||w&&!P,v=t||(A?f:null);return{isLoading:E,error:v,isReady:!E&&!v&&i!==null&&(!A||T!==null),retry:()=>{t&&n(),f&&o&&j()},app:{isLoading:e,error:t,data:i},tenant:o?{isLoading:y,error:f,data:T}:null,auth:l?{isReady:I}:null,featureFlags:p?{isReady:L}:null,subscription:w?{isReady:P}:null}}const Er={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 Mr({tenants:s,currentTenantId:e,onSelect:t,styles:n={},className:i="",dropdownClassName:o="",itemClassName:l="",renderItem:p,placeholder:w="Select tenant",disabled:y=!1,showCurrentTenant:f=!0}){var E;const T={...Er,...n},h=Re(),[j,I]=a.useState(!1),L=a.useRef(null),P=s??(h==null?void 0:h.userTenants)??[],A=e??((E=h==null?void 0:h.currentUser)==null?void 0:E.tenantId)??null,u=async v=>{I(!1),t?t(v):h!=null&&h.switchToTenant&&await h.switchToTenant(v)};a.useEffect(()=>{const v=D=>{L.current&&!L.current.contains(D.target)&&I(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]);const S=P.find(v=>v.id===A);if(P.length===0)return null;if(P.length===1&&f)return r.jsx("div",{className:i,children:r.jsx("span",{children:P[0].name})});const N=(v,D)=>r.jsxs("span",{style:{fontWeight:D?"bold":"normal"},children:[v.name,v.role&&r.jsxs("span",{style:T.itemRole,children:["(",v.role,")"]})]});return r.jsxs("div",{ref:L,className:i,style:T.wrapper,children:[r.jsxs("button",{type:"button",onClick:()=>!y&&I(!j),disabled:y,style:{...T.button,...y?T.buttonDisabled:{}},children:[S?S.name:w,r.jsx("span",{style:T.arrow,children:j?"▲":"▼"})]}),j&&r.jsx("div",{className:o,style:T.dropdown,children:P.map(v=>{const D=v.id===A;return r.jsx("div",{className:l,onClick:()=>u(v.id),style:{...T.item,...D?T.itemSelected:{}},onMouseEnter:c=>{D||Object.assign(c.currentTarget.style,T.itemHover)},onMouseLeave:c=>{if(!D){const C=T.item||{};Object.keys(T.itemHover||{}).forEach(x=>{c.currentTarget.style[x]=C[x]??""})}},children:p?p(v,D):N(v,D)},v.id)})})]})}class Ir{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 Lr{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 Fr{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class Nr{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 Xe="returnTo",Se="zone_return_to",ve="zone_return_to";function Dr(s={}){const{zoneRoots:e={},returnToParam:t=Xe,returnToStorage:n="url"}=s,i=ne.useNavigate(),[o,l]=ne.useSearchParams(),{isAuthenticated:p,currentUser:w}=ie(),{tenant:y}=ae(),f=a.useMemo(()=>({...ye,...e}),[e]),T=!!y,h=w==null?void 0:w.userType,j=a.useMemo(()=>{switch(n){case"url":return o.get(t);case"session":return sessionStorage.getItem(Se);case"local":return localStorage.getItem(ve);default:return null}},[n,o,t]),I=a.useCallback(()=>{switch(n){case"url":{const u=new URLSearchParams(o);u.delete(t),l(u,{replace:!0});break}case"session":sessionStorage.removeItem(Se);break;case"local":localStorage.removeItem(ve);break}},[n,o,t,l]),L=a.useCallback(u=>{switch(n){case"url":{const S=new URLSearchParams(o);S.set(t,u),l(S,{replace:!0});break}case"session":sessionStorage.setItem(Se,u);break;case"local":localStorage.setItem(ve,u);break}},[n,o,t,l]),P=a.useCallback(u=>{const S=f[u]||f.default;i(S)},[i,f]),A=a.useCallback(()=>T?p?h===ee.TENANT_ADMIN?f.tenantAdmin:f.tenantUser:f.tenantGuest:p?h===ee.TENANT_ADMIN?f.publicAdmin:f.publicUser:f.publicGuest,[T,p,h,f]);return{returnToUrl:j,clearReturnTo:I,setReturnTo:L,navigateToZone:P,getSmartRedirect:A}}function Cr(s,e,t=Xe,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=Zt;exports.ApiMappers=Nr;exports.AppApiService=Te;exports.AppLoader=Pr;exports.AppProvider=pt;exports.AuthApiService=_e;exports.AuthProvider=At;exports.AuthenticatedZone=Wt;exports.DEFAULT_ZONE_PRESETS=Ie;exports.DEFAULT_ZONE_ROOTS=ye;exports.FeatureFlag=nr;exports.FeatureFlagApiService=Ve;exports.FeatureFlagProvider=jt;exports.GuestZone=Gt;exports.HealthApiService=Fr;exports.HttpService=re;exports.LandingRoute=$t;exports.LoginForm=cr;exports.MagicLinkForm=gr;exports.MagicLinkVerify=Sr;exports.OpenZone=Kt;exports.PasswordRecoveryForm=kr;exports.PermissionApiService=Ir;exports.Protected=It;exports.ProtectedRoute=Nt;exports.PublicZone=Vt;exports.RoleApiService=ke;exports.RoutingProvider=Rt;exports.SessionExpiredError=X;exports.SessionManager=ue;exports.SignupForm=hr;exports.SubscriptionApiService=Ze;exports.SubscriptionGuard=tr;exports.SubscriptionPlanApiService=Lr;exports.SubscriptionProvider=Pt;exports.TenantApiService=he;exports.TenantAuthenticatedZone=Jt;exports.TenantGuestZone=Xt;exports.TenantOpenZone=Yt;exports.TenantProvider=vt;exports.TenantRoute=Ct;exports.TenantSelector=Mr;exports.TenantZone=zt;exports.TokenRefreshError=qe;exports.TokenRefreshTimeoutError=Oe;exports.UserApiService=ze;exports.UserType=ee;exports.UserZone=Qt;exports.ZoneRoute=se;exports.buildRedirectUrl=Cr;exports.useApi=ft;exports.useApp=pe;exports.useAppLoaderState=Rr;exports.useAuth=ie;exports.useFeatureFlags=We;exports.useRouting=Et;exports.useRoutingOptional=Je;exports.useSettings=kt;exports.useSubscription=Qe;exports.useTenant=ae;exports.useTenantInfo=le;exports.useTenantOptional=ge;exports.useTenantSettings=Tt;exports.useZoneNavigation=Dr;
|
|
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
|