@buildbase/sdk 0.0.67 → 0.0.68

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.
@@ -1,2 +0,0 @@
1
- "use client";
2
- import{jsxs as e,jsx as t,Fragment as r}from"react/jsx-runtime";import*as n from"react";import s,{Component as a,useMemo as i,useSyncExternalStore as o,createContext as c,useRef as l,useContext as d,useEffect as u,useCallback as p,useState as m,Suspense as h,lazy as g}from"react";import{clsx as f}from"clsx";import{twMerge as y}from"tailwind-merge";import b from"intl-messageformat";import{zodResolver as w}from"@hookform/resolvers/zod";import{Controller as v,FormProvider as k,useFormContext as S,useForm as C}from"react-hook-form";import{Slot as x}from"@radix-ui/react-slot";import{cva as N}from"class-variance-authority";import{Loader2 as P,ChevronDown as I,Check as _,Copy as E,ExternalLink as U,Bot as A,Plus as T,Monitor as O,Smartphone as R,X as W,ShieldCheck as $,Bell as F,MonitorSmartphone as L,ChevronRight as D,Building2 as j,RefreshCcw as M,Search as q,Users as B,Smile as z,Image as V}from"lucide-react";import*as G from"@radix-ui/react-label";import{z as J}from"zod";import*as K from"@radix-ui/react-avatar";import*as H from"@radix-ui/react-dialog";import{Cross2Icon as Y,CheckIcon as Q}from"@radix-ui/react-icons";import*as Z from"@radix-ui/react-radio-group";import*as X from"@radix-ui/react-scroll-area";import*as ee from"@radix-ui/react-separator";import*as te from"@radix-ui/react-accordion";import*as re from"@radix-ui/react-alert-dialog";function ne(...e){return y(f(e))}let se=!0;function ae(e,...t){se&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function ie(e,...t){console.error(e,...t)}function oe(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function ce(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function le(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await ce(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await ce(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class de extends Error{constructor(e,t,r,n){super(e),this.code=t,this.context=r,this.originalError=n,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,de)}}const ue=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(se=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(oe(e))return;const r=e instanceof Error?e:new de("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),n=r instanceof de?r:new de(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&ae(`[SDK Error] ${t.component||"Unknown"}:`,{message:n.message,code:n.code,context:n.context,originalError:n.originalError,stack:n.stack}),this.config.onError)try{this.config.onError(n,t)}catch(e){ie("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(n,t)}catch(e){ie("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(n,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function pe(e,t={}){ue.handleError(e,t)}function me(e,t={}){return!oe(e)&&(ue.handleError(e,t),!0)}function he(e,t,r){return e instanceof Error?e.message:r(t)}function ge(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return pe(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function fe(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){pe(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function ye(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){pe(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}const be="saas-session-id",we="saas-device-id",ve="code",ke="state";function Se(e){fe(be,e)}function Ce(){ye(be)}function xe(){return function(){if("undefined"==typeof window)return null;try{return ge(be)}catch(e){return pe(e,{component:"auth-utils",action:"getSessionId",metadata:{key:be}}),null}}()}function Ne(e){if("undefined"!=typeof window&&e)try{fe(we,e)}catch(e){pe(e,{component:"auth-utils",action:"setDeviceId",metadata:{key:we}})}}function Pe(){const e=xe(),t={};e&&(t["x-session-id"]=e);const r=function(){if("undefined"==typeof window)return null;try{return ge(we)??null}catch(e){return pe(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:we}}),null}}();return r&&(t["x-device-id"]=r),t}function Ie(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(ve)}catch(e){return pe(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:ve}}),null}}function _e(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(ve),e.searchParams.delete(ke),window.history.replaceState({},"",e.toString())}catch(e){pe(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:ve}})}}const Ee=new WeakSet,Ue=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Ae="SDK is not ready (missing serverUrl, version, or orgId)";class Te{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(Ae);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(Ae)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:Pe()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){Ee.has(e)||(Ee.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((r,n)=>{const s=()=>{clearTimeout(a),n(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const a=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,r){const n=(t.method??"GET").toUpperCase(),s=r??e,a=this.buildHeaders(t),i={...t,headers:a},o=Ue.has(n);let c,l;if(this._timeout>0){l=new AbortController;const e=l;c=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const n=new AbortController,s=e=>{n.signal.aborted||n.abort(e.reason)};for(const r of[e,t]){if(r.aborted){s(r);break}r.addEventListener("abort",()=>s(r),{once:!0})}return n.signal}(t.signal,e.signal):e.signal}const d=e=>{if(l?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${n} ${s}`);return this.reportError(e,{method:n,path:s}),e}return e},u=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const r=this._fetch.bind(globalThis),s=await r(e,i);if(this._debug&&console.log(`[BuildBase] ${n} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&o&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await Te.delay(e,i.signal),u(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw d(e);if(o&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await Te.delay(e,i.signal)}catch(e){throw d(e)}return u(t+1)}throw e instanceof Error&&this.reportError(e,{method:n,path:s}),e}};try{return await u(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await le(n,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},r="Request failed"){const n=await this.fetchResponse(e,t);return n.ok||await this.throwResponseError(n,r),this.unwrapResponse(n,r)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw Object.assign(new Error(r),{status:e.status})}apiPath(e,...t){return e.reduce((e,r,n)=>e+r+(n<t.length?encodeURIComponent(String(t[n])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class Oe extends Te{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,r="Failed to initiate authentication",n=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let s=await n(e);if(400===s.status&&(e.trackingConsent||e.trackingIdentity)){const{trackingConsent:t,trackingIdentity:r,...a}=e;s=await n(a)}return s.ok||await this.throwResponseError(s,r),this.unwrapResponse(s,r)}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}async getDeviceToken(e,t){try{const r=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return r?.deviceToken??""}catch{return""}}}class Re extends Te{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}let We=class{constructor(e){this.api=new Re(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},r=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),n=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),s=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),a=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:r,language:n,timezone:s,currency:a}})}};class $e extends Te{constructor(e){super(e)}async list(e){const t=await this.fetchJson("connected-agents",{signal:e},"Failed to load connected agents");return t?.agents??[]}async revoke(e){await this.fetchJson("connected-agents/revoke",{method:"POST",body:JSON.stringify({clientId:e})},"Failed to disconnect agent")}}class Fe extends Te{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,r){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}class Le extends Te{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class De extends Te{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class je extends Te{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class Me extends Te{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class qe extends Te{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}async updateWorkspace(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:r},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to invite member")}async removeUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:r},"Failed to remove user")}async updateUser(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r),signal:n},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:r},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}}),signal:n},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,r){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:r},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create checkout session")}async selectFreePlan(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:r},"Failed to select free plan")}async updateSubscription(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:r},"Failed to update subscription")}async createBillingPortalSession(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:r})}async listInvoices(e,t=10,r,n){const s=new URLSearchParams;return s.append("limit",t.toString()),r&&s.append("starting_after",r),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:n},"Failed to fetch invoices")}async getInvoice(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:r},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record usage")}async recordUsageBatch(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:r},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,r){const n=new URLSearchParams;t?.quotaSlug&&n.append("quotaSlug",t.quotaSlug),t?.from&&n.append("from",t.from),t?.to&&n.append("to",t.to),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),a=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(a,{signal:r},"Failed to fetch usage logs")}async sendNotification(e,t,r,n,s){const a={event:t};return r&&(a.userId=r),n&&(a.data=n),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(a),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,r){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:r},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,r){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:r});if(!n.ok){if(402===n.status){const e=await n.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(n,"Failed to consume credits")}return this.unwrapResponse(n,"Failed to consume credits")}async purchaseCredits(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const r=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t,r){const n=new URLSearchParams;t?.type&&n.append("type",t.type),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),a=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(a,{signal:r},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,r){const n=new URLSearchParams;t?.status&&n.append("status",t.status),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),a=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(a,{signal:r},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,r){const n=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+n,{signal:r},"Failed to fetch expiring credits")}}var Be;function ze(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}!function(e){e.V1="v1"}(Be||(Be={}));const Ve={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted"};class Ge{constructor(){this.callbacks=null,this.listeners=new Map}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){pe(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const r=this.listeners.get(e);if(r)for(const n of[...r])try{n(t)}catch(t){pe(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const r=this.listeners.get(e)??new Set;return r.add(t),this.listeners.set(e,r),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(Ve.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(Ve.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(Ve.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(Ve.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit(Ve.WorkspaceUserAdded,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit(Ve.WorkspaceUserRemoved,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,n){await this.emit(Ve.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:r,newRole:n})}async emitWorkspaceCreated(e){await this.emit(Ve.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(Ve.WorkspaceDeleted,{workspace:e})}}const Je=new Ge;function Ke(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const He=Ke(),Ye=He.subscribe,Qe=He.invalidate,Ze=Ke(),Xe=Ze.subscribe,et=Ze.invalidate,tt=Ke(),rt=tt.subscribe,nt=tt.invalidate,st="bb",at={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},it={Success:"success",Cancel:"cancel",Error:"error"},ot={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function ct(e,t){const r=t??("undefined"!=typeof window?window.location.href:"https://localhost");let n;try{n=new URL(r)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(r)}`)}return n.search="",n.searchParams.set(st,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),n.toString()}function lt(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:ct({action:at.Checkout,status:it.Success,ws:e,screen:ot.Subscription},r),cancelUrl:ct({action:at.Checkout,status:it.Cancel,ws:e,screen:ot.Subscription},r)}}function dt(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:ct({action:at.CreditPurchase,status:it.Success,ws:e,screen:ot.Credits},r),cancelUrl:ct({action:at.CreditPurchase,status:it.Cancel,ws:e,screen:ot.Credits},r)}}function ut(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(st);if(!e)return null;const t=function(e){const t={};if(!e)return t;const r=e.split(",");for(const e of r){const r=e.indexOf(":");if(-1===r)continue;const n=decodeURIComponent(e.slice(0,r)),s=decodeURIComponent(e.slice(r+1));n&&(t[n]=s)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function pt(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(st)&&(e.searchParams.delete(st),window.history.replaceState({},"",e.toString()))}catch{}}const mt="__buildbaseBeforeLeave",ht=globalThis,gt=ht[mt]??(ht[mt]=new Set);function ft(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let r;try{r=new URL(e)}catch{return null}const n="https:"===r.protocol,s="http:"===r.protocol&&("localhost"===r.hostname||"127.0.0.1"===r.hostname||"[::1]"===r.hostname);if(!n&&!s)return null;const{sameOrigin:a,allowedOrigins:i}=t;return a||i?.length?a&&"undefined"!=typeof window&&window.location&&r.origin===window.location.origin||i?.some(e=>e.replace(/\/+$/,"")===r.origin)?e:null:e}function yt(e,t="/",r={}){if("undefined"==typeof window||!window.location)return!1;const n=ft(e,r)??ft(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===gt.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of gt)try{e()}catch{}}(n),window.location.href=n,!0}const bt="saas-auth-intent";function wt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function vt(e){ft(e,{sameOrigin:!0})&&function(e,t){try{fe(e,JSON.stringify(t))}catch(t){pe(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}(bt,{returnUrl:e,createdAt:Date.now()})}function kt(){const e=function(e,t){const r=ge(e);if(!r)return null;try{const n=JSON.parse(r);return t&&!t(n)?(pe(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),ye(e),null):n}catch(t){return pe(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),ye(e),null}}(bt,wt);return ye(bt),e?Date.now()-e.createdAt>6e5?null:ft(e.returnUrl,{sameOrigin:!0}):null}function St(){ye(bt)}const Ct={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},xt={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function Nt(e){return e&&e.trim()?xt[e.trim().toLowerCase()]??"":""}function Pt(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Ct[t]??t.toUpperCase()}const It=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],_t=It.map(e=>({value:e,label:`${e.toUpperCase()} (${Pt(e)})`})),Et=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),Ut=new Set(["bhd","jod","kwd","omr","tnd"]),At=new Map;function Tt(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(Et.has(t))return 0;if(Ut.has(t))return 3;if("isk"===t)return 2;let r=At.get(t);if(void 0===r){try{r=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{r=2}At.set(t,r)}return r}function Ot(e){return""!==(e??"").trim()&&0===Tt(e)}function Rt(e,t){const r=Tt(t);return 0===r?e.toLocaleString("en-US"):(e/10**r).toFixed(r)}function Wt(e,t,r="en-US"){const n=(t??"").trim(),s=Tt(n),a=e/10**s;if(!n)return a.toFixed(s);try{return new Intl.NumberFormat(r,{style:"currency",currency:n.toUpperCase(),minimumFractionDigits:s,maximumFractionDigits:s}).format(a)}catch{return Pt(n)+(0===s?a.toLocaleString("en-US"):a.toFixed(s))}}function $t(e,t){return Pt(t)+Rt(e,t)}const Ft={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};function Lt(e,t,r,n,s){if(null==e||e<0)return null;const a={...Ft,...n},i=null!=t&&t>=1?t:1,o=Pt(r),c=Rt(e,r);return 1===i?`${o}${c}/${a.unit}`:`${o}${c}/${i.toLocaleString(s)} ${a.units}`}function Dt(e,t,r,n,s,a,i){if(null==e||e<0)return null;const o={...Ft,...a},c=null!=t&&t>=1?t:1,l=Pt(n),d=Rt(e,n);if(r){const e=s??(r.endsWith("s")?r:`${r}s`);return c>=2?`${l}${d}/${c.toLocaleString(i)} ${e}`:`${l}${d}/${r}`}return 1===c?`${l}${d}/${o.unit}`:`${l}${d}/${c.toLocaleString(i)} ${o.units}`}function jt(e,t="unit"){const r=(e||"").trim().toLowerCase();if(!r)return t;const n=r.split(/\s+/)[0]??r;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(n)?n:n.endsWith("ies")&&n.length>3?n.slice(0,-3)+"y":n.endsWith("ses")||n.endsWith("xes")||n.endsWith("zes")||n.endsWith("ches")||n.endsWith("shes")?n.slice(0,-2):n.endsWith("s")&&!n.endsWith("ss")&&n.length>1?n.slice(0,-1):n||t}function Mt(e,t,r,n,s,a,i,o,c){const l={...Ft,...i};if(!1===o)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:i?.hardLimit??"Hard limit";const d=a??(r.endsWith("s")?r:`${r}s`),u=null!=s&&s>=2?`${s.toLocaleString(c)} ${d}`:r;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${$t(t,n)}/${u}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${$t(t,n)}/${u}`:"—"}function qt(e,t){if(null==e)return null;const r=e[t??"monthly"];return r?{included:r.included,...void 0!==r.overage&&{overage:r.overage},...void 0!==r.unitSize&&{unitSize:r.unitSize},allowOverage:!1!==e.allowOverage}:null}const Bt={included:"included",then:"then",hardLimit:"hard limit"};function zt(e,t,r={}){const{overageInCents:n=!0,currency:s}=r,a={...Bt,...r.labels},i=r.currencySymbol??Pt(s??"");if(null==e)return"—";const{included:o,overage:c}=e,l=`${o} ${a.included}`;if(!1===e.allowOverage)return`${l} (${a.hardLimit})`;if(null==c)return l;const d=Tt(s),u=n&&d>0?c/10**d:c,p="number"==typeof u&&Number.isFinite(u)?0===d?u.toLocaleString("en-US"):u.toFixed(d):String(c),m=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${a.then} ${i}${p}${m}`}function Vt(e,t,r={}){if(null==e)return null;const{overageInCents:n=!0,currency:s,locale:a="en"}=r,{included:i,overage:o}=e;if(!(!1!==e.allowOverage))return{included:i,hasOverage:!1,allowOverage:!1,price:"",unit:""};if(null==o)return{included:i,hasOverage:!1,allowOverage:!0,price:"",unit:""};const c=Tt(s),l=n&&c>0?o/10**c:o,d=(s??"").trim().toUpperCase();let u;if(d&&"number"==typeof l&&Number.isFinite(l))try{u=new Intl.NumberFormat(a,{style:"currency",currency:d,minimumFractionDigits:c,maximumFractionDigits:c}).format(l)}catch{u=`${r.currencySymbol??Pt(s??"")}${l.toFixed(c)}`}else{u=`${r.currencySymbol??Pt(s??"")}${"number"==typeof l?l.toFixed(c):String(o)}`}return{included:i,hasOverage:!0,allowOverage:!0,price:u,unit:t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(a)} ${t}`:t||""}}const Gt={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},Jt={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},Kt={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},Ht={Feature:"feature",Limit:"limit",Quota:"quota"},Yt={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},Qt={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},Zt={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},Xt={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function er(e,t){const r=e.pricingVariants;if(!r?.length)return null;const n=t.toLowerCase();return r.find(e=>e.currency?.toLowerCase()===n)??null}function tr(e,t,r){const n=er(e,t);if(!n?.basePricing)return null;const s=n.basePricing[r];return null!=s?s:null}function rr(e,t,r){const n=er(e,t);if(!n?.stripePrices)return null;const s=r===Gt.Monthly?"monthlyPriceId":r===Gt.Yearly?"yearlyPriceId":"quarterlyPriceId",a=r===Gt.Monthly?"monthly":r===Gt.Yearly?"yearly":void 0;return n.stripePrices[s]??(a?n.stripePrices[a]:void 0)??null}function nr(e,t,r,n){const s=er(e,t),a=s?.quotaOverages?.[r];if(a)return a[n]}function sr(e,t){const r=er(e,t);return r?r.currency:e.plan?.currency??""}function ar(e){const t=new Set;for(const r of e)r.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function ir(e,t,r,n){const s=e.quotas?.[r];if(null==s)return null;const a=s[n];if(!a)return null;const i=nr(e,t,r,n);return{included:a.included,...void 0!==a.unitSize&&{unitSize:a.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==s.allowOverage}}function or(e,t){if(!e)return null;for(const r of t){const t=r.pricingVariants;if(t?.length)for(const r of t){const t=r.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:r.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:r.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:r.currency}}}}return null}function cr(e,t){const r=er(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function lr(e,t,r){const n=cr(e,t);return n?.perSeat?n.perSeat[r]??null:null}function dr(e,t){return Math.max(0,e-(t||0))}function ur(e,t,r,n){const s=cr(e,t);if(!s)return null;return dr(n,s.includedSeats)*(lr(e,t,r)??0)}function pr(e,t,r,n){const s=tr(e,t,r);if(null===s)return null;if(void 0===n)return s;return s+(ur(e,t,r,n)??0)}function mr(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:n}=e;if(t){const e=cr(t,r);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=n&&n>0?{maxUsers:n,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function hr(e){const{memberCount:t,maxUsersConfig:r,hasSubscription:n=!0,requireSubscription:s=!1}=e;if(s&&!n)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:a,source:i}=r;if(a<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=a){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:a}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const gr="saas-workspace-current",fr=e=>{e?fe(gr,e._id):ye(gr)},yr=()=>ge(gr),br=()=>{ye(gr)},wr=(e,t)=>!!e&&t.some(t=>t._id===e);function vr(e,t){if(!t)return!1;const r=(n=e.createdBy)?"string"==typeof n?n:"object"==typeof n&&"_id"in n&&"string"==typeof n._id?n._id:null:null;var n;return null!==r&&r===t}function kr(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}const Sr={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view"},Cr=Object.values(Sr),xr={admin:Cr.filter(e=>e!==Sr.WORKSPACE_DELETE),member:[Sr.WORKSPACE_SETTINGS_VIEW,Sr.WORKSPACE_MEMBERS_VIEW,Sr.WORKSPACE_FEATURES_VIEW,Sr.WORKSPACE_BILLING_VIEW,Sr.WORKSPACE_USAGE_VIEW],viewer:[Sr.WORKSPACE_SETTINGS_VIEW,Sr.WORKSPACE_MEMBERS_VIEW]};function Nr(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function Pr(e){const{userId:t,workspace:r,settings:n,appPermissions:s}=e;if(!r||!t)return new Set;if(vr(r,t)){const e=new Set(Cr);if(s)for(const t of Nr(s))e.add(t);if(r.permissions)for(const t of Nr(r.permissions))e.add(t);if(n?.workspace?.permissions)for(const t of Nr(n.workspace.permissions))e.add(t);return e}const a=e.workspaceRole??kr(r,t);if(!a)return new Set;const i=r.permissions,o=n?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),d=!!i&&a in i,u=!!o&&a in o,p=a in xr;let m;if(d)m=c(i[a]);else if(u)m=c(o[a]);else if(p)m=xr[a];else{const e=n?.workspace?.defaultRole;m=e&&e in xr?xr[e]:[]}const h=new Set(m),g=d?l(i[a]):[],f=s?.[a]?l(s[a]):[],y=d?g:f;for(const e of y)h.add(e);return function(e,t,r){if(!r?.workspace)return;const{canInviteMembers:n}=r.workspace;(!1===n||"admin-only"===n&&"admin"!==t)&&e.delete(Sr.WORKSPACE_MEMBERS_INVITE)}(h,a,n),h}function Ir(e,t){const r=Pr(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}const _r="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n try {\n const payload = event.data.json();\n // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n";var Er;function Ur(e){return{isAuthenticated:e===Er.authenticated,isLoading:e===Er.loading||e===Er.redirecting||e===Er.authenticating,isRedirecting:e===Er.redirecting}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Er||(Er={}));class Ar extends a{constructor(e){super(e),this.resetError=()=>{this.setState({hasError:!1,error:null})},this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){if(pe(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){ie("[SDK ErrorBoundary] Error in onError callback:",e)}}componentDidUpdate(e){this.state.hasError&&!1!==this.props.resetOnPropsChange&&e.children!==this.props.children&&this.resetError()}render(){return this.state.hasError&&this.state.error?this.props.fallback?"function"==typeof this.props.fallback?this.props.fallback(this.state.error,this.resetError):this.props.fallback:e("div",{style:{padding:"1rem",border:"1px solid hsl(var(--destructive, 0 84.2% 60.2%))",borderRadius:"0.5rem",backgroundColor:"hsl(var(--destructive, 0 84.2% 60.2%) / 0.08)",color:"hsl(var(--destructive, 0 70% 35%))"},children:[t("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:this.props.errorTitle??"Something went wrong"}),t("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),t("button",{onClick:this.resetError,style:{padding:"0.5rem 1rem",backgroundColor:"hsl(var(--destructive, 0 84.2% 60.2%))",color:"hsl(var(--destructive-foreground, 210 40% 98%))",border:"none",borderRadius:"0.25rem",cursor:"pointer",fontSize:"0.875rem"},children:this.props.retryLabel??"Try again"})]}):this.props.children}}const Tr=()=>({type:"AUTHENTICATION_STARTED"}),Or=()=>({type:"AUTHENTICATION_PROCESSING"}),Rr=()=>({type:"AUTHENTICATION_FAILED"}),Wr=e=>({type:"SET_SESSION",payload:e}),$r=()=>({type:"REMOVE_SESSION"});function Fr(e,t,r,n){const s=i(()=>{const t=r??(e=>e);let s,a,i=!1;return()=>{const r=e();if(!i)return i=!0,s=r,a=t(r),a;if(Object.is(s,r))return a;const o=t(r);s=r;return(n?n(a,o):Object.is(a,o))||(a=o),a}},[e,r,n]);return o(t,s,s)}function Lr({name:e,initialState:r,reducer:n,initializer:a}){const o=c(null);o.displayName=`${e}StoreContext`;const d=s.memo(({children:e})=>{const s=l(null);return null===s.current&&(s.current=function(e,t,r){let n=r?r(e):e;const s=new Set;return{getState:()=>n,dispatch:e=>{const r=t(n,e);Object.is(r,n)||(n=r,s.forEach(e=>e()))},subscribe:e=>(s.add(e),()=>{s.delete(e)})}}(r,n,a)),t(o.Provider,{value:s.current,children:e})});d.displayName=`${e}Provider`;const u=(t="Store")=>{const r=s.useContext(o);if(!r)throw(t=>new Error(`use${e}${t} must be used within a ${e}Provider. Make sure SaaSOSProvider is wrapping your application.`))(t);return r};return{Provider:d,useContext:()=>{const e=u("Context"),t=Fr(e.getState,e.subscribe);return i(()=>({state:t,dispatch:e.dispatch}),[t,e])},useState:()=>{const e=u("State");return Fr(e.getState,e.subscribe)},useDispatch:()=>u("Dispatch").dispatch,useSelector:(e,t)=>{const r=u("Selector");return Fr(r.getState,r.subscribe,e,t)},useStore:u}}function Dr(e,t,r){return{...e,[t]:r}}function jr(e,t){return{...e,...t}}const{Provider:Mr,useDispatch:qr,useStore:Br}=Lr({name:"Auth",initialState:{session:null,status:Er.loading},reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return Dr(e,"status",Er.redirecting);case"AUTHENTICATION_PROCESSING":return Dr(e,"status",Er.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return jr(e,{session:null,status:Er.unauthenticated});case"SET_SESSION":return jr(e,{session:t.payload,status:Er.authenticated});default:return e}}}),zr=Mr,Vr=qr,Gr=Br,Jr=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),Kr=e=>({type:"SET_SETTINGS",payload:e}),Hr=(e,t)=>({type:"SET_SETTINGS_STATUS",payload:{status:e,error:t}}),Yr=()=>({serverUrl:"",version:Be.V1,orgId:"",settings:null,settingsStatus:"idle",settingsError:null}),{Provider:Qr,useDispatch:Zr,useStore:Xr}=Lr({name:"OS",initialState:Yr(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return jr(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return Yr();case"SET_SETTINGS":return jr(e,{settings:t.payload,settingsStatus:"loaded",settingsError:null});case"SET_SETTINGS_STATUS":return jr(e,{settingsStatus:t.payload.status,settingsError:t.payload.error??null});default:return e}}}),en=Qr,tn=Zr,rn=Xr,nn=e=>({type:"SET_WORKSPACES",payload:e}),sn=e=>({type:"ADD_WORKSPACE",payload:e}),an=e=>({type:"UPDATE_WORKSPACE",payload:e}),on=e=>({type:"REMOVE_WORKSPACE",payload:e}),cn=e=>({type:"SET_ALL_FEATURES",payload:e}),ln=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),dn=()=>({type:"RESET_CURRENT_WORKSPACE"}),un=e=>({type:"SET_IS_INITIALIZED",payload:e}),pn=e=>({type:"SET_LOADING",payload:e}),mn=e=>({type:"SET_ERROR",payload:e}),hn=e=>({type:"SET_REFRESHING",payload:e}),gn=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:fn,useDispatch:yn,useStore:bn}=Lr({name:"Workspace",initialState:{workspaces:[],loading:!1,error:null,currentWorkspace:null,refreshing:!1,switchingToId:null,isInitialized:!1,allFeatures:[]},reducer:(e,t)=>{switch(t.type){case"SET_WORKSPACES":return Dr(e,"workspaces",t.payload);case"ADD_WORKSPACE":return Dr(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return Dr(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return Dr(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return Dr(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return Dr(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return Dr(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return Dr(e,"isInitialized",t.payload);case"SET_LOADING":return Dr(e,"loading",t.payload);case"SET_ERROR":return Dr(e,"error",t.payload);case"SET_REFRESHING":return Dr(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return Dr(e,"switchingToId",t.payload);default:return e}}}),wn=fn,vn=yn,kn=bn,Sn=s.memo(({children:e})=>t(en,{children:t(zr,{children:t(wn,{children:e})})}));Sn.displayName="SDKContextProvider";const Cn=c({});Cn.displayName="CheckoutConfigContext";const xn=s.memo(({getCheckoutStripeParams:e,children:r})=>{const n=s.useMemo(()=>({getCheckoutStripeParams:e}),[e]);return t(Cn.Provider,{value:n,children:r})});xn.displayName="CheckoutConfigProvider";const Nn={settings:{titles:{profile:"Account",security:"Security",devices:"Devices & sessions",general:"Workspace Settings",users:"Workspace Members",subscription:"Plan & Billing",usage:"Usage",credits:"Credits",features:"Workspace Features",notifications:"Notifications",permissions:"Permissions",danger:"Danger Zone"},sidebar:{account:"Account",workspace:"Workspace",profile:"Account",security:"Security",devices:"Devices",general:"Settings",users:"Members",subscription:"Plan & Billing",usage:"Usage",credits:"Credits",features:"Features",notifications:"Notifications",permissions:"Permissions",danger:"Danger Zone"},common:{refresh:"Refresh",refreshing:"Refreshing...",retry:"Retry",retrying:"Retrying...",save:"Save",saving:"Saving...",cancel:"Cancel",delete:"Delete",dismiss:"Dismiss",loading:"Loading...",success:"Success!",error:"Error",refreshAction:"{loading, select, true {Refreshing...} other {Refresh}}",retryAction:"{loading, select, true {Retrying...} other {Retry}}",noPermissionTitle:"Access Restricted",noPermissionDescription:"You don't have permission to access this section. Contact a workspace admin if you need access.",billingManageOnly:"Only users with billing management permissions can perform this action.",openSettings:"Open settings",back:"Back",close:"Close"}},subscription:{managePlan:"Manage your plan and billing",changePlan:"Change Plan",viewPricingPlans:"View Pricing Plans",viewPlans:"View Plans",upgradePlan:"Upgrade Now",subscribe:"Subscribe",currentPlan:"Current Plan",noSubscription:"You don't have an active subscription",choosePlan:"Choose Your Plan",choosePlanDescription:"Compare plans and select the one that fits your needs",forWorkspace:"for {name}",planUpdateAvailable:"Plan update available",updateSuccess:"Subscription updated successfully!",updateFailed:"Update failed",cancelTitle:"Cancel Subscription",cancelConfirm:"Are you sure you want to cancel your subscription?",cancelKeep:"Keep Subscription",cancelButton:"Yes, Cancel Subscription",canceling:"Canceling...",cancelSuccess:"Subscription will be canceled at the end of the billing period.",cancelNotCharged:"You won't be charged again after cancellation",cancelResumeAnytime:"You can resume your subscription anytime before it ends",cancelTrialTitle:"Cancel Trial",cancelTrialConfirm:"Are you sure you want to cancel your trial?",cancelTrialAccess:"Your trial will continue until",cancelTrialNoCharge:"You won't be charged — your trial will simply expire",cancelTrialResume:"You can resume your trial anytime before it ends",cancelTrialKeep:"Keep Trial",cancelTrialButton:"Yes, Cancel Trial",resumeTitle:"Resume Subscription",resumeTrial:"Resume Trial",resumeConfirm:"Are you sure you want to resume your subscription?",resumeKeep:"Keep Canceled",resumeButton:"Yes, Resume Subscription",resuming:"Resuming...",resumeSuccess:"Subscription has been resumed.",managePayment:"Manage Payment",openingPortal:"Opening...",viewAllPlans:"View All Plans",scheduledCancellation:"Subscription scheduled for cancellation",scheduledTrialCancellation:"Trial scheduled for cancellation",paymentPastDue:"Payment past due",paymentPastDueDescription:"Please update your payment method to avoid service interruption.",subscriptionPaused:"Subscription paused",subscriptionPausedDescription:"Your subscription is currently paused. Resume to restore full access.",errorLoading:"Error loading subscription data",errorLoadingDescription:"Please check your connection and try again.",errorProcessing:"Failed to process subscription",errorCanceling:"Failed to cancel subscription",errorResuming:"Failed to resume subscription",invalidWorkspace:"Invalid workspace ID",billingInterval:{monthly:"Monthly",quarterly:"Quarterly",yearly:"Yearly",perMonth:"/month",perQuarter:"/quarter",perYear:"/year"},seats:{title:"Seats",members:"Members",included:"Included",billable:"Billable",perExtraSeat:"Per extra seat",limit:"Limit",includedSeats:"Included seats",maxSeats:"Max seats",freeWithBase:"Free with base price",allIncluded:"All included",extra:"extra",unlimited:"Unlimited"},items:{features:"Features",limits:"Limits",quotas:"Usage Quotas",credits:"AI Credits",creditsPerMonth:"Credits per month",creditsOneTime:"Credits (given once)",creditRenewal:"Credit renewal",creditModeReset:"Fresh every month",creditModeTopup:"Adds up every month",creditModeLifetime:"Given once",creditsPerPeriod:"Credits per month",creditRollover:"Credit renewal"},checkout:{upgrade:"Upgrade",downgrade:"Downgrade",switchTo:"Switch to",select:"Select"},status:{active:"Active",canceling:"Canceling",trial:"Trial",canceled:"Canceled",pastDue:"Past Due",paused:"Paused",deprecated:"Deprecated",unknown:"Unknown"},plan:"Plan",invoicesTab:"Invoices",tabsLabel:"Subscription tabs",endsOn:"(ends {date})",versionLabel:"Version {version}",changePlanButton:"Change Plan",noPlanAssigned:"No plan assigned",free:"Free",perSeatDisplay:"+ {price}/seat{interval}",estTotalDisplay:"Est. total: {total}{interval} ({count, plural, one {# extra seat} other {# extra seats}})",nextBillingDisplay:"Next billing: {date}",membersInWorkspace:"{count, plural, one {# member} other {# members}} in workspace",billingInCurrency:"Billing in {currency}",savingsPercent:"Save {percent, number}%",switchToInterval:"Switch to {interval}",seatPriceDisplay:"+ {price}/seat{interval} ({included} {includedLabel})",trialEnded:"Your trial has ended.",trialEndsIn:"Your trial ends in {days, plural, one {# day} other {# days}}.",onTrial:"You are on a trial.",upgradeToKeepAccess:"Upgrade to keep access.",viewInvoices:"View Invoices",cancelTrial:"Cancel Trial",dunningFinal:"Final warning: Subscription will be suspended",dunningSuspended:"Subscription suspended",dunningRecovery:"Payment recovery in progress",dunningSuspendedDescription:"Your subscription has been suspended due to repeated payment failures. Update your payment method to restore access.",dunningRecoveryDescription:"We were unable to process your payment. Please update your payment method to avoid losing access.",cancelEndDescription:"Your subscription will end on",trialEndDescription:"Your trial will end on",cancelEndFallback:"Your subscription will be canceled at the end of the current billing period. You won't be charged again.",resumeChargeDate:"You will be charged again on",resumeChargeFallback:"the next billing date",resumeContinue:"Your subscription will continue automatically and you'll be billed according to your plan",resumeCancelAnytime:"You can cancel anytime before the next billing date if you change your mind",retainAccess:"You'll retain full access to this plan until",retainAccessFallback:"the end of your current billing period",noPlansAvailable:"No plan groups are available for this workspace. Please contact support if you believe this is an error.",noPlansAvailableHint:"No plan groups are available for this workspace.",startTrialDescription:"Try the full plan with no commitment. You can upgrade or cancel anytime.",noSubscriptionDescription:"Choose a plan to get started with your workspace",startFreeTrial:"Start Free Trial",startTrialDays:"Start {days}-day Free Trial",trialBadge:"{days}-day trial"},users:{emailPlaceholder:"example@example.com",title:"Workspace Members",adminOnly:"Only workspace admin can manage users and roles.",inviteByEmail:"Invite member by email",inviteButton:"Invite",inviting:"Inviting...",inviteSuccess:"User invited successfully",emailRequired:"Email is required",invalidEmail:"Invalid email address format",inviteFailed:"Failed to invite member",seatLimitReached:"Seat limit reached",memberLimitReached:"Member limit reached",role:"Role",you:"You",owner:"Owner",noMembers:"No members found in this workspace.",extraSeatCost:"Each additional member adds {price}/{interval, select, yearly {yr} quarterly {qtr} other {mo}} to your subscription",unknownUser:"Unknown User",seats:"Seats",members:"Members",included:"included",perExtraSeat:"/extra seat",maxMembers:"max members",available:"available",noMemberLimit:"No member limit",seatHeading:"{hasSeatPricing, select, true {Seats} other {Members}}",limitReached:"{reason, select, seat_limit_reached {Seat limit reached} other {Member limit reached}}",memberCount:"{count, plural, one {# member} other {# members}}",subscriptionRequired:"A subscription is required to invite members.",seatLimitMessage:"Your plan allows up to {maxUsers, number} members. Upgrade for more seats.",settingsLimitMessage:"This workspace allows up to {maxUsers, number} members.",memberLimitMessage:"Member limit of {maxUsers, number} reached.",selectRole:"Select a role",inviteAs:"Invite as {role}"},invoices:{title:"Billing History",description:"View and download your invoices",pay:"Pay",view:"View",viewDetails:"View Details",download:"PDF",errorLoading:"Error loading invoices",noInvoices:"No invoices yet. Subscribe to a plan to receive invoices.",noInvoicesWithSub:"No invoices with download option found",paidAmount:"Paid: {amount}",na:"N/A",status:{draft:"Draft",open:"Open",paid:"Paid",uncollectible:"Uncollectible",void:"Void"}},usage:{title:"Usage",description:"Monitor your resource consumption and quotas",totalResources:"Total Resources",overallUsage:"Overall Usage",inOverage:"In Overage",estOverageCost:"Est. Overage Cost",overageDetected:"Overage Detected",overageDescription:"Additional usage will be billed as overage on your next invoice.",overageUnits:"Overage units",rate:"Rate",billableBlocks:"Billable blocks",estimatedCharge:"Estimated charge",noData:"No quota usage data available for this workspace.",noDataHint:"Quotas will appear here once your plan includes metered resources.",used:"used",remaining:"remaining",overLimit:"over limit",percentUsed:"{percent, number}% used",availableRemaining:"{count} remaining",overLimitCount:"{count} over limit",overageWarning:"{count, plural, one {# resource has exceeded the included quota.} other {# resources have exceeded the included quota.}} Additional usage will be billed as overage on your next invoice.",fullyUsed:"Fully used",renewingSoon:"renewing soon",almostFull:"Almost full",overage:"Overage",errorLoading:"Failed to load usage data",perUnit:"/ unit",perUnits:"/ units",rateDisplay:"{rate} {unitSize, plural, =1 {/ unit} other {/ {unitSize, number} units}}",resourcesExceeded:"{count, plural, one {# resource has exceeded the included quota.} other {# resources have exceeded the included quota.}}",estOverageCharges:"Estimated overage charges this period: {amount}",overageRateDisplay:"Overage rate: {rate}",resetDateDisplay:"Usage resets on {date}",daysRemainingDisplay:"{count, plural, one {# day remaining} other {# days remaining}}"},profile:{email:"Email",name:"Name",language:"Language",country:"Country",currency:"Currency",timezone:"Timezone",profileImage:"Profile Image",success:"Profile saved successfully",nameMinLength:"Name must be at least 2 characters.",save:"Save",reset:"Reset"},general:{ownerOnly:"Only the workspace owner can change the workspace settings.",name:"Name",namePlaceholder:"My Awesome Workspace",nameMinLength:"Workspace name must be at least 2 characters.",billingCurrency:"Billing currency",icon:"Icon",iconDescription:"Choose an emoji or upload a custom image for your workspace.",imageUrl:"Image URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"Enter a valid URL for your workspace image. Supports PNG, JPG, and SVG formats.",previewLabel:"Preview:",previewImageAlt:"Workspace preview",success:"Workspace settings saved successfully",chooseEmoji:"Choose Emoji",customImageUrl:"Custom Image URL",updateWorkspace:"Update Workspace"},features:{title:"Workspace Features",ownerOnly:"Only the workspace owner can change the features.",noFeatures:"Workspace has no features to manage.",enabled:"enabled",disabled:"disabled",enabling:"Enabling",disabling:"Disabling",featureSuccess:"successfully",updateSuccess:"{feature} {enabled, select, true {enabled} other {disabled}} successfully",actionStatus:"{action, select, enabling {Enabling} disabling {Disabling} other {}}",fallbackName:"Feature"},danger:{title:"Delete Workspace",adminOnly:"Only workspace admins can delete workspaces.",deleteWorkspace:"Delete Workspace",deleteConfirm:"Are you absolutely sure?",deleteWarning:"This action cannot be undone. This will permanently delete the workspace and all associated data.",deleting:"Deleting...",deleteDescription:"Once you delete a workspace, there is no going back. This will permanently delete the workspace and all of its data, including members, settings, and features.",deleteConfirmDescription:"This action cannot be undone. This will permanently delete the workspace and all of its data.",failedToDelete:"Failed to delete workspace"},notifications:{title:"Notification Preferences",permissionDenied:"Notification permission denied",notSupported:"Push notifications are not supported in this browser.",manageDescription:"Manage how you receive notifications from this workspace.",blocked:"Notifications Blocked",blockedDescription:"You previously blocked notifications for this site. To enable them, update your browser settings:",pushTitle:"Push Notifications",pushEnabledDescription:"You will receive browser notifications for important updates.",pushDisabledDescription:"Get notified about payment issues, trial expiry, and other important updates.",enabling:"Enabling...",disabling:"Disabling...",enable:"Enable",disable:"Disable",toggleAction:"{loading, select, true {{subscribed, select, true {Disabling...} other {Enabling...}}} other {{subscribed, select, true {Disable} other {Enable}}}}",pushDescription:"{subscribed, select, true {You will receive browser notifications for important updates.} other {Get notified about payment issues, trial expiry, and other important updates.}}",deviceNote:"Notifications are sent to this device. Enable on other devices separately.",prefsSaved:"Notification preferences saved.",loadingPrefs:"Loading preferences...",categories:{workspace:"Workspace",billing:"Billing & Payments"},events:{workspace_invite:"Member Invited",workspace_invite_desc:"When a new member is added to the workspace",workspace_removed:"Member Removed",workspace_removed_desc:"When a member is removed from the workspace",workspace_role_changed:"Role Changed",workspace_role_changed_desc:"When a member's role is updated",subscription_created:"Subscription Created",subscription_created_desc:"When a new subscription is activated",subscription_upgraded:"Plan Upgraded",subscription_upgraded_desc:"When the subscription plan is upgraded",subscription_canceled:"Subscription Canceled",subscription_canceled_desc:"When the subscription is canceled",subscription_suspended:"Access Suspended",subscription_suspended_desc:"When access is suspended due to payment failures",trial_ending:"Trial Ending",trial_ending_desc:"A few days before the trial expires",trial_expired:"Trial Expired",trial_expired_desc:"When the trial period has ended",payment_failed:"Payment Failed",payment_failed_desc:"When a payment could not be processed",payment_action_required:"Payment Action Required",payment_action_required_desc:"When a payment requires additional verification",payment_succeeded:"Payment Received",payment_succeeded_desc:"When a payment is successfully processed"},unblock:{firefox:{step1:"Click the lock icon (or shield icon) in the address bar",step2:'Find "Notifications" in the permissions list',step3:'Change from "Blocked" to "Allow"',step4:"Reload this page"},safari:{step1:"Open Safari → Settings → Websites → Notifications",step2:"Find this website in the list",step3:'Change from "Deny" to "Allow"',step4:"Reload this page"},edge:{step1:"Click the lock icon in the address bar",step2:'Click "Permissions for this site"',step3:'Set "Notifications" to "Allow"',step4:"Reload this page"},chrome:{step1:"Click the lock icon (or tune icon) in the address bar",step2:'Click "Site settings"',step3:'Set "Notifications" to "Allow"',step4:"Reload this page"}}},quota:{includedOnly:"{count, number}/mo",includedWithOverage:"{count, number}/mo, then {price} / {unit}",includedHardLimit:"{count, number}/mo (hard limit)",unitFallback:"unit"},pricing:{title:"Choose Your Plan",description:"Compare plans and select the one that fits your needs",currency:"Currency",billingIn:"Billing in",noPlansCurrency:"No plans available for your billing currency.",noPlansCurrencyHint:"Something went wrong. Please contact support.",noPlans:"No plans available",free:"Free",included:"included",save:"Save",current:"Current",processing:"Processing...",unavailable:"Unavailable",selectCurrency:"Select billing currency",billingInterval:"Billing interval"},beta:{logoAlt:"Logo",nameLabel:"Name",emailLabel:"Email",submitText:"Submit",submittingText:"Submitting...",errorMessage:"An error occurred",tryAgain:"Try Again",privacyConsent:"By submitting this form, you consent to our",privacyPolicy:"Privacy Policy",and:"and",termsOfService:"Terms of Service"},workspace:{switchTitle:"Switch Workspace",switchDescription:"Select a workspace to switch to or create a new one.",notLoggedIn:"Looks like you are not logged in. Please login to continue.",availableWorkspaces:"Available Workspaces ({count, number})",loadingWorkspaces:"Loading workspaces...",searchPlaceholder:"Search workspaces...",noWorkspacesFound:"No workspaces found",noWorkspacesAvailable:"No workspaces available",switchTo:"Switch to",membersCount:"{count, plural, one {# member} other {# members}}",createNew:"Create New Workspace",createTitle:"Create New Workspace",createDescription:"Create a new workspace to get started.",workspaceName:"Workspace Name",workspaceNamePlaceholder:"My Awesome Workspace",workspaceNameMinLength:"Workspace name must be at least 2 characters.",workspaceIcon:"Workspace Icon",iconDescription:"Choose an emoji or upload a custom image for your workspace.",chooseEmoji:"Choose Emoji",customImageUrl:"Custom Image URL",imageUrl:"Image URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"Enter a valid URL for your workspace image. Supports PNG, JPG, and SVG formats.",invalidUrl:"Please enter a valid URL",creating:"Creating...",createWorkspace:"Create Workspace"},dropdowns:{search:"Search...",chooseOption:"Choose option",chooseCountry:"Choose country",searchCountry:"Choose country...",chooseLanguage:"Choose language",searchLanguage:"Choose language...",chooseCurrency:"Choose currency",searchCurrency:"Choose currency...",chooseTimezone:"Choose timezone",searchTimezone:"Choose timezone...",noResults:"No results found"},push:{failedToSubscribe:"Failed to subscribe to push notifications",failedToUnsubscribe:"Failed to unsubscribe from push notifications"},permissions:{title:"Permissions",description:"Permissions assigned to each role in this workspace.",ownerOnly:"Only the workspace owner can manage permissions.",save:"Save Permissions",saving:"Saving...",saveSuccess:"Permissions saved successfully"},credits:{title:"Credits",description:"Credits can be used for premium actions like AI generation.",balance:"Credit Balance",available:"Available",totalGranted:"Total Granted",totalConsumed:"Total Consumed",totalExpired:"Total Expired",noCredits:"No credits yet",noCreditsHint:"Credits will appear here when granted by your plan or purchased.",buyCredits:"Buy Credits",buyAmount:"Buy {count} Credits",purchasing:"Redirecting...",packages:"Credit Packages",noPackages:"No credit packages available.",creditsAmount:"{count} credits",validityDays:"Valid for {count} days",validityUnlimited:"No expiry",transactions:"Recent Transactions",noTransactions:"No transactions yet.",loadMore:"Load More",viewAll:"View All",expiringSoon:"Expiring Soon",expiringInDays:"{count} credits expiring within {days} days",noExpiring:"No credits expiring soon.",type:{plan_grant:"Plan Grant",pack_purchased:"Purchased",consumed:"Consumed",expired:"Expired",admin_grant:"Granted",admin_revoke:"Revoked",refund:"Refund"},dialogTitle:"Buy Credit Packages",dialogDescription:"Choose a credit package to purchase.",dialogDescriptionWorkspace:"Purchase credits for {workspace}.",perCredit:"{price} per credit",purchaseSuccess:"Credits purchased successfully! Your balance has been updated.",purchaseCanceled:"Credit purchase was canceled. No charges were made.",purchaseFailed:"Credit purchase failed. Please try again or contact support.",errorLoading:"Failed to load credit data",insufficientCredits:"Not enough credits",insufficientDetail:"Insufficient credits. Available: {available}, requested: {requested}"},loading:{restoringSession:"Restoring your session...",redirecting:"Redirecting...",signingIn:"Signing you in...",verifyingAccount:"Verifying your account...",almostThere:"Almost there..."},errors:{networkError:"Network error: Please check your internet connection",unauthorized:"Unauthorized - Please check your session",notFound:"Resource not found",generic:"An error occurred",fetchPlans:"Failed to fetch plans",fetchPlanGroup:"Failed to fetch plan group",fetchPlanGroupVersion:"Failed to fetch plan group version",fetchPlanGroupVersions:"Failed to fetch plan group versions",fetchSubscription:"Failed to fetch subscription",createCheckout:"Failed to create checkout session",updateSubscription:"Failed to update subscription",fetchInvoices:"Failed to fetch invoices",fetchInvoice:"Failed to fetch invoice",openBillingPortal:"Failed to open billing portal",cancelSubscription:"Failed to cancel subscription",resumeSubscription:"Failed to resume subscription",recordUsage:"Failed to record usage",fetchQuotaUsage:"Failed to fetch quota usage status",fetchAllQuotaUsage:"Failed to fetch all quota usage",fetchUsageLogs:"Failed to fetch usage logs",fetchCreditBalance:"Failed to fetch credit balance",consumeCredits:"Failed to consume credits",purchaseCredits:"Failed to purchase credits",fetchCreditPackages:"Failed to fetch credit packages",fetchCreditTransactions:"Failed to fetch credit transactions",fetchExpiringCredits:"Failed to fetch expiring credits",fetchWorkspaces:"Failed to fetch workspaces"},security:{connectedAgentsTitle:"Connected agents",connectedAgentsDescription:"AI agents you've authorized to access your account. Disconnect any you no longer use — it revokes access immediately.",connectedAgentsDisconnect:"Disconnect",connectedAgentsEmpty:"No connected agents.",connectedAgentsAccess:"Access",connectedAgentsGranted:"Granted",connectedAgentsLoadFailed:"Failed to load connected agents",connectedAgentsRevokeFailed:"Failed to disconnect",mcpConnectAction:"Connect an agent",mcpGuideTitle:"Connect an AI agent",mcpGuideDescription:"Let an AI assistant securely work in your account. Choose your app below and follow the steps — it only takes a minute.",mcpServerUrlLabel:"Server address",mcpServerUrlHint:"Some apps just ask you to paste this address.",mcpPromptLabel:"Or paste this into your AI",mcpPromptHint:"Works with chat assistants that can add tools — paste it into the chat and send.",mcpPromptTemplate:"Please connect to my {{name}} account using the MCP server at {{url}}, then use its tools to help me.",mcpClientsLabel:"Step-by-step for popular apps",mcpAddToConfigFile:"Open the file {path} and add this:",mcpClientChatgptInstructions:"In ChatGPT, go to Settings → Connectors, choose “Add custom connector”, and paste the server address above.",mcpClientClaudeInstructions:"In Claude, go to Settings → Connectors, choose “Add custom connector”, and paste the server address above.",mcpClientClineInstructions:"In Cline, open the MCP Servers panel, choose “Add remote server”, and paste the server address above.",mcpCopy:"Copy",mcpCopied:"Copied",mcpLearnMore:"Learn more",inactive:"Inactive",inactiveHint:"Registered on a previous sign-in domain and can no longer be used. You can remove it.",passkeysTitle:"Passkeys",passkeysDescription:"Passkeys let you sign in with your fingerprint, face, or device PIN.",noPasskeys:"No passkeys registered",addHint:'To add a passkey, choose "Add a passkey" the next time you sign in on the device you want to use.',rename:"Rename",remove:"Remove",removeTitle:"Remove passkey",removeDescription:"You will no longer be able to sign in with this passkey.",renamePlaceholder:"Passkey name",lastUsed:"Last used",added:"Added",devicesTitle:"Your devices",devicesDescription:"Phones and computers you've used to sign in. Sign out or remove any you don't recognize.",devicesEmpty:"You haven't signed in from any devices yet.",devicesLoadFailed:"Couldn't load your devices. Please try again.",deviceCurrent:"This device",deviceTrusted:"Trusted",deviceActiveSessions:"{count, plural, one {# active session} other {# active sessions}}",devicePushEnabled:"Notifications on",deviceLastActive:"Last used: {date}",deviceRename:"Rename",deviceRenamePlaceholder:"Device name",deviceRenameFailed:"Couldn't rename the device. Please try again.",deviceSave:"Save",deviceCancel:"Cancel",deviceSignOut:"Sign out",deviceSignOutFailed:"Couldn't sign out the device. Please try again.",deviceForget:"Remove",deviceForgetFailed:"Couldn't remove the device. Please try again.",deviceForgetConfirmTitle:"Remove this device?",deviceForgetConfirmBody:"This signs the device out and removes it from your list. If you sign in from it again, it'll show up here.",sessionsTitle:"Where you're signed in",sessionsDescription:"You're currently signed in on these. Sign out any you don't recognize.",sessionsEmpty:"You're not signed in anywhere else.",sessionsLoadFailed:"Couldn't load your sessions. Please try again.",sessionCurrent:"This one",sessionExpires:"Signs out: {date}",sessionLastActive:"Last used: {date}",sessionSignOut:"Sign out",sessionSignOutFailed:"Couldn't sign out that session. Please try again."}},Pn={en:async()=>Nn,es:async()=>(await import("./es-BWGnjJKJ.mjs")).es,fr:async()=>(await import("./fr-Big5DFPB.mjs")).fr,de:async()=>(await import("./de-CdPeKWZ2.mjs")).de,ja:async()=>(await import("./ja-Cwdz0hCu.mjs")).ja,zh:async()=>(await import("./zh-glRKcdia.mjs")).zh,hi:async()=>(await import("./hi-jArNRknR.mjs")).hi,ar:async()=>(await import("./ar-CHTRXlXt.mjs")).ar},In=["en","es","fr","de","ja","zh","hi","ar"];const _n={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function En(e,t){const r={...e};for(const n of Object.keys(t)){const s=t[n],a=e[n];"string"==typeof s?r[n]=s:s&&"object"==typeof s&&a&&"object"==typeof a&&(r[n]=En(a,s))}return r}const Un=c({messages:Nn,locale:"en",formattingLocale:"en"});function An({locale:e="en",messageOverrides:t,children:r}){const n=function(e){const t=e.toLowerCase().replace("_","-");if(In.includes(t))return t;const r=t.split("-")[0];return In.includes(r)?r:"en"}(e),[a,o]=s.useState(Nn);s.useEffect(()=>{if("en"===n)return void o(Nn);let e=!1;const t=Pn[n];return t&&t().then(t=>{e||o(t)}),()=>{e=!0}},[n]);const c=i(()=>t?En(a,t):a,[a,t]),l=function(e){return _n[e]??e}(n),d=i(()=>({messages:c,locale:n,formattingLocale:l}),[c,n,l]);return s.createElement(Un.Provider,{value:d},r)}const Tn=new Map,On=new Map,Rn=new Map;function Wn(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const $n={getNumberFormat(e,t){const r=Wn(e,t);let n=Tn.get(r);return n||(n=new Intl.NumberFormat(e,t),Tn.set(r,n)),n},getDateTimeFormat(e,t){const r=Wn(e,t);let n=On.get(r);return n||(n=new Intl.DateTimeFormat(e,t),On.set(r,n)),n},getPluralRules(e,t){const r=Wn(e,t);let n=Rn.get(r);return n||(n=new Intl.PluralRules(e,t),Rn.set(r,n)),n}},Fn=new Map;function Ln(){const{messages:e,locale:t,formattingLocale:r}=d(Un),n=i(()=>{const t=(e,t)=>{let r=e;for(const e of t.split(".")){if(!r||"object"!=typeof r||!(e in r))return;r=r[e]}return"string"==typeof r?r:void 0};return(n,s)=>{const a=t(e,n)??t(Nn,n)??n;if(!s)return a;try{const e=function(e,t){const r=`${t}:${e}`;let n=Fn.get(r);return n||(n=new b(e,t,void 0,{formatters:$n}),Fn.set(r,n)),n}(a,r),t=e.format(s);return"string"==typeof t?t:String(t)}catch{return a.replace(/\{(\w+)\}/g,(e,t)=>String(s[t]??`{${t}}`))}}},[e,r]),s="ar"===t?"rtl":"ltr",a=i(()=>e=>e.toLocaleString(r),[r]),o=i(()=>(e,t)=>Wt(e,t,r),[r]);return{t:n,locale:t,formattingLocale:r,dir:s,fmtNum:a,fmtCents:o,messages:e}}function Dn(){const e=l(null);u(()=>()=>e.current?.abort(),[]);return{begin:p(()=>{e.current?.abort();const t=new AbortController;return e.current=t,t},[]),settle:p(t=>e.current===t&&(e.current=null,!t.signal.aborted),[])}}const jn="bb_attr",Mn=["gclid","gbraid","wbraid","dclid","fbclid","msclkid","li_fat_id","twclid","ttclid","rdt_cid","epik","irclickid","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_id"],qn=/^[\w.~-]{1,200}$/;function Bn(){return"undefined"==typeof window?null:window}function zn(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const r=t??Bn()?.document;if(!r)return"";const n=e.split(".");for(let e=n.length-2;e>=0;e--){const t="."+n.slice(e).join("."),s=`__bb_probe_${Date.now()}`;r.cookie=`${s}=1; domain=${t}; path=/; SameSite=Lax`;const a=r.cookie.includes(`${s}=1`);if(r.cookie=`${s}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,a)return t}return""}function Vn(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${jn}=`));if(!t)return{};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));return"object"==typeof e&&e?e:{}}catch{return{}}}function Gn(){const e=Bn();if(!e)return{};const t=e.document,r=Vn(t),n={...function(e){const t=new URLSearchParams(e),r={};for(const e of Mn){const n=t.get(e);n&&(n.length>200||qn.test(n)&&(r[e]=n))}return r}(e.location.search),...r};if(0===Object.keys(n).length)return{};return Object.keys(n).some(e=>void 0===r[e])&&function(e,t,r){const n=encodeURIComponent(JSON.stringify(t));e.cookie=`${jn}=${n}; path=/; max-age=7776000; SameSite=Lax`+(r?`; domain=${r}`:"")}(t,n,zn(e.location.hostname,t)),n}function Jn(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const Kn="bb_pending_checkout",Hn=216e5;function Yn(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}function Qn(e){try{Yn()?.setItem(Kn,JSON.stringify(e))}catch{}!function(e){if(!e.sessionId)return;const t=Xn();if(!t)return;try{const r=zn(window.location?.hostname??"",t);t.cookie=`${Zn}=${encodeURIComponent(JSON.stringify(e))}; path=/; max-age=21600; SameSite=Lax`+(r?`; domain=${r}`:"")}catch{}}(e)}const Zn="bb_co";function Xn(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function es(){const e=Xn();if(e)try{const t=zn(window.location?.hostname??"",e);e.cookie=`${Zn}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function ts(e,t){if(!e)return null;try{const r=JSON.parse(e);return r&&"string"==typeof r.eventId&&r.eventId?"number"!=typeof r.startedAt||t-r.startedAt>Hn?null:r:null}catch{return null}}function rs(e=Date.now()){const t=Yn();if(!t)return null;let r=null;try{r=t.getItem(Kn),t.removeItem(Kn)}catch{return null}const n=ts(r,e);return n&&es(),n}function ns(e){try{return ts(Yn()?.getItem(Kn)??null,e)}catch{return null}}function ss(e,t=Date.now()){let r=null;try{r=new URLSearchParams(e).get("session_id")}catch{return null}if(!r)return null;const n=ns(t);if(n?.sessionId===r)return rs(t);const s=function(e){const t=Xn();if(!t||"string"!=typeof t.cookie)return null;const r=t.cookie.split("; ").find(e=>e.startsWith(`${Zn}=`));return r?ts(decodeURIComponent(r.slice(Zn.length+1)),e):null}(t);return s?.sessionId!==r?null:(es(),s)}function as(e,t=Date.now()){return function(e){let t=null;try{t=new URLSearchParams(e).get("bb")}catch{return!1}if(!t)return!1;const r={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{r[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===r.action&&"cancel"===r.status}(e)&&ns(t)?rs(t):null}const is=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),os=new Set(["bhd","jod","kwd","omr","tnd"]);function cs(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const r=(t??"").toLowerCase();return is.has(r)?e:e/(os.has(r)?1e3:100)}function ls(){return"undefined"==typeof window?null:window}function ds(e){const t=ls();if(!t)return;t.gtag?.("consent","update",{ad_storage:e.marketing?"granted":"denied",ad_user_data:e.marketing?"granted":"denied",ad_personalization:e.marketing?"granted":"denied",analytics_storage:e.analytics?"granted":"denied"});const r=t.fbq;r?.("consent",e.marketing?"grant":"revoke")}function us(){const e={};try{if("undefined"==typeof document||"string"!=typeof document.cookie)return e;for(const t of document.cookie.split("; ")){const r=t.indexOf("=");r>0&&(e[t.slice(0,r)]=t.slice(r+1))}}catch{}return e}function ps(e){if(!e)return;const t=e.split(".");if(t.length<4)return;const r=t.slice(-2).join(".");return/^\d+\.\d+$/.test(r)?r:void 0}function ms(e){if(!e)return;const t=/^GS2\.\d+\.(?:.*?\$)?s(\d+)/.exec(e)??/^GS2\.\d+\.s(\d+)/.exec(e);if(t)return t[1];const r=/^GS1\.\d+\.(\d+)\./.exec(e);return r?r[1]:void 0}function hs(e){const t={},r=(e,r)=>{r&&(t[`bb_${e}`]=r.slice(0,400))};if("undefined"==typeof window||"undefined"==typeof document)return t;const n=us();r("fbp",n._fbp),r("fbc",n._fbc),r("ga_cid",ps(n._ga));const s=Object.keys(n).find(e=>e.startsWith("_ga_"));r("ga_sid",s?ms(n[s]):void 0);try{"undefined"!=typeof navigator&&r("ua",navigator.userAgent),"undefined"!=typeof window&&window.location?.origin&&r("url",window.location.origin+window.location.pathname)}catch{}r("consent",function(e){if(!e)return;const t=[e.analytics&&"analytics",e.marketing&&"marketing"].filter(Boolean);return t.length?t.join(","):"none"}(e));try{const e=window.__buildbase?.tracking;r("client",e?.clientId)}catch{}return t}function gs(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}const fs=new Set(["workspace_id","workspace_role","workspace_owner","workspace_member_count","workspace_plan","subscription_status"]);function ys(e){const t={};if(!e)return t;for(const[r,n]of Object.entries(e)){if(Object.keys(t).length>=10)break;if(null==n)continue;if(fs.has(r))continue;const e=typeof n;"string"!==e&&"number"!==e&&"boolean"!==e||/^[a-z][a-z0-9_]{0,39}$/.test(r)&&(t[`bbp_${r}`]=String(n).slice(0,200))}return t}function bs(...e){const t=Math.max(0,...e.map(e=>e?Object.keys(e).length:0));return Math.max(0,Math.min(30,40-t))}function ws(e,t,r,n=30){const s={bb_event_id:e,...hs(t),...ys(r)};for(const[e,t]of Object.entries(function(){const e=Bn();return e?Vn(e.document):{}}())){if(Object.keys(s).length>=30)break;"string"==typeof t&&t&&(s[`bb_${e}`]=t)}const a=Math.max(0,Math.min(n,30));return Object.fromEntries(Object.entries(s).slice(0,a))}const vs={gtm:{title:"Google Tag Manager",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Container ID",idPattern:"^GTM-[A-Z0-9]{4,10}$",idExample:"GTM-ABC1234",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},ga4:{title:"Google Analytics 4",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Measurement ID",idPattern:"^G-[A-Z0-9]{8,12}$",idExample:"G-ABCD123456",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"analytics",supportsConsentMode:!0,needsConversionIds:!1},google_ads:{title:"Google Ads",vendor:"Google LLC",privacyUrl:"https://policies.google.com/privacy",idLabel:"Conversion ID",idPattern:"^AW-[0-9]{9,12}$",idExample:"AW-123456789",scriptOrigin:"https://www.googletagmanager.com",defaultConsentCategory:"marketing",supportsConsentMode:!0,needsConversionIds:!0},meta_pixel:{title:"Meta Pixel",vendor:"Meta Platforms Ireland Limited",privacyUrl:"https://www.facebook.com/privacy/policy",idLabel:"Pixel ID",idPattern:"^[0-9]{15,16}$",idExample:"123456789012345",scriptOrigin:"https://connect.facebook.net",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},x_pixel:{title:"X (Twitter) Pixel",vendor:"X Corp.",privacyUrl:"https://x.com/en/privacy",idLabel:"Pixel ID",idPattern:"^o[a-z0-9]{4,6}$",idExample:"o1a2b3",scriptOrigin:"https://static.ads-twitter.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},linkedin:{title:"LinkedIn Insight Tag",vendor:"LinkedIn Ireland Unlimited Company",privacyUrl:"https://www.linkedin.com/legal/privacy-policy",idLabel:"Partner ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://snap.licdn.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!0,multiInstance:!0},tiktok:{title:"TikTok Pixel",vendor:"TikTok Information Technologies UK Limited",privacyUrl:"https://www.tiktok.com/legal/privacy-policy",idLabel:"Pixel ID",idPattern:"^[A-Z0-9]{20}$",idExample:"C4A1B2C3D4E5F6G7H8I9",scriptOrigin:"https://analytics.tiktok.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},reddit:{title:"Reddit Pixel",vendor:"Reddit, Inc.",privacyUrl:"https://www.reddit.com/policies/privacy-policy",idLabel:"Advertiser ID",idPattern:"^t2_[a-z0-9]{4,12}$",idExample:"t2_abc123",scriptOrigin:"https://www.redditstatic.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},bing_uet:{title:"Microsoft Advertising (UET)",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Tag ID",idPattern:"^[0-9]{7,9}$",idExample:"12345678",scriptOrigin:"https://bat.bing.com",defaultConsentCategory:"marketing",supportsConsentMode:!1,needsConversionIds:!1,multiInstance:!0},clarity:{title:"Microsoft Clarity",vendor:"Microsoft Corporation",privacyUrl:"https://privacy.microsoft.com/en-us/privacystatement",idLabel:"Project ID",idPattern:"^[a-z0-9]{10}$",idExample:"ab12cd34ef",scriptOrigin:"https://www.clarity.ms",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},hotjar:{title:"Hotjar",vendor:"Hotjar Limited",privacyUrl:"https://www.hotjar.com/legal/policies/privacy/",idLabel:"Site ID",idPattern:"^[0-9]{6,9}$",idExample:"1234567",scriptOrigin:"https://static.hotjar.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},posthog:{title:"PostHog",vendor:"PostHog, Inc.",privacyUrl:"https://posthog.com/privacy",idLabel:"Project API key",idPattern:"^phc_[A-Za-z0-9]{32,48}$",idExample:"phc_abcdefghijklmnopqrstuvwxyz012345",scriptOrigin:"https://us-assets.i.posthog.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1,hosts:["us.i.posthog.com","eu.i.posthog.com"]},plausible:{title:"Plausible Analytics",vendor:"Plausible Insights OÜ",privacyUrl:"https://plausible.io/privacy",idLabel:"Domain",idPattern:"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$",idExample:"example.com",scriptOrigin:"https://plausible.io",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1},ahrefs:{title:"Ahrefs Analytics",vendor:"Ahrefs Pte. Ltd.",privacyUrl:"https://ahrefs.com/privacy",idLabel:"Analytics key",idPattern:"^[A-Za-z0-9+/=]{20,64}$",idExample:"AbCdEfGhIjKlMnOpQrStUv==",scriptOrigin:"https://analytics.ahrefs.com",defaultConsentCategory:"analytics",supportsConsentMode:!1,needsConversionIds:!1}},ks=Object.keys(vs);function Ss(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(vs,e)}function Cs(e,t){return!!Ss(e)&&("string"==typeof t&&0!==t.length&&new RegExp(vs[e].idPattern).test(t))}const xs=/^[a-z][a-z0-9-]{0,40}$/,Ns=/^[\w.:/@+=-]{1,200}$/;function Ps(e){return function(e){if("string"!=typeof e)return!1;if(0===e.length||e.length>300)return!1;let t;try{t=new URL(e)}catch{return!1}return!("https:"!==t.protocol||!t.hostname||!t.hostname.includes(".")||e.includes("?")||e.includes("#")||t.username||t.password)}(e.src)&&function(e){if(null==e)return!0;if("object"!=typeof e||Array.isArray(e))return!1;const t=Object.entries(e);return!(t.length>12)&&t.every(([e,t])=>xs.test(e)&&"string"==typeof t&&Ns.test(t))}(e.dataAttributes)}Array.from(new Set(ks.map(e=>vs[e].scriptOrigin))).sort();const Is={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},_s=Object.keys(Is);function Es(e){return _s.includes(e)}function Us(){return"undefined"==typeof window?null:window}const As={gtm:"dataLayer",ga4:"gtag",google_ads:"gtag",meta_pixel:"fbq",x_pixel:"twq",linkedin:"lintrk",tiktok:"ttq",reddit:"rdt",bing_uet:"uetq",clarity:"clarity",hotjar:"hj",posthog:"posthog",plausible:"plausible",ahrefs:"__ahrefs_loaded"};function Ts(){return"undefined"==typeof window?null:window}function Os(e,t={}){const r=Ts();if(!r)return null;const n=r.document.createElement("script");n.async=!0,n.src=e;for(const[e,r]of Object.entries(t))n.setAttribute(e,r);return r.document.head.appendChild(n),n}function Rs(e){const t=Ts();if(!t)return;const r=t.document.createElement("script");r.text=e,t.document.head.appendChild(r)}function Ws(e){const t=Ts();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const $s=new Set;function Fs(e){for(const t of $s)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function Ls(e,t){const r=Ts();if(!r)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=r.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const n=As[e];if(!n)return!1;if(void 0===r[n])return!1;if($s.has(`${e}:${t}`))return!0;return!vs[e].multiInstance||!Fs(e)}const Ds={meta_pixel:e=>`fbq('init','${e}');fbq('track','PageView');`,x_pixel:e=>`twq('config','${e}');`,tiktok:e=>`ttq.load('${e}');ttq.page();`,reddit:e=>`rdt('init','${e}');rdt('track','PageVisit');`,bing_uet:e=>`window.uetq=window.uetq||[];window.uetq.push({ti:'${e}',enableAutoSpaTracking:false});`,linkedin:e=>`window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${e}');`};function js(e,t,r){const n=function(e,t,r){const n=Ts();if(!n)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[r,n]of Object.entries(e.dataAttributes??{}))t[`data-${r}`]=n;return Os(e.src,t),!0}const s=e.provider,a=vs[s];if(!a)return!1;const i=e.providerId;if(!i)return!1;const o=Ds[s];if(o&&Fs(s))return Rs(o(i)),!0;switch(s){case"gtm":{Ws(t),n[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return Os(`${a.scriptOrigin}/gtm.js?id=${i}${e}`),!0}case"ga4":case"google_ads":{Ws(t),Os(`${a.scriptOrigin}/gtag/js?id=${i}`);const e=n.gtag;e("js",new Date);const o="ga4"===s&&r?.gaClientId?{client_id:r.gaClientId}:void 0;return o?e("config",i,o):e("config",i),!0}case"meta_pixel":return Rs(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${a.scriptOrigin}/en_US/fbevents.js');fbq('init','${i}');fbq('track','PageView');`),!0;case"x_pixel":return Rs(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${a.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${i}');`),!0;case"linkedin":return Rs(`window._linkedin_partner_id='${i}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${i}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),Os(`${a.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return Rs(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${a.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${i}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return Rs(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${a.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${i}');rdt('track','PageVisit');`),!0;case"bing_uet":return Rs(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${i}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${a.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return Rs(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${a.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${i}');`),!0;case"hotjar":return Rs(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${i},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${a.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=a.hosts,r=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return Rs(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${a.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${i}',{api_host:'https://${r}'});`),!0}case"plausible":return Rs("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),Os(`${a.scriptOrigin}/js/script.js`,{"data-domain":i,defer:"true"}),!0;case"ahrefs":return Os(`${a.scriptOrigin}/analytics.js`,{"data-key":i}),n.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,r);return n&&"external"!==e.provider&&e.providerId&&$s.add(`${e.provider}:${e.providerId}`),n}const Ms=Symbol.for("@buildbase/sdk.tracking.context"),qs=globalThis,Bs=qs[Ms]??(qs[Ms]=c(null)),zs={consent:{manifest:[],state:null,set:()=>{}},track:()=>{},setUser:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function Vs(){return d(Bs)??zs}function Gs(){return null!==d(Bs)}const Js=({serverUrl:e,orgId:r,clientId:n,enabled:s=!0,consent:a="auto",autoPageview:o=!0,events:c,onEvent:d,properties:h,enrich:g,identity:f,debug:y=!1,children:b})=>{const w=l(f);w.current=f;const[v,k]=m(null),[S,C]=m(!1),[x,N]=m(!1),P="granted"===a?{analytics:!0,marketing:!0}:"denied"===a?{analytics:!1,marketing:!1}:null,[I,_]=m(P),E=l(null),U=l(d);U.current=d;const A=l(g);A.current=g;const T=l({});T.current=h??{};const O=l({}),R=p(()=>({...T.current,...O.current}),[]),W=p(e=>{const t={...O.current,...e};for(const[e,r]of Object.entries(t))void 0===r&&delete t[e];O.current=t},[]),[$,F]=m({}),L=l({}),[D,j]=m(0),M=v?.dataLayerName??"dataLayer",q=p((...e)=>{y&&console.info("[buildbase:tracking]",...e)},[y]);u(()=>{return e=()=>{0!==Object.keys(L.current).length&&window.dispatchEvent("function"==typeof PageTransitionEvent?new PageTransitionEvent("pagehide",{persisted:!1}):new Event("pagehide"))},gt.add(e),()=>{gt.delete(e)};var e},[]),u(()=>{if(!(s&&e&&r&&n))return void C(!0);let t=!1;const a=`${e.replace(/\/$/,"")}/api/v1/public/${r}/tracking?clientId=${encodeURIComponent(n)}`;return fetch(a).then(e=>e.ok?e.json():null).then(e=>{if(t||!e)return;const r=e.data??e;r&&Array.isArray(r.scripts)&&k(r)}).catch(()=>{q("config fetch failed; nothing installed")}).finally(()=>{t||C(!0)}),()=>{t=!0}},[s,e,r,n,q]),u(()=>{s&&F(Gn())},[s]),u(()=>{s&&v?.enabled&&(Ws(M),function(e,t){const r=ls();if(!r)return;Array.isArray(r[e])||(r[e]=[]),"function"!=typeof r.gtag&&(r.gtag=function(){r[e].push(arguments)});const n="granted"===t?"granted":"denied";r.gtag("consent","default",{ad_storage:n,ad_user_data:n,ad_personalization:n,analytics_storage:n,wait_for_update:500})}(M,a),E.current&&ds(E.current))},[s,v?.enabled,M,a]);const B=i(()=>v?.enabled?v.scripts.filter(e=>{const t=Ss(e.provider)&&vs[e.provider].supportsConsentMode;return function(e,t,r,n){return"denied"!==n&&("granted"===n||(r?"marketing"===e?r.marketing:r.analytics:t&&"analytics"===e))}(e.consentCategory,t,I,a)}):[],[v,I,a]),[z,V]=m(()=>"undefined"==typeof window||!Jn(window.location.search));u(()=>{if(z)return;const e=setInterval(()=>{Jn(window.location.search)||V(!0)},50),t=setTimeout(()=>V(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[z]),u(()=>{if(!z)return;if(!s||!v?.enabled)return void(S&&N(!0));let e=0;for(const t of B)if(!L.current[t.key]){if("external"===t.provider){if(!Ps({src:t.src,dataAttributes:t.dataAttributes})){q("rejected external script",t.key);continue}}else{if(!Ss(t.provider)){q("rejected unknown provider",t.provider);continue}if(!Cs(t.provider,t.providerId)){q("rejected id for",t.provider);continue}if(Ls(t.provider,t.providerId??"")){q(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}js(t,M,w.current)&&(L.current[t.key]=t.providerId??t.src??"",e+=1,q("installed",t.key))}e&&j(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...L.current},dataLayerName:M,clientId:n};const r=Object.keys(L.current).length>0,a=null!==I||0===v.scripts.length;(r||a)&&N(!0)},[s,v,B,S,I,M,q,z,n]),u(()=>{if(!s||!o||!v?.enabled)return;if("undefined"==typeof window)return;if(!z)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const r=Us();if(!r)return;const n=r[t];Array.isArray(n)&&n.push({event:"page_view",page_path:r.location.pathname,page_location:r.location.href,page_title:r.document.title});for(const t of e)switch(t.provider){case"ga4":r.gtag?.("event","page_view",{send_to:t.providerId,page_path:r.location.pathname,page_location:r.location.href,page_title:r.document.title});break;case"meta_pixel":r.fbq?.("track","PageView");break;case"tiktok":{const e=r.ttq;e?.page?.();break}case"reddit":r.rdt?.("track","PageVisit")}}(B,M),50)},r=window.history,n=r.pushState,a=r.replaceState;return r.pushState=function(...e){const r=n.apply(this,e);return t(),r},r.replaceState=function(...e){const r=a.apply(this,e);return t(),r},window.addEventListener("popstate",t),()=>{r.pushState=n,r.replaceState=a,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[s,o,v?.enabled,B,M,z]),u(()=>{if(!s)return;const e=function(e,t){const r=e?.mode??"auto",n=e?.overrides??{};if(("manual"===r||Object.values(n).some(e=>"manual"===e))&&!t)return'[buildbase:tracking] events are set to "manual" but no onEvent handler was provided, so those events would never fire anywhere. Pass onEvent, or use mode "auto".';for(const e of Object.keys(n))if(!Es(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(c,!!d);if(e)throw new Error(e)},[s,c,d]);const G=p((e,t={},r)=>{if(!s)return;const n=r?.eventId||gs(),a=c?.mode??"auto",i=(Es(e)?c?.overrides?.[e]:void 0)??a,o={...T.current,...O.current,...$,...t},l=A.current?.({name:e,params:o})??{},d={...o,...l},u=U.current?.({name:e,params:d,eventId:n,handledBy:i});"manual"!==i&&!0!==u?(!function(e,t,r,n,s){const a=Us();if(!a)return;const i=a[s];Array.isArray(i)&&i.push({event:e,...t,event_id:r});const o=Es(e)?Is[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const s of n){const n=s.provider,i=vs[n];if(i){if(i.needsConversionIds){const i=s.conversionIds?.[e];if(!i)continue;"google_ads"===n?a.gtag?.("event","conversion",{send_to:`${s.providerId}/${i}`,transaction_id:r,...t}):"x_pixel"===n?a.twq?.("event",i,{...t,conversion_id:r}):"linkedin"===n&&a.lintrk?.("track",{conversion_id:i});continue}switch(n){case"ga4":o.ga4&&a.gtag?.("event",o.ga4,{...t,send_to:s.providerId,event_id:r});break;case"meta_pixel":o.meta&&a.fbq?.("track",o.meta,t,{eventID:r});break;case"tiktok":if(o.tiktok){const e=a.ttq;e?.track?.(o.tiktok,{...t,event_id:r})}break;case"reddit":o.reddit&&a.rdt?.("track",o.reddit,{...t,conversionId:r});break;case"bing_uet":{const n=a.uetq;n?.push?.("event",o.ga4??e,{...t,event_id:r});break}case"clarity":a.clarity?.("event",e);break;case"hotjar":{const t=a.hj;t?.("event",e);break}case"posthog":{const n=a.posthog;n?.capture?.(e,{...t,event_id:r});break}case"plausible":a.plausible?.(e,{props:t})}}}}(e,d,n,B,M),q("event fired:",e,n)):q("event handled by app:",e)},[s,c,B,M,$,q]),J=p(async(t,n={})=>{const s=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(t);let a=s.params;if(t.sessionId&&e&&r){const n=await async function(e,t){try{const r=e.serverUrl.replace(/\/$/,""),n=await fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!n.ok)return null;const s=await n.json(),a=s?.data??s;return"number"!=typeof a?.amount?null:{value:cs(a.amount,a.currency),currency:"string"==typeof a.currency?a.currency:void 0,...Array.isArray(a.items)&&a.items.length?{items:a.items}:{}}}catch{return null}}({serverUrl:e,orgId:r},t.sessionId);n&&"number"==typeof n.value&&(a={...a,value:n.value,...n.currency?{currency:n.currency.toUpperCase()}:{},...n.items?.length?{items:n.items}:{}})}if(G(s.name,{...a,...n},{eventId:t.eventId}),"purchase"===s.name&&t.sessionId&&e&&r){const n=(v?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);n&&Ls("ga4",n.providerId??"")&&function(e,t,r){try{const n=e.serverUrl.replace(/\/$/,"");fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:e,orgId:r},t.sessionId,"ga4")}},[e,r,G,v]),[K]=m(()=>"undefined"==typeof window?"":window.location.search);u(()=>{if(!s||!x)return;if("undefined"==typeof window)return;const e=ss(window.location.search);if(e)return void J(e);const t=as(K);t&&G("checkout_abandoned",{...t.workspaceId?{workspace_id:t.workspaceId}:{},...t.planVersionId?{plan_version_id:t.planVersionId}:{},...t.creditPackageId?{credit_package_id:t.creditPackageId}:{},...t.billingInterval?{billing_interval:t.billingInterval}:{},...t.currency?{currency:t.currency.toUpperCase()}:{},..."number"==typeof t.value?{value:t.value}:{},seconds_at_checkout:Math.max(0,Math.round((Date.now()-t.startedAt)/1e3))})},[s,x,J,K,G]);const H=p(e=>{E.current=e,_(e),ds(e)},[]),Y=p((e,t)=>function(e,t,r){const n=Us();if(!n)return;const s=!!r&&Object.keys(r).length>0;for(const a of t)switch(a.provider){case"ga4":case"google_ads":n.gtag?.("set",{user_id:e}),s&&n.gtag?.("set",{user_properties:r});break;case"meta_pixel":a.providerId&&n.fbq?.("init",a.providerId,{external_id:e});break;case"posthog":n.posthog?.identify?.(e,s?r:void 0);break;case"clarity":if(n.clarity?.("identify",e),s)for(const[e,t]of Object.entries(r))n.clarity?.("set",e,String(t));break;case"hotjar":n.hj?.("identify",e,{});break;case"tiktok":{const t=n.ttq;t?.identify?.({external_id:e});break}}}(e,B,t),[B]),Q=i(()=>({consent:{manifest:v?.consent?.manifest??[],state:I,set:H},track:G,setUser:Y,setProperties:W,getProperties:R,completeCheckout:J,installed:{...L.current},ready:x,attribution:$}),[v,I,H,G,Y,W,R,J,x,D,$]);return t(Bs.Provider,{value:Q,children:b})};function Ks(){const e=Vr(),t=tn(),r=vn();return i(()=>({auth:e,os:t,workspaces:r}),[e,t,r])}function Hs(e,t){const r=rn(),n=Gr(),s=kn(),a=p(e=>{const t=[r.subscribe(e),n.subscribe(e),s.subscribe(e)];return()=>t.forEach(e=>e())},[r,n,s]);return Fr(i(()=>{let e=null;return()=>(null!==e&&e.os===r.getState()&&e.auth===n.getState()&&e.workspaces===s.getState()||(e={os:r.getState(),auth:n.getState(),workspaces:s.getState()}),e)},[r,n,s]),a,e,t)}function Ys(e,t,r){u(()=>{const t=new AbortController;return e(t.signal).catch(e=>{oe(e)||(r?.onError?r.onError(e):pe(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},t)}function Qs(){return Hs(e=>e.os)}Js.displayName="BuildBaseTracking";const Zs=new Map;let Xs=null;function ea(){const e=Ks(),t=Qs(),{serverUrl:r,version:n,orgId:s,settings:a,settingsStatus:o,settingsError:c}=t,l=i(()=>ze(t)?new je({serverUrl:r,version:n,orgId:s}):null,[r,n,s]),d=p(async t=>{if(!l)return null;const a=((e,t,r)=>`${e}|${t}|${r}`)(r,n,s);Xs=a;const i=Zs.get(a);if(i)return i;const o=(async()=>{e.os(Hr("loading"));try{const t=await l.getSettings();return Xs===a&&e.os(Kr(t)),t}catch(t){return Xs===a&&e.os(Hr("error",t instanceof Error?t.message:"Failed to load settings")),me(t,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:r,version:n,orgId:s}}),null}finally{Zs.delete(a)}})();return Zs.set(a,o),o},[l,e,r,n,s]);Ys(async()=>{a||ze(t)&&await d()},[r,n,s],{onError:e=>me(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:r,version:n,orgId:s}})});const u="loading"===o||("idle"===o||void 0===o)&&ze(t);return i(()=>({settings:a,loading:u,error:c??null,refetch:d,getSettings:d}),[a,u,c,d])}function ta(){const e=Qs(),t=Ks(),r=p(()=>{Ce(),t.auth($r()),e.auth?.callbacks?.onSessionExpired?.("expired")},[t,e.auth?.callbacks?.onSessionExpired]),n=function(e,t){return i(()=>new qe({...e,onUnauthorized:t}),[e.serverUrl,e.version,e.orgId,t])}(e,r);return i(()=>({os:e,api:n}),[e,n])}const ra=e=>{const{t:t}=Ln(),{os:r,api:n}=ta(),s=ze(r),[a,i]=m(null),[o,c]=m(!1),[l,d]=m(null),[h,g]=m(null),{begin:f,settle:y}=Dn(),b=p(async()=>{if(!e||!s)return f(),i(null),g(null),void c(!1);const r=f();c(!0),d(null);try{const t=await n.getPublicPlans(e);if(r.signal.aborted)return;i(t),g(e)}catch(n){if(r.signal.aborted)return;g(e);const s=he(n,"errors.fetchPlans",t);d(s),pe(n,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{y(r)&&c(!1)}},[n,e,s,f,y]);u(()=>{b()},[b]);const w=!(!e||s&&h===e),v=w||o;return{items:w?[]:a?.items??[],plans:w?[]:a?.plans??[],notes:w?void 0:a?.notes,loading:v,error:l,refetch:b}},na=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(null),[a,i]=m(!1),[o,c]=m(null),{begin:l,settle:d}=Dn(),h=p(async()=>{if(!e)return l(),s(null),void i(!1);const n=l();i(!0),c(null);try{const t=await r.getPlanGroupVersion(e);if(n.signal.aborted)return;s(t)}catch(r){if(n.signal.aborted)return;const s=he(r,"errors.fetchPlanGroupVersion",t);c(s),pe(r,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{d(n)&&i(!1)}},[r,e,l,d]);return u(()=>{h()},[h]),{planGroupVersion:n,loading:a,error:o,refetch:h}},sa=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(null),[a,i]=m(!1),[o,c]=m(null),[l,d]=m(null),{begin:h,settle:g}=Dn(),f=p(async()=>{if(!e)return h(),s(null),d(null),void i(!1);const n=h();i(!0),c(null);try{const t=await r.getCurrentSubscription(e);if(n.signal.aborted)return;s(t),d(e)}catch(r){if(n.signal.aborted)return;d(e);const s=he(r,"errors.fetchSubscription",t);c(s),pe(r,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{g(n)&&i(!1)}},[r,e,h,g]);u(()=>{f()},[f]);const y=!!e&&l!==e;return{subscription:y?null:n,loading:a||y,error:o,refetch:f}},aa=(e,t)=>{const{t:r}=Ln(),{api:n}=ta(),[s,a]=m(null),[i,o]=m(!1),[c,l]=m(null),{begin:d,settle:h}=Dn(),g=p(async()=>{if(!e)return d(),a(null),void o(!1);const s=d();o(!0),l(null);try{const r=t?await n.getPlanGroupByVersion(e,t):await n.getPlanGroup(e);if(s.signal.aborted)return;a(r)}catch(n){if(s.signal.aborted)return;const a=he(n,"errors.fetchPlanGroup",r);l(a),pe(n,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:t}})}finally{h(s)&&o(!1)}},[n,e,t,d,h]);return u(()=>{g()},[g]),{planGroup:s,loading:i,error:c,refetch:g}},ia=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(null),[a,i]=m(!1),[o,c]=m(null),{begin:l,settle:d}=Dn(),h=p(async()=>{if(!e)return l(),s(null),void i(!1);const n=l();i(!0),c(null);try{const t=await r.getPlanGroupVersions(e);if(n.signal.aborted)return;s(t)}catch(r){if(n.signal.aborted)return;const s=he(r,"errors.fetchPlanGroupVersions",t);c(s),pe(r,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{d(n)&&i(!1)}},[r,e,l,d]);return u(()=>{h()},[h]),{versions:n,loading:a,error:o,refetch:h}},oa=e=>{const{t:t}=Ln(),{api:r}=ta(),{getCheckoutStripeParams:n}=d(Cn),{track:s,consent:a,getProperties:i}=Vs(),o=Gs(),[c,l]=m(!1),[u,h]=m(null);return{createCheckoutSession:p(async c=>{if(!e)throw new Error("Workspace ID is required");l(!0),h(null);const d=gs();try{const t=n?await n(c):void 0,l=o?ws(d,a.state,i(),bs({...c.stripeOptions?.metadata,...t?.metadata},{...c.stripeOptions?.subscriptionMetadata,...t?.subscriptionMetadata})):{},u=Object.keys(l).length>0||t?{...c,stripeOptions:{...c.stripeOptions,...t,metadata:{...l,...c.stripeOptions?.metadata,...t?.metadata},subscriptionMetadata:{...l,...c.stripeOptions?.subscriptionMetadata,...t?.subscriptionMetadata}}}:c,p=await r.createCheckoutSession(e,u),m="checkout"!==p.type&&p.type?void 0:p,h=m?.currency??c.currency,g=cs(m?.amountTotal,h);return m&&o&&Qn({eventId:d,workspaceId:e,planVersionId:c.planVersionId,billingInterval:c.billingInterval,currency:h,sessionId:m.sessionId,value:g,kind:m.trial?"trial_started":"purchase",startedAt:Date.now()}),s("trial_started"===p.type?"trial_started":"checkout_started",{plan_version_id:c.planVersionId,...c.billingInterval?{billing_interval:c.billingInterval}:{},...h?{currency:h.toUpperCase()}:{},..."number"==typeof g?{value:g}:{}},{eventId:d}),"trial_started"===p.type&&(nt(),et()),p}catch(r){const n=he(r,"errors.createCheckout",t);throw h(n),pe(r,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:c}}),r}finally{l(!1)}},[r,e,n,s,t,a.state,o]),loading:c,error:u}},ca=e=>{const{t:t}=Ln(),{api:r}=ta(),{track:n}=Vs(),s=Gs(),[a,i]=m(!1),[o,c]=m(null);return{updateSubscription:p(async(a,o)=>{if(!e)throw new Error("Workspace ID is required");i(!0),c(null);try{const t={planVersionId:a,...o?.billingInterval&&{billingInterval:o.billingInterval},...o?.successUrl&&{successUrl:o.successUrl},...o?.cancelUrl&&{cancelUrl:o.cancelUrl}},i=gs(),c=await r.updateSubscription(e,t),l="checkoutUrl"in c&&c.checkoutUrl?c:null;if(l){const t=l.currency,r=cs(l.amountTotal,t);s&&Qn({eventId:i,workspaceId:e,planVersionId:a,billingInterval:o?.billingInterval,currency:t,sessionId:l.sessionId,value:r,kind:l.trial?"trial_started":"purchase",startedAt:Date.now()}),n("checkout_started",{plan_version_id:a,...o?.billingInterval?{billing_interval:o.billingInterval}:{},...t?{currency:t.toUpperCase()}:{},..."number"==typeof r?{value:r}:{}},{eventId:i})}else{const e=c,t=e.invoice?.amount_due;n("subscription_upgraded",{plan_version_id:a,...o?.billingInterval?{billing_interval:o.billingInterval}:{},..."number"==typeof t&&t>0?{value:cs(t,void 0)}:{}},{eventId:i})}return nt(),c}catch(r){const n=he(r,"errors.updateSubscription",t);throw c(n),pe(r,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:a,options:o}}),r}finally{i(!1)}},[r,e,n,s]),loading:a,error:o}},la=(e,t)=>{const r=sa(e),n=aa(e,t),s=ca(e),a=p(async()=>{await Promise.all([r.refetch(),n.refetch()])},[r.refetch,n.refetch]);return{subscription:r.subscription,planGroup:n.planGroup,loading:r.loading||n.loading||s.loading,error:r.error||n.error||s.error,updateSubscription:s.updateSubscription,refetch:a}},da=(e,t=10,r)=>{const{t:n}=Ln(),{api:s}=ta(),[a,i]=m([]),[o,c]=m(!1),[l,d]=m(!1),[h,g]=m(null),{begin:f,settle:y}=Dn(),b=p(async()=>{if(!e)return f(),i([]),c(!1),void d(!1);const a=f();d(!0),g(null);try{const n=await s.listInvoices(e,t,r);if(a.signal.aborted)return;i(n.invoices||[]),c(n.has_more||!1)}catch(s){if(a.signal.aborted)return;const i=he(s,"errors.fetchInvoices",n);g(i),pe(s,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:t,startingAfter:r}})}finally{y(a)&&d(!1)}},[s,e,t,r,f,y]);return u(()=>{b()},[b]),{invoices:a,hasMore:o,loading:l,error:h,refetch:b}},ua=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(!1),[a,i]=m(null);return{openBillingPortal:p(async n=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const t=n||window.location.href,s=await r.createBillingPortalSession(e,t);return s.url&&window.open(s.url,"_blank","noopener,noreferrer"),s}catch(r){const n=he(r,"errors.openBillingPortal",t);throw i(n),pe(r,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),r}finally{s(!1)}},[e,r]),loading:n,error:a}},pa=(e,t)=>{const{t:r}=Ln(),{api:n}=ta(),[s,a]=m(null),[i,o]=m(!1),[c,l]=m(null),{begin:d,settle:h}=Dn(),g=p(async()=>{if(!e||!t)return d(),a(null),void o(!1);const s=d();o(!0),l(null);try{const r=await n.getInvoice(e,t);if(s.signal.aborted)return;a(r.invoice)}catch(n){if(s.signal.aborted)return;const a=he(n,"errors.fetchInvoice",r);l(a),pe(n,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:t}})}finally{h(s)&&o(!1)}},[n,e,t,d,h]);return u(()=>{g()},[g]),{invoice:s,loading:i,error:c,refetch:g}},ma=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(!1),[a,i]=m(null);return{cancelSubscription:p(async()=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const t=await r.cancelSubscriptionAtPeriodEnd(e);return nt(),t}catch(r){const n=he(r,"errors.cancelSubscription",t);throw i(n),pe(r,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),r}finally{s(!1)}},[r,e]),loading:n,error:a}},ha=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(!1),[a,i]=m(null);return{resumeSubscription:p(async()=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const t=await r.resumeSubscription(e);return nt(),t}catch(r){const n=he(r,"errors.resumeSubscription",t);throw i(n),pe(r,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),r}finally{s(!1)}},[r,e]),loading:n,error:a}},ga=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(!1),[a,i]=m(null);return{recordUsage:p(async n=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const t=await r.recordUsage(e,n);return et(),t}catch(r){const s=he(r,"errors.recordUsage",t);throw i(s),pe(r,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:n}}),r}finally{s(!1)}},[r,e]),loading:n,error:a}},fa=(e,t)=>{const{t:r}=Ln(),{api:n}=ta(),[s,a]=m(null),[i,o]=m(!1),[c,l]=m(null),{begin:d,settle:h}=Dn(),g=p(async()=>{if(!e||!t)return d(),a(null),void o(!1);const s=d();o(!0),l(null);try{const r=await n.getQuotaUsageStatus(e,t);if(s.signal.aborted)return;a(r)}catch(n){if(s.signal.aborted)return;const a=he(n,"errors.fetchQuotaUsage",r);l(a),pe(n,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:t}})}finally{h(s)&&o(!1)}},[n,e,t,d,h]);return u(()=>{g()},[g]),{status:s,loading:i,error:c,refetch:g}},ya=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(null),[a,i]=m(!1),[o,c]=m(null),[l,d]=m(null),{begin:h,settle:g}=Dn(),f=p(async()=>{if(!e)return h(),s(null),d(null),void i(!1);const n=h();i(!0),c(null);try{const t=await r.getAllQuotaUsage(e);if(n.signal.aborted)return;s(t.quotas),d(e)}catch(r){if(n.signal.aborted)return;d(e);const s=he(r,"errors.fetchAllQuotaUsage",t);c(s),pe(r,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{g(n)&&i(!1)}},[r,e,h,g]);u(()=>{f()},[f]);const y=!!e&&l!==e;return{quotas:y?null:n,loading:a||y,error:o,refetch:f}},ba=(e,t,r)=>{const{t:n}=Ln(),{api:s}=ta(),[a,i]=m([]),[o,c]=m(0),[l,d]=m(0),[h,g]=m(1),[f,y]=m(!1),[b,w]=m(!1),[v,k]=m(!1),[S,C]=m(null),{begin:x,settle:N}=Dn(),P=r?.from,I=r?.to,_=r?.source,E=r?.page,U=r?.limit,A=p(async()=>{if(!e)return x(),i([]),c(0),d(0),g(1),y(!1),w(!1),void k(!1);const r=x();k(!0),C(null);try{const n={...t&&{quotaSlug:t},...P&&{from:P},...I&&{to:I},..._&&{source:_},...E&&{page:E},...U&&{limit:U}},a=await s.getUsageLogs(e,n);if(r.signal.aborted)return;i(a.docs||[]),c(a.totalDocs||0),d(a.totalPages||0),g(a.page||1),y(a.hasNextPage||!1),w(a.hasPrevPage||!1)}catch(s){if(r.signal.aborted)return;const a=he(s,"errors.fetchUsageLogs",n);C(a),pe(s,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:t}})}finally{N(r)&&k(!1)}},[s,e,t,P,I,_,E,U,x,N]);return u(()=>{A()},[A]),{logs:a,totalDocs:o,totalPages:l,page:h,hasNextPage:f,hasPrevPage:b,loading:v,error:S,refetch:A}},wa=c(null);wa.displayName="SubscriptionContext";const va=s.memo(function({children:e}){const r=Hs(e=>e.workspaces.currentWorkspace),{subscription:n,loading:s,error:a,refetch:o}=sa(r?._id);u(()=>rt(o),[o]);const c=i(()=>({response:n,loading:s,error:a,refetch:o}),[n,s,a,o]);return t(wa.Provider,{value:c,children:e})});function ka(){const e=d(wa);if(null===e)throw new Error("useSubscriptionContext must be used within SubscriptionContextProvider. Make sure SubscriptionContextProvider is wrapping your application (or the tree that uses subscription gates).");return e}va.displayName="SubscriptionContextProvider";const Sa=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(null),[a,i]=m(!1),[o,c]=m(null),{begin:l,settle:d}=Dn(),h=p(async()=>{if(!e)return l(),s(null),void i(!1);const n=l();i(!0),c(null);try{const t=await r.getCreditBalance(e);if(n.signal.aborted)return;s(t)}catch(r){if(n.signal.aborted)return;const s=he(r,"errors.fetchCreditBalance",t);c(s),pe(r,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{d(n)&&i(!1)}},[r,e,l,d]);return u(()=>{h()},[h]),{balance:n,loading:a,error:o,refetch:h}},Ca=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m(!1),[a,i]=m(null);return{consumeCredits:p(async n=>{if(!e)throw new Error("Workspace ID is required");s(!0),i(null);try{const t=await r.consumeCredits(e,n);return Qe(),t}catch(r){const s="INSUFFICIENT_CREDITS"===r.code?t("credits.insufficientDetail",{available:r.available,requested:r.requested}):he(r,"errors.consumeCredits",t);throw i(s),pe(r,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:n}}),r}finally{s(!1)}},[r,e]),loading:n,error:a}},xa=e=>{const{t:t}=Ln(),{api:r}=ta(),{track:n,consent:s,getProperties:a}=Vs(),i=Gs(),[o,c]=m(!1),[l,d]=m(null);return{purchaseCredits:p(async o=>{if(!e)throw new Error("Workspace ID is required");c(!0),d(null);const l=gs(),u=i?ws(l,s.state,a(),Math.min(bs(o.metadata),20-Object.keys(o.metadata??{}).length)):{},p=Object.keys(u).length>0?{...o,metadata:{...u,...o.metadata}}:o;try{let t;try{t=await r.purchaseCredits(e,p)}catch(n){const s=n?.status;if(p===o||o.metadata||400!==s)throw n;t=await r.purchaseCredits(e,o)}const s=t.currency??o.currency,a=cs(t.amountTotal,s);return i&&Qn({eventId:l,workspaceId:e,creditPackageId:o.creditPackageId,currency:s,sessionId:t.sessionId,value:a,kind:"purchase",startedAt:Date.now()}),n("checkout_started",{credit_package_id:o.creditPackageId,...s?{currency:s.toUpperCase()}:{},..."number"==typeof a?{value:a}:{}},{eventId:l}),t}catch(r){const n=he(r,"errors.purchaseCredits",t);throw d(n),pe(r,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:o}}),r}finally{c(!1)}},[r,e,n,s.state,i]),loading:o,error:l}},Na=e=>{const{t:t}=Ln(),{api:r}=ta(),[n,s]=m([]),[a,i]=m(!1),[o,c]=m(null),{begin:l,settle:d}=Dn(),h=p(async()=>{if(!e)return l(),s([]),void i(!1);const n=l();i(!0),c(null);try{const t=await r.getCreditPackages(e);if(n.signal.aborted)return;s(t)}catch(r){if(n.signal.aborted)return;const s=he(r,"errors.fetchCreditPackages",t);c(s),pe(r,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{d(n)&&i(!1)}},[r,e,l,d]);return u(()=>{h()},[h]),{packages:n,loading:a,error:o,refetch:h}},Pa=(e,t)=>{const{t:r}=Ln(),{api:n}=ta(),[s,a]=m([]),[i,o]=m(0),[c,l]=m(0),[d,h]=m(1),[g,f]=m(!1),[y,b]=m(!1),[w,v]=m(!1),[k,S]=m(null),{begin:C,settle:x}=Dn(),N=t?.type,P=t?.page,I=t?.limit,_=p(async()=>{if(!e)return C(),a([]),o(0),l(0),h(1),f(!1),b(!1),void v(!1);const t=C();v(!0),S(null);try{const r=await n.getCreditTransactions(e,{type:N,page:P,limit:I});if(t.signal.aborted)return;a(r.docs||[]),o(r.totalDocs||0),l(r.totalPages||0),h(r.page||1),f(r.hasNextPage||!1),b(r.hasPrevPage||!1)}catch(n){if(t.signal.aborted)return;const s=he(n,"errors.fetchCreditTransactions",r);S(s),pe(n,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{x(t)&&v(!1)}},[n,e,N,P,I,C,x]);return u(()=>{_()},[_]),{transactions:s,totalDocs:i,totalPages:c,page:d,hasNextPage:g,hasPrevPage:y,loading:w,error:k,refetch:_}},Ia=(e,t)=>{const{t:r}=Ln(),{api:n}=ta(),[s,a]=m(null),[i,o]=m(!1),[c,l]=m(null),{begin:d,settle:h}=Dn(),g=p(async()=>{if(!e)return d(),a(null),void o(!1);const s=d();o(!0),l(null);try{const r=await n.getExpiringCredits(e,t);if(s.signal.aborted)return;a(r)}catch(n){if(s.signal.aborted)return;const a=he(n,"errors.fetchExpiringCredits",r);l(a),pe(n,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:t}})}finally{h(s)&&o(!1)}},[n,e,t,d,h]);return u(()=>{g()},[g]),{expiringCredits:s?.expiringCredits??0,buckets:s?.buckets??[],days:s?.days??t??7,loading:i,error:c,refetch:g}},_a=()=>{const{t:e}=Ln(),{os:t,api:r}=ta(),n=ze(t),[s,a]=m([]),[i,o]=m(),[c,l]=m(!1),[d,h]=m(null),{begin:g,settle:f}=Dn(),y=p(async()=>{if(!n)return g(),a([]),void l(!1);const t=g();l(!0),h(null);try{const e=await r.getPublicCreditPackages();if(t.signal.aborted)return;a(e.packages||[]),o(e.notes)}catch(r){if(t.signal.aborted)return;const n=he(r,"errors.fetchCreditPackages",e);h(n),pe(r,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{f(t)&&l(!1)}},[r,n,g,f]);u(()=>{y()},[y]);return{packages:s,notes:i,loading:!n||c,error:d,refetch:y}},Ea=c(null);Ea.displayName="CreditBalanceContext";const Ua=s.memo(function({children:e}){const r=Hs(e=>e.workspaces.currentWorkspace),{balance:n,loading:s,error:a,refetch:o}=Sa(r?._id);u(()=>Ye(o),[o]);const c=i(()=>({balance:n,loading:s,error:a,refetch:o}),[n,s,a,o]);return t(Ea.Provider,{value:c,children:e})});function Aa(){const e=d(Ea);if(null===e)throw new Error("useCreditBalanceContext must be used within CreditBalanceContextProvider. Make sure CreditBalanceContextProvider is wrapping your application (included in SaaSOSProvider by default).");return e}Ua.displayName="CreditBalanceContextProvider";const Ta=({message:n})=>e(r,{children:[t("div",{className:"bb-fs-loader-spinner",style:{width:40,height:40,border:"3px solid hsl(var(--muted, 210 40% 96%))",borderTopColor:"hsl(var(--muted-foreground, 215.4 16.3% 46.9%))",borderRadius:"50%",animation:"bb-fs-loader-spin 0.6s linear infinite"}}),t("p",{"aria-hidden":"true",style:{marginTop:16,color:"hsl(var(--muted-foreground, 215.4 16.3% 46.9%))",fontSize:14},children:n}),t("style",{children:"\n @keyframes bb-fs-loader-spin { to { transform: rotate(360deg) } }\n @media (prefers-reduced-motion: reduce) {\n .bb-fs-loader-spinner { animation: none !important; }\n }\n @media (prefers-color-scheme: dark) {\n .bb-fs-loader-spinner {\n border-color: hsl(var(--muted, 217.2 32.6% 17.5%)) !important;\n border-top-color: hsl(var(--muted-foreground, 215 20.2% 65.1%)) !important;\n }\n }\n "})]}),Oa=({children:r,message:n,backgroundColor:s})=>{const{t:a}=Ln(),i=n??a("settings.common.loading");return e("div",{role:"status","aria-live":"polite","aria-busy":"true",className:"bb-fs-loader",style:{position:"fixed",inset:0,zIndex:2147483647,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",backgroundColor:s??void 0},children:[t("span",{style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:i}),r??t(Ta,{message:i}),t("style",{children:"\n .bb-fs-loader {\n background-color: hsl(var(--background, 0 0% 100%));\n }\n @media (prefers-color-scheme: dark) {\n .bb-fs-loader {\n background-color: hsl(var(--background, 222.2 84% 4.9%));\n }\n .bb-fs-loader p {\n color: hsl(var(--muted-foreground, 215 20.2% 65.1%)) !important;\n }\n }\n "})]})};Oa.displayName="FullScreenLoader";const Ra=c(null),Wa=({children:r,loadingComponent:n})=>{const[s,a]=m({visible:!1,message:""}),o=l(null),c=p(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=p(()=>{c(),a({visible:!1,message:""})},[c]),h=p(e=>{c(),a({visible:!0,message:e}),o.current=setTimeout(()=>{pe(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),a({visible:!1,message:""})},6e4)},[c]);u(()=>()=>c(),[c]);const g=i(()=>({show:h,hide:d,visible:s.visible,message:s.message}),[h,d,s.visible,s.message]),f="function"==typeof n?n({message:s.message}):n;return e(Ra.Provider,{value:g,children:[r,s.visible&&t(Oa,{message:s.message,children:f})]})};function $a(){const e=d(Ra);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}Wa.displayName="FullScreenLoaderProvider";const Fa=c(null);function La(e,t){return e?e.replace(/\{\{(\w+)\}\}/g,(e,r)=>r in t?t[r]:e):e}function Da(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"app"}function ja({mcp:e,children:r}){const n=i(()=>e?.url?{...e,url:e.url.replace(/\/+$/,"")}:null,[e]);return t(Fa.Provider,{value:n,children:r})}function Ma(){return d(Fa)}const qa=c({appPermissions:void 0});function Ba({appPermissions:e,children:r}){const n=i(()=>({appPermissions:e}),[e]);return t(qa.Provider,{value:n,children:r})}function za(){return d(qa)}const Va=c(null);Va.displayName="QuotaUsageContext";const Ga=s.memo(function({children:e}){const r=Hs(e=>e.workspaces.currentWorkspace),{quotas:n,loading:s,error:a,refetch:o}=ya(r?._id);u(()=>Xe(o),[o]);const c=i(()=>({quotas:n,loading:s,error:a,refetch:o}),[n,s,a,o]);return t(Va.Provider,{value:c,children:e})});function Ja(){const e=d(Va);if(null===e)throw new Error("useQuotaUsageContext must be used within QuotaUsageContextProvider. Make sure QuotaUsageContextProvider is wrapping your application (or the tree that uses quota gates).");return e}Ga.displayName="QuotaUsageContextProvider";const Ka=c({});function Ha({ui:e,children:r}){const n=i(()=>e??{},[e]);return t(Ka.Provider,{value:n,children:r})}function Ya(){return d(Ka)}function Qa(e,t){return t?Za(e,t):e}function Za(e,t){if(!e||!t||"object"!=typeof e||"object"!=typeof t||Array.isArray(e)||Array.isArray(t))return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=e in r?Za(r[e],n):n;return r}let Xa=!1;function ei(){Xa=!0}const ti="saas-oauth-state";function ri(){ye(ti)}function ni(e={}){const t={};for(const[r,n]of Object.entries(e))null!=n&&""!==n&&("string"==typeof n?t[r]=n.slice(0,100):("number"==typeof n?Number.isFinite(n):"boolean"==typeof n)&&(t[r]=n));return t}const si=new Set;function ai(e){return!si.has(e)&&(si.add(e),!0)}function ii(e,t,r,n){const{emitOnce:s}=oi(),a=l(n);a.current=n,u(()=>{e&&s(t,r,a.current)},[e,t,r,s])}function oi(){const{track:e,ready:t}=Vs(),r=p((t,r)=>{try{e(t,ni(r))}catch{}},[e]),n=p((e,n,s)=>{t&&ai(`${n}|${e}`)&&r(n,s)},[r,t]);return{emit:r,emitOnce:n,ready:t}}const ci={Profile:"profile",Security:"security",Devices:"devices",ConnectedAgents:"connected-agents",General:"general",Users:"users",Subscription:"subscription",Usage:"usage",Credits:"credits",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"},li=new Set(Object.values(ci));const di=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:ci.Profile}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getState(){return this.currentState}openWorkspaceSettings(e,t){this.currentState={open:!0,section:e||ci.Profile,params:t},this.notifyListeners()}closeSettings(){this.currentState={...this.currentState,open:!1,params:void 0},this.notifyListeners()}setSection(e){this.currentState={...this.currentState,section:e},this.notifyListeners()}clearParams(){void 0!==this.currentState.params&&(this.currentState={...this.currentState,params:void 0},this.notifyListeners())}notifyListeners(){this.listeners.forEach(e=>{e(this.currentState)})}},ui=c(null);ui.displayName="WorkspaceActionsContext";const pi=({children:e})=>{const r=Ks(),{os:n,api:a}=ta(),{settings:o}=ea(),{t:c}=Ln(),l=s.useRef(c);u(()=>{l.current=c},[c]);const d=Hs(e=>e.workspaces),m=Hs(e=>e.auth.session?.user),h=s.useRef(!1),g=s.useRef(!1),f=s.useRef(0),y=p((e,t)=>{if((!(e._id===d.currentWorkspace?._id)||t?.forceEmit)&&e){const t=d.currentWorkspace;fr(e),r.workspaces(ln(e)),Je.emitWorkspaceChanged(e,t).catch(t=>{pe(t,{component:"WorkspaceProvider",action:"emitWorkspaceChanged",metadata:{workspaceId:e._id}})})}},[d.currentWorkspace,r]),b=p(async(e,t)=>{const s=++f.current;r.workspaces(gn(e._id));try{const r=n.auth?.callbacks?.onWorkspaceChange;if(r){const t=kr(e,m?.id);try{await r({workspace:e,user:m??null,role:t})}catch(t){throw pe(t,{component:"WorkspaceProvider",action:"onWorkspaceChange",metadata:{workspaceId:e._id}}),t}if(s!==f.current)return}y(e,t)}finally{s===f.current&&r.workspaces(gn(null))}},[r,n.auth?.callbacks?.onWorkspaceChange,y,m]),w=s.useRef(b);w.current=b,u(()=>{if(!d.isInitialized){const e=yr();if(r.workspaces(un(!0)),e){const t=d.workspaces.find(t=>t._id===e);t&&w.current(t,{forceEmit:!0}).catch(t=>{pe(t,{component:"WorkspaceProvider",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:e}})})}}},[d.isInitialized,d.workspaces,r]);const v=p(()=>{br(),r.workspaces(dn())},[r]),k=p(async()=>{if(!d.loading&&!h.current){h.current=!0,r.workspaces(pn(!0)),r.workspaces(mn(null));try{const e=await a.getWorkspaces();if(r.workspaces(nn(e)),e.length>0){const t=yr();if(t&&wr(t,e)){const r=e.find(e=>e._id===t);if(r)try{await b(r,{forceEmit:!0})}catch{}}else{const t=e[0];try{await b(t,{forceEmit:!0})}catch{}}}}catch(e){r.workspaces(mn(he(e,"errors.fetchWorkspaces",l.current)))}finally{r.workspaces(pn(!1)),h.current=!1}}},[a,d.loading,r,b]),S=p(async()=>{if(!d.refreshing&&!h.current){h.current=!0,r.workspaces(hn(!0));try{const e=await a.getWorkspaces();r.workspaces(nn(e))}catch(e){}finally{r.workspaces(hn(!1)),h.current=!1}}},[a,d.refreshing,r]),C=s.useRef(null);u(()=>()=>{C.current&&clearTimeout(C.current)},[]);const x=p(async(e,t)=>{const n=await a.createWorkspace(t?{name:e,image:t}:{name:e});r.workspaces(sn(n)),await b(n),Je.emitWorkspaceCreated(n).catch(e=>{pe(e,{component:"WorkspaceProvider",action:"emitWorkspaceCreated",metadata:{workspaceId:n._id}})}),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{C.current=null,di.openWorkspaceSettings(ci.Subscription)},300)},[a,r,b]),N=p(async(e,t)=>{const n=await a.updateWorkspace(e._id,t);r.workspaces(an(n)),Je.emitWorkspaceUpdated(n).catch(e=>{pe(e,{component:"WorkspaceProvider",action:"emitWorkspaceUpdated",metadata:{workspaceId:n._id}})})},[a,r]),P=p(async()=>{if(g.current)return d.allFeatures.length>0?d.allFeatures:null;if(d.allFeatures.length>0)return d.allFeatures;g.current=!0;try{const e=await a.getFeatures();return r.workspaces(cn(e)),e}catch(e){return pe(e,{component:"WorkspaceProvider",action:"getFeatures"}),null}finally{g.current=!1}},[a,r,d.allFeatures]),I=p(async(e,t,r)=>await a.updateFeature(e,t,r),[a]),_=p(async e=>a.updateSettings(e),[a]),E=p(async(e,t)=>{const r=await a.updateWorkspacePermissions(e,t);return await S(),r},[a,S]);u(()=>{if(!d.currentWorkspace?._id||0===d.workspaces.length)return;const e=d.currentWorkspace._id,t=d.workspaces.find(t=>t._id===e);if(t)t!==d.currentWorkspace&&(fr(t),r.workspaces(ln(t)));else if(d.workspaces.length>0){const t=d.workspaces[0];t._id!==e&&b(t).catch(e=>{pe(e,{component:"WorkspaceProvider",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:t._id}})})}},[d.workspaces,d.currentWorkspace,r,b]);const U=p(async e=>await a.getWorkspaceUsers(e),[a]),A=p(async(e,t,r)=>{const n=d.workspaces.find(t=>t._id===e);if(n){const e=mr({settingsMaxUsers:o?.workspace?.maxWorkspaceUsers}),t=hr({memberCount:n.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessageKey||"users.memberLimitReached")}const s=await a.addUser(e,{email:t,role:r});return n&&Je.emitWorkspaceUserAdded(s.userId,n,r).catch(t=>{pe(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:s.userId,role:r}})}),S().catch(e=>{pe(e,{component:"WorkspaceProvider",action:"refreshAfterAddUser"})}),nt(),s},[a,d.workspaces,S,o]),T=p(async(e,t)=>{const r=d.workspaces.find(t=>t._id===e);if(r&&vr(r,t))throw new Error("Cannot remove the workspace owner");const n=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),s=await a.removeUser(e,t);if(r&&n){const t=n.role;Je.emitWorkspaceUserRemoved(s.userId,r,t).catch(r=>{pe(r,{component:"WorkspaceProvider",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:s.userId,role:t}})})}return S().catch(e=>{pe(e,{component:"WorkspaceProvider",action:"refreshAfterRemoveUser"})}),nt(),s},[a,d.workspaces,S]),O=p(async(e,t,r)=>{if(r.role){const r=d.workspaces.find(t=>t._id===e);if(r&&vr(r,t))throw new Error("Cannot change the role of the workspace owner")}let n;if(r.role){const r=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);n=r?.role}const s=await a.updateUser(e,t,r);return r.role&&n&&n!==r.role&&Je.emitWorkspaceUserRoleChanged(s.userId,s.workspace,n,r.role).catch(s=>{pe(s,{component:"WorkspaceProvider",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:n,newRole:r.role}})}),s},[a,d.workspaces]),R=p(async e=>{const t=await a.getProfile().catch(()=>null),r=await a.updateUserProfile(e);return Je.emitUserUpdated(r,t||void 0).catch(e=>{pe(e,{component:"WorkspaceProvider",action:"emitUserUpdated",metadata:{userId:r._id}})}),r},[a]),W=p(async()=>await a.getProfile(),[a]),$=p(async e=>await a.getWorkspace(e),[a]),F=p(async e=>{if(!m)throw new Error("User must be authenticated to delete a workspace");const t=d.workspaces.find(t=>t._id===e);if(!t)throw new Error("Workspace not found");if(!vr(t,m.id))throw new Error("Only the workspace creator can delete the workspace");const n=await a.deleteWorkspace(e);return r.workspaces(on(e)),d.currentWorkspace?._id===e&&(br(),r.workspaces(dn())),t&&Je.emitWorkspaceDeleted(t).catch(t=>{pe(t,{component:"WorkspaceProvider",action:"emitWorkspaceDeleted",metadata:{workspaceId:e}})}),n},[a,d.workspaces,d.currentWorkspace,r,m]),L=i(()=>({fetchWorkspaces:k,refreshWorkspaces:S,setCurrentWorkspace:y,switchToWorkspace:b,resetCurrentWorkspace:v,createWorkspace:x,updateWorkspace:N,deleteWorkspace:F,getWorkspace:$,getUsers:U,addUser:A,removeUser:T,updateUser:O,getProfile:W,updateUserProfile:R,getFeatures:P,updateFeature:I,updateWorkspaceSettings:_,updateWorkspacePermissions:E}),[k,S,y,b,v,x,N,F,$,U,A,T,O,W,R,P,I,_,E]);return t(ui.Provider,{value:L,children:e})};pi.displayName="WorkspaceProviderInner";const mi=({children:e})=>{const n=s.useContext(ui);return t(n?r:pi,{children:e})};mi.displayName="WorkspaceProvider";const hi=()=>{const e=s.useContext(ui);if(!e)throw new Error("useSaaSWorkspaces must be used within a WorkspaceProvider. Make sure SaaSOSProvider is wrapping your application.");const t=Hs(e=>e.workspaces);return i(()=>({workspaces:t.workspaces,loading:t.loading,error:t.error,refreshing:t.refreshing,currentWorkspace:t.currentWorkspace,allFeatures:t.allFeatures,switching:null!==t.switchingToId,switchingToId:t.switchingToId,...e}),[t,e])};function gi(e,t,r){const n=e._id||e.id;if(!n||"string"!=typeof n)throw new Error("User data missing required ID field");if(!e.email||"string"!=typeof e.email)throw new Error("User data missing required email field");return{id:n,name:e.name||"",org:t,email:e.email,emailVerified:!1!==e.emailVerified,clientId:r,role:e.role||"",image:e.image,createdAt:"string"==typeof e.createdAt?e.createdAt:void 0,firstAuthAt:"string"==typeof e.firstAuthAt?e.firstAuthAt:void 0}}function fi(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function yi(){return Hs(e=>e.auth)}function bi(){const{t:e}=Ln(),t=Ks(),r=yi(),n=Qs(),{serverUrl:s,orgId:a,auth:o}=n,{resetCurrentWorkspace:c,currentWorkspace:l}=hi(),d=$a(),{consent:u}=Vs(),{emit:m}=oi(),h=i(()=>new Oe({serverUrl:s,version:n.version}),[s,n.version]),g=p(async r=>{vt(r||window.location.href),m("sign_in_started",{from_path:window.location.pathname}),t.auth(Tr()),d.show(e("loading.redirecting"));try{const e=function(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return fe(ti,t),t}(),{redirectUrl:t}=await h.requestAuth({orgId:a,clientId:o?.clientId??"",redirect:{success:o?.redirectUrl||window.location.href,error:o?.redirectUrl||window.location.href},state:e,...u.state?{trackingConsent:{analytics:!!u.state.analytics,marketing:!!u.state.marketing}}:{},...(()=>{const e=function(){const e=us(),t=Object.keys(e).find(e=>e.startsWith("_ga_")),r={},n=ps(e._ga);n&&(r.gaClientId=n);const s=t?ms(e[t]):void 0;return s&&(r.gaSessionId=s),r}();return Object.keys(e).length?{trackingIdentity:e}:{}})()});yt(t)}catch(e){throw d.hide(),t.auth(Rr()),pe(e,{component:"useSaaSAuth",action:"signIn"}),e}},[h,a,o,t,d,e,u.state,m]),f=p(async()=>{try{o?.callbacks?.onSignOut&&"function"==typeof o.callbacks.onSignOut&&await o.callbacks.onSignOut()}catch(e){pe(e,{component:"useSaaSAuth",action:"signOut"})}finally{Ce(),t.auth($r()),c()}},[t,c,o?.callbacks?.onSignOut]),y=p(e=>{l?di.openWorkspaceSettings(e):pe(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),b=p(()=>{l?di.openWorkspaceSettings(ci.Credits,{action:at.OpenCreditStore}):pe(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),w=p(()=>{l?di.openWorkspaceSettings(ci.Subscription,{action:at.SelectPlan}):pe(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),v=i(()=>Ur(r.status),[r.status]);return i(()=>({user:r.session?.user,session:r.session,status:r.status,...v,signIn:g,signOut:f,openWorkspaceSettings:y,openCreditStore:b,openPlanPicker:w}),[r.session,r.status,v,g,f,y,b,w])}const wi=s.memo(({children:e,callbacks:n})=>{const{t:a}=Ln(),i=Ks(),o=yi(),c=Qs(),l=Ur(o.status).isAuthenticated,d=$a(),m=s.useRef(!1),h=s.useRef(null),g=s.useRef(!1),f=s.useRef(null),y=p(async e=>{try{if(n?.handleAuthentication){d.show(a("loading.signingIn"));const{sessionId:t}=await n.handleAuthentication(e);if(!t||"string"!=typeof t||""===t.trim())throw new Error("Invalid sessionId received from authentication callback");const r=c;if(!ze(r))throw new Error("OS configuration is not available");const{serverUrl:s,version:o,orgId:l}=r;d.show(a("loading.verifyingAccount"));const u=new Oe({serverUrl:s,version:o}),p=await u.getProfile(t),m=fi(gi(p,l,r.auth?.clientId||""),t);d.show(a("loading.almostThere")),Se(m.sessionId),u.getDeviceToken(m.sessionId).then(e=>e&&Ne(e)).catch(()=>{}),_e();const h=kt(),g=!!h&&h!==window.location.href;g&&ei(),i.auth(Wr(m)),g&&yt(h),d.hide()}}catch(t){throw d.hide(),kt(),pe(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),i.auth(Rr()),t}},[i,n,c,d,a]);return s.useEffect(()=>{if("undefined"==typeof window)return;if(l)return;if(g.current)return;if(f.current)return;if(!ze(c))return;if(Ie())return;if(!n?.getSession)return g.current=!0,void i.auth(Rr());const e=n.getSession,{serverUrl:t,version:r,orgId:s}=c,o=c.auth?.clientId||"";f.current=(async()=>{d.show(a("loading.restoringSession"));let c=null;try{c=await e()}catch(e){pe(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!c)return g.current=!0,i.auth(Rr()),d.hide(),"undefined"!=typeof window&&vt(window.location.href),void n?.onSessionExpired?.("missing");try{d.show(a("loading.verifyingAccount"));const e=new Oe({serverUrl:t,version:r}),n=await e.getProfile(c),l=fi(gi(n,s,o),c);Se(l.sessionId),e.getDeviceToken(l.sessionId).then(e=>e&&Ne(e)).catch(()=>{}),g.current=!0;const u=kt(),p=!!u&&u!==window.location.href;p&&ei(),i.auth(Wr(l)),d.hide(),p&&yt(u)}catch(e){pe(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),g.current=!0,i.auth(Rr()),d.hide(),"undefined"!=typeof window&&vt(window.location.href),n?.onSessionExpired?.("expired")}finally{f.current=null}})()},[l,i,c,n]),u(()=>{const e=Ie();if(!e)return;if(m.current||h.current===e)return;if(!ze(c))return;const t=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(ke)}catch(e){return pe(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:ke}}),null}}();if(t&&!function(e){if(!e)return!1;const t=ge(ti);if(ye(ti),!t)return!1;if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return 0===r}(t))return ri(),_e(),pe(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void i.auth(Rr());ri(),m.current=!0,h.current=e;let r=!1;return i.auth(Or()),y(e).then(()=>{r||(h.current=null)}).catch(e=>{r||(pe(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),_e(),h.current=null)}).finally(()=>{m.current=!1}),()=>{r=!0}},[y,c.serverUrl,c.version,c.orgId]),t(r,{children:e})});wi.displayName="AuthProviderWrapper";const vi=s.memo(({config:e,auth:n,children:a})=>{const i=Ks();Qs();const o=s.useMemo(()=>({clientId:n?.clientId||"",redirectUrl:n?.redirectUrl||"",callbacks:n?.callbacks}),[n?.clientId,n?.redirectUrl,n?.callbacks]);return u(()=>{i.os(Jr({...e,auth:o}))},[e,o,i]),t(r,{children:a})});vi.displayName="ContextConfigProvider";const ki=c({container:null,setContainer:()=>{}}),Si=s.memo(({children:r})=>{const[n,a]=s.useState(null),i=s.useMemo(()=>({container:n,setContainer:a}),[n]);return e(ki.Provider,{value:i,children:[r,t("div",{ref:a,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});Si.displayName="PortalProvider";const Ci=c(null);function xi(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}const Ni=s.memo(function({children:e,serviceWorkerPath:r="/push-sw.js",autoSubscribe:n=!1}){const{t:s}=Ln(),a=Qs(),{isAuthenticated:o}=bi(),c=i(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=i(()=>new Le({serverUrl:a.serverUrl,version:a.version,orgId:a.orgId}),[a.serverUrl,a.version,a.orgId]),[d,h]=m({permission:c?Notification.permission:"default",isSubscribed:!1,isSupported:c,loading:!1,error:null});u(()=>{if(!o||!c)return;let e=!1;return(async()=>{try{const t=await navigator.serviceWorker.getRegistration(r);if(e)return;if(!t)return void h(e=>({...e,isSubscribed:!1}));const n=await t.pushManager.getSubscription();if(e)return;h(e=>({...e,isSubscribed:!!n,permission:Notification.permission}))}catch{e||h(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[o,c,r]);const g=p(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return h(t=>({...t,permission:e})),"granted"===e},[c]),f=p(async()=>{if(c&&o){h(e=>({...e,loading:!0,error:null}));try{if(!await g())return void h(e=>({...e,loading:!1,error:s("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(r);await navigator.serviceWorker.ready;const n=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:xi(e)})).toJSON();await l.subscribe({endpoint:n.endpoint,keys:{p256dh:n.keys.p256dh,auth:n.keys.auth}},navigator.userAgent),h(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:s("push.failedToSubscribe");h(e=>({...e,loading:!1,error:t})),pe(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,o,l,r,g]),y=p(async()=>{if(c){h(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(r);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}h(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:s("push.failedToUnsubscribe");h(e=>({...e,loading:!1,error:t})),pe(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,r]),b=i(()=>({...d,requestPermission:g,subscribe:f,unsubscribe:y}),[d,g,f,y]);return t(Ci.Provider,{value:b,children:e})});function Pi(){const e=d(Ci);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e}const Ii="bb_seen_users",_i=12e4;function Ei(){try{const e=window.localStorage.getItem(Ii),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function Ui(e,t,r=Date.now()){if(!e)return"login";if("undefined"==typeof window)return"login";if(Ei().includes(e))return"login";if(function(e){try{const t=[e,...Ei().filter(t=>t!==e)].slice(0,20);window.localStorage.setItem(Ii,JSON.stringify(t))}catch{}}(e),!t)return"login";const n=Date.parse(t);return Number.isNaN(n)||n>r||r-n>_i||function(e){try{const t=window.document?.cookie;return"string"==typeof t&&t.split("; ").includes(`${Ai}=${e}`)}catch{return!1}}(e)?"login":(function(e){try{const t=window.document;if(!t||!Ti.test(e))return;const r=zn(window.location?.hostname??"",t);t.cookie=`${Ai}=${e}; path=/; max-age=120; SameSite=Lax`+(r?`; domain=${r}`:"")}catch{}}(e),"sign_up")}const Ai="bb_su",Ti=/^[\w-]{1,64}$/;const Oi="bb_announced_session";const Ri={[Ve.UserCreated]:"user_created",[Ve.UserUpdated]:"user_updated",[Ve.WorkspaceCreated]:"workspace_created",[Ve.WorkspaceUpdated]:"workspace_updated",[Ve.WorkspaceChanged]:"workspace_switched",[Ve.WorkspaceDeleted]:"workspace_deleted",[Ve.WorkspaceUserAdded]:"workspace_member_added",[Ve.WorkspaceUserRemoved]:"workspace_member_removed",[Ve.WorkspaceUserRoleChanged]:"workspace_member_role_changed"};const Wi=Object.keys(Ri),$i="undefined"==typeof window?s.useEffect:s.useLayoutEffect;function Fi({children:e}){const{track:n,setUser:a,setProperties:i,ready:o}=Vs(),c=yi().session,l=c?.user?.id,d=c?.sessionId,{currentWorkspace:u}=hi(),{response:p,loading:m}=ka(),h=s.useMemo(()=>function(e){const{workspace:t,userId:r,subscription:n,subscriptionLoading:s}=e,a={workspace_id:void 0,workspace_role:void 0,workspace_owner:void 0,workspace_member_count:void 0,workspace_plan:void 0,subscription_status:void 0};if(!t?._id)return a;const i=Array.isArray(t.users)?t.users.length:void 0,o=s?void 0:n?.subscription?n.plan?.slug??void 0:"none";return{workspace_id:String(t._id),workspace_role:kr(t,r)??void 0,workspace_owner:r?vr(t,r):void 0,workspace_member_count:i,workspace_plan:o,subscription_status:s?void 0:n?.subscription?.subscriptionStatus??"none"}}({workspace:l?u:null,userId:l,subscription:p,subscriptionLoading:m}),[u,l,p,m]),g=JSON.stringify(h),f=s.useRef(null);$i(()=>{f.current!==g&&(f.current=g,i(h))},[g,i]);const y=function(e){const t={};return void 0!==e.workspace_plan&&(t.workspace_plan=e.workspace_plan),void 0!==e.workspace_role&&(t.workspace_role=e.workspace_role),void 0!==e.subscription_status&&(t.subscription_status=e.subscription_status),t}(h),b=JSON.stringify(y),w=s.useRef(null);s.useEffect(()=>{if(!o||!l||0===Object.keys(y).length)return;const e=`${l}|${b}`;w.current!==e&&(w.current=e,a(l,y))},[o,l,b,a]),s.useEffect(()=>{o&&l&&d&&(Xa||function(e){if(!e)return!1;if("undefined"==typeof window)return!1;try{return window.localStorage.getItem(Oi)!==e&&(window.localStorage.setItem(Oi,e),!0)}catch{return!0}}(d)&&(a(l),n(Ui(l,c?.user?.firstAuthAt),{method:"buildbase"})))},[o,l,d,c?.user?.firstAuthAt,n,a]),s.useEffect(()=>{const e=Wi.map(e=>Je.on(e,t=>{(function(e,t){if(e!==Ve.WorkspaceChanged)return!0;const r=t,n=r.workspace?._id,s=r.previousWorkspace?._id;return!!n&&!!s&&n!==s})(e,t)&&n(Ri[e],function(e,t){const r=t,n={},s=r.workspace;s?._id&&(n.workspace_id=s._id);const a=r.previousWorkspace;a?._id&&(n.previous_workspace_id=a._id);const i=r.user;return(i?._id||i?.id)&&(n.user_id=i._id??i.id),"string"==typeof r.userId&&(n.member_id=r.userId),"string"==typeof r.role&&(n.role=r.role),"string"==typeof r.previousRole&&(n.previous_role=r.previousRole),"string"==typeof r.newRole&&(n.new_role=r.newRole),n}(0,t))}));return()=>e.forEach(e=>e())},[n]);const v=s.useRef(o);v.current=o;const k=s.useRef([]);return s.useEffect(()=>ue.subscribe((e,t)=>{if(!ai(`sdk_error|${`${t.component??"unknown"}|${t.action??"unknown"}`}`))return;const r=ni({component:t.component,action:t.action,code:e.code});v.current?n("sdk_error",r):k.current.length<20&&k.current.push(r)}),[n]),s.useEffect(()=>{if(!o||0===k.current.length)return;const e=k.current;k.current=[],e.forEach(e=>n("sdk_error",e))},[o,n]),t(r,{children:e})}Fi.displayName="TrackingBridge";const Li=s.createContext(void 0),Di=s.memo(({children:e})=>{const{t:r}=Ln(),n=Qs(),a=function(){const e=Qs();return i(()=>new Me(e),[e.serverUrl,e.version])}(),{isAuthenticated:o}=bi(),{serverUrl:c,version:l}=n,[d,u]=m({}),[h,g]=m({}),[f,y]=m(!1),[b,w]=m(!1),[v,k]=m(null),[S,C]=m(null),x=p(async e=>{if(c&&l&&o){k(null);try{const t=await a.getAttributes(e);u(t)}catch(e){if(oe(e))return;const t=e instanceof Error?e:new Error(r("errors.generic"));k(t),pe(e,{component:"UserProvider",action:"fetchAttributes"})}}else u({})},[a,c,l,o,r]),N=p(async()=>{if(c&&l&&o){y(!0);try{await x()}finally{y(!1)}}},[c,l,o,x]),P=p(async e=>{y(!0),k(null);try{const t=await a.updateAttributes(e);return await x(),t}catch(t){const n=t instanceof Error?t:new Error(r("errors.generic"));throw k(n),pe(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{y(!1)}},[a,x,r]),I=p(async(e,t)=>{y(!0),k(null);try{const r=await a.updateAttribute(e,t);return await x(),r}catch(n){const s=n instanceof Error?n:new Error(r("errors.generic"));throw k(s),pe(n,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),n}finally{y(!1)}},[a,x,r]),_=p(async e=>{if(c&&l&&o){C(null);try{const t=await a.getFeatures(e);g(t)}catch(e){if(oe(e))return;const t=e instanceof Error?e:new Error(r("errors.generic"));C(t),pe(e,{component:"UserProvider",action:"fetchFeatures"})}}else g({})},[a,c,l,o,r]),E=p(async()=>{if(c&&l&&o){w(!0);try{await _()}finally{w(!1)}}},[c,l,o,_]);Ys(async e=>{if(!o||!c||!l)return u({}),void g({});y(!0),w(!0),await Promise.all([x(e).finally(()=>y(!1)),_(e).finally(()=>w(!1))])},[o,c,l,x,_],{onError:e=>pe(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const U=s.useMemo(()=>({attributes:d,features:h,isLoading:f||b,error:v??S,attributesLoading:f,featuresLoading:b,attributesError:v,featuresError:S,updateAttributes:P,updateAttribute:I,refreshAttributes:N,refreshFeatures:E}),[d,h,f,b,v,S,P,I,N,E]);return t(Li.Provider,{value:U,children:e})});Di.displayName="UserProvider";const ji=N("inline-flex items-center justify-center rounded-full font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"underline-offset-4 hover:underline text-primary"},withIcon:{true:"flex"},fullWidth:{true:"w-full"},size:{default:"h-10 sm:h-9 py-2 px-4 text-sm",sm:"h-9 sm:h-8 px-3 text-xs",lg:"h-11 sm:h-10 px-6 text-base",icon:"h-10 w-10 sm:h-9 sm:w-9"}},compoundVariants:[{size:"lg",withIcon:!0,className:"gap-x-1.5"},{size:"default",withIcon:!0,className:"gap-x-1"},{size:"sm",withIcon:!0,className:"gap-x-0.5"}],defaultVariants:{variant:"default",size:"default"}}),Mi=n.forwardRef(({className:r,variant:s,progress:a,size:i,startIcon:o,endIcon:c,asChild:l=!1,...d},u)=>{const p=l?x:"button",m=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(i);return e(p,{disabled:a||d.disabled,className:ne(ji({variant:s,size:i,withIcon:null!=a||null!=o||null!=c,className:r})),ref:u,...d,children:[a&&t(P,{size:m,className:"animate-spin"}),o&&n.cloneElement(o,{size:m}),d.children,c&&n.cloneElement(c,{size:m})]})});Mi.displayName="Button";const qi=H.Root,Bi=H.Trigger,zi=H.Portal,Vi=n.forwardRef(({className:e,...r},n)=>t(H.Overlay,{ref:n,className:ne("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...r}));Vi.displayName=H.Overlay.displayName;const Gi=n.forwardRef(({className:r,children:s,...a},i)=>{const{container:o}=n.useContext(ki),{t:c}=Ln();return e(zi,{container:o,children:[t(Vi,{}),e(H.Content,{ref:i,className:ne("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",r),...a,children:[s,e(H.Close,{className:"absolute right-2 rtl:right-auto rtl:left-2 top-2 z-20 p-2 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[t(Y,{className:"h-4 w-4"}),t("span",{className:"sr-only",children:c("settings.common.close")})]})]})]})});Gi.displayName=H.Content.displayName;const Ji=({className:e,...r})=>t("div",{className:ne("flex flex-col space-y-1.5 text-center sm:text-start",e),...r});Ji.displayName="DialogHeader";const Ki=n.forwardRef(({className:e,...r},n)=>t(H.Title,{ref:n,className:ne("text-lg font-semibold leading-none tracking-tight",e),...r}));Ki.displayName=H.Title.displayName;const Hi=n.forwardRef(({className:e,...r},n)=>t(H.Description,{ref:n,className:ne("text-sm text-muted-foreground",e),...r}));function Yi(e){const{user:t}=bi(),{currentWorkspace:r}=hi(),{settings:n}=ea(),{appPermissions:s}=za(),a=e??r??null,o=t?.id??null,c=i(()=>a?kr(a,o):null,[a,o]),l=i(()=>!!a&&vr(a,o),[a,o]),d=i(()=>Pr({userId:o,workspaceRole:c,workspace:a,settings:n,appPermissions:s}),[o,c,a,n,s]);return{can:p(e=>Array.isArray(e)?e.every(e=>d.has(e)):d.has(e),[d]),permissions:d,isOwner:l,role:c}}function Qi(){const e=Ya(),{can:t}=Yi();return{visible:p((r,n)=>!1!==r(e)&&(void 0===n||t(n)),[e,t]),ui:e}}function Zi(){const e=Qs();return i(()=>new $e(e),[e.serverUrl,e.version])}function Xi(){const e=Zi(),{t:t}=Ln(),[r,n]=m([]),[s,a]=m(!0),[o,c]=m(null),[d,h]=m(null),g=l(null),f=l(t);u(()=>{f.current=t},[t]);const y=p(async()=>{g.current?.abort();const t=new AbortController;g.current=t,a(!0),c(null);try{const r=await e.list(t.signal);t.signal.aborted||n(r)}catch(e){if(t.signal.aborted)return;me(e,{component:"useConnectedAgents",action:"list"}),c(he(e,"security.connectedAgentsLoadFailed",f.current))}finally{g.current===t&&(g.current=null,a(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const b=p(async t=>{h(t),c(null);try{await e.revoke(t),n(e=>e.filter(e=>e.clientId!==t))}catch(e){me(e,{component:"useConnectedAgents",action:"revoke"}),c(he(e,"security.connectedAgentsRevokeFailed",f.current))}finally{h(null)}},[e]);return i(()=>({agents:r,loading:s,error:o,revoking:d,refresh:y,revoke:b}),[r,s,o,d,y,b])}function eo(e,t="en-US",r){try{const n=new Date(e);return isNaN(n.getTime())?"":new Intl.DateTimeFormat(t,r??{month:"short",day:"numeric",year:"numeric"}).format(n)}catch{return""}}function to(e,t="en-US"){return eo(e,t,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function ro(e,t="en-US"){return e?new Date(1e3*e).toLocaleDateString(t,{year:"numeric",month:"short",day:"numeric"}):""}function no({icon:r,title:n,description:s,action:a,className:i}){return e("div",{className:ne("flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",i),children:[r&&t("span",{"aria-hidden":"true",children:r}),n&&t("p",{className:"text-sm font-medium",children:n}),s&&t("p",{className:"text-sm text-muted-foreground",children:s}),a]})}function so({title:r,description:n,actions:s,className:a,titleClassName:i}){return r||n||s?e("div",{className:ne(a),children:[(r||s)&&e("div",{className:ne("flex items-center gap-2",r?"justify-between":"justify-end"),children:[r&&t("h3",{className:ne("text-sm font-medium",i),children:r}),s]}),n&&t("p",{className:"text-sm text-muted-foreground",children:n})]}):null}function ao({className:e,...r}){return t("div",{className:ne("animate-pulse rounded-md bg-primary/10",e),...r})}Hi.displayName=H.Description.displayName;const io=te.Root,oo=n.forwardRef(({className:e,...r},n)=>t(te.Item,{ref:n,className:ne("border-b last:border-b-0",e),...r}));oo.displayName="AccordionItem";const co=n.forwardRef(({className:r,children:n,...s},a)=>t(te.Header,{className:"flex",children:e(te.Trigger,{ref:a,className:ne("flex flex-1 items-center gap-2 py-3 text-start text-sm font-medium transition-all hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm [&[data-state=open]>svg]:rotate-180",r),...s,children:[t(I,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200","aria-hidden":"true"}),t("span",{className:"min-w-0 flex-1",children:n})]})}));co.displayName="AccordionTrigger";const lo=n.forwardRef(({className:e,children:r,...n},s)=>t(te.Content,{ref:s,className:"overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:t("div",{className:ne("pb-3 pt-0",e),children:r})}));function uo({value:r,displayValue:s,copyLabel:a,copiedLabel:i,variant:o="inline",className:c}){const l=s??r,[d,u]=n.useState(!1),p=n.useRef(null);n.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const m=async()=>{await async function(e){try{if("undefined"!=typeof navigator&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}if("undefined"==typeof document)return!1;try{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t),t.select();const r=document.execCommand("copy");return document.body.removeChild(t),r}catch{return!1}}(r)&&(u(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>u(!1),2e3))},h=r=>e(Mi,{type:"button",variant:"ghost",size:"sm",onClick:m,"aria-label":d?i:a,className:"h-7 shrink-0 gap-1.5 px-2",children:[t(d?_:E,{className:"h-3.5 w-3.5","aria-hidden":"true"}),t("span",{className:ne("text-xs",r&&"hidden sm:inline"),children:d?i:a})]});return e("div","inline"===o?{dir:"ltr",className:ne("flex items-center gap-2 rounded-md border bg-muted/40 py-1 ps-3 pe-1",c),children:[t("code",{className:"min-w-0 flex-1 truncate text-xs",title:r,children:l}),h(!0)]}:{dir:"code"===o?"ltr":void 0,className:ne("overflow-hidden rounded-md border bg-muted/40",c),children:[t("div",{className:"flex justify-end border-b bg-muted/30 px-1.5 py-1",children:h(!1)}),"code"===o?t("pre",{className:"overflow-x-auto p-3 text-start text-xs leading-relaxed",children:t("code",{children:l})}):t("p",{className:"p-3 text-sm leading-relaxed",children:l})]})}function po({config:r,title:n,description:s,className:a}){const{t:i}=Ln(),o=Ma(),c=r??o;if(!c?.url)return null;const l=c.name?.trim()||"app",d={url:c.url,name:l,key:Da(l)},u=(e,t,r,n)=>({id:e,name:t,instructions:i("security.mcpAddToConfigFile",{path:`⁦${r}⁩`}),snippet:n}),p=[{id:"chatgpt",name:"ChatGPT",instructions:i("security.mcpClientChatgptInstructions")},{id:"claude",name:"Claude",instructions:i("security.mcpClientClaudeInstructions")},u("cursor","Cursor","~/.cursor/mcp.json",'{\n "mcpServers": {\n "{{key}}": {\n "url": "{{url}}"\n }\n }\n}'),u("vscode","VS Code",".vscode/mcp.json",'{\n "servers": {\n "{{key}}": {\n "type": "http",\n "url": "{{url}}"\n }\n }\n}'),u("windsurf","Windsurf","~/.codeium/windsurf/mcp_config.json",'{\n "mcpServers": {\n "{{key}}": {\n "serverUrl": "{{url}}"\n }\n }\n}'),{id:"cline",name:"Cline",instructions:i("security.mcpClientClineInstructions")}],m=c.clients??p,h=void 0===n?i("security.mcpGuideTitle"):n,g=void 0===s?i("security.mcpGuideDescription"):s,f=i("security.mcpCopy"),y=i("security.mcpCopied"),b=!1===c.prompt?null:c.prompt??i("security.mcpPromptTemplate"),w=La(b??void 0,d),v=La(b??void 0,{...d,url:`⁦${d.url}⁩`,name:`⁨${d.name}⁩`});return e("div",{className:ne("space-y-5",a),children:[t(so,{title:h,description:g}),e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:i("security.mcpServerUrlLabel")}),t("p",{className:"text-xs text-muted-foreground",children:i("security.mcpServerUrlHint")}),t(uo,{value:c.url,copyLabel:f,copiedLabel:y})]}),w&&e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:i("security.mcpPromptLabel")}),t("p",{className:"text-xs text-muted-foreground",children:i("security.mcpPromptHint")}),t(uo,{value:w,displayValue:v,copyLabel:f,copiedLabel:y,variant:"text"})]}),m.length>0&&e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:i("security.mcpClientsLabel")}),t(io,{type:"single",collapsible:!0,defaultValue:m[0]?.id,className:"rounded-md border px-3",children:m.map(r=>{const n=La(r.instructions,d),s=La(r.snippet,d);return e(oo,{value:r.id,children:[t(co,{children:r.name}),t(lo,{children:e("div",{className:"space-y-2",children:[n&&t("p",{className:"text-sm text-muted-foreground",children:n}),s&&t(uo,{value:s,copyLabel:f,copiedLabel:y,variant:"code"}),r.actionUrl&&e("a",{href:r.actionUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[r.actionLabel??r.actionUrl,t(U,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})})]},r.id)})})]}),c.docsUrl&&e("a",{href:c.docsUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[i("security.mcpLearnMore"),t(U,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}function mo({className:r,title:n,description:s,disconnectLabel:a,emptyLabel:i,showConnectGuide:o=!0}){const{t:c,formattingLocale:d}=Ln(),{formats:p}=Ya(),{agents:h,loading:g,error:f,revoking:y,revoke:b}=Xi(),w=Ma(),v=o&&Boolean(w?.url),[k,S]=m(!1),C=l(!1);u(()=>{if(C.current||!v)return;const e=di.getState().params;e?.action===at.OpenConnectGuide&&(C.current=!0,di.clearParams(),S(!0))},[v]);const x=void 0===n?c("security.connectedAgentsTitle"):n,N=void 0===s?c("security.connectedAgentsDescription"):s,P=a??c("security.connectedAgentsDisconnect"),I=i??c("security.connectedAgentsEmpty"),_=c("security.mcpConnectAction"),E=r=>v?e(Mi,{size:"sm",onClick:()=>S(!0),"aria-label":_,className:"shrink-0 gap-1.5",children:[t(T,{className:"h-4 w-4","aria-hidden":"true"}),t("span",{className:r?"hidden sm:inline":void 0,children:_})]}):null;return e("div",{className:ne("space-y-4",r),children:[t(so,{title:x,description:N,actions:!g&&h.length>0?E(!0):void 0}),g&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(ao,{className:"h-20 rounded-md"},e))}),f&&!g&&t("p",{className:"text-destructive text-sm",children:f}),!g&&!f&&0===h.length&&t(no,{icon:t(A,{className:"h-5 w-5 text-muted-foreground"}),description:I,action:E(!1)??void 0}),!g&&h.length>0&&t("ul",{className:"space-y-3",children:h.map(r=>{return e("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e("div",{className:"flex min-w-0 flex-col gap-y-1",children:[t("span",{className:"text-sm font-medium break-words",children:r.title}),r.scope.length>0&&e("span",{className:"text-muted-foreground text-xs break-words",children:[c("security.connectedAgentsAccess"),": ",r.scope.join(", ")]}),r.lastGrantedAt&&e("span",{className:"text-muted-foreground text-xs",children:[c("security.connectedAgentsGranted"),": ",(n=r.lastGrantedAt,eo(n,d,p?.date??{dateStyle:"medium"}))]})]}),t(Mi,{variant:"outline",size:"sm",progress:y===r.clientId,onClick:()=>b(r.clientId),className:"shrink-0",children:P})]},r.clientId);var n})}),v&&t(qi,{open:k,onOpenChange:S,children:e(Gi,{className:"h-dvh max-h-dvh min-w-full gap-4 overflow-y-auto p-4 sm:h-auto sm:max-h-[90vh] sm:w-full sm:min-w-0 sm:max-w-lg sm:p-6",children:[e(Ji,{className:"pe-8",children:[t(Ki,{children:c("security.mcpGuideTitle")}),t(Hi,{children:c("security.mcpGuideDescription")})]}),t(po,{title:null,description:null})]})})]})}function ho({label:r,className:n}){const{t:s}=Ln();return e("div",{role:"status","aria-live":"polite",className:ne("flex items-center gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground",n),children:[t(P,{className:"h-4 w-4 animate-spin flex-shrink-0"}),t("span",{children:r??s("settings.common.loading")})]})}lo.displayName="AccordionContent";const go={error:{box:"bg-destructive/10 border-destructive/20 text-destructive",sub:"text-destructive/80",button:"border-destructive/20 text-destructive hover:bg-destructive/10"},success:{box:"bg-success/10 border-success/20 text-success",sub:"text-success/80",button:"border-success/20 text-success hover:bg-success/10"},warning:{box:"bg-warning/10 border-warning/20 text-warning",sub:"text-warning/80",button:"border-warning/20 text-warning hover:bg-warning/10"},info:{box:"bg-info/10 border-info/20 text-info",sub:"text-info/80",button:"border-info/20 text-info hover:bg-info/10"}};function fo({variant:r,title:n,message:s,description:a,icon:i,actionLabel:o,onAction:c,actionDisabled:l,className:d}){const u=go[r];return e("div",{role:"error"===r?"alert":"status","aria-live":"error"===r?"assertive":"polite","aria-atomic":"true",className:ne("border px-4 py-3 rounded-lg flex items-start justify-between gap-2 sm:gap-4",u.box,d),children:[e("div",{className:"flex items-start gap-2 min-w-0",children:[i,e("div",{className:"min-w-0",children:[n&&t("p",{className:"text-sm font-medium",children:n}),s&&t("p",{className:ne("text-sm",n&&"mt-1"),children:s}),a&&t("p",{className:ne("text-xs mt-2",u.sub),children:a})]})]}),o&&t(Mi,{variant:"outline",size:"sm",onClick:c,disabled:l,className:ne("flex-shrink-0",u.button),children:o})]})}const yo=re.Root,bo=re.Trigger,wo=re.Portal,vo=n.forwardRef(({className:e,...r},n)=>t(re.Overlay,{className:ne("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...r,ref:n}));vo.displayName=re.Overlay.displayName;const ko=n.forwardRef(({className:r,...s},a)=>{const{container:i}=n.useContext(ki);return e(wo,{container:i,children:[t(vo,{}),t(re.Content,{ref:a,className:ne("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg md:w-full",r),...s})]})});ko.displayName=re.Content.displayName;const So=({className:e,...r})=>t("div",{className:ne("flex flex-col space-y-2 text-center sm:text-start",e),...r});So.displayName="AlertDialogHeader";const Co=({className:e,...r})=>t("div",{className:ne("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...r});Co.displayName="AlertDialogFooter";const xo=n.forwardRef(({className:e,...r},n)=>t(re.Title,{ref:n,className:ne("text-lg font-semibold",e),...r}));xo.displayName=re.Title.displayName;const No=n.forwardRef(({className:e,...r},n)=>t(re.Description,{ref:n,className:ne("text-sm text-muted-foreground",e),...r}));No.displayName=re.Description.displayName;const Po=n.forwardRef(({className:e,...r},n)=>t(re.Action,{ref:n,className:ne(ji(),e),...r}));Po.displayName=re.Action.displayName;const Io=n.forwardRef(({className:e,...r},n)=>t(re.Cancel,{ref:n,className:ne(ji({variant:"outline"}),"mt-2 sm:mt-0",e),...r}));function _o(){const e=Qs();return i(()=>new Fe(e),[e.serverUrl,e.version])}function Eo(){const e=_o(),{t:t}=Ln(),[r,n]=m([]),[s,a]=m(!0),[o,c]=m(null),[d,h]=m(null),g=l(null),f=l(t);u(()=>{f.current=t},[t]);const y=p(async()=>{g.current?.abort();const t=new AbortController;g.current=t,a(!0),c(null);try{const r=await e.list(t.signal);t.signal.aborted||n(r)}catch(e){if(t.signal.aborted)return;me(e,{component:"useDevices",action:"list"}),c(he(e,"security.devicesLoadFailed",f.current))}finally{g.current===t&&(g.current=null,a(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const b=p(async(t,r)=>{h(t),c(null);try{await e.rename(t,r),n(e=>e.map(e=>e.deviceId===t?{...e,name:r}:e))}catch(e){me(e,{component:"useDevices",action:"rename"}),c(he(e,"security.deviceRenameFailed",f.current))}finally{h(null)}},[e]),w=p(async t=>{h(t),c(null);try{await e.signOut(t),n(e=>e.map(e=>e.deviceId===t?{...e,activeSessions:0}:e))}catch(e){me(e,{component:"useDevices",action:"signOut"}),c(he(e,"security.deviceSignOutFailed",f.current))}finally{h(null)}},[e]),v=p(async t=>{h(t),c(null);try{await e.forget(t),n(e=>e.filter(e=>e.deviceId!==t))}catch(e){me(e,{component:"useDevices",action:"forget"}),c(he(e,"security.deviceForgetFailed",f.current))}finally{h(null)}},[e]);return i(()=>({devices:r,loading:s,error:o,busyId:d,refresh:y,rename:b,signOut:w,forget:v}),[r,s,o,d,y,b,w,v])}function Uo(e){return!!e&&/Mobi|Android|iPhone|iPad|iPod|Windows Phone/i.test(e)}function Ao(e){return/Windows NT/.test(e)?"Windows":/iPhone/.test(e)?"iPhone":/iPad/.test(e)?"iPad":/Android/.test(e)?"Android":/Mac OS X|Macintosh/.test(e)?"macOS":/CrOS/.test(e)?"ChromeOS":/Linux/.test(e)?"Linux":""}function To(e){return e?[(t=e,/Edg\//.test(t)?"Edge":/OPR\/|Opera/.test(t)?"Opera":/Firefox\//.test(t)?"Firefox":/Chrome\//.test(t)?"Chrome":/Safari\//.test(t)&&/Version\//.test(t)?"Safari":""),Ao(e)].filter(Boolean).join(" · "):"";var t}Io.displayName=re.Cancel.displayName;const Oo=n.forwardRef(({className:e,type:r,...n},s)=>t("input",{type:r,className:ne("flex h-10 sm:h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base sm:text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:s,...n}));function Ro({className:n,title:s,description:a,showRename:i,showSignOut:o,showRemove:c,renameLabel:l,signOutLabel:d,removeLabel:u,emptyLabel:p}){const{t:h,formattingLocale:g}=Ln(),{formats:f}=Ya(),{visible:y}=Qi(),{devices:b,loading:w,error:v,busyId:k,rename:S,signOut:C,forget:x}=Eo(),[N,P]=m(null),[I,E]=m(""),[U,A]=m(null),T=i??y(e=>e.settings?.devices?.rename),L=o??y(e=>e.settings?.devices?.signOut),D=c??y(e=>e.settings?.devices?.forget),j=T||L||D,M=void 0===s?h("security.devicesTitle"):s,q=void 0===a?h("security.devicesDescription"):a,B=l??h("security.deviceRename"),z=d??h("security.deviceSignOut"),V=u??h("security.deviceForget"),G=p??h("security.devicesEmpty"),J=async e=>{const t=I.trim();t&&await S(e,t),P(null)};return e("div",{className:ne("space-y-4",n),children:[t(so,{title:M,description:q}),w&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(ao,{className:"h-24 rounded-md"},e))}),v&&!w&&t("p",{className:"text-destructive text-sm",children:v}),!w&&!v&&0===b.length&&t(no,{icon:t(O,{className:"h-5 w-5 text-muted-foreground"}),description:G}),!w&&b.length>0&&t("ul",{className:"space-y-3",children:b.map(n=>{const s=N===n.deviceId,a=k===n.deviceId,i=To(n.userAgent),o=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(n),c=Uo(n.userAgent)?R:O;return e("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e("div",{className:"flex min-w-0 gap-x-3",children:[t(c,{className:"text-muted-foreground mt-0.5 h-5 w-5 shrink-0","aria-hidden":"true"}),e("div",{className:"flex min-w-0 flex-col gap-y-1",children:[e("div",s?{className:"flex items-center gap-x-2",children:[t(Oo,{value:I,onChange:e=>E(e.target.value),placeholder:h("security.deviceRenamePlaceholder"),className:"h-8 w-48",autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&J(n.deviceId),"Escape"===e.key&&P(null)}}),t(Mi,{size:"sm",variant:"ghost","aria-label":h("security.deviceSave"),progress:a,onClick:()=>J(n.deviceId),children:t(_,{className:"h-4 w-4","aria-hidden":"true"})}),t(Mi,{size:"sm",variant:"ghost","aria-label":h("security.deviceCancel"),onClick:()=>P(null),children:t(W,{className:"h-4 w-4","aria-hidden":"true"})})]}:{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[t("span",{className:"text-sm font-medium break-words",children:n.name}),n.current&&t("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:h("security.deviceCurrent")}),n.trusted&&e("span",{className:"text-primary inline-flex items-center gap-x-1 text-xs",children:[t($,{className:"h-3.5 w-3.5","aria-hidden":"true"}),h("security.deviceTrusted")]}),n.pushEnabled&&t("span",{className:"text-muted-foreground inline-flex","aria-label":h("security.devicePushEnabled"),title:h("security.devicePushEnabled"),children:t(F,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),i&&t("span",{className:"text-muted-foreground text-xs break-words",children:i}),o&&t("span",{className:"text-muted-foreground text-xs break-words",children:o}),e("span",{className:"text-muted-foreground text-xs",children:[n.lastActiveAt&&h("security.deviceLastActive",{date:(l=n.lastActiveAt,eo(l,g,f?.date??{dateStyle:"medium"}))}),n.activeSessions>0&&e(r,{children:[n.lastActiveAt&&" · ",h("security.deviceActiveSessions",{count:n.activeSessions})]})]})]})]}),!s&&j&&e("div",{className:"flex shrink-0 flex-col items-end gap-y-1.5",children:[(T||L)&&e("div",{className:"flex items-center gap-x-1.5",children:[T&&t(Mi,{variant:"ghost",size:"sm",disabled:a,onClick:()=>(e=>{P(e.deviceId),E(e.name)})(n),children:B}),L&&n.activeSessions>0&&t(Mi,{variant:"outline",size:"sm",progress:a,onClick:()=>C(n.deviceId),children:z})]}),D&&t(Mi,{variant:"ghost",size:"sm",className:"text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:a,onClick:()=>A(n),children:V})]})]},n.deviceId);var l})}),t(yo,{open:null!==U,onOpenChange:e=>{e||A(null)},children:e(ko,{children:[e(So,{children:[t(xo,{children:h("security.deviceForgetConfirmTitle")}),t(No,{children:h("security.deviceForgetConfirmBody")})]}),e(Co,{children:[t(Io,{children:h("security.deviceCancel")}),t(Po,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{if(!U)return;const{deviceId:e}=U;A(null),await x(e)},children:V})]})]})})]})}function Wo(){const e=Qs();return i(()=>new De(e),[e.serverUrl,e.version])}function $o(){const e=Wo(),{t:t}=Ln(),[r,n]=m([]),[s,a]=m(!0),[o,c]=m(null),[d,h]=m(null),g=l(null),f=l(t);u(()=>{f.current=t},[t]);const y=p(async()=>{g.current?.abort();const t=new AbortController;g.current=t,a(!0),c(null);try{const r=await e.list(t.signal);t.signal.aborted||n(r)}catch(e){if(t.signal.aborted)return;me(e,{component:"useSessions",action:"list"}),c(he(e,"security.sessionsLoadFailed",f.current))}finally{g.current===t&&(g.current=null,a(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const b=p(async t=>{h(t),c(null);try{await e.revoke(t),n(e=>e.filter(e=>e.id!==t))}catch(e){me(e,{component:"useSessions",action:"revoke"}),c(he(e,"security.sessionSignOutFailed",f.current))}finally{h(null)}},[e]);return i(()=>({sessions:r,loading:s,error:o,revoking:d,refresh:y,revoke:b}),[r,s,o,d,y,b])}function Fo({className:n,title:s,description:a,showSignOut:i,signOutLabel:o,emptyLabel:c}){const{t:l,formattingLocale:d}=Ln(),{formats:u}=Ya(),{visible:p}=Qi(),{sessions:m,loading:h,error:g,revoking:f,revoke:y}=$o(),b=i??p(e=>e.settings?.devices?.sessionSignOut),w=void 0===s?l("security.sessionsTitle"):s,v=void 0===a?l("security.sessionsDescription"):a,k=o??l("security.sessionSignOut"),S=c??l("security.sessionsEmpty"),C=e=>eo(e,d,u?.date??{dateStyle:"medium"});return e("div",{className:ne("space-y-4",n),children:[t(so,{title:w,description:v}),h&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(ao,{className:"h-20 rounded-md"},e))}),g&&!h&&t("p",{className:"text-destructive text-sm",children:g}),!h&&!g&&0===m.length&&t(no,{icon:t(L,{className:"h-5 w-5 text-muted-foreground"}),description:S}),!h&&m.length>0&&t("ul",{className:"space-y-3",children:m.map(n=>{const s=To(n.userAgent),a=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(n),i=n.device?.name||s||l("security.sessionsTitle"),o=Uo(n.userAgent)?R:O;return e("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e("div",{className:"flex min-w-0 gap-x-3",children:[t(o,{className:"text-muted-foreground mt-0.5 h-5 w-5 shrink-0","aria-hidden":"true"}),e("div",{className:"flex min-w-0 flex-col gap-y-1",children:[e("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[t("span",{className:"text-sm font-medium break-words",children:i}),n.current&&t("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:l("security.sessionCurrent")})]}),s&&i!==s&&t("span",{className:"text-muted-foreground text-xs break-words",children:s}),a&&t("span",{className:"text-muted-foreground text-xs break-words",children:a}),e("span",{className:"text-muted-foreground text-xs",children:[n.lastActiveAt&&e(r,{children:[l("security.sessionLastActive",{date:C(n.lastActiveAt)}),n.expiresAt&&" · "]}),n.expiresAt&&l("security.sessionExpires",{date:C(n.expiresAt)})]})]})]}),!n.current&&b&&t(Mi,{variant:"ghost",size:"sm",progress:f===n.id,onClick:()=>y(n.id),className:"text-destructive hover:bg-destructive/10 hover:text-destructive shrink-0",children:k})]},n.id)})})]})}Oo.displayName="Input";const Lo=N("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Do=n.forwardRef(({className:e,...r},n)=>t(G.Root,{ref:n,className:ne(Lo(),e),...r}));Do.displayName=G.Root.displayName;const jo=k,Mo=n.createContext({}),qo=({...e})=>t(Mo.Provider,{value:{name:e.name},children:t(v,{...e})}),Bo=()=>{const e=n.useContext(Mo),t=n.useContext(zo),{getFieldState:r,formState:s}=S(),a=r(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...a}},zo=n.createContext({}),Vo=n.forwardRef(({className:e,...r},s)=>{const a=n.useId();return t(zo.Provider,{value:{id:a},children:t("div",{ref:s,className:ne("space-y-2",e),...r})})});Vo.displayName="FormItem";const Go=n.forwardRef(({className:e,...r},n)=>{const{error:s,formItemId:a}=Bo();return t(Do,{ref:n,className:ne(s&&"text-destructive",e),htmlFor:a,...r})});Go.displayName="FormLabel";const Jo=n.forwardRef(({...e},r)=>{const{error:n,formItemId:s,formDescriptionId:a,formMessageId:i}=Bo();return t(x,{ref:r,id:s,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...e})});Jo.displayName="FormControl";const Ko=n.forwardRef(({className:e,...r},n)=>{const{formDescriptionId:s}=Bo();return t("p",{ref:n,id:s,className:ne("text-sm text-muted-foreground",e),...r})});Ko.displayName="FormDescription";const Ho=n.forwardRef(({className:e,children:r,...n},s)=>{const{error:a,formMessageId:i}=Bo(),o=a?String(a?.message):r;return o?t("p",{ref:s,id:i,className:ne("text-sm font-medium text-destructive",e),...n,children:o}):null});Ho.displayName="FormMessage";const Yo=n.forwardRef(({className:e,...r},n)=>t(Z.Root,{className:ne("grid gap-2",e),...r,ref:n}));Yo.displayName=Z.Root.displayName;const Qo=n.forwardRef(({className:e,...r},n)=>t(Z.Item,{ref:n,className:ne("aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),...r,children:t(Z.Indicator,{className:"flex items-center justify-center",children:t(Q,{className:"h-3.5 w-3.5 fill-primary"})})}));Qo.displayName=Z.Item.displayName;const Zo=n.forwardRef(({className:r,children:n,...s},a)=>e(X.Root,{ref:a,className:ne("relative overflow-hidden",r),...s,children:[t(X.Viewport,{className:"h-full w-full rounded-[inherit]",children:n}),t(Xo,{}),t(X.Corner,{})]}));Zo.displayName=X.Root.displayName;const Xo=n.forwardRef(({className:e,orientation:r="vertical",...n},s)=>t(X.ScrollAreaScrollbar,{ref:s,orientation:r,className:ne("flex touch-none select-none transition-colors","vertical"===r&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===r&&"h-2.5 border-t border-t-transparent p-[1px]",e),...n,children:t(X.ScrollAreaThumb,{className:ne("relative rounded-full bg-border","vertical"===r&&"flex-1")})}));function ec(e){return`data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text x="50%" y="50%" dominant-baseline="middle" alignment-baseline="middle" text-anchor="middle" font-size="50" font-family="sans-serif">${e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}</text></svg>`}Xo.displayName=X.ScrollAreaScrollbar.displayName;const tc=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑‍💻","👨‍💻","👩‍💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨‍💼","👩‍💼","👨‍🏫","👩‍🏫","👨‍🔬","👩‍🔬","👨‍🎨","👩‍🎨","👨‍🔧","👩‍🔧","👨‍🚀","👩‍🚀","👨‍⚖️","👩‍⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️‍🌈","🎟️","🎫"];function rc(e,t){const{response:r}=ka();return i(()=>{if(!e)return{hasSeatPricing:!1,memberCount:0,includedSeats:0,maxUsers:0,maxSeats:0,limitSource:"none",billableSeats:0,availableSeats:1/0,isAtMax:!1,isNearMax:!1,perSeatPriceCents:null,currency:"",canInvite:!0,inviteBlockReason:null,inviteBlockMessageKey:null,inviteBlockMessageValues:null};const n=e.users?.length??0,s=r?.planVersion,a=r?.subscription,i=e.billingCurrency||"usd",o=mr({planVersion:s,currency:i,settingsMaxUsers:t?.settingsMaxUsers}),{maxUsers:c,hasSeatPricing:l,includedSeats:d}=o,u=l?Math.max(0,n-d):0,p=c>0?Math.max(0,c-n):1/0,m=c>0&&n>=c,h=c>0&&n>=.8*c&&!m,g=l&&s?lr(s,i,a?.billingInterval??"monthly"):null,f=hr({memberCount:n,maxUsersConfig:o});return{hasSeatPricing:l,memberCount:n,includedSeats:d,maxUsers:c,maxSeats:c,limitSource:o.source,billableSeats:u,availableSeats:p,isAtMax:m,isNearMax:h,perSeatPriceCents:g,currency:i,canInvite:f.canInvite,inviteBlockReason:f.blockReason,inviteBlockMessageKey:f.blockMessageKey,inviteBlockMessageValues:f.blockMessageValues}},[r,e,t?.settingsMaxUsers])}function nc({title:r,children:n,className:s}){return e("div",{className:ne("px-2 flex flex-col gap-1",s),children:[t("div",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wide px-2 pb-1 shrink-0 whitespace-nowrap",children:r}),n]})}function sc({icon:r,label:n,active:s=!1,onClick:a,className:i}){return e("button",{className:ne("flex w-full text-start px-2 py-2.5 sm:py-1 rounded text-sm items-center gap-x-2 sm:gap-x-1 whitespace-nowrap shrink-0",s?"bg-primary/10 text-primary font-medium":"hover:bg-muted hover:text-foreground",i),onClick:a,"aria-current":s?"true":void 0,children:[r,t("span",{className:"min-w-0 truncate",children:n}),t(D,{"aria-hidden":"true",className:"h-4 w-4 ms-auto opacity-40 sm:hidden rtl:rotate-180"})]})}const ac=g(()=>import("./SettingsDialog-D2lDYNYo.mjs").then(function(e){return e.S}).then(e=>({default:e.default})));const ic=({children:n})=>{const{currentWorkspace:s,switchToWorkspace:a,workspaces:i}=hi(),[o,c]=m(!1),[d,p]=m(ci.Profile),g=l(!1);return u(()=>{const e=di.getState();c(e.open),p(e.section);return di.subscribe(e=>{c(e.open),p(e.section)})},[]),u(()=>{if(g.current)return;if(!s)return;const e=ut();if(!e)return;const t=function(e){if(e.screen&&li.has(e.screen))return e.screen;switch(e.action){case at.Checkout:case at.Billing:case at.SelectPlan:return ci.Subscription;case at.CreditPurchase:return ci.Credits;case at.OpenConnectGuide:return ci.ConnectedAgents;default:return null}}(e);if(!t)return g.current=!0,void pt();const r=e.ws;if(r&&r!==s._id){const e=i.find(e=>e._id===r);return e?void a(e).catch(e=>{pe(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:r}}),g.current=!0,pt()}):(g.current=!0,void pt())}g.current=!0,di.openWorkspaceSettings(t,e),pt()},[s,i,a]),e(r,{children:[n,s&&o&&t(Ar,{fallback:null,children:t(h,{fallback:null,children:t(ac,{workspace:s,open:o,onOpenChange:e=>{e||di.closeSettings()},section:d,onSectionChange:e=>{di.setSection(e)},showTrigger:!1})})})]})},oc=(e,t,r)=>{if(t!==Be.V1)throw new Error(`Invalid version: "${t}". Only "${Be.V1}" is currently supported.`);if(!e||"string"!=typeof e)throw new Error("serverUrl is required and must be a string");if(!(e=>{try{return new URL(e),!0}catch{return!1}})(e))throw new Error(`Invalid serverUrl: "${e}". Must be a valid URL.`);if(!r||"string"!=typeof r)throw new Error("orgId is required and must be a string");if(!/^[0-9a-fA-F]{24}$/.test(r))throw new Error(`Invalid orgId: "${r}". Must be a valid MongoDB ObjectId (24 hexadecimal characters).`)},cc=s.memo(({serverUrl:e,version:r,orgId:n,auth:a,locale:i,defaultPermissions:o,getCheckoutStripeParams:c,loadingComponent:l,ui:d,mcp:p,tracking:m,children:h})=>{oc(e,r,n);const g=s.useMemo(()=>({serverUrl:e,version:r,orgId:n}),[e,r,n]),f=s.useMemo(()=>a?.callbacks,[a?.callbacks?.handleAuthentication,a?.callbacks?.onSignOut,a?.callbacks?.getSession,a?.callbacks?.onSessionExpired,a?.callbacks?.handleEvent,a?.callbacks?.onWorkspaceChange]),y=a?.callbacks?.handleEvent;return u(()=>(Je.setCallbacks(y?{handleEvent:y}:null),()=>{Je.setCallbacks(null)}),[y]),t(An,{locale:i,messageOverrides:d?.messages,children:t(Sn,{children:t(Wa,{loadingComponent:l,children:t(wi,{callbacks:f,children:t(Si,{children:t(vi,{config:g,auth:a,children:t(mi,{children:t(xn,{getCheckoutStripeParams:c,children:t(Ba,{appPermissions:o,children:t(Ha,{ui:d,children:t(ja,{mcp:p,children:t(Di,{children:t(va,{children:t(Ga,{children:t(Ua,{children:t(Ni,{children:m&&a?.clientId?t(Js,{serverUrl:e,orgId:n,clientId:a.clientId,...m,children:t(ic,{children:t(Fi,{children:h})})}):t(ic,{children:h})})})})})})})})})})})})})})})})})});cc.displayName="SaaSOSProviderInner";const lc=({children:e,...r})=>t(Ar,{errorTitle:r.ui?.errorBoundary?.title,retryLabel:r.ui?.errorBoundary?.retryLabel,children:t(cc,{...r,children:e})});lc.displayName="SaaSOSProvider";const dc=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{status:s}=bi();return Ur(s).isLoading?r??null:s!==Er.authenticated?n??null:t},uc=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{status:s}=bi();return Ur(s).isLoading?r??null:s!==Er.unauthenticated?n??null:t};dc.displayName="WhenAuthenticated",uc.displayName="WhenUnauthenticated";const pc="https://www.buildbase.app",mc={"built-with":{sm:{width:120,height:40},md:{width:144,height:48},lg:{width:168,height:56}},"powered-by":{sm:{width:150,height:30},md:{width:180,height:36},lg:{width:210,height:42}},mark:{sm:{width:88,height:24},md:{width:110,height:30},lg:{width:132,height:36}}},hc={"built-with":"Built with BuildBase","powered-by":"Powered by BuildBase",mark:"BuildBase"};function gc(e,t){return`${pc}/badge/v1/${e}.svg?theme=${t}`}function fc(e){const t=(e??"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64).replace(/-+$/g,"");return t.length>0?t:void 0}function yc(e,{refCode:t,params:r}={}){const n=new URLSearchParams({utm_source:"badge",utm_medium:e}),s=fc(t);s&&n.set("ref",s);for(const[e,t]of Object.entries(r??{}))e&&null!=t&&n.set(e,String(t));return`${pc}/?${n.toString()}`}const bc=({variant:e="built-with",theme:r="auto",size:n="md",alt:s,className:a,link:i=!0,refCode:o,params:c})=>{const l=mc[e][n],d=t("img",{src:gc(e,r),alt:s??hc[e],width:l.width,height:l.height,loading:"lazy",decoding:"async"});return i?t("a",{href:yc(e,{refCode:o,params:c}),target:"_blank",rel:"noopener",className:ne("inline-block",a),children:d}):t("span",{className:a,children:d})},wc=e=>{const{children:t,fallback:r,roles:n}=e,{user:s}=bi();return n.includes(s?.role??"")?t:r||null},vc=e=>{const{children:t,fallback:r,roles:n}=e,{user:s}=bi(),{currentWorkspace:a}=hi(),i=a?.users.find(e=>e._id===s?.id);return i&&n.includes(i?.role??"")?t:r||null};wc.displayName="WhenRoles",vc.displayName="WhenWorkspaceRoles";const kc=e=>{const{children:t,fallback:r,permission:n}=e,{can:s}=Yi();return s(n)?t:r??null};function Sc(){const e=d(Li);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return i(()=>({attributes:e.attributes,loading:e.attributesLoading,error:e.attributesError,refetch:e.refreshAttributes,updateAttributes:e.updateAttributes,updateAttribute:e.updateAttribute,isLoading:e.isLoading,refreshAttributes:e.refreshAttributes}),[e])}function Cc(){const e=d(Li);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return i(()=>({features:e.features,loading:e.featuresLoading,error:e.featuresError,refetch:e.refreshFeatures,isFeatureEnabled:t=>Boolean(e.features[t]),isLoading:e.featuresLoading,refreshFeatures:e.refreshFeatures}),[e])}kc.displayName="WhenPermission";const xc=e=>{const{children:t,slug:r}=e,{currentWorkspace:n}=hi(),s=n?.features?.[r];return s?t:null},Nc=e=>{const{children:t,slug:r}=e,{currentWorkspace:n}=hi(),s=n?.features?.[r];return ii(!!n&&!s,`workspace:${r}`,"feature_gate_shown",{feature:r,scope:"workspace"}),s?null:t},Pc=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:n}=Cc();return n(r)?t:null},Ic=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:n,loading:s}=Cc(),a=n(r);return ii(!s&&!a,`user:${r}`,"feature_gate_shown",{feature:r,scope:"user"}),a?null:t};xc.displayName="WhenWorkspaceFeatureEnabled",Nc.displayName="WhenWorkspaceFeatureDisabled",Pc.displayName="WhenUserFeatureEnabled",Ic.displayName="WhenUserFeatureDisabled";const _c=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:s,loading:a}=ka();return a?r??null:s?.subscription?t:n??null},Ec=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:s,loading:a}=ka();return a?r??null:s?.subscription?n??null:t},Uc=e=>{const{children:t,plans:r,loadingComponent:n,fallbackComponent:s}=e,{response:a,loading:i}=ka(),o=a?.subscription?a.plan??a.subscription?.plan:void 0,c=r.map(e=>e.trim().toLowerCase()),l=(o?.slug??"").toLowerCase(),d=!!o&&c.includes(l),{currentWorkspace:u}=hi();return ii(!!u&&!i&&!d&&null!=s,c.join(","),"plan_gate_shown",{required_plans:c.join(","),current_plan:l||"none"}),i?n??null:d?t:s??null},Ac=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:s,loading:a}=ka();return a?r??null:"trialing"!==s?.subscription?.subscriptionStatus?n??null:t},Tc=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{response:s,loading:a}=ka();return a?r??null:s?.subscription?.subscriptionStatus===Jt.Trialing?n??null:t},Oc=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{behavior:s}=Ya(),a=e.daysThreshold??s?.trialEndingDays??3,{response:i,loading:o}=ka();if(o)return r??null;const c=i?.subscription;if(!c||"trialing"!==c.subscriptionStatus)return n??null;const l=c.trialEnd||c.stripeCurrentPeriodEnd;if(!l)return n??null;const d=new Date(l);if(isNaN(d.getTime()))return n??null;return Math.max(0,Math.ceil((d.getTime()-Date.now())/864e5))>a?n??null:t};_c.displayName="WhenSubscription",Ec.displayName="WhenNoSubscription",Uc.displayName="WhenSubscriptionToPlans",Ac.displayName="WhenTrialing",Tc.displayName="WhenNotTrialing",Oc.displayName="WhenTrialEnding";const Rc=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:s}=e,{quotas:a,loading:i}=Ja(),o=i?void 0:a?.[t];return ii(!!o&&o.available<=0&&null!=s,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),i?n??null:o?o.available<=0?s??null:r:s??null},Wc=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:s}=e,{quotas:a,loading:i}=Ja(),o=i?void 0:a?.[t];return ii(!!o&&o.available<=0,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),i?n??null:o?o.available>0?s??null:r:s??null},$c=e=>{const{slug:t,children:r,loadingComponent:n,fallbackComponent:s}=e,{quotas:a,loading:i}=Ja();if(i)return n??null;const o=a?.[t];return o&&o.hasOverage&&!1!==o.allowOverage?r:s??null},Fc=e=>{const{slug:t,threshold:r,children:n,loadingComponent:s,fallbackComponent:a}=e,{quotas:i,loading:o}=Ja(),c=o?void 0:i?.[t],l=c?c.included>0?c.consumed/c.included*100:c.consumed>0?100:0:0;return ii(!!c&&l>=r,`${t}@${r}`,"quota_threshold_reached",{quota:t,threshold:r,percent_used:Math.round(l)}),o?s??null:c?l<r?a??null:n:a??null};Rc.displayName="WhenQuotaAvailable",Wc.displayName="WhenQuotaExhausted",$c.displayName="WhenQuotaOverage",Fc.displayName="WhenQuotaThreshold";const Lc=({children:e})=>{const{currentWorkspace:t}=hi(),r=t?._id,{balance:n,loading:s,error:a,refetch:i}=Aa(),{packages:o,loading:c}=Na(r),{consumeCredits:l,loading:d,error:u}=Ca(r),{purchaseCredits:p,loading:m,error:h}=xa(r);return e({balance:n,loading:s,packages:o,packagesLoading:c,consume:l,consuming:d,purchase:async e=>{if(!r)throw new Error("No workspace selected");const{successUrl:t,cancelUrl:n}=dt(r),s=await p({creditPackageId:e._id,successUrl:t,cancelUrl:n});s.url&&yt(s.url)},purchasing:m,refetch:i,error:u||h||a})};Lc.displayName="CreditActionsProvider";const Dc=({children:e})=>{const{balance:t,loading:r,error:n,refetch:s}=Aa();return e({balance:t,loading:r,error:n,refetch:s})};function jc({children:n,loadingFallback:s,errorFallback:a,redirectBaseUrl:i}){const{packages:o,notes:c,loading:l,error:d,refetch:u}=_a(),{isAuthenticated:m,signIn:h}=bi(),g=p(e=>{if(m)di.openWorkspaceSettings(ci.Credits,{action:at.CreditPurchase,packageId:e});else if(i){const t=ct({action:at.CreditPurchase,screen:"credits",packageId:e},i);h(t)}else h()},[m,h,i]);return l?void 0!==s?t(r,{children:s}):e("div",{className:"space-y-4",children:[t(ao,{className:"h-8 w-48"}),t("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(e=>t(ao,{className:"h-48 rounded-lg"},e))})]}):d?a?t(r,{children:a(d)}):t("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:d}):t(r,{children:n({loading:l,error:d,packages:o,notes:c,refetch:u,selectPackage:g})})}Dc.displayName="CreditBalance";const Mc=e=>{const{min:t=1,children:r,loadingComponent:n,fallbackComponent:s}=e,{balance:a,loading:i}=Aa();return i?n??null:a?a.available<t?s??null:r:s??null},qc=e=>{const{children:t,loadingComponent:r,fallbackComponent:n}=e,{balance:s,loading:a}=Aa();return a?r??null:s?s.available>0?n??null:t:n??null},Bc=e=>{const{threshold:t,children:r,loadingComponent:n,fallbackComponent:s}=e,{balance:a,loading:i}=Aa();return i?n??null:a?a.available>t?s??null:r:s??null};function zc(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}function Vc(){const{response:e}=ka();return i(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const r=zc(t.trialEnd)??zc(t.stripeCurrentPeriodEnd),n=zc(t.trialStart),s=r?Math.max(0,Math.ceil((r.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:s,trialEndsAt:r,trialStartedAt:n,isTrialEnding:s<=3}},[e])}Mc.displayName="WhenCreditsAvailable",qc.displayName="WhenCreditsExhausted",Bc.displayName="WhenCreditsLow";const Gc=J.object({name:J.string().min(1,"Please enter your name").max(50,"Name must be less than 50 characters").regex(/^[\p{L}\p{M}\s'-]*$/u,"Name can only contain letters and spaces"),email:J.string().min(1,"Please enter your email address").email("Please enter a valid email address").max(100,"Email must be less than 100 characters").regex(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,"Please enter a valid email format (e.g., name@domain.com)")}),Jc=({onSuccess:n,onError:s,className:a="w-full",fieldClassName:i="flex flex-col gap-1.5 w-full",autoFocus:o=!0,showSuccessMessage:c=!0,hideLogo:l=!1,hideTitles:d=!1})=>{const{t:h}=Ln(),[g,f]=m(!1),[y,b]=m(!1),{submitBetaForm:v,isLoading:S,isSubmitting:x,error:N,config:P,success:I,message:_}=(()=>{const{t:e}=Ln(),t=Qs(),[r,n]=m(null),[s,a]=m(!0),[i,o]=m(!1),[c,l]=m(null),[d,h]=m(!1),[g,f]=m(null);return u(()=>{let r=!1;return(async()=>{a(!0),l(null);try{const e=new We(t),s=await e.fetchConfig();r||n(s)}catch(t){r||l(t instanceof Error?t.message:e("beta.errorMessage"))}finally{r||a(!1)}})(),()=>{r=!0}},[t]),{isLoading:s,isSubmitting:i,config:r,error:c,success:d,message:g,submitBetaForm:p(async r=>{if(!t){const t=e("errors.generic");return l(t),{success:!1,message:t}}try{o(!0),l(null),h(!1),f(null);const e=new We(t),n=await e.submitBetaUser({name:r.name||"",email:r.email}),s="success"===n.status;return h(s),f(n.message),{success:s,message:n.message}}catch(t){const r=t instanceof Error?t.message:e("beta.errorMessage");return l(r),h(!1),f(r),{success:!1,message:r}}finally{o(!1)}},[t])}})();u(()=>{I&&c&&(f(!0),b(!0)),N&&b(!0)},[I,c,N]);const E=C({resolver:w(Gc),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});u(()=>{o&&E.setFocus("name")},[o,E]);const U=E.formState.isValid&&!x;return t("div",{className:"saas-os-ui",style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:e("div",S?{className:ne("flex flex-col items-center justify-center w-full px-2.5 sm:px-6 py-2.5 sm:py-6 gap-y-2.5 sm:gap-y-4",a),children:[t(ao,{className:"h-24 w-24 rounded-lg"}),t(ao,{className:"h-6 w-32"}),e("div",{className:"w-full space-y-4",children:[e("div",{className:"space-y-2",children:[t(ao,{className:"h-4 w-16"}),t(ao,{className:"h-10 w-full"})]}),e("div",{className:"space-y-2",children:[t(ao,{className:"h-4 w-16"}),t(ao,{className:"h-10 w-full"})]}),t(ao,{className:"h-10 w-full"})]})]}:{className:"flex flex-col items-center justify-center w-full px-2.5 sm:px-6 py-2.5 sm:py-6 gap-y-2.5 sm:gap-y-4",children:[!l&&e("div",{className:"flex flex-col items-center justify-center w-full",children:[P?.logo&&t(Hc,{logo:P?.logo}),P?.name&&t("div",{children:P?.name})]}),t(k,{...E,children:e("form",{onSubmit:E.handleSubmit(async e=>{try{const t=await v(e);t.success?(n?.(),E.reset(),c&&f(!0),b(!0)):(s?.(t.message),b(!0))}catch(e){s?.(e instanceof Error?e.message:h("beta.errorMessage")),b(!0)}}),className:a,noValidate:!0,"aria-busy":x,children:[!y&&e(r,{children:[!d&&P?.screen?.register&&t(Kc,{screen:P?.screen?.register}),t(qo,{control:E.control,name:"name",render:({field:r})=>e(Vo,{className:i,children:[t(Go,{children:h("beta.nameLabel")}),t(Jo,{children:t(Oo,{...r})}),t(Ko,{}),t(Ho,{})]})}),t(qo,{control:E.control,name:"email",render:({field:r})=>e(Vo,{className:i,children:[t(Go,{children:h("beta.emailLabel")}),t(Jo,{children:t(Oo,{...r})}),t(Ko,{}),t(Ho,{})]})}),t(Mi,{type:"submit",disabled:!U,className:i,children:h(x?"beta.submittingText":"beta.submitText")})]}),y&&N&&e("div",{className:"flex flex-col items-center justify-center w-full",children:[e("div",{className:"border-destructive/30 text-destructive",role:"alert","aria-live":"assertive","aria-atomic":!0,children:[t("span",{className:"text-4xl mb-2",role:"img","aria-label":h("settings.common.error"),children:"❗"}),N]}),t("div",{className:"mt-4 flex justify-center",children:t(Mi,{type:"button",onClick:()=>{b(!1),E.reset()},className:i,children:h("beta.tryAgain")})})]}),y&&g&&_&&t("div",{className:"flex flex-col items-center justify-center w-full text-success border-success/30 text-center",children:P?.screen?.thankYou&&t(Kc,{screen:P?.screen?.thankYou})})]})}),!y&&t("div",{children:e("div",{children:[h("beta.privacyConsent")," ",t("a",{href:P?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:h("beta.privacyPolicy")})," ",h("beta.and")," ",t("a",{href:P?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:h("beta.termsOfService")}),"."]})})]})})};function Kc({screen:r}){return e("div",{className:"flex flex-col items-center justify-center w-full",children:[t("p",{className:"text-2xl font-bold",children:r?.title}),t("p",{className:"text-sm text-muted-foreground",children:r?.description})]})}function Hc({logo:e}){const{t:r}=Ln();return t("img","string"==typeof e?{src:e,alt:r("beta.logoAlt"),className:"max-h-24"}:{src:e.bucket?.url,alt:r("beta.logoAlt"),className:"max-h-24"})}function Yc({slug:n,children:s,loadingFallback:a,errorFallback:i,redirectBaseUrl:o}){const{items:c,plans:l,notes:d,loading:u,error:m,refetch:h}=ra(n),{isAuthenticated:g,signIn:f}=bi(),{currentWorkspace:y,fetchWorkspaces:b}=hi(),{emit:w}=oi();ii(!u&&!m&&l.length>0,n,"pricing_viewed",{pricing_slug:n,plan_count:l.length,authenticated:g});const v=p((e,t,r)=>o?ct({action:"selectPlan",plan:e,interval:t,currency:r},o):null,[o]),k=p((e,t,r)=>{if(w("pricing_plan_selected",{pricing_slug:n,plan_version_id:e,billing_interval:t,currency:r?r.toUpperCase():void 0,authenticated:g}),g)return di.openWorkspaceSettings(ci.Subscription,{action:"selectPlan",plan:e,interval:t,currency:r}),void(y||b());const s=v(e,t,r);f(s??void 0)},[g,f,v,w,n,y,b]);return u?void 0!==a?t(r,{children:a}):e("div",{className:"space-y-4",children:[t(ao,{className:"h-8 w-48"}),t("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(e=>t(ao,{className:"h-64 rounded-lg"},e))})]}):m?i?t(r,{children:i(m)}):t("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:m}):t(r,{children:s({loading:u,error:m,items:c,plans:l,notes:d,refetch:h,selectPlan:k})})}const Qc=n.forwardRef(({className:e,...r},n)=>t(K.Root,{ref:n,className:ne("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...r}));Qc.displayName=K.Root.displayName;const Zc=n.forwardRef(({className:e,...r},n)=>t(K.Image,{ref:n,className:ne("aspect-square h-full w-full",e),...r}));Zc.displayName=K.Image.displayName;const Xc=n.forwardRef(({className:e,...r},n)=>t(K.Fallback,{ref:n,className:ne("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...r}));Xc.displayName=K.Fallback.displayName;const el=n.forwardRef(({className:e,orientation:r="horizontal",decorative:n=!0,...s},a)=>t(ee.Root,{ref:a,decorative:n,orientation:r,className:ne("shrink-0 bg-border","horizontal"===r?"h-[1px] w-full":"h-full w-[1px]",e),...s}));el.displayName=ee.Root.displayName;const tl=g(()=>import("./SettingsDialog-D2lDYNYo.mjs").then(function(e){return e.S}).then(e=>({default:e.default})));function rl(n){const{t:s,dir:a}=Ln(),{isAuthenticated:i,user:o}=bi(),c=ze(Qs()),{workspaces:l,currentWorkspace:d,loading:p,refreshing:g,switchingToId:f,fetchWorkspaces:y,getFeatures:b,refreshWorkspaces:w,setCurrentWorkspace:v,switchToWorkspace:k}=hi(),{settings:S,loading:C}=ea(),{visible:x}=Qi(),[N,I]=m(!1),[_,E]=m(0),[U,A]=m(""),T=p||g;u(()=>{i&&c&&(0===l.length?(y(),b()):b())},[i,c]),u(()=>{i&&c&&_>0&&w()},[_,i,c]);const O=l,R=O.filter(e=>e._id!==d?._id).filter(e=>e.name.toLowerCase().includes(U.toLowerCase())),W=(S?.workspace?.canCreateWorkspace??!0)&&x(e=>e.workspaceSwitcher?.createButton),$=(S?.workspace?.showSwitcher??!0)&&x(e=>e.workspaceSwitcher?.show),F=S?.workspace?.maxWorkspacesPerUser??0,L=O?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===o?.id?.toString()).length??0,D=!1!==W&&(0===F||L<F);u(()=>{!$&&l.length>0&&!d&&k(l[0]).catch(e=>{pe(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[$,l,d]);const{emit:B}=oi();return u(()=>{N&&$&&B("workspace_switcher_opened",{workspace_count:l.length})},[N]),C&&!S?t(r,{children:n.trigger?.(!0,d)}):!$&&d?e(r,{children:[t("div",{role:"button",tabIndex:0,"aria-label":s("settings.common.openSettings"),className:"cursor-pointer",onClick:()=>I(!0),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),I(!0))},children:n.trigger?.(T,d)}),t(h,{fallback:null,children:t(tl,{workspace:d,open:N,onOpenChange:I,showTrigger:!1})})]}):e(qi,{open:N,onOpenChange:I,children:[t(Bi,{children:n.trigger?.(T,d)}),e(Gi,{dir:a,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e(Ji,{dir:a,children:[e(Ki,{className:"flex items-center gap-2",children:[t(j,{className:"h-5 w-5"}),s("workspace.switchTitle")]}),t(Hi,{children:s("workspace.switchDescription")})]}),!o&&t("div",{className:"flex flex-col items-center justify-center h-full py-4 sm:py-8",children:t("div",{className:"text-sm font-medium text-muted-foreground",children:s("workspace.notLoggedIn")})}),o&&e("div",{dir:a,className:"flex flex-col gap-4",children:[d&&t(nl,{workspace:d,isCurrentWorkspace:!0,switchToWorkspace:k,switchingToId:f,setCurrentWorkspace:v,setOpen:I,workspacesToUse:O}),t(el,{}),e("div",{children:[e("div",{className:"flex items-center justify-between",children:[t("div",{className:"text-sm font-medium text-muted-foreground",children:s("workspace.availableWorkspaces",{count:R.length})}),t("div",{children:t(Mi,{progress:g,disabled:g,variant:"ghost",onClick:function(){i&&c&&E(e=>e+1)},startIcon:t(M,{}),children:s("settings.common.refreshAction",{loading:String(g)})})})]}),e("div",{className:"relative",children:[t(q,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),t(Oo,{placeholder:s("workspace.searchPlaceholder"),value:U,onChange:e=>A(e.target.value),className:"ps-10"})]}),p?e("div",{className:"flex items-center justify-center py-8",children:[t(P,{className:"h-6 w-6 animate-spin text-muted-foreground"}),t("span",{className:"ms-2 text-sm text-muted-foreground",children:s("workspace.loadingWorkspaces")})]}):0===R.length?e("div",{className:"text-center py-8",children:[t(j,{className:"mx-auto h-12 w-12 text-muted-foreground"}),t("p",{className:"mt-2 text-sm text-muted-foreground",children:s(U?"workspace.noWorkspacesFound":"workspace.noWorkspacesAvailable")})]}):t(Zo,{className:"h-64",dir:a,children:t("div",{dir:a,className:"flex flex-col gap-2 my-2.5",children:R.map(e=>{const r=e._id===d?._id;return t(nl,{workspace:e,isCurrentWorkspace:r,switchToWorkspace:k,switchingToId:f,setCurrentWorkspace:v,setOpen:I,workspacesToUse:O},e._id)})})})]}),D&&e(r,{children:[t(el,{}),t(sl,{onCreated:()=>{y()}})]})]})]})]})}function nl(r){const{t:n}=Ln(),{visible:s}=Qi(),a=s(e=>e.workspaceSwitcher?.memberCount),i=s(e=>e.workspaceSwitcher?.planBadge),{workspace:o,setCurrentWorkspace:c,setOpen:l,workspacesToUse:d,switchingToId:u}=r,p=r.isCurrentWorkspace??!1,m=u===o._id,g=o.subscription??null,f=null!=g&&"object"==typeof g?g.plan??null:null,y=f?.name??"";return e("div",{className:ne("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":p}),children:[e(Qc,{className:"h-8 w-8 flex items-center justify-center",children:[t("div",{children:t(Zc,{src:o.image&&o.image.trim()?o.image:void 0})}),t(Xc,{children:(b=o.name,b.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2))})]}),e("div",{className:"flex-1 min-w-0 max-w-full",children:[t("div",{className:"flex items-center gap-2",children:t("span",{className:"font-medium line-clamp-1 text-ellipsis overflow-hidden max-w-full",children:o.name})}),a&&e("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[t(B,{className:"h-3 w-3"}),t("span",{children:n("workspace.membersCount",{count:o.users?.length||0})})]}),i&&y&&t("div",{className:"max-w-fit",children:t("div",{className:"flex items-center gap-1 text-sm bg-success text-success-foreground rounded-full px-2 py-0.5",children:t("span",{className:"text-xs",children:y})})})]}),e("div",{className:"flex items-center gap-2",children:[p?null:t(Mi,{size:"sm",disabled:null!==u||m,progress:m,onClick:()=>{r.switchToWorkspace(o).then(()=>l(!1)).catch(e=>{pe(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:o._id}})})},children:n("workspace.switchTo")}),t(h,{fallback:null,children:t(tl,{workspace:o,onClose:()=>{if(p){const e=d.findIndex(e=>e._id?.toString()===o._id?.toString());-1!==e&&c(d[e])}}})})]})]});var b}function sl(n){const{t:s,dir:a}=Ln(),{switching:i}=hi(),[o,c]=m(!1),[l,d]=m("emoji"),[u,p]=m("🏢"),[h,g]=m(!1),{createWorkspace:f}=hi(),y=J.object({name:J.string().min(2,{message:s("workspace.workspaceNameMinLength")}),image:J.string().optional()}),b=C({resolver:w(y),defaultValues:{name:"",image:""}});return e(qi,{open:o,onOpenChange:c,children:[t(Bi,{asChild:!0,children:e(Mi,{className:"w-full rounded-none",disabled:i,children:[t(T,{className:"h-4 w-4 me-2"}),s("workspace.createNew")]})}),e(Gi,{dir:a,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e(Ji,{children:[t(Ki,{children:s("workspace.createTitle")}),t(Hi,{children:s("workspace.createDescription")})]}),t(jo,{...b,children:e("form",{onSubmit:b.handleSubmit(async function(e){let t="";if("emoji"===l)t=ec(u);else if("url"===l&&e.image)try{new URL(e.image),t=e.image}catch{return void b.setError("image",{message:s("workspace.invalidUrl")})}g(!0);try{await f(e.name,t),c(!1),b.reset(),p("🏢"),d("emoji"),n?.onCreated?.()}catch(t){pe(t,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{g(!1)}}),children:[t(qo,{control:b.control,name:"name",render:({field:r})=>e(Vo,{children:[t(Go,{children:s("workspace.workspaceName")}),t(Jo,{children:t(Oo,{placeholder:s("workspace.workspaceNamePlaceholder"),...r})}),t(Ho,{})]})}),e("div",{className:"flex flex-col gap-y-2 my-2",children:[e("div",{children:[t(Do,{className:"text-sm font-medium",children:s("workspace.workspaceIcon")}),t(Ko,{children:s("workspace.iconDescription")})]}),e(Yo,{value:l,onValueChange:e=>d(e),className:"flex flex-col gap-y-2",children:[e("div",{className:"flex items-center gap-x-2 my-1",children:[t(Qo,{value:"emoji",id:"emoji"}),e(Do,{htmlFor:"emoji",className:"flex items-center gap-2",children:[t(z,{className:"h-4 w-4"}),s("workspace.chooseEmoji")]})]}),e("div",{className:"flex items-center gap-x-2 my-1",children:[t(Qo,{value:"url",id:"url"}),e(Do,{htmlFor:"url",className:"flex items-center gap-2",children:[t(V,{className:"h-4 w-4"}),s("workspace.customImageUrl")]})]})]}),"emoji"===l&&e("div",{className:"flex flex-col gap-y-2",children:[e("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-medium",children:s("general.previewLabel")}),t("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:u})]}),t(Zo,{className:"h-32 w-full rounded-md border",children:t("div",{className:"p-4 grid grid-cols-8 gap-2",children:tc.map((e,r)=>t("button",{type:"button",onClick:()=>(e=>{p(e),b.setValue("image",ec(e))})(e),"aria-label":e,"aria-pressed":u===e,className:"w-10 h-10 sm:w-8 sm:h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(u===e?"bg-primary text-primary-foreground":""),children:e},r))})})]}),"url"===l&&e("div",{className:"flex flex-col gap-y-2",children:[t(qo,{control:b.control,name:"image",render:({field:r})=>e(Vo,{children:[t(Go,{children:s("workspace.imageUrl")}),t(Jo,{children:t(Oo,{placeholder:s("workspace.imageUrlPlaceholder"),...r})}),t(Ko,{children:s("workspace.imageUrlDescription")}),t(Ho,{})]})}),b.watch("image")&&b.watch("image")?.trim()&&e("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-medium",children:s("general.previewLabel")}),t("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:t("img",{src:b.watch("image")||void 0,alt:s("general.previewImageAlt"),className:"w-full h-full object-cover",onError:e=>{e.currentTarget.style.display="none"}})})]})]})]}),e("div",{className:"flex justify-end gap-3 pt-4",children:[t(Mi,{type:"button",variant:"outline",onClick:()=>{c(!1),b.reset(),p("🏢"),d("emoji")},disabled:h,children:s("settings.common.cancel")}),t(Mi,{type:"submit",disabled:h,children:h?e(r,{children:[t(P,{className:"me-2 h-4 w-4 animate-spin"}),s("workspace.creating")]}):s("workspace.createWorkspace")})]})]})})]})]})}export{Do as $,ea as A,Mi as B,mo as C,qi as D,no as E,yo as F,bo as G,ko as H,So as I,xo as J,No as K,ho as L,Co as M,Io as N,Po as O,Sr as P,pe as Q,Ro as R,ao as S,Fo as T,jo as U,qo as V,Vo as W,Go as X,Jo as Y,Oo as Z,Ho as _,Gi as a,Ct as a$,Nt as a0,Ko as a1,Yo as a2,Qo as a3,Zo as a4,tc as a5,ec as a6,Pi as a7,ta as a8,za as a9,nt as aA,Ja as aB,ka as aC,nr as aD,bi as aE,rc as aF,vr as aG,ci as aH,nc as aI,sc as aJ,Ya as aK,Qa as aL,Ha as aM,Bi as aN,li as aO,er as aP,ar as aQ,cs as aR,Be as aS,Oe as aT,Er as aU,ot as aV,st as aW,Te as aX,Jc as aY,bc as aZ,lc as a_,ki as aa,eo as ab,da as ac,ro as ad,Kt as ae,Vt as af,Gt as ag,Ht as ah,ir as ai,qt as aj,Jt as ak,ii as al,la as am,oa as an,ma as ao,ha as ap,ua as aq,ia as ar,oi as as,or as at,tr as au,cr as av,lr as aw,Yt as ax,rr as ay,lt as az,Ki as b,Mt as b$,xt as b0,po as b1,$e as b2,Lc as b3,Dc as b4,Ua as b5,Qt as b6,Zt as b7,jc as b8,xr as b9,Fc as bA,wc as bB,_c as bC,Uc as bD,Oc as bE,Ac as bF,uc as bG,Ic as bH,Pc as bI,Nc as bJ,xc as bK,vc as bL,qe as bM,rl as bN,dr as bO,ur as bP,pr as bQ,pt as bR,St as bS,fc as bT,kt as bU,ct as bV,Je as bW,La as bX,$t as bY,Lt as bZ,Dt as b_,Fe as ba,Ge as bb,Oa as bc,It as bd,_t as be,_r as bf,Yc as bg,Le as bh,Ni as bi,Ga as bj,Ve as bk,In as bl,De as bm,je as bn,va as bo,Me as bp,dc as bq,Mc as br,qc as bs,Bc as bt,Ec as bu,Tc as bv,kc as bw,Rc as bx,Wc as by,$c as bz,Hi as c,zt as c0,sr as c1,jt as c2,Ir as c3,et as c4,Ot as c5,Da as c6,Rt as c7,ut as c8,mr as c9,Cc as cA,hr as cB,ft as cC,Pr as ca,vt as cb,ya as cc,Xi as cd,Zi as ce,Ca as cf,Sa as cg,Eo as ch,_o as ci,$a as cj,pa as ck,Ma as cl,aa as cm,_a as cn,na as co,ra as cp,fa as cq,ga as cr,Qs as cs,$o as ct,Wo as cu,sa as cv,Vc as cw,ca as cx,ba as cy,Sc as cz,ne as d,Tt as e,Wt as f,Pt as g,Yi as h,Qi as i,Aa as j,Na as k,Ia as l,Pa as m,xa as n,at as o,it as p,Qe as q,fo as r,so as s,to as t,Ln as u,dt as v,di as w,yt as x,Xt as y,hi as z};