@skylabs-digital/react-identity-access 2.9.0 → 2.10.1
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/ProtectedRoute.d.ts +2 -2
- package/dist/components/ProtectedRoute.d.ts.map +1 -1
- package/dist/components/TenantSelector.d.ts +18 -0
- package/dist/components/TenantSelector.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +1287 -1108
- 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 +9 -1
- package/dist/providers/AuthProvider.d.ts.map +1 -1
- package/dist/services/AuthApiService.d.ts +3 -1
- package/dist/services/AuthApiService.d.ts.map +1 -1
- package/dist/types/api.d.ts +18 -1
- 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"),re=require("react-router-dom");class Z{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async request(e,t,s,n){return this.executeRequest(e,t,s,n,!1)}async executeRequest(e,t,s,n,o=!1){const l=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,g=(n==null?void 0:n.timeout)||this.timeout;let w={"Content-Type":"application/json",...n==null?void 0:n.headers};if(!(n!=null&&n.skipAuth)&&this.sessionManager)try{const x=await this.sessionManager.getAuthHeaders();w={...w,...x}}catch(x){console.warn("Failed to inject auth headers:",x)}const m=new AbortController,S=setTimeout(()=>m.abort(),g);try{const x=await fetch(l,{method:e,headers:w,body:s?JSON.stringify(s):void 0,signal:m.signal});if(clearTimeout(S),x.status===401&&!(n!=null&&n.skipRetry)&&!o&&this.sessionManager)try{const k=this.sessionManager.getTokens();if(k!=null&&k.refreshToken)return await this.sessionManager.getAuthHeaders(),this.executeRequest(e,t,s,n,!0)}catch{throw new Error(`HTTP ${x.status}: ${x.statusText}`)}if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);const f=x.headers.get("content-type");return!f||!f.includes("application/json")?{}:await x.json()}catch(x){throw clearTimeout(S),x instanceof Error&&x.name==="AbortError"?new Error(`Request timeout after ${g}ms`):x}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,s){return this.request("POST",e,t,s)}async put(e,t,s){return this.request("PUT",e,t,s)}async delete(e,t){return this.request("DELETE",e,void 0,t)}}class pe{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/apps/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:s})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:s})).data}async updateSettingsSchema(e,t,s){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:s},{headers:n})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const me=a.createContext(null);function Ve({config:i,children:e}){const t=a.useMemo(()=>{var f,k,F;return{enabled:((f=i.cache)==null?void 0:f.enabled)??!0,ttl:((k=i.cache)==null?void 0:k.ttl)??3e5,storageKey:((F=i.cache)==null?void 0:F.storageKey)??`app_cache_${i.appId}`}},[i.cache,i.appId]),[s,n]=a.useState(()=>{if(!t.enabled)return null;try{const f=localStorage.getItem(t.storageKey);if(!f)return null;const k=JSON.parse(f);return Date.now()-k.timestamp<t.ttl&&k.appId===i.appId?k.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[o,l]=a.useState(!s),[g,w]=a.useState(null),m=a.useMemo(()=>{const f=()=>{S()};return{appId:i.appId,baseUrl:i.baseUrl,appInfo:s,isAppLoading:o,appError:g,retryApp:f}},[i,s,o,g]),S=a.useCallback(async(f=!1)=>{if(!(!f&&t.enabled&&s))try{l(!0),w(null);const k=new Z(i.baseUrl),C=await new pe(k,{}).getPublicAppInfo(i.appId);if(n(C),t.enabled)try{const R={data:C,timestamp:Date.now(),appId:i.appId};localStorage.setItem(t.storageKey,JSON.stringify(R))}catch(R){console.warn("Failed to cache app info:",R)}}catch(k){const F=k instanceof Error?k:new Error("Failed to load app information");w(F),n(null)}finally{l(!1)}},[i.baseUrl,i.appId,t,s]),x=a.useCallback(async()=>{if(!(!t.enabled||!s))try{const f=localStorage.getItem(t.storageKey);if(!f)return;const k=JSON.parse(f);if(Date.now()-k.timestamp>t.ttl*.5){const C=new Z(i.baseUrl),T=await new pe(C,{}).getPublicAppInfo(i.appId);n(T);const u={data:T,timestamp:Date.now(),appId:i.appId};localStorage.setItem(t.storageKey,JSON.stringify(u))}}catch(f){console.warn("Background app refresh failed:",f)}},[i,t,s]);return a.useEffect(()=>{s?x():S()},[]),r.jsx(me.Provider,{value:m,children:e})}function ie(){const i=a.useContext(me);if(!i)throw new Error("useApp must be used within an AppProvider");return i}function Ae(){return a.useContext(me)}const Ge=ie;class de{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],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.baseUrl=e.baseUrl||"",this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey)}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{}}}}setTokens(e){const t={...e,expiresAt:e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)};this.tokenStorage.set(t)}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:s,expiresIn:n,tokenType:o}=this.tokenStorage.get()||{};return e?{accessToken:e,refreshToken:t,expiresAt:s,expiresIn:n,tokenType:o}:null}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}async getAuthHeaders(){const e=this.getTokens();if(!(e!=null&&e.accessToken))return{};if(!this.shouldRefreshToken(e))return{Authorization:`Bearer ${e.accessToken}`};if(!e.refreshToken)return this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{};if(this.refreshPromise)return new Promise((t,s)=>{this.refreshQueue.push({resolve:t,reject:s})});this.refreshPromise=this.performTokenRefresh(e.refreshToken);try{await this.refreshPromise;const t=this.getTokens(),s=t!=null&&t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{};return this.refreshQueue.forEach(({resolve:n})=>n(s)),this.refreshQueue=[],s}catch(t){const s=t instanceof Error?t:new Error("Token refresh failed");return this.refreshQueue.forEach(({reject:n})=>n(s)),this.refreshQueue=[],this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{}}finally{this.refreshPromise=null}}async performTokenRefresh(e){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const t=`${this.baseUrl}/auth/refresh`,s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);const n=await s.json();this.setTokens({accessToken:n.accessToken,refreshToken:n.refreshToken||e,expiresIn:n.expiresIn})}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.clearTokens(),this.clearUser()}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 s=t[1],n=atob(s.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(n)}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)}}class Te{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 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 fe{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:s})).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 s=new URLSearchParams;t!=null&&t.page&&s.append("page",t.page.toString()),t!=null&&t.limit&&s.append("limit",t.limit.toString()),t!=null&&t.sortBy&&s.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&s.append("sortOrder",t.sortOrder);const n=`/roles/app/${e}${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n);return{roles:o.data,meta:o.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:s})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:s})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders(),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 o=`/roles/user/${e}${n.toString()?`?${n.toString()}`:""}`,l=await this.httpService.get(o,{headers:s});return{roles:l.data,meta:l.meta}}}class je{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/users/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:s})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class ne{constructor(e,t,s){this.httpService=e,this.appId=t,this.sessionManager=s}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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/tenants/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:s})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:s})).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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:s})).data}}function _e(i,e){if(i==="localhost"||i.startsWith("127.")||i.startsWith("192.168."))return null;if(e){const n=e.toLowerCase(),o=i.toLowerCase();if(o===n||o===`www.${n}`)return null;if(o.endsWith(`.${n}`)){const l=o.slice(0,-(n.length+1));return l==="www"?null:l}return null}const s=i.split(".");return s.length>=3&&s[0]!=="www"?s[0]:null}function Ke(i,e="tenant",t){const n=new URLSearchParams(i).get(e);return n?(t&&t.setItem("tenant",n),n):t?t.getItem("tenant"):null}function Je(i,e,t){const{tenantMode:s,baseDomain:n,selectorParam:o}=i;return s==="subdomain"?_e(e.hostname,n):s==="selector"?Ke(e.search,o,t):null}function Ye(i,e,t){if(t)return`${i}.${t}`;const s=e.split(".");return s.length===2?`${i}.${e}`:s.length>=3?(s[0]=i,s.join(".")):null}const ue="_auth";function Qe(i){const e=JSON.stringify(i);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Xe(i){try{let e=i.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";const t=atob(e),s=JSON.parse(t);return typeof s.accessToken=="string"&&typeof s.refreshToken=="string"&&typeof s.expiresIn=="number"?s:null}catch{return null}}function Ze(){if(typeof window>"u")return console.log("[CrossDomainAuth] SSR environment, skipping URL token extraction"),null;const e=new URLSearchParams(window.location.search).get(ue);if(console.log("[CrossDomainAuth] extractAuthTokensFromUrl called",{hasAuthParam:!!e,searchParams:window.location.search,encodedLength:e==null?void 0:e.length}),!e)return null;const t=Xe(e);return console.log("[CrossDomainAuth] Token decode result:",{success:!!t,hasAccessToken:!!(t!=null&&t.accessToken),hasRefreshToken:!!(t!=null&&t.refreshToken),expiresIn:t==null?void 0:t.expiresIn}),t}function et(){if(typeof window>"u")return;const i=new URL(window.location.href);i.searchParams.delete(ue),console.log("[CrossDomainAuth] Clearing auth tokens from URL",{oldUrl:window.location.href,newUrl:i.toString()}),window.history.replaceState({},"",i.toString())}const ye=a.createContext(null);function tt({config:i,children:e}){const{baseUrl:t,appInfo:s,appId:n}=ie(),o=a.useCallback(()=>typeof window>"u"?null:Je({tenantMode:i.tenantMode||"selector",baseDomain:i.baseDomain,selectorParam:i.selectorParam},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[i.tenantMode,i.baseDomain,i.selectorParam]),[l,g]=a.useState(()=>o()),w=a.useMemo(()=>{var c,M,A;return{enabled:((c=i.cache)==null?void 0:c.enabled)??!0,ttl:((M=i.cache)==null?void 0:M.ttl)??5*60*1e3,storageKey:((A=i.cache)==null?void 0:A.storageKey)??`tenant_cache_${l||"default"}`}},[i.cache,l]),[m,S]=a.useState(()=>{if(i.initialTenant)return i.initialTenant;if(!w.enabled||!l)return null;try{const c=localStorage.getItem(w.storageKey);if(!c)return null;const M=JSON.parse(c);return Date.now()-M.timestamp<w.ttl&&M.tenantSlug===l?M.data:(localStorage.removeItem(w.storageKey),null)}catch{return null}}),[x,f]=a.useState(!m&&!i.initialTenant),[k,F]=a.useState(null),[C,R]=a.useState(null),[T,u]=a.useState(!1),[j,B]=a.useState(null);a.useEffect(()=>{const c=o();g(c)},[o]);const $=(s==null?void 0:s.settingsSchema)||null,p=a.useCallback(async(c,M=!1)=>{if(!(!M&&w.enabled&&m&&m.domain===c))try{f(!0),F(null);const A=new Z(t),d=await new ne(A,n).getPublicTenantInfo(c);if(S(d),w.enabled)try{const y={data:d,timestamp:Date.now(),tenantSlug:c};localStorage.setItem(w.storageKey,JSON.stringify(y))}catch(y){console.warn("Failed to cache tenant info:",y)}}catch(A){const h=A instanceof Error?A:new Error("Failed to load tenant information");F(h),S(null)}finally{f(!1)}},[t,n,w,m]),q=a.useCallback(async()=>{if(!(!w.enabled||!m||!l))try{const c=localStorage.getItem(w.storageKey);if(!c)return;const M=JSON.parse(c);if(Date.now()-M.timestamp>w.ttl*.5){const h=new Z(t),y=await new ne(h,n).getPublicTenantInfo(l);S(y);const V={data:y,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(w.storageKey,JSON.stringify(V))}}catch(c){console.warn("Background tenant refresh failed:",c)}},[t,n,w,m,l]),b=a.useCallback(async()=>{if(m!=null&&m.id)try{u(!0),B(null);const c=new Z(t),A=await new ne(c,m.appId).getTenantSettings(m.id);R(A)}catch(c){const M=c instanceof Error?c:new Error("Failed to load tenant settings");B(M),R(null)}finally{u(!1)}},[t,m]),I=a.useCallback(()=>{b()},[b]),v=a.useCallback(c=>{if(!$)return{isValid:!0,errors:[]};const M=[];try{return $.properties&&Object.entries($.properties).forEach(([A,h])=>{var y;const d=c[A];if((y=$.required)!=null&&y.includes(A)&&d==null){M.push(`Field '${A}' is required`);return}if(d!=null){if(h.type){const V=h.type,E=typeof d;V==="string"&&E!=="string"?M.push(`Field '${A}' must be a string`):(V==="number"||V==="integer")&&E!=="number"?M.push(`Field '${A}' must be a number`):V==="boolean"&&E!=="boolean"?M.push(`Field '${A}' must be a boolean`):V==="array"&&!Array.isArray(d)&&M.push(`Field '${A}' must be an array`)}h.minLength!==void 0&&typeof d=="string"&&d.length<h.minLength&&M.push(`Field '${A}' must be at least ${h.minLength} characters long`),h.maxLength!==void 0&&typeof d=="string"&&d.length>h.maxLength&&M.push(`Field '${A}' must be no more than ${h.maxLength} characters long`),h.minimum!==void 0&&typeof d=="number"&&d<h.minimum&&M.push(`Field '${A}' must be at least ${h.minimum}`),h.maximum!==void 0&&typeof d=="number"&&d>h.maximum&&M.push(`Field '${A}' must be no more than ${h.maximum}`),h.pattern&&typeof d=="string"&&(new RegExp(h.pattern).test(d)||M.push(`Field '${A}' does not match the required pattern`)),h.enum&&!h.enum.includes(d)&&M.push(`Field '${A}' must be one of: ${h.enum.join(", ")}`)}}),{isValid:M.length===0,errors:M}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[$]);a.useEffect(()=>{!i.initialTenant&&l?m?q():p(l):!i.initialTenant&&!l&&(S(null),F(null),f(!1))},[i.initialTenant,l,m,p,q]),a.useEffect(()=>{m!=null&&m.id?b():(R(null),B(null),u(!1))},[m==null?void 0:m.id,b]);const P=a.useCallback((c,M)=>{const{mode:A="reload",tokens:h,redirectPath:d}=M||{},y=i.tenantMode||"selector";if(localStorage.setItem("tenant",c),y==="subdomain"){const V=window.location.hostname,E=Ye(c,V,i.baseDomain);if(!E){console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",V);return}const D=d||window.location.pathname,H=new URL(`${window.location.protocol}//${E}${D}`);new URLSearchParams(window.location.search).forEach((N,G)=>{G!==ue&&H.searchParams.set(G,N)}),h&&H.searchParams.set(ue,Qe(h)),window.location.href=H.toString()}else if(y==="selector"){const V=d||window.location.pathname,E=new URLSearchParams(window.location.search);if(E.set(i.selectorParam||"tenant",c),A==="reload"){const D=`${V}?${E.toString()}${window.location.hash}`;window.location.href=D}else{const D=`${V}?${E.toString()}${window.location.hash}`;window.history.pushState({},"",D),g(c),p(c)}}},[i.tenantMode,i.selectorParam,i.baseDomain,p]),L=a.useMemo(()=>({tenant:m,tenantSlug:l,isTenantLoading:x,tenantError:k,retryTenant:()=>{l&&p(l)},settings:C,settingsSchema:$,isSettingsLoading:T,settingsError:j,refreshSettings:I,switchTenant:P,validateSettings:v}),[m,l,x,k,C,$,T,j,I,P,v]);return r.jsx(ye.Provider,{value:L,children:e})}function ae(){const i=a.useContext(ye);if(!i)throw new Error("useTenant must be used within a TenantProvider");return i}function le(){return a.useContext(ye)}const rt=ae;function st(){const{settings:i,settingsSchema:e,isSettingsLoading:t,settingsError:s,validateSettings:n}=ae();return{settings:i,settingsSchema:e,isLoading:t,error:s,validateSettings:n}}function se(){const{tenant:i,tenantSlug:e,isTenantLoading:t,tenantError:s,retryTenant:n}=ae();return{tenant:i,tenantSlug:e,isLoading:t,error:s,retry:n}}const we=a.createContext(null);function nt({config:i={},children:e}){const{appId:t,baseUrl:s}=ie(),{tenant:n,tenantSlug:o,switchTenant:l}=ae(),[g,w]=a.useState(i.initialRoles||[]),[m,S]=a.useState(!i.initialRoles),[x,f]=a.useState(null),[k,F]=a.useState(!1),[C,R]=a.useState(null),[T,u]=a.useState(0),j=a.useRef({done:!1,urlTokens:null});j.current.done||(j.current.done=!0,j.current.urlTokens=Ze(),j.current.urlTokens&&console.log("[AuthProvider] SYNC: URL tokens found, will block isAuthReady until user loaded"));const[B,$]=a.useState(()=>{const E=j.current.urlTokens!==null;return console.log("[AuthProvider] SYNC: isLoadingAfterUrlTokens initial:",E),E}),p=a.useMemo(()=>{const E=new de({tenantSlug:o,onRefreshFailed:i.onRefreshFailed,baseUrl:s});return j.current.urlTokens&&(console.log("[AuthProvider] SYNC: Saving URL tokens to session manager"),E.setTokens({accessToken:j.current.urlTokens.accessToken,refreshToken:j.current.urlTokens.refreshToken,expiresIn:j.current.urlTokens.expiresIn}),console.log("[AuthProvider] SYNC: Session valid:",E.hasValidSession())),E},[o,s,i.onRefreshFailed]),q=j.current.done&&!B,b=a.useMemo(()=>{const E=new Z(s);return E.setSessionManager(p),E},[s,p]),I=a.useMemo(()=>new Te(new Z(s)),[s]),v=a.useMemo(()=>new je(b,p),[b,p]),P=a.useMemo(()=>new fe(new Z(s)),[s]),L=a.useMemo(()=>x||p.getUser(),[x,p]),c=a.useMemo(()=>L!=null&&L.roleId&&g.find(E=>E.id===L.roleId)||null,[L,g]),M=a.useMemo(()=>(c==null?void 0:c.permissions)||[],[c]),A=a.useMemo(()=>p.hasValidSession()&&x!==null,[p,x]),h=5*60*1e3,d=a.useMemo(()=>{const E=async(U=!1)=>{try{if(!p.hasValidSession())return;const z=Date.now();if(!U&&z-T<h&&x)return;const W=p.getUserId();if(!W){console.warn("[AuthProvider] No userId available in token or storage");return}F(!0),R(null);const Y=await v.getUserById(W);f(Y),p.setUser(Y),u(Date.now())}catch(z){const _=z instanceof Error?z:new Error("Failed to load user data");R(_),console.error("[AuthProvider] Failed to load user data:",_)}finally{F(!1)}},D=async()=>{await E()},H=async U=>{const{username:z,password:_,tenantSlug:W,redirectPath:Y}=U;let Q=n==null?void 0:n.id,J=o,K=p;W&&(Q=(await new ne(b,t).getPublicTenantInfo(W)).id,J=W);const X=await I.login({username:z,password:_,appId:t,tenantId:Q}),oe=W&&W!==o;if(oe&&(K=new de({tenantSlug:J,baseUrl:s})),K.setTokens({accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}),X.user){K.setUser(X.user),f(X.user);try{await E()}catch(ge){console.warn("Failed to load complete user data after login:",ge)}}return oe&&J&&J!==o&&l(J,{tokens:{accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn},redirectPath:Y}),X},O=async U=>{const{email:z,phoneNumber:_,name:W,password:Y,lastName:Q,tenantId:J}=U;if(!z&&!_)throw new Error("Either email or phoneNumber is required");if(!W||!Y)throw new Error("Name and password are required");const K=J??(n==null?void 0:n.id);return await I.signup({email:z,phoneNumber:_,name:W,password:Y,tenantId:K,lastName:Q,appId:t})},N=async U=>{const{email:z,phoneNumber:_,name:W,password:Y,tenantName:Q,lastName:J}=U;if(!z&&!_)throw new Error("Either email or phoneNumber is required");if(!W||!Y||!Q)throw new Error("Name, password, and tenantName are required");return await I.signupTenantAdmin({email:z,phoneNumber:_,name:W,password:Y,tenantName:Q,appId:t,lastName:J})},G=async U=>{const{currentPassword:z,newPassword:_}=U,W=await p.getAuthHeaders();await I.changePassword({currentPassword:z,newPassword:_},W)},ce=async U=>{const{email:z,tenantId:_}=U,W=_??(n==null?void 0:n.id);if(!W)throw new Error("tenantId is required for password reset");await I.requestPasswordReset({email:z,tenantId:W})},De=async U=>{const{token:z,newPassword:_}=U;await I.confirmPasswordReset({token:z,newPassword:_})},$e=async U=>{const{email:z,frontendUrl:_,name:W,lastName:Y,tenantId:Q}=U,J=Q??(n==null?void 0:n.id);if(!J)throw new Error("tenantId is required for magic link authentication");return await I.sendMagicLink({email:z,tenantId:J,frontendUrl:_,name:W,lastName:Y,appId:t})},He=async U=>{const{token:z,email:_,tenantSlug:W}=U;let Y=n==null?void 0:n.id,Q=o,J=p;W&&(Y=(await new ne(b,t).getPublicTenantInfo(W)).id,Q=W);const K=await I.verifyMagicLink({token:z,email:_,appId:t,tenantId:Y}),X=W&&W!==o;if(X&&(J=new de({tenantSlug:Q,baseUrl:s})),J.setTokens({accessToken:K.accessToken,refreshToken:K.refreshToken,expiresIn:K.expiresIn}),K.user){J.setUser(K.user),f(K.user);try{await E()}catch(oe){console.warn("Failed to load complete user data after magic link login:",oe)}}return X&&Q&&Q!==o&&l(Q,{tokens:{accessToken:K.accessToken,refreshToken:K.refreshToken,expiresIn:K.expiresIn}}),K},Ne=async()=>{const U=p.getTokens();if(!(U!=null&&U.refreshToken))throw new Error("No refresh token available");const z=await I.refreshToken({refreshToken:U.refreshToken});p.setTokens({accessToken:z.accessToken,refreshToken:z.refreshToken||U.refreshToken,expiresIn:z.expiresIn})},Ue=()=>{p.clearSession(),f(null),R(null)},Be=U=>{p.setTokens(U)},qe=()=>p.hasValidSession(),ze=()=>{p.clearSession(),f(null),R(null)},Oe=async()=>{if(t)try{S(!0);const{roles:U}=await P.getRolesByApp(t);w(U)}catch(U){console.error("Failed to fetch roles:",U)}finally{S(!1)}},We=async()=>{await Oe()},he=U=>{if(!M||M.length===0)return!1;if(typeof U=="string")return M.includes(U);const z=`${U.resource}.${U.action}`;return M.includes(z)};return{isAuthenticated:A,sessionManager:p,authenticatedHttpService:b,login:H,signup:O,signupTenantAdmin:N,sendMagicLink:$e,verifyMagicLink:He,changePassword:G,requestPasswordReset:ce,confirmPasswordReset:De,refreshToken:Ne,logout:Ue,setTokens:Be,hasValidSession:qe,clearSession:ze,currentUser:x,isUserLoading:k,userError:C,loadUserData:E,refreshUser:D,isAuthInitializing:!q,isAuthReady:q,userRole:c,userPermissions:M,availableRoles:g,rolesLoading:m,hasPermission:he,hasAnyPermission:U=>U.some(z=>he(z)),hasAllPermissions:U=>U.every(z=>he(z)),getUserPermissionStrings:()=>M||[],refreshRoles:We}},[A,p,b,I,v,P,t,n,o,l,g,x,k,C,q,c,M,T,h]);a.useEffect(()=>{!i.initialRoles&&t&&(async()=>{try{S(!0);const D=new Z(s),H=new fe(D),{roles:O}=await H.getRolesByApp(t);w(O)}catch(D){console.error("Failed to fetch roles:",D)}finally{S(!1)}})()},[t,s,i.initialRoles]);const[y,V]=a.useState(!1);return a.useEffect(()=>{y||(V(!0),j.current.urlTokens&&(console.log("[AuthProvider] EFFECT: Cleaning up URL after sync token processing"),et(),$(!0),console.log("[AuthProvider] EFFECT: Loading user data (blocking isAuthReady)..."),d.loadUserData().catch(E=>{console.error("[AuthProvider] Failed to load user data:",E)}).finally(()=>{console.log("[AuthProvider] EFFECT: User data loaded, releasing isAuthReady"),$(!1)})))},[d,y]),a.useEffect(()=>{const E=p.getUser();E&&p.hasValidSession()&&f(E)},[p]),a.useEffect(()=>{y&&(j.current.urlTokens||!x&&!k&&p.hasValidSession()&&(console.log("[AuthProvider] Auto-loading user data..."),d.loadUserData().catch(()=>{})))},[x,k,d,p,y]),a.useEffect(()=>{if(!p.hasValidSession()||!x)return;const E=setInterval(()=>{d.loadUserData().catch(()=>{})},h);return()=>clearInterval(E)},[p,x,d,h]),r.jsx(we.Provider,{value:d,children:e})}function te(){const i=a.useContext(we);if(!i)throw new Error("useAuth must be used within an AuthProvider");return i}function Pe(){return a.useContext(we)}class Me{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/feature-flags/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:s})).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 s=new URLSearchParams;s.append("tenantId",e),s.append("appId",t);const n=`/tenant-feature-flags${s.toString()?`?${s.toString()}`:""}`;return(await this.httpService.get(n,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,s){if(!e||!t||!s)throw new Error("Flag Key, Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",t),n.append("appId",s);const o=`/tenant-feature-flags/${e}${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(o,{headers:{"X-Tenant-ID":t}})).data}}const xe=a.createContext(null);function it({config:i={},children:e}){const t=Ae(),s=le(),n=(t==null?void 0:t.baseUrl)??"",o=(t==null?void 0:t.appId)??"",l=(s==null?void 0:s.tenant)??null,[g,w]=a.useState([]),[m,S]=a.useState(!1),[x,f]=a.useState(null),[k,F]=a.useState(!1),C=a.useMemo(()=>{const u=new Z(n);return new Me(u)},[n]),R=async()=>{if(!(l!=null&&l.id)){w([]);return}S(!0),f(null);try{const u=await C.getTenantFeatureFlags(l.id,o);w(u)}catch(u){const j=u instanceof Error?u.message:"Failed to fetch feature flags";f(j),i.onError&&i.onError(u instanceof Error?u:new Error(j))}finally{S(!1)}};a.useEffect(()=>{if(!n||!o)return;R().finally(()=>F(!0));const u=i.refreshInterval||5*60*1e3,j=setInterval(R,u);return()=>clearInterval(j)},[l==null?void 0:l.id,n,o,i.refreshInterval]);const T=a.useMemo(()=>{const u=q=>{const b=g.find(I=>I.key===q);return(b==null?void 0:b.value)===!0},j=q=>g.find(b=>b.key===q),B=q=>{const b=g.find(I=>I.key===q);return b?b.value?"enabled":"disabled":"not_found"},$=async()=>{await R()},p=!!(n&&o)&&(k||!(l!=null&&l.id));return{featureFlags:g,loading:m,error:x,isReady:p,isEnabled:u,getFlag:j,getFlagState:B,refresh:$}},[g,m,x,n,o,l==null?void 0:l.id,k]);return r.jsx(xe.Provider,{value:T,children:e})}function Re(){const i=a.useContext(xe);if(!i)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return i}function Fe(){return a.useContext(xe)}class Le{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:s})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:s})).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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:s})).data}}const be=a.createContext(void 0);function ot({config:i={},children:e}){const t=Ae(),s=le(),n=(t==null?void 0:t.baseUrl)??"",o=(s==null?void 0:s.tenant)??null,[l,g]=a.useState(null),[w,m]=a.useState(!1),[S,x]=a.useState(null),[f,k]=a.useState(!1),F=a.useMemo(()=>{const T=new Z(n);return new Le(T)},[n]),C=async()=>{if(!(o!=null&&o.id)){g(null);return}m(!0),x(null);try{const T=await F.getTenantSubscriptionFeatures(o.id);g(T)}catch(T){const u=T instanceof Error?T.message:"Failed to fetch subscription";x(u),i.onError&&i.onError(T instanceof Error?T:new Error(u))}finally{m(!1)}};a.useEffect(()=>{if(!n||(C().finally(()=>k(!0)),!i.refreshInterval))return;const T=i.refreshInterval||10*60*1e3,u=setInterval(C,T);return()=>clearInterval(u)},[o==null?void 0:o.id,n,i.refreshInterval]);const R=a.useMemo(()=>{const T=(l==null?void 0:l.features)||[],u=b=>{const I=T.find(v=>v.key===b);return I?I.type==="BOOLEAN"||I.type==="boolean"?I.value===!0:!!I.value:!1},j=b=>T.find(I=>I.key===b),B=(b,I)=>{const v=T.find(P=>P.key===b);return v?v.value:I},$=b=>!l||!l.isActive?!1:b.includes(l.planId),p=async()=>{await C()},q=!!n&&(f||!(o!=null&&o.id));return{subscription:l,features:T,loading:w,error:S,isReady:q,isFeatureEnabled:u,getFeature:j,getFeatureValue:B,hasAllowedPlan:$,refresh:p}},[l,w,S,n,o==null?void 0:o.id,f]);return r.jsx(be.Provider,{value:R,children:e})}function Ie(){const i=a.useContext(be);if(i===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return i}function Ee(){return a.useContext(be)??null}var ee=(i=>(i.SUPERUSER="SUPERUSER",i.TENANT_ADMIN="TENANT_ADMIN",i.USER="USER",i))(ee||{});const Se=()=>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"})]}),ve=({userType:i,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&&i?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:i})]})]}):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(", ")})]})]})]}),at=(i,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[i]>=t[e]};function lt({children:i,fallback:e,minUserType:t,requiredPermissions:s,requireAllPermissions:n=!1}){const{hasValidSession:o,sessionManager:l,hasPermission:g,hasAnyPermission:w,hasAllPermissions:m}=te();if(!o())return r.jsx(r.Fragment,{children:e||r.jsx(Se,{})});const S=l.getUser();if(!S)return r.jsx(r.Fragment,{children:e||r.jsx(Se,{})});if(t&&!at(S.userType,t))return r.jsx(ve,{userType:S.userType,minUserType:t});if(s&&s.length>0&&!(n?m(s):w(s))){const f=s.filter(k=>!g(k)).map(k=>typeof k=="string"?k:k.name);return r.jsx(ve,{missingPermissions:f})}return r.jsx(r.Fragment,{children:i})}const ct=({redirectPath:i})=>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 ",i,"..."]})]})}),ke=({userType:i,minUserType: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&&i?r.jsxs(r.Fragment,{children:[r.jsxs("p",{style:{color:"#6b7280",marginBottom:"1rem"},children:["This page requires ",r.jsx("strong",{children:e})," access level or higher."]}),r.jsxs("p",{style:{color:"#9ca3af",fontSize:"0.875rem"},children:["Your current access level: ",r.jsx("strong",{children:i})]})]}):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(", ")})]})]})]})}),dt=(i,e)=>{const t={[ee.USER]:1,[ee.TENANT_ADMIN]:2,[ee.SUPERUSER]:3};return t[i]>=t[e]};function ut({children:i,redirectTo:e="/login",minUserType:t,requiredPermissions:s,requireAllPermissions:n=!1,fallback:o}){const{hasValidSession:l,sessionManager:g,hasPermission:w,hasAnyPermission:m,hasAllPermissions:S}=te(),x=re.useLocation();if(!l())return o?r.jsx(r.Fragment,{children:o}):r.jsxs(r.Fragment,{children:[r.jsx(ct,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:x.pathname},replace:!0})]});const f=g.getUser();if(!f)return r.jsx(re.Navigate,{to:e,state:{from:x.pathname},replace:!0});if(t&&!dt(f.userType,t))return r.jsx(ke,{userType:f.userType,minUserType:t});if(s&&s.length>0&&!(n?S(s):m(s))){const F=s.filter(C=>!w(C)).map(C=>typeof C=="string"?C:C.name);return r.jsx(ke,{missingPermissions:F})}return r.jsx(r.Fragment,{children:i})}const ht=({redirectPath:i})=>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 ",i,"..."]})]})});function gt({children:i,redirectTo:e="/",fallback:t}){const{tenant:s,isLoading:n,error:o}=se(),l=re.useLocation();return n||o?null:s?r.jsx(r.Fragment,{children:i}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(ht,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const pt=({redirectPath:i})=>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 ",i,"..."]})]})});function ft({children:i,redirectTo:e="/dashboard",fallback:t}){const{tenant:s,isLoading:n,error:o}=se(),l=re.useLocation();return n||o?null:s?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(pt,{redirectPath:e}),r.jsx(re.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:i})}const mt=()=>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 yt({children:i,fallback:e=r.jsx(mt,{}),allowedPlans:t,requiredFeature:s}){const{subscription:n,hasAllowedPlan:o,isFeatureEnabled:l,loading:g}=Ie();return g?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):n?n.isActive?t&&t.length>0&&!o(t)?r.jsx(r.Fragment,{children:e}):s&&!l(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:i}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const wt=({flagName:i})=>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 "',i,'" is disabled']})]});function xt({name:i,children:e,fallback:t}){const{isEnabled:s,loading:n}=Re();return n?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):s(i)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(wt,{flagName:i})})}const bt=()=>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"})]}),St=()=>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"})]}),vt={showPassword:r.jsx(bt,{}),hidePassword:r.jsx(St,{})},kt={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..."},At={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"}};function Tt({copy:i={},styles:e={},icons:t={},onSuccess:s,onError:n,onForgotPassword:o,onSignupClick:l,onMagicLinkClick:g,showForgotPassword:w=!0,showSignupLink:m=!0,showMagicLinkOption:S=!0,className:x}){const[f,k]=a.useState(""),[F,C]=a.useState(""),[R,T]=a.useState(!1),[u,j]=a.useState(!1),[B,$]=a.useState(""),[p,q]=a.useState({}),{login:b}=te(),{tenant:I}=se(),v={...kt,...i},P={...At,...e},L={...vt,...t},c=()=>{const d={};return f.trim()||(d.username=!0),F.trim()||(d.password=!0),q(d),Object.keys(d).length===0},M=async d=>{if(d.preventDefault(),!!c()){if(!(I!=null&&I.id)){$("Tenant not found");return}j(!0),$("");try{const y=await b({username:f,password:F});s==null||s(y)}catch(y){const V=y.message||v.errorMessage;$(V),n==null||n(V)}finally{j(!1)}}},A=d=>({...P.input,...p[d]?P.inputError:{}}),h=()=>({...P.button,...u?P.buttonLoading:{},...!f||!F||u?P.buttonDisabled:{}});return r.jsxs("div",{className:x,style:P.container,children:[r.jsx("h2",{style:P.title,children:v.title}),r.jsxs("form",{onSubmit:M,style:P.form,children:[r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:v.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:f,onChange:d=>{k(d.target.value),p.username&&q(y=>({...y,username:!1}))},placeholder:v.usernamePlaceholder,style:A("username"),disabled:u})]}),r.jsxs("div",{style:P.fieldGroup,children:[r.jsx("label",{style:P.label,children:v.passwordLabel}),r.jsxs("div",{style:P.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:R?"text":"password",value:F,onChange:d=>{C(d.target.value),p.password&&q(y=>({...y,password:!1}))},placeholder:v.passwordPlaceholder,style:{...A("password"),paddingRight:"2.5rem"},disabled:u}),r.jsx("button",{type:"button",onClick:()=>T(!R),style:P.passwordToggle,disabled:u,"aria-label":R?"Hide password":"Show password",children:R?L.hidePassword:L.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!f||!F||u,style:h(),children:u?v.loadingText:v.submitButton}),B&&r.jsx("div",{style:P.errorText,children:B})]}),(w||m||S)&&r.jsxs("div",{style:P.linkContainer,children:[S&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[v.magicLinkText," "]}),r.jsx("a",{onClick:g,style:P.link,children:v.magicLinkLink})]}),S&&(w||m)&&r.jsx("div",{style:P.divider,children:"•"}),w&&r.jsx("a",{onClick:o,style:P.link,children:v.forgotPasswordLink}),w&&m&&r.jsx("div",{style:P.divider,children:"•"}),m&&r.jsxs("div",{children:[r.jsxs("span",{style:P.divider,children:[v.signupText," "]}),r.jsx("a",{onClick:l,style:P.link,children:v.signupLink})]})]})]})}const jt={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"},Pt={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"}};function Mt({copy:i={},styles:e={},signupType:t="user",onSuccess:s,onError:n,onLoginClick:o,onMagicLinkClick:l,showLoginLink:g=!0,showMagicLinkOption:w=!0,className:m}){const[S,x]=a.useState(""),[f,k]=a.useState(""),[F,C]=a.useState(""),[R,T]=a.useState(""),[u,j]=a.useState(""),[B,$]=a.useState(""),[p,q]=a.useState(""),[b,I]=a.useState(!1),[v,P]=a.useState(""),[L,c]=a.useState({}),{signup:M,signupTenantAdmin:A}=te(),{tenant:h}=se(),d={...jt,...i},y={...Pt,...e},V=()=>{const N={};return S.trim()||(N.name=!0),!F.trim()&&!R.trim()&&(N.email=!0,N.phoneNumber=!0),u.trim()||(N.password=!0),B.trim()||(N.confirmPassword=!0),t==="tenant"&&!p.trim()&&(N.tenantName=!0),c(N),Object.keys(N).length===0},E=async N=>{if(N.preventDefault(),!!V()){if(u!==B){P(d.passwordMismatchError),c({confirmPassword:!0});return}if(t==="user"&&!(h!=null&&h.id)){P("Tenant not found");return}I(!0),P("");try{let G;t==="tenant"?G=await A({email:F||void 0,phoneNumber:R||void 0,name:S,password:u,tenantName:p,lastName:f||void 0}):G=await M({email:F||void 0,phoneNumber:R||void 0,name:S,password:u,tenantId:h.id,lastName:f||void 0}),s==null||s(G)}catch(G){const ce=G.message||d.errorMessage;P(ce),n==null||n(ce)}finally{I(!1)}}},D=N=>({...y.input,...L[N]?y.inputError:{}}),H=()=>({...y.button,...b?y.buttonLoading:{},...!S||!F&&!R||!u||!B||b||t==="tenant"&&!p?y.buttonDisabled:{}}),O=S&&(F||R)&&u&&B&&(t==="user"||p);return r.jsxs("div",{className:m,style:y.container,children:[r.jsx("h2",{style:y.title,children:d.title}),r.jsxs("form",{onSubmit:E,style:y.form,children:[r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:S,onChange:N=>{x(N.target.value),L.name&&c(G=>({...G,name:!1}))},placeholder:d.namePlaceholder,style:D("name"),disabled:b})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:f,onChange:N=>k(N.target.value),placeholder:d.lastNamePlaceholder,style:y.input,disabled:b})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:F,onChange:N=>{C(N.target.value),L.email&&c(G=>({...G,email:!1,phoneNumber:!1}))},placeholder:d.emailPlaceholder,style:D("email"),disabled:b})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:R,onChange:N=>{T(N.target.value),L.phoneNumber&&c(G=>({...G,email:!1,phoneNumber:!1}))},placeholder:d.phoneNumberPlaceholder,style:D("phoneNumber"),disabled:b})]}),r.jsx("div",{style:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"},children:"At least one contact method (email or phone) is required"}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:u,onChange:N=>{j(N.target.value),L.password&&c(G=>({...G,password:!1}))},placeholder:d.passwordPlaceholder,style:D("password"),disabled:b})]}),r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:B,onChange:N=>{$(N.target.value),L.confirmPassword&&c(G=>({...G,confirmPassword:!1})),v===d.passwordMismatchError&&P("")},placeholder:d.confirmPasswordPlaceholder,style:D("confirmPassword"),disabled:b})]}),t==="tenant"&&r.jsxs("div",{style:y.fieldGroup,children:[r.jsx("label",{style:y.label,children:d.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:p,onChange:N=>{q(N.target.value),L.tenantName&&c(G=>({...G,tenantName:!1}))},placeholder:d.tenantNamePlaceholder,style:D("tenantName"),disabled:b})]}),r.jsx("button",{type:"submit",disabled:!O||b,style:H(),children:b?d.loadingText:d.submitButton}),v&&r.jsx("div",{style:y.errorText,children:v})]}),(g||w)&&r.jsxs("div",{style:y.linkContainer,children:[w&&r.jsxs("div",{children:[r.jsxs("span",{style:y.divider,children:[d.magicLinkText," "]}),r.jsx("a",{onClick:l,style:y.link,children:d.magicLinkLink})]}),w&&g&&r.jsx("div",{style:y.divider,children:"•"}),g&&r.jsxs("div",{children:[r.jsxs("span",{style:y.divider,children:[d.loginText," "]}),r.jsx("a",{onClick:o,style:y.link,children:d.loginLink})]})]})]})}const Rt={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...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you."},Ft={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"}};function Lt({copy:i={},styles:e={},onSuccess:t,onError:s,onLoginClick:n,onSignupClick:o,showTraditionalLinks:l=!0,className:g,verifyToken:w,frontendUrl:m}){const[S,x]=a.useState(""),[f,k]=a.useState(""),[F,C]=a.useState(""),[R,T]=a.useState(!1),[u,j]=a.useState(!1),[B,$]=a.useState(""),[p,q]=a.useState(""),[b,I]=a.useState({}),[v,P]=a.useState(!1),{sendMagicLink:L,verifyMagicLink:c}=te(),{tenant:M}=se(),A={...Rt,...i},h={...Ft,...e};a.useEffect(()=>{w&&d(w)},[w]);const d=async H=>{if(!M||!S){$("Missing tenant or email");return}j(!0),$("");try{const O=await c({token:H,email:S});t==null||t(O)}catch(O){const N=O.message||"Failed to verify magic link";$(N),s==null||s(N)}finally{j(!1)}},y=()=>{const H={};return S.trim()||(H.email=!0),v&&!f.trim()&&(H.name=!0),I(H),Object.keys(H).length===0},V=async H=>{if(H.preventDefault(),!!y()){if(!(M!=null&&M.id)){$("Tenant not found");return}T(!0),$(""),q("");try{const O=m||(typeof window<"u"?window.location.origin:""),N=await L({email:S,tenantId:M.id,frontendUrl:O,name:v?f:void 0,lastName:v?F:void 0});q(A.successMessage),t==null||t(N)}catch(O){const N=O.message||A.errorMessage;$(N),s==null||s(N)}finally{T(!1)}}},E=H=>({...h.input,...b[H]?h.inputError:{}}),D=()=>({...h.button,...R||u?h.buttonLoading:{},...!S||R||u?h.buttonDisabled:{}});return u?r.jsxs("div",{className:g,style:h.container,children:[r.jsx("h2",{style:h.title,children:A.verifyingText}),r.jsx("div",{style:{textAlign:"center",padding:"2rem"},children:r.jsx("div",{style:{fontSize:"1rem",color:"#6b7280"},children:"Please wait while we verify your magic link..."})})]}):r.jsxs("div",{className:g,style:h.container,children:[r.jsx("h2",{style:h.title,children:A.title}),r.jsx("p",{style:h.description,children:A.description}),r.jsxs("form",{onSubmit:V,style:h.form,children:[r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:A.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:S,onChange:H=>{x(H.target.value),b.email&&I(O=>({...O,email:!1}))},placeholder:A.emailPlaceholder,style:E("email"),disabled:R||u})]}),!v&&r.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:r.jsx("button",{type:"button",onClick:()=>P(!0),style:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"New user? Add your name"})}),v&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:A.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:f,onChange:H=>{k(H.target.value),b.name&&I(O=>({...O,name:!1}))},placeholder:A.namePlaceholder,style:E("name"),disabled:R||u})]}),r.jsxs("div",{style:h.fieldGroup,children:[r.jsx("label",{style:h.label,children:A.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:F,onChange:H=>C(H.target.value),placeholder:A.lastNamePlaceholder,style:h.input,disabled:R||u})]}),r.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:r.jsx("button",{type:"button",onClick:()=>{P(!1),k(""),C("")},style:{background:"none",border:"none",color:"#6b7280",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"Existing user? Hide name fields"})})]}),r.jsx("button",{type:"submit",disabled:!S||R||u,style:D(),children:R?A.loadingText:A.submitButton}),B&&r.jsx("div",{style:h.errorText,children:B}),p&&r.jsx("div",{style:h.successText,children:p})]}),l&&r.jsxs("div",{style:h.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:h.divider,children:[A.loginText," "]}),r.jsx("a",{onClick:n,style:h.link,children:A.loginLink})]}),r.jsx("div",{style:h.divider,children:"•"}),r.jsxs("div",{children:[r.jsxs("span",{style:h.divider,children:[A.signupText," "]}),r.jsx("a",{onClick:o,style:h.link,children:A.signupLink})]})]})]})}const It={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"},Ce={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"}},Et=()=>r.jsx("div",{style:Ce.spinner}),Ct=()=>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"})]}),Dt=()=>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"})]}),$t={loading:r.jsx(Et,{}),success:r.jsx(Ct,{}),error:r.jsx(Dt,{})};function Ht({copy:i={},styles:e={},icons:t={},onSuccess:s,onError:n,onRetry:o,onBackToLogin:l,className:g,token:w,email:m,appId:S,tenantSlug:x,autoRedirectDelay:f=3e3}){const[k,F]=a.useState("verifying"),[C,R]=a.useState(""),{verifyMagicLink:T}=te(),u={...It,...i},j={...Ce,...e},B={...$t,...t},$=()=>{if(typeof window>"u")return{};const v=new URLSearchParams(window.location.search);return{token:w||v.get("token")||"",email:m||v.get("email")||"",appId:S||v.get("appId")||"",tenantSlug:x||v.get("tenantSlug")||void 0}},p=async()=>{F("verifying"),R("");try{const v=$();if(!v.token||!v.email)throw new Error("Missing required parameters: token or email");const P=await T({token:v.token,email:v.email,tenantSlug:v.tenantSlug});F("success"),s==null||s(P),f>0&&setTimeout(()=>{F("redirecting")},f)}catch(v){const P=v.message||u.errorMessage;R(P),F("error"),n==null||n(P)}},q=()=>{o==null||o(),p()},b=()=>{l==null||l()};a.useEffect(()=>{p()},[]);const I=()=>{switch(k){case"verifying":return r.jsxs("div",{style:j.message,children:[B.loading,u.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[B.success,r.jsx("div",{style:j.successMessage,children:u.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[B.loading,r.jsx("div",{style:j.message,children:u.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[B.error,r.jsx("div",{style:j.errorMessage,children:C||u.errorMessage}),r.jsxs("div",{style:j.buttonContainer,children:[r.jsx("button",{onClick:q,style:j.retryButton,onMouseOver:v=>{v.currentTarget.style.backgroundColor="#2563eb"},onMouseOut:v=>{v.currentTarget.style.backgroundColor="#3b82f6"},children:u.retryButton}),r.jsx("button",{onClick:b,style:j.backButton,onMouseOver:v=>{v.currentTarget.style.backgroundColor="#e5e7eb"},onMouseOut:v=>{v.currentTarget.style.backgroundColor="#f3f4f6"},children:u.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:j.container,className:g,children:[r.jsx("style",{children:`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("react/jsx-runtime"),a=require("react"),te=require("react-router-dom");class Z{constructor(e,t=1e4){this.baseUrl=e.replace(/\/$/,""),this.timeout=t}setSessionManager(e){this.sessionManager=e}getBaseUrl(){return this.baseUrl}async request(e,t,s,n){return this.executeRequest(e,t,s,n,!1)}async executeRequest(e,t,s,n,i=!1){const l=`${this.baseUrl}${t.startsWith("/")?t:`/${t}`}`,m=(n==null?void 0:n.timeout)||this.timeout;let y={"Content-Type":"application/json",...n==null?void 0:n.headers};if(!(n!=null&&n.skipAuth)&&this.sessionManager)try{const b=await this.sessionManager.getAuthHeaders();y={...y,...b}}catch(b){console.warn("Failed to inject auth headers:",b)}const x=new AbortController,g=setTimeout(()=>x.abort(),m);try{const b=await fetch(l,{method:e,headers:y,body:s?JSON.stringify(s):void 0,signal:x.signal});if(clearTimeout(g),b.status===401&&!(n!=null&&n.skipRetry)&&!i&&this.sessionManager)try{const v=this.sessionManager.getTokens();if(v!=null&&v.refreshToken)return await this.sessionManager.getAuthHeaders(),this.executeRequest(e,t,s,n,!0)}catch{throw new Error(`HTTP ${b.status}: ${b.statusText}`)}if(!b.ok)throw new Error(`HTTP ${b.status}: ${b.statusText}`);const f=b.headers.get("content-type");return!f||!f.includes("application/json")?{}:await b.json()}catch(b){throw clearTimeout(g),b instanceof Error&&b.name==="AbortError"?new Error(`Request timeout after ${m}ms`):b}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,s){return this.request("POST",e,t,s)}async put(e,t,s){return this.request("PUT",e,t,s)}async delete(e,t){return this.request("DELETE",e,void 0,t)}}class me{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/apps/${s.toString()?`?${s.toString()}`:""}`,i=await this.httpService.get(n,{headers:t});return{apps:i.data,meta:i.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}`,t,{headers:s})).data}async getPublicAppInfo(e){return(await this.httpService.get(`/apps/${e}/public`)).data}async setDefaultSubscriptionPlan(e,t){const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/default-subscription-plan`,{planId:t},{headers:s})).data}async updateSettingsSchema(e,t,s){const n=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/apps/${e}/settings-schema`,{schema:t,defaultSettings:s},{headers:n})).data}async exportConfig(e){const t=await this.sessionManager.getAuthHeaders();return(await this.httpService.get(`/apps/${e}/export-config`,{headers:t})).data}}const we=a.createContext(null);function Xe({config:o,children:e}){const t=a.useMemo(()=>{var f,v,P;return{enabled:((f=o.cache)==null?void 0:f.enabled)??!0,ttl:((v=o.cache)==null?void 0:v.ttl)??3e5,storageKey:((P=o.cache)==null?void 0:P.storageKey)??`app_cache_${o.appId}`}},[o.cache,o.appId]),[s,n]=a.useState(()=>{if(!t.enabled)return null;try{const f=localStorage.getItem(t.storageKey);if(!f)return null;const v=JSON.parse(f);return Date.now()-v.timestamp<t.ttl&&v.appId===o.appId?v.data:(localStorage.removeItem(t.storageKey),null)}catch{return null}}),[i,l]=a.useState(!s),[m,y]=a.useState(null),x=a.useMemo(()=>{const f=()=>{g()};return{appId:o.appId,baseUrl:o.baseUrl,appInfo:s,isAppLoading:i,appError:m,retryApp:f}},[o,s,i,m]),g=a.useCallback(async(f=!1)=>{if(!(!f&&t.enabled&&s))try{l(!0),y(null);const v=new Z(o.baseUrl),F=await new me(v,{}).getPublicAppInfo(o.appId);if(n(F),t.enabled)try{const M={data:F,timestamp:Date.now(),appId:o.appId};localStorage.setItem(t.storageKey,JSON.stringify(M))}catch(M){console.warn("Failed to cache app info:",M)}}catch(v){const P=v instanceof Error?v:new Error("Failed to load app information");y(P),n(null)}finally{l(!1)}},[o.baseUrl,o.appId,t,s]),b=a.useCallback(async()=>{if(!(!t.enabled||!s))try{const f=localStorage.getItem(t.storageKey);if(!f)return;const v=JSON.parse(f);if(Date.now()-v.timestamp>t.ttl*.5){const F=new Z(o.baseUrl),k=await new me(F,{}).getPublicAppInfo(o.appId);n(k);const h={data:k,timestamp:Date.now(),appId:o.appId};localStorage.setItem(t.storageKey,JSON.stringify(h))}}catch(f){console.warn("Background app refresh failed:",f)}},[o,t,s]);return a.useEffect(()=>{s?b():g()},[]),r.jsx(we.Provider,{value:x,children:e})}function oe(){const o=a.useContext(we);if(!o)throw new Error("useApp must be used within an AppProvider");return o}function Ie(){return a.useContext(we)}const Ze=oe;class ue{constructor(e={}){this.refreshPromise=null,this.refreshQueue=[],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.baseUrl=e.baseUrl||"",this.tokenStorage=e.tokenStorage||this.createTokenStorage(this.storageKey)}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{}}}}setTokens(e){const t={...e,expiresAt:e.expiresAt||(e.expiresIn?Date.now()+e.expiresIn*1e3:void 0)};this.tokenStorage.set(t)}getTokens(){const{accessToken:e,refreshToken:t,expiresAt:s,expiresIn:n,tokenType:i}=this.tokenStorage.get()||{};return e?{accessToken:e,refreshToken:t,expiresAt:s,expiresIn:n,tokenType:i}:null}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}async getAuthHeaders(){const e=this.getTokens();if(!(e!=null&&e.accessToken))return{};if(!this.shouldRefreshToken(e))return{Authorization:`Bearer ${e.accessToken}`};if(!e.refreshToken)return this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{};if(this.refreshPromise)return new Promise((t,s)=>{this.refreshQueue.push({resolve:t,reject:s})});this.refreshPromise=this.performTokenRefresh(e.refreshToken);try{await this.refreshPromise;const t=this.getTokens(),s=t!=null&&t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{};return this.refreshQueue.forEach(({resolve:n})=>n(s)),this.refreshQueue=[],s}catch(t){const s=t instanceof Error?t:new Error("Token refresh failed");return this.refreshQueue.forEach(({reject:n})=>n(s)),this.refreshQueue=[],this.clearSession(),this.onRefreshFailed&&this.onRefreshFailed(),{}}finally{this.refreshPromise=null}}async performTokenRefresh(e){if(!this.baseUrl)throw new Error("Base URL not configured for token refresh");const t=`${this.baseUrl}/auth/refresh`,s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);const n=await s.json();this.setTokens({accessToken:n.accessToken,refreshToken:n.refreshToken||e,expiresIn:n.expiresIn})}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.clearTokens(),this.clearUser()}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 s=t[1],n=atob(s.replace(/-/g,"+").replace(/_/g,"/"));return JSON.parse(n)}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)}}class Re{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 ye{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/roles/${e}`,t,{headers:s})).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 s=new URLSearchParams;t!=null&&t.page&&s.append("page",t.page.toString()),t!=null&&t.limit&&s.append("limit",t.limit.toString()),t!=null&&t.sortBy&&s.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&s.append("sortOrder",t.sortOrder);const n=`/roles/app/${e}${s.toString()?`?${s.toString()}`:""}`,i=await this.httpService.get(n);return{roles:i.data,meta:i.meta}}async assignRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/assign`,t,{headers:s})}async revokeRole(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();await this.httpService.post(`/roles/${e}/revoke`,t,{headers:s})}async getUserRoles(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders(),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/user/${e}${n.toString()?`?${n.toString()}`:""}`,l=await this.httpService.get(i,{headers:s});return{roles:l.data,meta:l.meta}}}class Le{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/users/${s.toString()?`?${s.toString()}`:""}`,i=await this.httpService.get(n,{headers:t});return{users:i.data,meta:i.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/users/${e}`,t,{headers:s})).data}async deleteUser(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/users/${e}`,{headers:t})}}class ne{constructor(e,t,s){this.httpService=e,this.appId=t,this.sessionManager=s}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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/tenants/${s.toString()?`?${s.toString()}`:""}`,i=await this.httpService.get(n,{headers:t});return{tenants:i.data,meta:i.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}`,t,{headers:s})).data}async adminUpdateTenant(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/admin-update`,t,{headers:s})).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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/tenants/${e}/settings`,t,{headers:s})).data}}function et(o,e){if(o==="localhost"||o.startsWith("127.")||o.startsWith("192.168."))return null;if(e){const n=e.toLowerCase(),i=o.toLowerCase();if(i===n||i===`www.${n}`)return null;if(i.endsWith(`.${n}`)){const l=i.slice(0,-(n.length+1));return l==="www"?null:l}return null}const s=o.split(".");return s.length>=3&&s[0]!=="www"?s[0]:null}function tt(o,e="tenant",t){const n=new URLSearchParams(o).get(e);return n?(t&&t.setItem("tenant",n),n):t?t.getItem("tenant"):null}function rt(o,e,t){const{tenantMode:s,baseDomain:n,selectorParam:i}=o;return s==="subdomain"?et(e.hostname,n):s==="selector"?tt(e.search,i,t):null}function st(o,e,t){if(t)return`${o}.${t}`;const s=e.split(".");return s.length===2?`${o}.${e}`:s.length>=3?(s[0]=o,s.join(".")):null}const he="_auth";function nt(o){const e=JSON.stringify(o);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ot(o){try{let e=o.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";const t=atob(e),s=JSON.parse(t);return typeof s.accessToken=="string"&&typeof s.refreshToken=="string"&&typeof s.expiresIn=="number"?s:null}catch{return null}}function it(){if(typeof window>"u")return console.log("[CrossDomainAuth] SSR environment, skipping URL token extraction"),null;const e=new URLSearchParams(window.location.search).get(he);if(console.log("[CrossDomainAuth] extractAuthTokensFromUrl called",{hasAuthParam:!!e,searchParams:window.location.search,encodedLength:e==null?void 0:e.length}),!e)return null;const t=ot(e);return console.log("[CrossDomainAuth] Token decode result:",{success:!!t,hasAccessToken:!!(t!=null&&t.accessToken),hasRefreshToken:!!(t!=null&&t.refreshToken),expiresIn:t==null?void 0:t.expiresIn}),t}function at(){if(typeof window>"u")return;const o=new URL(window.location.href);o.searchParams.delete(he),console.log("[CrossDomainAuth] Clearing auth tokens from URL",{oldUrl:window.location.href,newUrl:o.toString()}),window.history.replaceState({},"",o.toString())}const xe=a.createContext(null);function lt({config:o,children:e}){const{baseUrl:t,appInfo:s,appId:n}=oe(),i=a.useCallback(()=>typeof window>"u"?null:rt({tenantMode:o.tenantMode||"selector",baseDomain:o.baseDomain,selectorParam:o.selectorParam},{hostname:window.location.hostname,search:window.location.search},window.localStorage),[o.tenantMode,o.baseDomain,o.selectorParam]),[l,m]=a.useState(()=>i()),y=a.useMemo(()=>{var c,D,j;return{enabled:((c=o.cache)==null?void 0:c.enabled)??!0,ttl:((D=o.cache)==null?void 0:D.ttl)??5*60*1e3,storageKey:((j=o.cache)==null?void 0:j.storageKey)??`tenant_cache_${l||"default"}`}},[o.cache,l]),[x,g]=a.useState(()=>{if(o.initialTenant)return o.initialTenant;if(!y.enabled||!l)return null;try{const c=localStorage.getItem(y.storageKey);if(!c)return null;const D=JSON.parse(c);return Date.now()-D.timestamp<y.ttl&&D.tenantSlug===l?D.data:(localStorage.removeItem(y.storageKey),null)}catch{return null}}),[b,f]=a.useState(!x&&!o.initialTenant),[v,P]=a.useState(null),[F,M]=a.useState(null),[k,h]=a.useState(!1),[C,T]=a.useState(null);a.useEffect(()=>{const c=i();m(c)},[i]);const R=(s==null?void 0:s.settingsSchema)||null,$=a.useCallback(async(c,D=!1)=>{if(!(!D&&y.enabled&&x&&x.domain===c))try{f(!0),P(null);const j=new Z(t),u=await new ne(j,n).getPublicTenantInfo(c);if(g(u),y.enabled)try{const w={data:u,timestamp:Date.now(),tenantSlug:c};localStorage.setItem(y.storageKey,JSON.stringify(w))}catch(w){console.warn("Failed to cache tenant info:",w)}}catch(j){const p=j instanceof Error?j:new Error("Failed to load tenant information");P(p),g(null)}finally{f(!1)}},[t,n,y,x]),E=a.useCallback(async()=>{if(!(!y.enabled||!x||!l))try{const c=localStorage.getItem(y.storageKey);if(!c)return;const D=JSON.parse(c);if(Date.now()-D.timestamp>y.ttl*.5){const p=new Z(t),w=await new ne(p,n).getPublicTenantInfo(l);g(w);const V={data:w,timestamp:Date.now(),tenantSlug:l};localStorage.setItem(y.storageKey,JSON.stringify(V))}}catch(c){console.warn("Background tenant refresh failed:",c)}},[t,n,y,x,l]),A=a.useCallback(async()=>{if(x!=null&&x.id)try{h(!0),T(null);const c=new Z(t),j=await new ne(c,x.appId).getTenantSettings(x.id);M(j)}catch(c){const D=c instanceof Error?c:new Error("Failed to load tenant settings");T(D),M(null)}finally{h(!1)}},[t,x]),q=a.useCallback(()=>{A()},[A]),d=a.useCallback(c=>{if(!R)return{isValid:!0,errors:[]};const D=[];try{return R.properties&&Object.entries(R.properties).forEach(([j,p])=>{var w;const u=c[j];if((w=R.required)!=null&&w.includes(j)&&u==null){D.push(`Field '${j}' is required`);return}if(u!=null){if(p.type){const V=p.type,_=typeof u;V==="string"&&_!=="string"?D.push(`Field '${j}' must be a string`):(V==="number"||V==="integer")&&_!=="number"?D.push(`Field '${j}' must be a number`):V==="boolean"&&_!=="boolean"?D.push(`Field '${j}' must be a boolean`):V==="array"&&!Array.isArray(u)&&D.push(`Field '${j}' must be an array`)}p.minLength!==void 0&&typeof u=="string"&&u.length<p.minLength&&D.push(`Field '${j}' must be at least ${p.minLength} characters long`),p.maxLength!==void 0&&typeof u=="string"&&u.length>p.maxLength&&D.push(`Field '${j}' must be no more than ${p.maxLength} characters long`),p.minimum!==void 0&&typeof u=="number"&&u<p.minimum&&D.push(`Field '${j}' must be at least ${p.minimum}`),p.maximum!==void 0&&typeof u=="number"&&u>p.maximum&&D.push(`Field '${j}' must be no more than ${p.maximum}`),p.pattern&&typeof u=="string"&&(new RegExp(p.pattern).test(u)||D.push(`Field '${j}' does not match the required pattern`)),p.enum&&!p.enum.includes(u)&&D.push(`Field '${j}' must be one of: ${p.enum.join(", ")}`)}}),{isValid:D.length===0,errors:D}}catch{return{isValid:!1,errors:["Invalid settings schema or validation error"]}}},[R]);a.useEffect(()=>{!o.initialTenant&&l?x?E():$(l):!o.initialTenant&&!l&&(g(null),P(null),f(!1))},[o.initialTenant,l,x,$,E]),a.useEffect(()=>{x!=null&&x.id?A():(M(null),T(null),h(!1))},[x==null?void 0:x.id,A]);const I=a.useCallback((c,D)=>{const{mode:j="reload",tokens:p,redirectPath:u}=D||{},w=o.tenantMode||"selector";if(localStorage.setItem("tenant",c),w==="subdomain"){const V=window.location.hostname,_=st(c,V,o.baseDomain);if(!_){console.warn("[TenantProvider] Cannot switch subdomain, invalid hostname:",V);return}const H=u||window.location.pathname,U=new URL(`${window.location.protocol}//${_}${H}`);new URLSearchParams(window.location.search).forEach((S,G)=>{G!==he&&U.searchParams.set(G,S)}),p&&U.searchParams.set(he,nt(p)),window.location.href=U.toString()}else if(w==="selector"){const V=u||window.location.pathname,_=new URLSearchParams(window.location.search);if(_.set(o.selectorParam||"tenant",c),j==="reload"){const H=`${V}?${_.toString()}${window.location.hash}`;window.location.href=H}else{const H=`${V}?${_.toString()}${window.location.hash}`;window.history.pushState({},"",H),m(c),$(c)}}},[o.tenantMode,o.selectorParam,o.baseDomain,$]),L=a.useMemo(()=>({tenant:x,tenantSlug:l,isTenantLoading:b,tenantError:v,retryTenant:()=>{l&&$(l)},settings:F,settingsSchema:R,isSettingsLoading:k,settingsError:C,refreshSettings:q,switchTenant:I,validateSettings:d}),[x,l,b,v,F,R,k,C,q,I,d]);return r.jsx(xe.Provider,{value:L,children:e})}function le(){const o=a.useContext(xe);if(!o)throw new Error("useTenant must be used within a TenantProvider");return o}function ce(){return a.useContext(xe)}const ct=le;function dt(){const{settings:o,settingsSchema:e,isSettingsLoading:t,settingsError:s,validateSettings:n}=le();return{settings:o,settingsSchema:e,isLoading:t,error:s,validateSettings:n}}function re(){const{tenant:o,tenantSlug:e,isTenantLoading:t,tenantError:s,retryTenant:n}=le();return{tenant:o,tenantSlug:e,isLoading:t,error:s,retry:n}}const be=a.createContext(null);function ut({config:o={},children:e}){const{appId:t,baseUrl:s}=oe(),{tenant:n,tenantSlug:i,switchTenant:l}=le(),[m,y]=a.useState(o.initialRoles||[]),[x,g]=a.useState(!o.initialRoles),[b,f]=a.useState(null),[v,P]=a.useState(!1),[F,M]=a.useState(null),[k,h]=a.useState(0),[C,T]=a.useState(()=>{try{const S=localStorage.getItem("userTenants");return S?JSON.parse(S):[]}catch{return[]}}),[R,$]=a.useState(!1),E=a.useRef({done:!1,urlTokens:null});E.current.done||(E.current.done=!0,E.current.urlTokens=it(),E.current.urlTokens&&console.log("[AuthProvider] SYNC: URL tokens found, will block isAuthReady until user loaded"));const[A,q]=a.useState(()=>{const S=E.current.urlTokens!==null;return console.log("[AuthProvider] SYNC: isLoadingAfterUrlTokens initial:",S),S}),d=a.useMemo(()=>{const S=new ue({tenantSlug:i,onRefreshFailed:o.onRefreshFailed,baseUrl:s});return E.current.urlTokens&&(console.log("[AuthProvider] SYNC: Saving URL tokens to session manager"),S.setTokens({accessToken:E.current.urlTokens.accessToken,refreshToken:E.current.urlTokens.refreshToken,expiresIn:E.current.urlTokens.expiresIn}),console.log("[AuthProvider] SYNC: Session valid:",S.hasValidSession())),S},[i,s,o.onRefreshFailed]),I=E.current.done&&!A,L=a.useMemo(()=>{const S=new Z(s);return S.setSessionManager(d),S},[s,d]),c=a.useMemo(()=>new Re(new Z(s)),[s]),D=a.useMemo(()=>new Le(L,d),[L,d]),j=a.useMemo(()=>new ye(new Z(s)),[s]),p=a.useMemo(()=>b||d.getUser(),[b,d]),u=a.useMemo(()=>p!=null&&p.roleId&&m.find(S=>S.id===p.roleId)||null,[p,m]),w=a.useMemo(()=>(u==null?void 0:u.permissions)||[],[u]),V=a.useMemo(()=>d.hasValidSession()&&b!==null,[d,b]),_=5*60*1e3,H=a.useMemo(()=>{const S=async(N=!1)=>{try{if(!d.hasValidSession())return;const B=Date.now();if(!N&&B-k<_&&b)return;const O=d.getUserId();if(!O){console.warn("[AuthProvider] No userId available in token or storage");return}P(!0),M(null);const K=await D.getUserById(O);f(K),d.setUser(K),h(Date.now())}catch(B){const J=B instanceof Error?B:new Error("Failed to load user data");M(J),console.error("[AuthProvider] Failed to load user data:",J)}finally{P(!1)}},G=async()=>{await S()},se=async N=>{var Te;const{username:B,password:J,tenantSlug:O,redirectPath:K}=N;let Y=n==null?void 0:n.id,Q=i,X=d;O&&(Y=(await new ne(L,t).getPublicTenantInfo(O)).id,Q=O);const W=await c.login({username:B,password:J,appId:t,tenantId:Y}),ie=O&&O!==i;if(ie&&(X=new ue({tenantSlug:Q,baseUrl:s})),X.setTokens({accessToken:W.accessToken,refreshToken:W.refreshToken,expiresIn:W.expiresIn}),W.user){X.setUser(W.user),f(W.user);try{await S()}catch(de){console.warn("Failed to load complete user data after login:",de)}}if(W.tenants&&W.tenants.length>0){T(W.tenants);try{localStorage.setItem("userTenants",JSON.stringify(W.tenants))}catch{}}const fe=((Te=W.user)==null?void 0:Te.tenantId)!==null;if($(fe),ie&&Q&&Q!==i&&l(Q,{tokens:{accessToken:W.accessToken,refreshToken:W.refreshToken,expiresIn:W.expiresIn},redirectPath:K}),!fe&&W.tenants&&W.tenants.length>0){const de=o.autoSwitchSingleTenant!==!1;if(W.tenants.length===1&&de){const Ae=W.tenants[0];l(Ae.subdomain,{tokens:{accessToken:W.accessToken,refreshToken:W.refreshToken,expiresIn:W.expiresIn},redirectPath:K})}else W.tenants.length>1&&o.onTenantSelectionRequired&&o.onTenantSelectionRequired(W.tenants)}return W},ge=async N=>{const{email:B,phoneNumber:J,name:O,password:K,lastName:Y,tenantId:Q}=N;if(!B&&!J)throw new Error("Either email or phoneNumber is required");if(!O||!K)throw new Error("Name and password are required");const X=Q??(n==null?void 0:n.id);return await c.signup({email:B,phoneNumber:J,name:O,password:K,tenantId:X,lastName:Y,appId:t})},Ue=async N=>{const{email:B,phoneNumber:J,name:O,password:K,tenantName:Y,lastName:Q}=N;if(!B&&!J)throw new Error("Either email or phoneNumber is required");if(!O||!K||!Y)throw new Error("Name, password, and tenantName are required");return await c.signupTenantAdmin({email:B,phoneNumber:J,name:O,password:K,tenantName:Y,appId:t,lastName:Q})},Be=async N=>{const{currentPassword:B,newPassword:J}=N,O=await d.getAuthHeaders();await c.changePassword({currentPassword:B,newPassword:J},O)},qe=async N=>{const{email:B,tenantId:J}=N,O=J??(n==null?void 0:n.id);if(!O)throw new Error("tenantId is required for password reset");await c.requestPasswordReset({email:B,tenantId:O})},Oe=async N=>{const{token:B,newPassword:J}=N;await c.confirmPasswordReset({token:B,newPassword:J})},ze=async N=>{const{email:B,frontendUrl:J,name:O,lastName:K,tenantId:Y}=N,Q=Y??(n==null?void 0:n.id);if(!Q)throw new Error("tenantId is required for magic link authentication");return await c.sendMagicLink({email:B,tenantId:Q,frontendUrl:J,name:O,lastName:K,appId:t})},We=async N=>{const{token:B,email:J,tenantSlug:O}=N;let K=n==null?void 0:n.id,Y=i,Q=d;O&&(K=(await new ne(L,t).getPublicTenantInfo(O)).id,Y=O);const X=await c.verifyMagicLink({token:B,email:J,appId:t,tenantId:K}),W=O&&O!==i;if(W&&(Q=new ue({tenantSlug:Y,baseUrl:s})),Q.setTokens({accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}),X.user){Q.setUser(X.user),f(X.user);try{await S()}catch(ie){console.warn("Failed to load complete user data after magic link login:",ie)}}return W&&Y&&Y!==i&&l(Y,{tokens:{accessToken:X.accessToken,refreshToken:X.refreshToken,expiresIn:X.expiresIn}}),X},Ve=async()=>{const N=d.getTokens();if(!(N!=null&&N.refreshToken))throw new Error("No refresh token available");const B=await c.refreshToken({refreshToken:N.refreshToken});d.setTokens({accessToken:B.accessToken,refreshToken:B.refreshToken||N.refreshToken,expiresIn:B.expiresIn})},Ge=()=>{d.clearSession(),f(null),M(null),T([]),$(!1);try{localStorage.removeItem("userTenants")}catch{}},_e=N=>{d.setTokens(N)},Je=()=>d.hasValidSession(),Ke=()=>{d.clearSession(),f(null),M(null)},Ye=async()=>{if(t)try{g(!0);const{roles:N}=await j.getRolesByApp(t);y(N)}catch(N){console.error("Failed to fetch roles:",N)}finally{g(!1)}},Qe=async()=>{await Ye()},pe=N=>{if(!w||w.length===0)return!1;if(typeof N=="string")return w.includes(N);const B=`${N.resource}.${N.action}`;return w.includes(B)};return{isAuthenticated:V,sessionManager:d,authenticatedHttpService:L,login:se,signup:ge,signupTenantAdmin:Ue,sendMagicLink:ze,verifyMagicLink:We,changePassword:Be,requestPasswordReset:qe,confirmPasswordReset:Oe,refreshToken:Ve,logout:Ge,setTokens:_e,hasValidSession:Je,clearSession:Ke,currentUser:b,isUserLoading:v,userError:F,loadUserData:S,refreshUser:G,isAuthInitializing:!I,isAuthReady:I,userRole:u,userPermissions:w,availableRoles:m,rolesLoading:x,hasPermission:pe,hasAnyPermission:N=>N.some(B=>pe(B)),hasAllPermissions:N=>N.every(B=>pe(B)),getUserPermissionStrings:()=>w||[],refreshRoles:Qe,userTenants:C,hasTenantContext:R,switchToTenant:async(N,B)=>{const{redirectPath:J}=B||{},O=d.getTokens();if(!(O!=null&&O.refreshToken))throw new Error("No refresh token available for tenant switch");const K=await c.switchTenant({refreshToken:O.refreshToken,tenantId:N});d.setTokens({accessToken:K.accessToken,refreshToken:O.refreshToken,expiresIn:K.expiresIn}),f(K.user),d.setUser(K.user),$(!0);const Y=C.find(Q=>Q.id===N);Y&&l(Y.subdomain,{tokens:{accessToken:K.accessToken,refreshToken:O.refreshToken,expiresIn:K.expiresIn},redirectPath:J})},refreshUserTenants:async()=>{const N=await d.getAuthHeaders(),B=await c.getUserTenants(N);T(B);try{localStorage.setItem("userTenants",JSON.stringify(B))}catch{}return B}}},[V,d,L,c,D,j,t,n,i,l,m,b,v,F,C,R,I,u,w,k,_]);a.useEffect(()=>{!o.initialRoles&&t&&(async()=>{try{g(!0);const G=new Z(s),se=new ye(G),{roles:ge}=await se.getRolesByApp(t);y(ge)}catch(G){console.error("Failed to fetch roles:",G)}finally{g(!1)}})()},[t,s,o.initialRoles]);const[U,z]=a.useState(!1);return a.useEffect(()=>{U||(z(!0),E.current.urlTokens&&(console.log("[AuthProvider] EFFECT: Cleaning up URL after sync token processing"),at(),q(!0),console.log("[AuthProvider] EFFECT: Loading user data (blocking isAuthReady)..."),H.loadUserData().catch(S=>{console.error("[AuthProvider] Failed to load user data:",S)}).finally(()=>{console.log("[AuthProvider] EFFECT: User data loaded, releasing isAuthReady"),q(!1)})))},[H,U]),a.useEffect(()=>{const S=d.getUser();S&&d.hasValidSession()&&f(S)},[d]),a.useEffect(()=>{U&&(E.current.urlTokens||!b&&!v&&d.hasValidSession()&&(console.log("[AuthProvider] Auto-loading user data..."),H.loadUserData().catch(()=>{})))},[b,v,H,d,U]),a.useEffect(()=>{if(!d.hasValidSession()||!b)return;const S=setInterval(()=>{H.loadUserData().catch(()=>{})},_);return()=>clearInterval(S)},[d,b,H,_]),r.jsx(be.Provider,{value:H,children:e})}function ee(){const o=a.useContext(be);if(!o)throw new Error("useAuth must be used within an AuthProvider");return o}function Se(){return a.useContext(be)}class Fe{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/feature-flags/${s.toString()?`?${s.toString()}`:""}`,i=await this.httpService.get(n,{headers:t});return{featureFlags:i.data,meta:i.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/feature-flags/${e}`,t,{headers:s})).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 s=new URLSearchParams;s.append("tenantId",e),s.append("appId",t);const n=`/tenant-feature-flags${s.toString()?`?${s.toString()}`:""}`;return(await this.httpService.get(n,{headers:{"X-Tenant-ID":e}})).data}async getTenantFeatureFlag(e,t,s){if(!e||!t||!s)throw new Error("Flag Key, Tenant ID and App ID are required");const n=new URLSearchParams;n.append("tenantId",t),n.append("appId",s);const i=`/tenant-feature-flags/${e}${n.toString()?`?${n.toString()}`:""}`;return(await this.httpService.get(i,{headers:{"X-Tenant-ID":t}})).data}}const ve=a.createContext(null);function ht({config:o={},children:e}){const t=Ie(),s=ce(),n=(t==null?void 0:t.baseUrl)??"",i=(t==null?void 0:t.appId)??"",l=(s==null?void 0:s.tenant)??null,[m,y]=a.useState([]),[x,g]=a.useState(!1),[b,f]=a.useState(null),[v,P]=a.useState(!1),F=a.useMemo(()=>{const h=new Z(n);return new Fe(h)},[n]),M=async()=>{if(!(l!=null&&l.id)){y([]);return}g(!0),f(null);try{const h=await F.getTenantFeatureFlags(l.id,i);y(h)}catch(h){const C=h instanceof Error?h.message:"Failed to fetch feature flags";f(C),o.onError&&o.onError(h instanceof Error?h:new Error(C))}finally{g(!1)}};a.useEffect(()=>{if(!n||!i)return;M().finally(()=>P(!0));const h=o.refreshInterval||5*60*1e3,C=setInterval(M,h);return()=>clearInterval(C)},[l==null?void 0:l.id,n,i,o.refreshInterval]);const k=a.useMemo(()=>{const h=E=>{const A=m.find(q=>q.key===E);return(A==null?void 0:A.value)===!0},C=E=>m.find(A=>A.key===E),T=E=>{const A=m.find(q=>q.key===E);return A?A.value?"enabled":"disabled":"not_found"},R=async()=>{await M()},$=!!(n&&i)&&(v||!(l!=null&&l.id));return{featureFlags:m,loading:x,error:b,isReady:$,isEnabled:h,getFlag:C,getFlagState:T,refresh:R}},[m,x,b,n,i,l==null?void 0:l.id,v]);return r.jsx(ve.Provider,{value:k,children:e})}function Ee(){const o=a.useContext(ve);if(!o)throw new Error("useFeatureFlags must be used within a FeatureFlagProvider");return o}function Ce(){return a.useContext(ve)}class De{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}`,t,{headers:s})).data}async changeSubscriptionPlan(e,t){if(!this.sessionManager)throw new Error("SessionManager is required for private endpoints");const s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscriptions/${e}/plan`,{planId:t},{headers:s})).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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.post(`/subscriptions/${e}/process-payment`,t,{headers:s})).data}}const ke=a.createContext(void 0);function gt({config:o={},children:e}){const t=Ie(),s=ce(),n=(t==null?void 0:t.baseUrl)??"",i=(s==null?void 0:s.tenant)??null,[l,m]=a.useState(null),[y,x]=a.useState(!1),[g,b]=a.useState(null),[f,v]=a.useState(!1),P=a.useMemo(()=>{const k=new Z(n);return new De(k)},[n]),F=async()=>{if(!(i!=null&&i.id)){m(null);return}x(!0),b(null);try{const k=await P.getTenantSubscriptionFeatures(i.id);m(k)}catch(k){const h=k instanceof Error?k.message:"Failed to fetch subscription";b(h),o.onError&&o.onError(k instanceof Error?k:new Error(h))}finally{x(!1)}};a.useEffect(()=>{if(!n||(F().finally(()=>v(!0)),!o.refreshInterval))return;const k=o.refreshInterval||10*60*1e3,h=setInterval(F,k);return()=>clearInterval(h)},[i==null?void 0:i.id,n,o.refreshInterval]);const M=a.useMemo(()=>{const k=(l==null?void 0:l.features)||[],h=A=>{const q=k.find(d=>d.key===A);return q?q.type==="BOOLEAN"||q.type==="boolean"?q.value===!0:!!q.value:!1},C=A=>k.find(q=>q.key===A),T=(A,q)=>{const d=k.find(I=>I.key===A);return d?d.value:q},R=A=>!l||!l.isActive?!1:A.includes(l.planId),$=async()=>{await F()},E=!!n&&(f||!(i!=null&&i.id));return{subscription:l,features:k,loading:y,error:g,isReady:E,isFeatureEnabled:h,getFeature:C,getFeatureValue:T,hasAllowedPlan:R,refresh:$}},[l,y,g,n,i==null?void 0:i.id,f]);return r.jsx(ke.Provider,{value:M,children:e})}function $e(){const o=a.useContext(ke);if(o===void 0)throw new Error("useSubscription must be used within a SubscriptionProvider");return o}function He(){return a.useContext(ke)??null}var ae=(o=>(o.SUPERUSER="SUPERUSER",o.TENANT_ADMIN="TENANT_ADMIN",o.USER="USER",o))(ae||{});const je=()=>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"})]}),Pe=({userType:o,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&&o?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:o})]})]}):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(", ")})]})]})]}),pt=(o,e)=>{const t={[ae.USER]:1,[ae.TENANT_ADMIN]:2,[ae.SUPERUSER]:3};return t[o]>=t[e]};function ft({children:o,fallback:e,minUserType:t,requiredPermissions:s,requireAllPermissions:n=!1}){const{hasValidSession:i,sessionManager:l,hasPermission:m,hasAnyPermission:y,hasAllPermissions:x}=ee();if(!i())return r.jsx(r.Fragment,{children:e||r.jsx(je,{})});const g=l.getUser();if(!g)return r.jsx(r.Fragment,{children:e||r.jsx(je,{})});if(t&&!pt(g.userType,t))return r.jsx(Pe,{userType:g.userType,minUserType:t});if(s&&s.length>0&&!(n?x(s):y(s))){const f=s.filter(v=>!m(v)).map(v=>typeof v=="string"?v:v.name);return r.jsx(Pe,{missingPermissions:f})}return r.jsx(r.Fragment,{children:o})}const mt=({redirectPath:o})=>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 ",o,"..."]})]})}),Me=({userType:o,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&&o?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:o})]})]}):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(", ")})]})]})]})}),yt=(o,e)=>o===e;function wt({children:o,redirectTo:e="/login",requiredUserType:t,requiredPermissions:s,requireAllPermissions:n=!1,fallback:i}){const{hasValidSession:l,sessionManager:m,hasPermission:y,hasAnyPermission:x,hasAllPermissions:g}=ee(),b=te.useLocation();if(!l())return i?r.jsx(r.Fragment,{children:i}):r.jsxs(r.Fragment,{children:[r.jsx(mt,{redirectPath:e}),r.jsx(te.Navigate,{to:e,state:{from:b.pathname},replace:!0})]});const f=m.getUser();if(!f)return r.jsx(te.Navigate,{to:e,state:{from:b.pathname},replace:!0});if(t&&!yt(f.userType,t))return r.jsx(Me,{userType:f.userType,requiredUserType:t});if(s&&s.length>0&&!(n?g(s):x(s))){const P=s.filter(F=>!y(F)).map(F=>typeof F=="string"?F:F.name);return r.jsx(Me,{missingPermissions:P})}return r.jsx(r.Fragment,{children:o})}const xt=({redirectPath:o})=>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 ",o,"..."]})]})});function bt({children:o,redirectTo:e="/",fallback:t}){const{tenant:s,isLoading:n,error:i}=re(),l=te.useLocation();return n||i?null:s?r.jsx(r.Fragment,{children:o}):t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(xt,{redirectPath:e}),r.jsx(te.Navigate,{to:e,state:{from:l.pathname},replace:!0})]})}const St=({redirectPath:o})=>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 ",o,"..."]})]})});function vt({children:o,redirectTo:e="/dashboard",fallback:t}){const{tenant:s,isLoading:n,error:i}=re(),l=te.useLocation();return n||i?null:s?t?r.jsx(r.Fragment,{children:t}):r.jsxs(r.Fragment,{children:[r.jsx(St,{redirectPath:e}),r.jsx(te.Navigate,{to:e,state:{from:l.pathname},replace:!0})]}):r.jsx(r.Fragment,{children:o})}const kt=()=>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 Tt({children:o,fallback:e=r.jsx(kt,{}),allowedPlans:t,requiredFeature:s}){const{subscription:n,hasAllowedPlan:i,isFeatureEnabled:l,loading:m}=$e();return m?r.jsx("div",{style:{padding:"2rem",textAlign:"center",color:"#6b7280"},children:"Loading subscription..."}):n?n.isActive?t&&t.length>0&&!i(t)?r.jsx(r.Fragment,{children:e}):s&&!l(s)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:o}):r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:e})}const At=({flagName:o})=>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 "',o,'" is disabled']})]});function jt({name:o,children:e,fallback:t}){const{isEnabled:s,loading:n}=Ee();return n?r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",padding:"10px",color:"#6c757d",fontSize:"14px"},children:"Loading feature flags..."}):s(o)?r.jsx(r.Fragment,{children:e}):r.jsx(r.Fragment,{children:t||r.jsx(At,{flagName:o})})}const Pt=()=>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"})]}),Mt=()=>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"})]}),It={showPassword:r.jsx(Pt,{}),hidePassword:r.jsx(Mt,{})},Rt={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..."},Lt={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"}};function Ft({copy:o={},styles:e={},icons:t={},onSuccess:s,onError:n,onForgotPassword:i,onSignupClick:l,onMagicLinkClick:m,showForgotPassword:y=!0,showSignupLink:x=!0,showMagicLinkOption:g=!0,className:b}){const[f,v]=a.useState(""),[P,F]=a.useState(""),[M,k]=a.useState(!1),[h,C]=a.useState(!1),[T,R]=a.useState(""),[$,E]=a.useState({}),{login:A}=ee(),{tenant:q}=re(),d={...Rt,...o},I={...Lt,...e},L={...It,...t},c=()=>{const u={};return f.trim()||(u.username=!0),P.trim()||(u.password=!0),E(u),Object.keys(u).length===0},D=async u=>{if(u.preventDefault(),!!c()){if(!(q!=null&&q.id)){R("Tenant not found");return}C(!0),R("");try{const w=await A({username:f,password:P});s==null||s(w)}catch(w){const V=w.message||d.errorMessage;R(V),n==null||n(V)}finally{C(!1)}}},j=u=>({...I.input,...$[u]?I.inputError:{}}),p=()=>({...I.button,...h?I.buttonLoading:{},...!f||!P||h?I.buttonDisabled:{}});return r.jsxs("div",{className:b,style:I.container,children:[r.jsx("h2",{style:I.title,children:d.title}),r.jsxs("form",{onSubmit:D,style:I.form,children:[r.jsxs("div",{style:I.fieldGroup,children:[r.jsx("label",{style:I.label,children:d.usernameLabel}),r.jsx("input",{id:"username",name:"username",type:"text",value:f,onChange:u=>{v(u.target.value),$.username&&E(w=>({...w,username:!1}))},placeholder:d.usernamePlaceholder,style:j("username"),disabled:h})]}),r.jsxs("div",{style:I.fieldGroup,children:[r.jsx("label",{style:I.label,children:d.passwordLabel}),r.jsxs("div",{style:I.inputContainer,children:[r.jsx("input",{id:"password",name:"password",type:M?"text":"password",value:P,onChange:u=>{F(u.target.value),$.password&&E(w=>({...w,password:!1}))},placeholder:d.passwordPlaceholder,style:{...j("password"),paddingRight:"2.5rem"},disabled:h}),r.jsx("button",{type:"button",onClick:()=>k(!M),style:I.passwordToggle,disabled:h,"aria-label":M?"Hide password":"Show password",children:M?L.hidePassword:L.showPassword})]})]}),r.jsx("button",{type:"submit",disabled:!f||!P||h,style:p(),children:h?d.loadingText:d.submitButton}),T&&r.jsx("div",{style:I.errorText,children:T})]}),(y||x||g)&&r.jsxs("div",{style:I.linkContainer,children:[g&&r.jsxs("div",{children:[r.jsxs("span",{style:I.divider,children:[d.magicLinkText," "]}),r.jsx("a",{onClick:m,style:I.link,children:d.magicLinkLink})]}),g&&(y||x)&&r.jsx("div",{style:I.divider,children:"•"}),y&&r.jsx("a",{onClick:i,style:I.link,children:d.forgotPasswordLink}),y&&x&&r.jsx("div",{style:I.divider,children:"•"}),x&&r.jsxs("div",{children:[r.jsxs("span",{style:I.divider,children:[d.signupText," "]}),r.jsx("a",{onClick:l,style:I.link,children:d.signupLink})]})]})]})}const Et={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"},Ct={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"}};function Dt({copy:o={},styles:e={},signupType:t="user",onSuccess:s,onError:n,onLoginClick:i,onMagicLinkClick:l,showLoginLink:m=!0,showMagicLinkOption:y=!0,className:x}){const[g,b]=a.useState(""),[f,v]=a.useState(""),[P,F]=a.useState(""),[M,k]=a.useState(""),[h,C]=a.useState(""),[T,R]=a.useState(""),[$,E]=a.useState(""),[A,q]=a.useState(!1),[d,I]=a.useState(""),[L,c]=a.useState({}),{signup:D,signupTenantAdmin:j}=ee(),{tenant:p}=re(),u={...Et,...o},w={...Ct,...e},V=()=>{const S={};return g.trim()||(S.name=!0),!P.trim()&&!M.trim()&&(S.email=!0,S.phoneNumber=!0),h.trim()||(S.password=!0),T.trim()||(S.confirmPassword=!0),t==="tenant"&&!$.trim()&&(S.tenantName=!0),c(S),Object.keys(S).length===0},_=async S=>{if(S.preventDefault(),!!V()){if(h!==T){I(u.passwordMismatchError),c({confirmPassword:!0});return}if(t==="user"&&!(p!=null&&p.id)){I("Tenant not found");return}q(!0),I("");try{let G;t==="tenant"?G=await j({email:P||void 0,phoneNumber:M||void 0,name:g,password:h,tenantName:$,lastName:f||void 0}):G=await D({email:P||void 0,phoneNumber:M||void 0,name:g,password:h,tenantId:p.id,lastName:f||void 0}),s==null||s(G)}catch(G){const se=G.message||u.errorMessage;I(se),n==null||n(se)}finally{q(!1)}}},H=S=>({...w.input,...L[S]?w.inputError:{}}),U=()=>({...w.button,...A?w.buttonLoading:{},...!g||!P&&!M||!h||!T||A||t==="tenant"&&!$?w.buttonDisabled:{}}),z=g&&(P||M)&&h&&T&&(t==="user"||$);return r.jsxs("div",{className:x,style:w.container,children:[r.jsx("h2",{style:w.title,children:u.title}),r.jsxs("form",{onSubmit:_,style:w.form,children:[r.jsxs("div",{style:w.fieldGroup,children:[r.jsx("label",{style:w.label,children:u.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:g,onChange:S=>{b(S.target.value),L.name&&c(G=>({...G,name:!1}))},placeholder:u.namePlaceholder,style:H("name"),disabled:A})]}),r.jsxs("div",{style:w.fieldGroup,children:[r.jsx("label",{style:w.label,children:u.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:f,onChange:S=>v(S.target.value),placeholder:u.lastNamePlaceholder,style:w.input,disabled:A})]}),r.jsxs("div",{style:w.fieldGroup,children:[r.jsx("label",{style:w.label,children:u.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:P,onChange:S=>{F(S.target.value),L.email&&c(G=>({...G,email:!1,phoneNumber:!1}))},placeholder:u.emailPlaceholder,style:H("email"),disabled:A})]}),r.jsxs("div",{style:w.fieldGroup,children:[r.jsx("label",{style:w.label,children:u.phoneNumberLabel}),r.jsx("input",{id:"phoneNumber",name:"phoneNumber",type:"tel",value:M,onChange:S=>{k(S.target.value),L.phoneNumber&&c(G=>({...G,email:!1,phoneNumber:!1}))},placeholder:u.phoneNumberPlaceholder,style:H("phoneNumber"),disabled:A})]}),r.jsx("div",{style:{fontSize:"0.875rem",color:"#6b7280",textAlign:"center",margin:"0.5rem 0"},children:"At least one contact method (email or phone) is required"}),r.jsxs("div",{style:w.fieldGroup,children:[r.jsx("label",{style:w.label,children:u.passwordLabel}),r.jsx("input",{id:"password",name:"password",type:"password",value:h,onChange:S=>{C(S.target.value),L.password&&c(G=>({...G,password:!1}))},placeholder:u.passwordPlaceholder,style:H("password"),disabled:A})]}),r.jsxs("div",{style:w.fieldGroup,children:[r.jsx("label",{style:w.label,children:u.confirmPasswordLabel}),r.jsx("input",{id:"confirmPassword",name:"confirmPassword",type:"password",value:T,onChange:S=>{R(S.target.value),L.confirmPassword&&c(G=>({...G,confirmPassword:!1})),d===u.passwordMismatchError&&I("")},placeholder:u.confirmPasswordPlaceholder,style:H("confirmPassword"),disabled:A})]}),t==="tenant"&&r.jsxs("div",{style:w.fieldGroup,children:[r.jsx("label",{style:w.label,children:u.tenantNameLabel}),r.jsx("input",{id:"tenantName",name:"tenantName",type:"text",value:$,onChange:S=>{E(S.target.value),L.tenantName&&c(G=>({...G,tenantName:!1}))},placeholder:u.tenantNamePlaceholder,style:H("tenantName"),disabled:A})]}),r.jsx("button",{type:"submit",disabled:!z||A,style:U(),children:A?u.loadingText:u.submitButton}),d&&r.jsx("div",{style:w.errorText,children:d})]}),(m||y)&&r.jsxs("div",{style:w.linkContainer,children:[y&&r.jsxs("div",{children:[r.jsxs("span",{style:w.divider,children:[u.magicLinkText," "]}),r.jsx("a",{onClick:l,style:w.link,children:u.magicLinkLink})]}),y&&m&&r.jsx("div",{style:w.divider,children:"•"}),m&&r.jsxs("div",{children:[r.jsxs("span",{style:w.divider,children:[u.loginText," "]}),r.jsx("a",{onClick:i,style:w.link,children:u.loginLink})]})]})]})}const $t={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...",description:"Enter your email to receive a magic link. If you don't have an account, we'll create one for you."},Ht={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"}};function Nt({copy:o={},styles:e={},onSuccess:t,onError:s,onLoginClick:n,onSignupClick:i,showTraditionalLinks:l=!0,className:m,verifyToken:y,frontendUrl:x}){const[g,b]=a.useState(""),[f,v]=a.useState(""),[P,F]=a.useState(""),[M,k]=a.useState(!1),[h,C]=a.useState(!1),[T,R]=a.useState(""),[$,E]=a.useState(""),[A,q]=a.useState({}),[d,I]=a.useState(!1),{sendMagicLink:L,verifyMagicLink:c}=ee(),{tenant:D}=re(),j={...$t,...o},p={...Ht,...e};a.useEffect(()=>{y&&u(y)},[y]);const u=async U=>{if(!D||!g){R("Missing tenant or email");return}C(!0),R("");try{const z=await c({token:U,email:g});t==null||t(z)}catch(z){const S=z.message||"Failed to verify magic link";R(S),s==null||s(S)}finally{C(!1)}},w=()=>{const U={};return g.trim()||(U.email=!0),d&&!f.trim()&&(U.name=!0),q(U),Object.keys(U).length===0},V=async U=>{if(U.preventDefault(),!!w()){if(!(D!=null&&D.id)){R("Tenant not found");return}k(!0),R(""),E("");try{const z=x||(typeof window<"u"?window.location.origin:""),S=await L({email:g,tenantId:D.id,frontendUrl:z,name:d?f:void 0,lastName:d?P:void 0});E(j.successMessage),t==null||t(S)}catch(z){const S=z.message||j.errorMessage;R(S),s==null||s(S)}finally{k(!1)}}},_=U=>({...p.input,...A[U]?p.inputError:{}}),H=()=>({...p.button,...M||h?p.buttonLoading:{},...!g||M||h?p.buttonDisabled:{}});return h?r.jsxs("div",{className:m,style:p.container,children:[r.jsx("h2",{style:p.title,children:j.verifyingText}),r.jsx("div",{style:{textAlign:"center",padding:"2rem"},children:r.jsx("div",{style:{fontSize:"1rem",color:"#6b7280"},children:"Please wait while we verify your magic link..."})})]}):r.jsxs("div",{className:m,style:p.container,children:[r.jsx("h2",{style:p.title,children:j.title}),r.jsx("p",{style:p.description,children:j.description}),r.jsxs("form",{onSubmit:V,style:p.form,children:[r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:j.emailLabel}),r.jsx("input",{id:"email",name:"email",type:"email",value:g,onChange:U=>{b(U.target.value),A.email&&q(z=>({...z,email:!1}))},placeholder:j.emailPlaceholder,style:_("email"),disabled:M||h})]}),!d&&r.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:r.jsx("button",{type:"button",onClick:()=>I(!0),style:{background:"none",border:"none",color:"#3b82f6",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"New user? Add your name"})}),d&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:j.nameLabel}),r.jsx("input",{id:"name",name:"name",type:"text",value:f,onChange:U=>{v(U.target.value),A.name&&q(z=>({...z,name:!1}))},placeholder:j.namePlaceholder,style:_("name"),disabled:M||h})]}),r.jsxs("div",{style:p.fieldGroup,children:[r.jsx("label",{style:p.label,children:j.lastNameLabel}),r.jsx("input",{id:"lastName",name:"lastName",type:"text",value:P,onChange:U=>F(U.target.value),placeholder:j.lastNamePlaceholder,style:p.input,disabled:M||h})]}),r.jsx("div",{style:{textAlign:"center",marginTop:"0.5rem"},children:r.jsx("button",{type:"button",onClick:()=>{I(!1),v(""),F("")},style:{background:"none",border:"none",color:"#6b7280",fontSize:"0.875rem",cursor:"pointer",textDecoration:"underline"},children:"Existing user? Hide name fields"})})]}),r.jsx("button",{type:"submit",disabled:!g||M||h,style:H(),children:M?j.loadingText:j.submitButton}),T&&r.jsx("div",{style:p.errorText,children:T}),$&&r.jsx("div",{style:p.successText,children:$})]}),l&&r.jsxs("div",{style:p.linkContainer,children:[r.jsxs("div",{children:[r.jsxs("span",{style:p.divider,children:[j.loginText," "]}),r.jsx("a",{onClick:n,style:p.link,children:j.loginLink})]}),r.jsx("div",{style:p.divider,children:"•"}),r.jsxs("div",{children:[r.jsxs("span",{style:p.divider,children:[j.signupText," "]}),r.jsx("a",{onClick:i,style:p.link,children:j.signupLink})]})]})]})}const Ut={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"},Ne={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"}},Bt=()=>r.jsx("div",{style:Ne.spinner}),qt=()=>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"})]}),Ot=()=>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"})]}),zt={loading:r.jsx(Bt,{}),success:r.jsx(qt,{}),error:r.jsx(Ot,{})};function Wt({copy:o={},styles:e={},icons:t={},onSuccess:s,onError:n,onRetry:i,onBackToLogin:l,className:m,token:y,email:x,appId:g,tenantSlug:b,autoRedirectDelay:f=3e3}){const[v,P]=a.useState("verifying"),[F,M]=a.useState(""),{verifyMagicLink:k}=ee(),h={...Ut,...o},C={...Ne,...e},T={...zt,...t},R=()=>{if(typeof window>"u")return{};const d=new URLSearchParams(window.location.search);return{token:y||d.get("token")||"",email:x||d.get("email")||"",appId:g||d.get("appId")||"",tenantSlug:b||d.get("tenantSlug")||void 0}},$=async()=>{P("verifying"),M("");try{const d=R();if(!d.token||!d.email)throw new Error("Missing required parameters: token or email");const I=await k({token:d.token,email:d.email,tenantSlug:d.tenantSlug});P("success"),s==null||s(I),f>0&&setTimeout(()=>{P("redirecting")},f)}catch(d){const I=d.message||h.errorMessage;M(I),P("error"),n==null||n(I)}},E=()=>{i==null||i(),$()},A=()=>{l==null||l()};a.useEffect(()=>{$()},[]);const q=()=>{switch(v){case"verifying":return r.jsxs("div",{style:C.message,children:[T.loading,h.verifyingMessage]});case"success":return r.jsxs(r.Fragment,{children:[T.success,r.jsx("div",{style:C.successMessage,children:h.successMessage})]});case"redirecting":return r.jsxs(r.Fragment,{children:[T.loading,r.jsx("div",{style:C.message,children:h.redirectingMessage})]});case"error":return r.jsxs(r.Fragment,{children:[T.error,r.jsx("div",{style:C.errorMessage,children:F||h.errorMessage}),r.jsxs("div",{style:C.buttonContainer,children:[r.jsx("button",{onClick:E,style:C.retryButton,onMouseOver:d=>{d.currentTarget.style.backgroundColor="#2563eb"},onMouseOut:d=>{d.currentTarget.style.backgroundColor="#3b82f6"},children:h.retryButton}),r.jsx("button",{onClick:A,style:C.backButton,onMouseOver:d=>{d.currentTarget.style.backgroundColor="#e5e7eb"},onMouseOut:d=>{d.currentTarget.style.backgroundColor="#f3f4f6"},children:h.backToLoginButton})]})]});default:return null}};return r.jsxs("div",{style:C.container,className:m,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:j.title,children:u.title}),I()]})}const Nt={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"},Ut={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"}};function Bt({copy:i={},styles:e={},mode:t="request",token:s="",onSuccess:n,onError:o,onBackToLogin:l,onModeChange:g,className:w}){const[m,S]=a.useState(""),[x,f]=a.useState(s),[k,F]=a.useState(""),[C,R]=a.useState(""),[T,u]=a.useState(!1),[j,B]=a.useState(""),[$,p]=a.useState(""),[q,b]=a.useState({}),{requestPasswordReset:I,confirmPasswordReset:v}=te(),{tenant:P}=se(),L={...Nt,...i},c={...Ut,...e},M=()=>{const D={};return m.trim()||(D.email=!0),b(D),Object.keys(D).length===0},A=()=>{const D={};return x.trim()||(D.token=!0),k.trim()||(D.newPassword=!0),C.trim()||(D.confirmPassword=!0),b(D),Object.keys(D).length===0},h=async D=>{if(D.preventDefault(),!!M()){if(!(P!=null&&P.id)){B("Tenant not found");return}u(!0),B(""),p("");try{await I({email:m,tenantId:P.id}),p(L.successMessage),n==null||n()}catch(H){const O=H.message||L.errorMessage;B(O),o==null||o(O)}finally{u(!1)}}},d=async D=>{if(D.preventDefault(),!!A()){if(k!==C){B(L.passwordMismatchError),b({confirmPassword:!0});return}u(!0),B(""),p("");try{await v({token:x,newPassword:k}),p(L.resetSuccessMessage),n==null||n()}catch(H){const O=H.message||L.errorMessage;B(O),o==null||o(O)}finally{u(!1)}}},y=D=>({...c.input,...q[D]?c.inputError:{}}),V=()=>({...c.button,...T?c.buttonLoading:{}});if(t==="reset"){const D=x&&k&&C;return r.jsxs("div",{className:w,style:c.container,children:[r.jsx("h2",{style:c.title,children:L.resetTitle}),r.jsx("p",{style:c.subtitle,children:L.resetSubtitle}),r.jsxs("form",{onSubmit:d,style:c.form,children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:L.tokenLabel}),r.jsx("input",{type:"text",value:x,onChange:H=>{f(H.target.value),q.token&&b(O=>({...O,token:!1}))},placeholder:L.tokenPlaceholder,style:y("token"),disabled:T})]}),r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:L.newPasswordLabel}),r.jsx("input",{type:"password",value:k,onChange:H=>{F(H.target.value),q.newPassword&&b(O=>({...O,newPassword:!1}))},placeholder:L.newPasswordPlaceholder,style:y("newPassword"),disabled:T})]}),r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:L.confirmPasswordLabel}),r.jsx("input",{type:"password",value:C,onChange:H=>{R(H.target.value),q.confirmPassword&&b(O=>({...O,confirmPassword:!1})),j===L.passwordMismatchError&&B("")},placeholder:L.confirmPasswordPlaceholder,style:y("confirmPassword"),disabled:T})]}),r.jsx("button",{type:"submit",disabled:!D||T,style:{...V(),...!D||T?c.buttonDisabled:{}},children:T?L.resetLoadingText:L.resetSubmitButton}),j&&r.jsx("div",{style:c.errorText,children:j}),$&&r.jsx("div",{style:c.successText,children:$})]}),r.jsxs("div",{style:c.linkContainer,children:[r.jsx("a",{onClick:l,style:c.link,children:L.backToLoginLink}),g&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),r.jsx("a",{onClick:()=>g("request"),style:c.link,children:"Request New Link"})]})]})]})}const E=m;return r.jsxs("div",{className:w,style:c.container,children:[r.jsx("h2",{style:c.title,children:L.title}),r.jsx("p",{style:c.subtitle,children:L.subtitle}),r.jsxs("form",{onSubmit:h,style:c.form,children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:L.emailLabel}),r.jsx("input",{type:"email",value:m,onChange:D=>{S(D.target.value),q.email&&b(H=>({...H,email:!1}))},placeholder:L.emailPlaceholder,style:y("email"),disabled:T})]}),r.jsx("button",{type:"submit",disabled:!E||T,style:{...V(),...!E||T?c.buttonDisabled:{}},children:T?L.loadingText:L.submitButton}),j&&r.jsx("div",{style:c.errorText,children:j}),$&&r.jsx("div",{style:c.successText,children:$})]}),r.jsxs("div",{style:c.linkContainer,children:[r.jsx("a",{onClick:l,style:c.link,children:L.backToLoginLink}),g&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),r.jsx("a",{onClick:()=>g("reset"),style:c.link,children:"I have a token"})]})]})]})}const qt=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),zt=({error:i,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:i.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 Ot({children:i,loadingFallback:e,errorFallback:t,requireTenant:s=!0}){const{isAppLoading:n,appError:o,retryApp:l}=ie(),g=le(),w=Pe(),m=Fe(),S=Ee(),x=(g==null?void 0:g.isTenantLoading)??!1,f=(g==null?void 0:g.tenantError)??null,k=(g==null?void 0:g.tenantSlug)??null,F=(g==null?void 0:g.retryTenant)??(()=>{}),C=(w==null?void 0:w.isAuthReady)??!0,R=(m==null?void 0:m.isReady)??!0,T=(S==null?void 0:S.isReady)??!0,u=s&&g&&k,p=n||u&&x||w&&!C||m&&!R||S&&!T,q=o||(u?f:null),b=()=>{o&&l(),f&&g&&F()};if(p)return r.jsx(r.Fragment,{children:e||r.jsx(qt,{})});if(q){const I=typeof t=="function"?t(q,b):t||r.jsx(zt,{error:q,retry:b});return r.jsx(r.Fragment,{children:I})}return r.jsx(r.Fragment,{children:i})}function Wt(i=!0){const{isAppLoading:e,appError:t,retryApp:s,appInfo:n}=ie(),o=le(),l=Pe(),g=Fe(),w=Ee(),m=(o==null?void 0:o.isTenantLoading)??!1,S=(o==null?void 0:o.tenantError)??null,x=(o==null?void 0:o.tenant)??null,f=(o==null?void 0:o.tenantSlug)??null,k=(o==null?void 0:o.retryTenant)??(()=>{}),F=(l==null?void 0:l.isAuthReady)??!0,C=(g==null?void 0:g.isReady)??!0,R=(w==null?void 0:w.isReady)??!0,T=i&&o&&f,$=e||T&&m||l&&!F||g&&!C||w&&!R,p=t||(T?S:null);return{isLoading:$,error:p,isReady:!$&&!p&&n!==null&&(!T||x!==null),retry:()=>{t&&s(),S&&o&&k()},app:{isLoading:e,error:t,data:n},tenant:o?{isLoading:m,error:S,data:x}:null,auth:l?{isReady:F}:null,featureFlags:g?{isReady:C}:null,subscription:w?{isReady:R}:null}}class Vt{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/permissions/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:s})).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 s=new URLSearchParams;t!=null&&t.page&&s.append("page",t.page.toString()),t!=null&&t.limit&&s.append("limit",t.limit.toString()),t!=null&&t.sortBy&&s.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&s.append("sortOrder",t.sortOrder);const n=`/permissions/apps/${e}${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n);return{permissions:o.data,meta:o.meta}}}class Gt{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder),e!=null&&e.appId&&s.append("appId",e.appId);const n=`/subscription-plans/${s.toString()?`?${s.toString()}`:""}`,o=await this.httpService.get(n,{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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:s})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class _t{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class Kt{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(([s,n])=>{n!=null&&n!==""&&t.append(s,String(n))}),t}}exports.ApiMappers=Kt;exports.AppApiService=pe;exports.AppLoader=Ot;exports.AppProvider=Ve;exports.AuthApiService=Te;exports.AuthProvider=nt;exports.FeatureFlag=xt;exports.FeatureFlagApiService=Me;exports.FeatureFlagProvider=it;exports.HealthApiService=_t;exports.HttpService=Z;exports.LandingRoute=ft;exports.LoginForm=Tt;exports.MagicLinkForm=Lt;exports.MagicLinkVerify=Ht;exports.PasswordRecoveryForm=Bt;exports.PermissionApiService=Vt;exports.Protected=lt;exports.ProtectedRoute=ut;exports.RoleApiService=fe;exports.SessionManager=de;exports.SignupForm=Mt;exports.SubscriptionApiService=Le;exports.SubscriptionGuard=yt;exports.SubscriptionPlanApiService=Gt;exports.SubscriptionProvider=ot;exports.TenantApiService=ne;exports.TenantProvider=tt;exports.TenantRoute=gt;exports.UserApiService=je;exports.UserType=ee;exports.useApi=Ge;exports.useApp=ie;exports.useAppLoaderState=Wt;exports.useAuth=te;exports.useFeatureFlags=Re;exports.useSettings=st;exports.useSubscription=Ie;exports.useTenant=ae;exports.useTenantInfo=se;exports.useTenantOptional=le;exports.useTenantSettings=rt;
|
|
6
|
+
`}),r.jsx("h1",{style:C.title,children:h.title}),q()]})}const Vt={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"},Gt={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"}};function _t({copy:o={},styles:e={},mode:t="request",token:s="",onSuccess:n,onError:i,onBackToLogin:l,onModeChange:m,className:y}){const[x,g]=a.useState(""),[b,f]=a.useState(s),[v,P]=a.useState(""),[F,M]=a.useState(""),[k,h]=a.useState(!1),[C,T]=a.useState(""),[R,$]=a.useState(""),[E,A]=a.useState({}),{requestPasswordReset:q,confirmPasswordReset:d}=ee(),{tenant:I}=re(),L={...Vt,...o},c={...Gt,...e},D=()=>{const H={};return x.trim()||(H.email=!0),A(H),Object.keys(H).length===0},j=()=>{const H={};return b.trim()||(H.token=!0),v.trim()||(H.newPassword=!0),F.trim()||(H.confirmPassword=!0),A(H),Object.keys(H).length===0},p=async H=>{if(H.preventDefault(),!!D()){if(!(I!=null&&I.id)){T("Tenant not found");return}h(!0),T(""),$("");try{await q({email:x,tenantId:I.id}),$(L.successMessage),n==null||n()}catch(U){const z=U.message||L.errorMessage;T(z),i==null||i(z)}finally{h(!1)}}},u=async H=>{if(H.preventDefault(),!!j()){if(v!==F){T(L.passwordMismatchError),A({confirmPassword:!0});return}h(!0),T(""),$("");try{await d({token:b,newPassword:v}),$(L.resetSuccessMessage),n==null||n()}catch(U){const z=U.message||L.errorMessage;T(z),i==null||i(z)}finally{h(!1)}}},w=H=>({...c.input,...E[H]?c.inputError:{}}),V=()=>({...c.button,...k?c.buttonLoading:{}});if(t==="reset"){const H=b&&v&&F;return r.jsxs("div",{className:y,style:c.container,children:[r.jsx("h2",{style:c.title,children:L.resetTitle}),r.jsx("p",{style:c.subtitle,children:L.resetSubtitle}),r.jsxs("form",{onSubmit:u,style:c.form,children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:L.tokenLabel}),r.jsx("input",{type:"text",value:b,onChange:U=>{f(U.target.value),E.token&&A(z=>({...z,token:!1}))},placeholder:L.tokenPlaceholder,style:w("token"),disabled:k})]}),r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:L.newPasswordLabel}),r.jsx("input",{type:"password",value:v,onChange:U=>{P(U.target.value),E.newPassword&&A(z=>({...z,newPassword:!1}))},placeholder:L.newPasswordPlaceholder,style:w("newPassword"),disabled:k})]}),r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:L.confirmPasswordLabel}),r.jsx("input",{type:"password",value:F,onChange:U=>{M(U.target.value),E.confirmPassword&&A(z=>({...z,confirmPassword:!1})),C===L.passwordMismatchError&&T("")},placeholder:L.confirmPasswordPlaceholder,style:w("confirmPassword"),disabled:k})]}),r.jsx("button",{type:"submit",disabled:!H||k,style:{...V(),...!H||k?c.buttonDisabled:{}},children:k?L.resetLoadingText:L.resetSubmitButton}),C&&r.jsx("div",{style:c.errorText,children:C}),R&&r.jsx("div",{style:c.successText,children:R})]}),r.jsxs("div",{style:c.linkContainer,children:[r.jsx("a",{onClick:l,style:c.link,children:L.backToLoginLink}),m&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),r.jsx("a",{onClick:()=>m("request"),style:c.link,children:"Request New Link"})]})]})]})}const _=x;return r.jsxs("div",{className:y,style:c.container,children:[r.jsx("h2",{style:c.title,children:L.title}),r.jsx("p",{style:c.subtitle,children:L.subtitle}),r.jsxs("form",{onSubmit:p,style:c.form,children:[r.jsxs("div",{style:c.fieldGroup,children:[r.jsx("label",{style:c.label,children:L.emailLabel}),r.jsx("input",{type:"email",value:x,onChange:H=>{g(H.target.value),E.email&&A(U=>({...U,email:!1}))},placeholder:L.emailPlaceholder,style:w("email"),disabled:k})]}),r.jsx("button",{type:"submit",disabled:!_||k,style:{...V(),...!_||k?c.buttonDisabled:{}},children:k?L.loadingText:L.submitButton}),C&&r.jsx("div",{style:c.errorText,children:C}),R&&r.jsx("div",{style:c.successText,children:R})]}),r.jsxs("div",{style:c.linkContainer,children:[r.jsx("a",{onClick:l,style:c.link,children:L.backToLoginLink}),m&&r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{margin:"0 0.5rem",color:"#6b7280"},children:"•"}),r.jsx("a",{onClick:()=>m("reset"),style:c.link,children:"I have a token"})]})]})]})}const Jt=()=>r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh",fontFamily:"system-ui, sans-serif"},children:r.jsx("div",{children:"Loading..."})}),Kt=({error:o,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:o.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 Yt({children:o,loadingFallback:e,errorFallback:t,requireTenant:s=!0}){const{isAppLoading:n,appError:i,retryApp:l}=oe(),m=ce(),y=Se(),x=Ce(),g=He(),b=(m==null?void 0:m.isTenantLoading)??!1,f=(m==null?void 0:m.tenantError)??null,v=(m==null?void 0:m.tenantSlug)??null,P=(m==null?void 0:m.retryTenant)??(()=>{}),F=(y==null?void 0:y.isAuthReady)??!0,M=(x==null?void 0:x.isReady)??!0,k=(g==null?void 0:g.isReady)??!0,h=s&&m&&v,$=n||h&&b||y&&!F||x&&!M||g&&!k,E=i||(h?f:null),A=()=>{i&&l(),f&&m&&P()};if($)return r.jsx(r.Fragment,{children:e||r.jsx(Jt,{})});if(E){const q=typeof t=="function"?t(E,A):t||r.jsx(Kt,{error:E,retry:A});return r.jsx(r.Fragment,{children:q})}return r.jsx(r.Fragment,{children:o})}function Qt(o=!0){const{isAppLoading:e,appError:t,retryApp:s,appInfo:n}=oe(),i=ce(),l=Se(),m=Ce(),y=He(),x=(i==null?void 0:i.isTenantLoading)??!1,g=(i==null?void 0:i.tenantError)??null,b=(i==null?void 0:i.tenant)??null,f=(i==null?void 0:i.tenantSlug)??null,v=(i==null?void 0:i.retryTenant)??(()=>{}),P=(l==null?void 0:l.isAuthReady)??!0,F=(m==null?void 0:m.isReady)??!0,M=(y==null?void 0:y.isReady)??!0,k=o&&i&&f,R=e||k&&x||l&&!P||m&&!F||y&&!M,$=t||(k?g:null);return{isLoading:R,error:$,isReady:!R&&!$&&n!==null&&(!k||b!==null),retry:()=>{t&&s(),g&&i&&v()},app:{isLoading:e,error:t,data:n},tenant:i?{isLoading:x,error:g,data:b}:null,auth:l?{isReady:P}:null,featureFlags:m?{isReady:F}:null,subscription:y?{isReady:M}:null}}function Xt({tenants:o,currentTenantId:e,onSelect:t,className:s="",dropdownClassName:n="",itemClassName:i="",renderItem:l,placeholder:m="Select tenant",disabled:y=!1,showCurrentTenant:x=!0}){var C;const g=Se(),[b,f]=a.useState(!1),v=a.useRef(null),P=o??(g==null?void 0:g.userTenants)??[],F=e??((C=g==null?void 0:g.currentUser)==null?void 0:C.tenantId)??null,M=async T=>{f(!1),t?t(T):g!=null&&g.switchToTenant&&await g.switchToTenant(T)};a.useEffect(()=>{const T=R=>{v.current&&!v.current.contains(R.target)&&f(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[]);const k=P.find(T=>T.id===F);if(P.length===0)return null;if(P.length===1&&x)return r.jsx("div",{className:s,children:r.jsx("span",{children:P[0].name})});const h=(T,R)=>r.jsxs("span",{style:{fontWeight:R?"bold":"normal"},children:[T.name,T.role&&r.jsxs("span",{style:{opacity:.7,marginLeft:8},children:["(",T.role,")"]})]});return r.jsxs("div",{ref:v,className:s,style:{position:"relative"},children:[r.jsxs("button",{type:"button",onClick:()=>!y&&f(!b),disabled:y,style:{cursor:y?"not-allowed":"pointer",opacity:y?.6:1},children:[k?k.name:m,r.jsx("span",{style:{marginLeft:8},children:b?"▲":"▼"})]}),b&&r.jsx("div",{className:n,style:{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"},children:P.map(T=>{const R=T.id===F;return r.jsx("div",{className:i,onClick:()=>M(T.id),style:{padding:"8px 12px",cursor:"pointer",backgroundColor:R?"#f0f0f0":"transparent"},onMouseEnter:$=>{R||($.target.style.backgroundColor="#f5f5f5")},onMouseLeave:$=>{R||($.target.style.backgroundColor="transparent")},children:l?l(T,R):h(T,R)},T.id)})})]})}class Zt{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder);const n=`/permissions/${s.toString()?`?${s.toString()}`:""}`,i=await this.httpService.get(n,{headers:t});return{permissions:i.data,meta:i.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/permissions/${e}`,t,{headers:s})).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 s=new URLSearchParams;t!=null&&t.page&&s.append("page",t.page.toString()),t!=null&&t.limit&&s.append("limit",t.limit.toString()),t!=null&&t.sortBy&&s.append("sortBy",t.sortBy),t!=null&&t.sortOrder&&s.append("sortOrder",t.sortOrder);const n=`/permissions/apps/${e}${s.toString()?`?${s.toString()}`:""}`,i=await this.httpService.get(n);return{permissions:i.data,meta:i.meta}}}class er{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(),s=new URLSearchParams;e!=null&&e.page&&s.append("page",e.page.toString()),e!=null&&e.limit&&s.append("limit",e.limit.toString()),e!=null&&e.sortBy&&s.append("sortBy",e.sortBy),e!=null&&e.sortOrder&&s.append("sortOrder",e.sortOrder),e!=null&&e.appId&&s.append("appId",e.appId);const n=`/subscription-plans/${s.toString()?`?${s.toString()}`:""}`,i=await this.httpService.get(n,{headers:t});return{plans:i.data,meta:i.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 s=await this.sessionManager.getAuthHeaders();return(await this.httpService.put(`/subscription-plans/${e}`,t,{headers:s})).data}async deleteSubscriptionPlan(e){const t=await this.sessionManager.getAuthHeaders();await this.httpService.delete(`/subscription-plans/${e}`,{headers:t})}}class tr{constructor(e){this.httpService=e}async checkHealth(){return await this.httpService.get("/health")}}class rr{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(([s,n])=>{n!=null&&n!==""&&t.append(s,String(n))}),t}}exports.ApiMappers=rr;exports.AppApiService=me;exports.AppLoader=Yt;exports.AppProvider=Xe;exports.AuthApiService=Re;exports.AuthProvider=ut;exports.FeatureFlag=jt;exports.FeatureFlagApiService=Fe;exports.FeatureFlagProvider=ht;exports.HealthApiService=tr;exports.HttpService=Z;exports.LandingRoute=vt;exports.LoginForm=Ft;exports.MagicLinkForm=Nt;exports.MagicLinkVerify=Wt;exports.PasswordRecoveryForm=_t;exports.PermissionApiService=Zt;exports.Protected=ft;exports.ProtectedRoute=wt;exports.RoleApiService=ye;exports.SessionManager=ue;exports.SignupForm=Dt;exports.SubscriptionApiService=De;exports.SubscriptionGuard=Tt;exports.SubscriptionPlanApiService=er;exports.SubscriptionProvider=gt;exports.TenantApiService=ne;exports.TenantProvider=lt;exports.TenantRoute=bt;exports.TenantSelector=Xt;exports.UserApiService=Le;exports.UserType=ae;exports.useApi=Ze;exports.useApp=oe;exports.useAppLoaderState=Qt;exports.useAuth=ee;exports.useFeatureFlags=Ee;exports.useSettings=dt;exports.useSubscription=$e;exports.useTenant=le;exports.useTenantInfo=re;exports.useTenantOptional=ce;exports.useTenantSettings=ct;
|
|
7
7
|
//# sourceMappingURL=index.js.map
|