@buildbase/sdk 0.0.82 → 0.0.84
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +11 -3
- package/CHANGELOG.md +95 -0
- package/README.md +138 -41
- package/dist/css/styles.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +288 -8
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -1
- package/dist/mcp/index.d.ts +40 -0
- package/dist/mcp/index.mjs +1 -1
- package/dist/react/chunks/SettingsDialog-DImZc0fo.cjs +2 -0
- package/dist/react/chunks/SettingsDialog-DuqMmX00.mjs +2 -0
- package/dist/react/chunks/{SubscriptionDialog-CuUoM9hd.cjs → SubscriptionDialog-C4I66PXv.cjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-ClWD2NgN.mjs → SubscriptionDialog-hXscplmw.mjs} +1 -1
- package/dist/react/chunks/ar-Bv7MJdID.mjs +2 -0
- package/dist/react/chunks/ar-UyL2IcEN.cjs +2 -0
- package/dist/react/chunks/de-BjV4j4L8.mjs +2 -0
- package/dist/react/chunks/de-BpFTP77W.cjs +2 -0
- package/dist/react/chunks/es-BD83AlAI.mjs +2 -0
- package/dist/react/chunks/es-Cg0WHGyt.cjs +2 -0
- package/dist/react/chunks/fr-DC4nKToc.cjs +2 -0
- package/dist/react/chunks/fr-DUSYz0eM.mjs +2 -0
- package/dist/react/chunks/hi-BUaHa-qu.mjs +2 -0
- package/dist/react/chunks/hi-LZW4ZZQj.cjs +2 -0
- package/dist/react/chunks/ja-BYVJft1g.cjs +2 -0
- package/dist/react/chunks/ja-CXjz9Ptf.mjs +2 -0
- package/dist/react/chunks/react-BW__KLHg.mjs +2 -0
- package/dist/react/chunks/react-BoHqKQID.cjs +2 -0
- package/dist/react/chunks/zh-BBVxXvHQ.mjs +2 -0
- package/dist/react/chunks/zh-BtxE6oq5.cjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +189 -6
- package/dist/react/index.mjs +1 -1
- package/docs/ARCHITECTURE.md +7 -6
- package/docs/ERROR_CODES.md +35 -0
- package/docs/MCP-AND-AGENT-READINESS.md +1 -1
- package/docs/SERVER-CONTENT.md +10 -5
- package/package.json +2 -1
- package/dist/react/chunks/SettingsDialog-B0s01DfC.cjs +0 -2
- package/dist/react/chunks/SettingsDialog-BDzOpoTW.mjs +0 -2
- package/dist/react/chunks/ar-4O9xrkV6.mjs +0 -2
- package/dist/react/chunks/ar-Dcph0Rl-.cjs +0 -2
- package/dist/react/chunks/de-D0wYkKfr.cjs +0 -2
- package/dist/react/chunks/de-ITC4I4gE.mjs +0 -2
- package/dist/react/chunks/es-D4d7IQzB.cjs +0 -2
- package/dist/react/chunks/es-DDUCoxrg.mjs +0 -2
- package/dist/react/chunks/fr-BomsBzOa.cjs +0 -2
- package/dist/react/chunks/fr-BsWwwise.mjs +0 -2
- package/dist/react/chunks/hi-BmpRGcI3.cjs +0 -2
- package/dist/react/chunks/hi-D5uXZGQc.mjs +0 -2
- package/dist/react/chunks/ja-D5amIGZT.cjs +0 -2
- package/dist/react/chunks/ja-DkMcdOxv.mjs +0 -2
- package/dist/react/chunks/react-Cs1KN_wQ.mjs +0 -2
- package/dist/react/chunks/react-DWVzbgNV.cjs +0 -2
- package/dist/react/chunks/zh-BRYcvEMm.cjs +0 -2
- package/dist/react/chunks/zh-C8cgAVXA.mjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import*as r from"react";import i,{Component as a,useMemo as s,useSyncExternalStore as o,createContext as c,useRef as l,useContext as d,useEffect as u,useCallback as p,useState as h,Suspense as m,lazy as g}from"react";import{clsx as f}from"clsx";import{twMerge as y}from"tailwind-merge";import w from"intl-messageformat";import{Slot as v}from"@radix-ui/react-slot";import{cva as b}from"class-variance-authority";import{Loader2 as k,ChevronDown as S,Check as I,Copy as x,ExternalLink as C,Bot as N,Plus as P,Monitor as _,Smartphone as E,X as A,ShieldCheck as U,Bell as T,MonitorSmartphone as O,ChevronRight as R,MailOpen as W,BellOff as F,Mail as L,Archive as $,Building2 as D,RefreshCcw as M,Search as j,Users as q,Smile as B,Image as V}from"lucide-react";import*as z from"@radix-ui/react-dialog";import{Cross2Icon as G,CheckIcon as J}from"@radix-ui/react-icons";import{zodResolver as H}from"@hookform/resolvers/zod";import{Controller as K,FormProvider as Y,useFormContext as Q,useForm as Z}from"react-hook-form";import*as X from"@radix-ui/react-label";import{z as ee}from"zod";import*as te from"@radix-ui/react-avatar";import*as ne from"@radix-ui/react-radio-group";import*as re from"@radix-ui/react-scroll-area";import*as ie from"@radix-ui/react-separator";import*as ae from"@radix-ui/react-accordion";import*as se from"@radix-ui/react-alert-dialog";import*as oe from"@radix-ui/react-popover";function ce(...e){return y(f(e))}let le=!0;function de(e,...t){le&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function ue(e,...t){console.error(e,...t)}function pe(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,i=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){i(n);break}n.addEventListener("abort",()=>i(n),{once:!0})}return r.signal}function he(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function me(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 ge(e,t="Request failed"){if(!e.ok){let n,r=t;try{const t=await me(e);r=t.message||t.error||r,"string"==typeof t.code&&(n=t.code)}catch{r=function(e,t){const n={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}: ${n})`)}(e,t).message}throw Object.assign(new Error(r),{status:e.status,...n?{code:n}:{}})}try{return await me(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class fe extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,fe)}}const ye=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&&(le=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(he(e))return;const n=e instanceof Error?e:new fe("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),r=n instanceof fe?n:new fe(n.message,"SDK_ERROR",t,n);if(this.config.enableConsoleLogging&&de(`[SDK Error] ${t.component||"Unknown"}:`,{message:r.message,code:r.code,context:r.context,originalError:r.originalError,stack:r.stack}),this.config.onError)try{this.config.onError(r,t)}catch(e){ue("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(r,t)}catch(e){ue("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(r,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function we(e,t={}){ye.handleError(e,t)}function ve(e,t={}){return!he(e)&&(ye.handleError(e,t),!0)}function be(e,t,n){return e instanceof Error?e.message:n(t)}function ke(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return we(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function Se(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){we(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function Ie(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){we(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function xe(e,t){const n=ke(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(we(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),Ie(e),null):r}catch(t){return we(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),Ie(e),null}}function Ce(e,t){try{Se(e,JSON.stringify(t))}catch(t){we(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const Ne="saas-session-id",Pe="saas-device-id",_e="code",Ee="state";function Ae(e){Se(Ne,e)}function Ue(){Ie(Ne)}function Te(){if("undefined"==typeof window)return null;try{return ke(Ne)}catch(e){return we(e,{component:"auth-utils",action:"getSessionId",metadata:{key:Ne}}),null}}function Oe(e){if("undefined"!=typeof window&&e)try{Se(Pe,e)}catch(e){we(e,{component:"auth-utils",action:"setDeviceId",metadata:{key:Pe}})}}function Re(){const e=Te(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return ke(Pe)??null}catch(e){return we(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:Pe}}),null}}();return n&&(t["x-device-id"]=n),t}function We(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(_e)}catch(e){return we(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:_e}}),null}}function Fe(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(_e),e.searchParams.delete(Ee),window.history.replaceState({},"",e.toString())}catch(e){we(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:_e}})}}const Le=new WeakSet,$e=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),De="SDK is not ready (missing serverUrl, version, or orgId)";class Me{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(De);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(De)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:Re()}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){Le.has(e)||(Le.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((n,r)=>{const i=()=>{clearTimeout(a),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return i();const a=setTimeout(()=>{t?.removeEventListener("abort",i),n()},e);t?.addEventListener("abort",i,{once:!0})})}async executeFetchUrl(e,t,n){const r=(t.method??"GET").toUpperCase(),i=n??e,a=this.buildHeaders(t),s={...t,headers:a},o=$e.has(r);let c,l;if(this._timeout>0){l=new AbortController;const e=l;c=setTimeout(()=>e.abort(),this._timeout),s.signal=t.signal?pe(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: ${r} ${i}`);return this.reportError(e,{method:r,path:i}),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 n=this._fetch.bind(globalThis),i=await n(e,s);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${i.status}`),401===i.status&&this._onUnauthorized&&this._onUnauthorized(),i.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 Me.delay(e,s.signal),u(t+1)}return i}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 Me.delay(e,s.signal)}catch(e){throw d(e)}return u(t+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:i}),e}};try{return await u(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await ge(r,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async fetchForeign(e,t={}){return this._fetch.call(globalThis,e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw Object.assign(new Error(n),{status:e.status})}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class je extends Me{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let i=await r(e);if(400===i.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:a,invitationToken:s,...o}=e;i=await r(o)}return i.ok||await this.throwResponseError(i,n),this.unwrapResponse(i,n)}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 n=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return n?.deviceToken??""}catch{return""}}async logout(e,t,n){await this.fetchJson("logout",{method:"POST",...e?{headers:{"x-session-id":e}}:{},...t?.all?{body:JSON.stringify({all:!0})}:{},signal:n},"Failed to sign out")}}class qe extends Me{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 Be=class{constructor(e){this.api=new qe(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),i=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:n,language:r,timezone:i,currency:a}})}};class Ve extends Me{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 ze extends Me{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,n){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"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")}}function Ge(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))void 0!==r&&""!==r&&!1!==r&&t.set(n,String(r));const n=t.toString();return n?`?${n}`:""}const Je=e=>JSON.stringify(e?{workspaceId:e}:{});class He extends Me{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${Ge({workspaceId:e.workspaceId,unread:e.unread,archived:e.archived,page:e.page,limit:e.limit})}`,{signal:t},"Failed to load notifications");return{notifications:n?.notifications??[],page:n?.page??e.page??1,limit:n?.limit??e.limit??20,total:n?.total??0,hasNextPage:Boolean(n?.hasNextPage)}}async counts(e,t){const n=await this.fetchJson(`notifications/unread-count${Ge({workspaceId:e})}`,{signal:t},"Failed to load notification count");return{unread:n?.unread??0,unseen:n?.unseen??0}}markRead(e){return this.itemAction(this.apiPath`notifications/${e}/read`,"POST",!0)}markUnread(e){return this.itemAction(this.apiPath`notifications/${e}/unread`,"POST")}archive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"POST")}unarchive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"DELETE")}async markAllRead(e){await this.fetchJson("notifications/read-all",{method:"POST",body:Je(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:Je(e)},"Failed to mark notifications seen")}async itemAction(e,t,n=!1){return this.fetchJson(e,n?{method:t,keepalive:n}:{method:t},"Failed to update notification")}}class Ke extends Me{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 Ye extends Me{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 Qe extends Me{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}const Ze="image/png,image/jpeg,image/gif,image/webp,image/svg+xml",Xe=5242880,et={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"};function tt(e){if(e.type)return e.type;const t=(e.name??"").split(".").pop()?.toLowerCase()??"";return et[t]??""}function nt(e){const{status:t,code:n}=e??{};return"UPLOAD_TOO_LARGE"===n||413===t?"tooLarge":"INVALID_UPLOAD"===n?"invalid":"UPLOADS_DISABLED"===n?"disabled":"USER_UPLOAD_LIMIT"===n?"userLimit":"UPLOADS_UNAVAILABLE"===n||429===t||501===t||503===t?"unavailable":"failed"}function rt(e){const t=e?.uploads,n=Number(t?.maxFileBytes);return{enabled:!!t&&!1!==t.enabled,maxFileBytes:Number.isFinite(n)&&n>0?Math.min(n,Xe):Xe}}function it(e,t){return t.enabled?e.size>t.maxFileBytes?"tooLarge":null:"disabled"}function at(e,t){const n=1048576,[r,i]=e>=n?[e/n,"megabyte"]:[e/1024,"kilobyte"];try{return new Intl.NumberFormat(t,{style:"unit",unit:i,unitDisplay:"short",maximumFractionDigits:1}).format(r)}catch{return`${Math.round(10*r)/10} ${"megabyte"===i?"MB":"KB"}`}}class st extends Me{constructor(e){super(e)}async upload(e,t){const{purpose:n,signal:r}=t,i=await this.fetchJson("uploads",{method:"POST",body:JSON.stringify({purpose:n,name:e.name??"file",size:e.size,contentType:tt(e)}),signal:r},"Could not start the upload");let a;const s=new AbortController,o=setTimeout(()=>s.abort(),12e4);try{a=await this.fetchForeign(i.url,{method:"PUT",headers:i.headers,body:e,signal:r?pe(r,s.signal):s.signal})}catch(e){if(r?.aborted)throw e;throw new Error("The upload to storage did not finish. Check the connection and try again.")}finally{clearTimeout(o)}if(!a.ok)throw Object.assign(new Error(`The upload to storage was refused (HTTP ${a.status}). Try again.`),{status:a.status});return this.fetchJson(this.apiPath`uploads/${i.uploadId}/complete`,{method:"POST",body:"{}",signal:r},"Could not finish the upload")}}class ot extends Me{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 n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}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 n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}const ct={NOT_FOUND:"INVITATION_NOT_FOUND",EXPIRED:"INVITATION_EXPIRED",ALREADY_HANDLED:"INVITATION_ALREADY_HANDLED",EMAIL_MISMATCH:"INVITATION_EMAIL_MISMATCH",EMAIL_NOT_VERIFIED:"EMAIL_NOT_VERIFIED",INVITES_DISABLED:"WORKSPACE_INVITES_DISABLED",RATE_LIMITED:"INVITATION_RATE_LIMITED",EMAIL_FAILED:"INVITATION_EMAIL_FAILED",SEAT_LIMIT:"SEAT_LIMIT_REACHED",USER_BLOCKED:"USER_BLOCKED",NO_SENDER_CONFIGURED:"NO_SENDER_CONFIGURED"},lt={402:ct.SEAT_LIMIT,404:ct.NOT_FOUND,409:ct.ALREADY_HANDLED,410:ct.EXPIRED,429:ct.RATE_LIMITED,502:ct.EMAIL_FAILED,503:ct.NO_SENDER_CONFIGURED};function dt(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function ut(e){return"string"==typeof e&&e?e:void 0}async function pt(e,t){let n=null;try{n=await e.json()}catch{n=null}return function(e,t,n){const r=t&&"object"==typeof t?t:{},i=ut(r.message)??ut(r.error)??n,a={status:e,code:ut(r.code)??lt[e]??`HTTP_${e}`,currentUserCount:dt(r.currentUserCount),limit:dt(r.limit),retryAfterSeconds:dt(r.retryAfterSeconds),invitedEmail:ut(r.invitedEmail),invitationId:ut(r.invitationId),invitationStatus:ut(r.status)};return Object.assign(new Error(i),a)}(e.status,n,t)}function ht(e){return e instanceof Error&&"number"==typeof e.status}class mt extends Me{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"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,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await pt(r,n);return ge(r,n)}async listInvitations(e,t){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{signal:t},"Failed to fetch invitations")}async inviteMember(e,t,n){const r={email:t.email,role:t.role};return t.landingUrl&&(r.landingUrl=t.landingUrl),this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{method:"POST",body:JSON.stringify(r),signal:n},"Failed to send invitation")}async resendInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}/resend`,{method:"POST",signal:n},"Failed to resend invitation")}async revokeInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}`,{method:"DELETE",signal:n},"Failed to revoke invitation")}async myInvitations(e){return this.fetchInvitation("invitations",{signal:e},"Failed to fetch your invitations")}async acceptInvitation(e,t,n){return this.fetchInvitation(this.apiPath`invitations/${e}/accept`,{method:"PATCH",signal:n,...t?.token?{body:JSON.stringify({token:t.token})}:{}},"Failed to accept invitation")}async declineInvitation(e,t){return this.fetchInvitation(this.apiPath`invitations/${e}/reject`,{method:"PATCH",signal:t},"Failed to decline invitation")}async previewInvitation(e,t){if(!this.orgId)throw new Error("orgId is required for previewInvitation");return this.fetchInvitation(this.apiPath`${this.orgId}/invitations/preview/${e}`,{signal:t},"Failed to load invitation")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"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,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getMyPermissions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/permissions/me`,{signal:t},"Failed to fetch workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"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,n){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"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,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"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,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const i=new URLSearchParams;return i.append("limit",t.toString()),n&&i.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${i.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"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,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"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,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),a=this.apiPath`workspaces/${e}/subscription/usage/logs`+(i?`?${i}`:"");return this.fetchUnwrapped(a,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,i){const a={event:t};return n&&(a.userId=n),r&&(a.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(a),signal:i},"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,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getMyNotificationPreferences(e,t){const n=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{signal:t},"Failed to fetch your notification preferences");return{defaults:n?.defaults??{},mine:n?.mine??{}}}async updateMyNotificationPreferences(e,t,n){const r=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update your notification preferences");return{defaults:r?.defaults??{},mine:r?.mine??{}}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.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(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),a=this.apiPath`workspaces/${e}/credits/transactions`+(i?`?${i}`:"");return this.fetchUnwrapped(a,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const i=r.toString(),a=this.apiPath`workspaces/${e}/credits/buckets`+(i?`?${i}`:"");return this.fetchUnwrapped(a,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}var gt;function ft(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}!function(e){e.V1="v1"}(gt||(gt={}));const yt={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",WorkspaceInvitationSent:"workspace:invitation-sent",WorkspaceInvitationAccepted:"workspace:invitation-accepted",WorkspaceInvitationDeclined:"workspace:invitation-declined",WorkspaceInvitationRevoked:"workspace:invitation-revoked"};class wt{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){we(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const n=this.listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch(t){we(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(yt.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(yt.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(yt.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(yt.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(yt.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(yt.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(yt.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(yt.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(yt.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(yt.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(yt.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(yt.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(yt.WorkspaceDeleted,{workspace:e})}}const vt=new wt,bt=globalThis;function kt(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=bt[t]??(bt[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const St=kt("credit-balance"),It=St.subscribe,xt=St.invalidate,Ct=kt("quota-usage"),Nt=Ct.subscribe,Pt=Ct.invalidate,_t=kt("subscription"),Et=_t.subscribe,At=_t.invalidate,Ut="bb",Tt={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},Ot={Success:"success",Cancel:"cancel",Error:"error"},Rt={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function Wt(e,t){const n=t??("undefined"!=typeof window?window.location.href:"https://localhost");let r;try{r=new URL(n)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(n)}`)}return r.search="",r.searchParams.set(Ut,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function Ft(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Wt({action:Tt.Checkout,status:Ot.Success,ws:e,screen:Rt.Subscription},n),cancelUrl:Wt({action:Tt.Checkout,status:Ot.Cancel,ws:e,screen:Rt.Subscription},n)}}function Lt(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Wt({action:Tt.CreditPurchase,status:Ot.Success,ws:e,screen:Rt.Credits},n),cancelUrl:Wt({action:Tt.CreditPurchase,status:Ot.Cancel,ws:e,screen:Rt.Credits},n)}}function $t(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(Ut);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),i=decodeURIComponent(e.slice(n+1));r&&(t[r]=i)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function Dt(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(Ut)&&(e.searchParams.delete(Ut),window.history.replaceState({},"",e.toString()))}catch{}}const Mt="__buildbaseBeforeLeave",jt=globalThis,qt=jt[Mt]??(jt[Mt]=new Set);function Bt(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let n;try{n=new URL(e)}catch{return null}const r="https:"===n.protocol,i="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!i)return null;const{sameOrigin:a,allowedOrigins:s}=t;return a||s?.length?a&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||s?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}function Vt(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=Bt(e,n)??Bt(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===qt.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of qt)try{e()}catch{}}(r),window.location.href=r,!0}const zt="saas-auth-intent";function Gt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function Jt(e){Bt(e,{sameOrigin:!0})&&Ce(zt,{returnUrl:e,createdAt:Date.now()})}function Ht(){const e=xe(zt,Gt);return Ie(zt),e?Date.now()-e.createdAt>6e5?null:Bt(e.returnUrl,{sameOrigin:!0}):null}function Kt(){Ie(zt)}const Yt={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:"฿"},Qt={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function Zt(e){return e&&e.trim()?Qt[e.trim().toLowerCase()]??"":""}function Xt(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Yt[t]??t.toUpperCase()}const en=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],tn=en.map(e=>({value:e,label:`${e.toUpperCase()} (${Xt(e)})`})),nn=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),rn=new Set(["bhd","jod","kwd","omr","tnd"]),an=new Map;function sn(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(nn.has(t))return 0;if(rn.has(t))return 3;if("isk"===t)return 2;let n=an.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}an.set(t,n)}return n}function on(e){return""!==(e??"").trim()&&0===sn(e)}function cn(e,t){const n=sn(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function ln(e,t,n="en-US"){const r=(t??"").trim(),i=sn(r),a=e/10**i;if(!r)return a.toFixed(i);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:i,maximumFractionDigits:i}).format(a)}catch{return Xt(r)+(0===i?a.toLocaleString("en-US"):a.toFixed(i))}}function dn(e,t){return Xt(t)+cn(e,t)}const un={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};function pn(e,t,n,r,i){if(null==e||e<0)return null;const a={...un,...r},s=null!=t&&t>=1?t:1,o=Xt(n),c=cn(e,n);return 1===s?`${o}${c}/${a.unit}`:`${o}${c}/${s.toLocaleString(i)} ${a.units}`}function hn(e,t,n,r,i,a,s){if(null==e||e<0)return null;const o={...un,...a},c=null!=t&&t>=1?t:1,l=Xt(r),d=cn(e,r);if(n){const e=i??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${d}/${c.toLocaleString(s)} ${e}`:`${l}${d}/${n}`}return 1===c?`${l}${d}/${o.unit}`:`${l}${d}/${c.toLocaleString(s)} ${o.units}`}function mn(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t}function gn(e,t,n,r,i,a,s,o,c){const l={...un,...s};if(!1===o)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:s?.hardLimit??"Hard limit";const d=a??(n.endsWith("s")?n:`${n}s`),u=null!=i&&i>=2?`${i.toLocaleString(c)} ${d}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${dn(t,r)}/${u}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${dn(t,r)}/${u}`:"—"}function fn(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null}const yn={included:"included",then:"then",hardLimit:"hard limit"};function wn(e,t,n={}){const{overageInCents:r=!0,currency:i}=n,a={...yn,...n.labels},s=n.currencySymbol??Xt(i??"");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=sn(i),u=r&&d>0?c/10**d:c,p="number"==typeof u&&Number.isFinite(u)?0===d?u.toLocaleString("en-US"):u.toFixed(d):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${a.then} ${s}${p}${h}`}function vn(e,t,n={}){if(null==e)return null;const{overageInCents:r=!0,currency:i,locale:a="en"}=n,{included:s,overage:o}=e;if(!(!1!==e.allowOverage))return{included:s,hasOverage:!1,allowOverage:!1,price:"",unit:""};if(null==o)return{included:s,hasOverage:!1,allowOverage:!0,price:"",unit:""};const c=sn(i),l=r&&c>0?o/10**c:o,d=(i??"").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=`${n.currencySymbol??Xt(i??"")}${l.toFixed(c)}`}else{u=`${n.currencySymbol??Xt(i??"")}${"number"==typeof l?l.toFixed(c):String(o)}`}return{included:s,hasOverage:!0,allowOverage:!0,price:u,unit:t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(a)} ${t}`:t||""}}const bn={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},kn={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},Sn={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},In={Feature:"feature",Limit:"limit",Quota:"quota"},xn={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},Cn={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},Nn={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},Pn={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function _n(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function En(e,t,n){const r=_n(e,t);if(!r?.basePricing)return null;const i=r.basePricing[n];return null!=i?i:null}function An(e,t,n){const r=_n(e,t);if(!r?.stripePrices)return null;const i=n===bn.Monthly?"monthlyPriceId":n===bn.Yearly?"yearlyPriceId":"quarterlyPriceId",a=n===bn.Monthly?"monthly":n===bn.Yearly?"yearly":void 0;return r.stripePrices[i]??(a?r.stripePrices[a]:void 0)??null}function Un(e,t,n,r){const i=_n(e,t),a=i?.quotaOverages?.[n];if(a)return a[r]}function Tn(e,t){const n=_n(e,t);return n?n.currency:e.plan?.currency??""}function On(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function Rn(e,t,n,r){const i=e.quotas?.[n];if(null==i)return null;const a=i[r];if(!a)return null;const s=Un(e,t,n,r);return{included:a.included,...void 0!==a.unitSize&&{unitSize:a.unitSize},...void 0!==s&&{overage:s},allowOverage:!1!==i.allowOverage}}function Wn(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null}function Fn(e,t){const n=_n(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Ln(e,t,n){const r=Fn(e,t);return r?.perSeat?r.perSeat[n]??null:null}function $n(e,t){return Math.max(0,e-(t||0))}function Dn(e,t,n,r){const i=Fn(e,t);if(!i)return null;return $n(r,i.includedSeats)*(Ln(e,t,n)??0)}function Mn(e,t,n,r){const i=En(e,t,n);if(null===i)return null;if(void 0===r)return i;return i+(Dn(e,t,n,r)??0)}function jn(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=Fn(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function qn(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:i=!1}=e;if(i&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:a,source:s}=n;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"}[s]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[s]??"users.memberLimitMessage",blockMessageValues:{maxUsers:a}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}function Bn(e,t){return[bn.Monthly,bn.Quarterly,bn.Yearly].filter(n=>n===bn.Monthly||e.some(e=>null!=En(e,t,n)))}const Vn="saas-workspace-current",zn=e=>{e?Se(Vn,e._id):Ie(Vn)},Gn=()=>ke(Vn),Jn=()=>{Ie(Vn)},Hn=(e,t)=>!!e&&t.some(t=>t._id===e);function Kn(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}function Yn(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}const Qn={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",WORKSPACE_USAGE_RECORD:"workspace:usage:record"},Zn=Object.values(Qn),Xn={admin:Zn.filter(e=>e!==Qn.WORKSPACE_DELETE),editor:[Qn.WORKSPACE_SETTINGS_VIEW,Qn.WORKSPACE_MEMBERS_VIEW,Qn.WORKSPACE_FEATURES_VIEW,Qn.WORKSPACE_BILLING_VIEW,Qn.WORKSPACE_USAGE_VIEW,Qn.WORKSPACE_USAGE_RECORD],viewer:[Qn.WORKSPACE_SETTINGS_VIEW,Qn.WORKSPACE_MEMBERS_VIEW]},er="viewer";function tr(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(er)?er:e.find(e=>"admin"!==e)??""}function nr(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function rr(e){const{userId:t,workspace:n,settings:r,appPermissions:i}=e;if(!n||!t)return new Set;if(Kn(n,t)){const e=new Set(Zn);if(i)for(const t of nr(i))e.add(t);if(n.permissions)for(const t of nr(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of nr(r.workspace.permissions))e.add(t);return e}const a=e.workspaceRole??Yn(n,t);return a?ir(a,e):new Set}function ir(e,t,n={}){const{workspace:r,settings:i,appPermissions:a}=t;if(!r)return new Set;const s=r.permissions,o=i?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),d=e=>!!s&&e in s,u=e=>!!o&&e in o,p=e=>d(e)||u(e)||e in Xn;let h,m=e;if(!p(e)){const e=i?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;m=e}h=d(m)?c(s[m]):u(m)?c(o[m]):Xn[m]??[];const g=new Set(h),f=new Set((i?.workspace?.customPermissions??[]).map(e=>e.key)),y=a?.[m]?l(a[m]).filter(e=>!f.has(e)):[];let w;w=d(m)?l(s[m]):u(m)?[...l(o[m]),...y]:a?.[m]?l(a[m]):[];for(const e of w)g.add(e);if("admin"===m){for(const e of Xn.admin)g.add(e);for(const e of f)g.add(e);if(a)for(const e of l(nr(a)))g.add(e)}return!1!==n.applyRestrictions&&function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(Qn.WORKSPACE_MEMBERS_INVITE)}(g,m,i),g}function ar(e,t){const n=rr(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const sr="App";function or(e,t){const n=e?.workspace?.customPermissions??[],r=new Map;for(const e of n)e?.key&&!e.key.startsWith("workspace:")&&r.set(e.key,{key:e.key,label:e.label||e.key,group:e.group||sr});for(const e of Object.values(t??{}))for(const t of e??[])t.startsWith("workspace:")||r.has(t)||r.set(t,{key:t,label:t,group:sr});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))}const cr="\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 let payload;\n try {\n payload = event.data.json();\n } catch (e) {\n console.error('[PushSW] Push payload is not JSON:', e);\n return;\n }\n if (!payload || typeof payload !== 'object') return;\n\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 // The tracked click URL (/api/push-track/link/...) wins over any url in\n // payload.data, so a click is always counted.\n const data = Object.assign({}, payload.data && typeof payload.data === 'object' ? payload.data : {});\n if (payload.url) data.url = payload.url;\n // A notification with the same tag replaces the earlier one instead of\n // stacking. No tag means every notification is shown on its own.\n const tag = payload.tag ? String(payload.tag) : undefined;\n const actions = Array.isArray(payload.actions)\n ? payload.actions.filter(function(a) {\n return a && typeof a.action === 'string' && typeof a.title === 'string';\n })\n : undefined;\n\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.badge || payload.icon || undefined,\n image: payload.image || undefined,\n tag: tag,\n // The browser rejects renotify without a tag.\n renotify: tag ? !!payload.renotify : false,\n actions: actions && actions.length ? actions : undefined,\n silent: !!payload.silent,\n requireInteraction: !!payload.requireInteraction,\n timestamp: typeof payload.timestamp === 'number' ? payload.timestamp : undefined,\n dir: payload.dir === 'ltr' || payload.dir === 'rtl' ? payload.dir : 'auto',\n data: data,\n };\n\n event.waitUntil(\n Promise.resolve()\n .then(function() {\n return self.registration.showNotification(title, options);\n })\n .catch(function(e) {\n // A field this browser refuses must not cost the user the\n // notification: show it again with the basics only.\n console.error('[PushSW] Failed to show notification, retrying without rich options:', e);\n return self.registration.showNotification(title, {\n body: options.body,\n icon: options.icon,\n tag: tag,\n data: data,\n });\n })\n );\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n // A click on an action button (event.action is its id) opens the same\n // tracked URL as a click on the notification body.\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 lr;function dr(e){return{isAuthenticated:e===lr.authenticated,isLoading:e===lr.loading||e===lr.redirecting||e===lr.authenticating,isRedirecting:e===lr.redirecting}}function ur(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function pr(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||ur(n.invitedAt)-ur(e.invitedAt))}function hr(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||ur(e.validTill)>t.getTime())}function mr(e,t=new Date){return pr(e.filter(e=>hr(e,t)))}function gr(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!hr(e,t)}function fr(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""}function yr(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace}function wr(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null}function vr(e,t=new Date){const n=ur(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0}function br(e){return e.canView}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(lr||(lr={}));const kr="saas-pending-invite",Sr=/^[0-9a-f]{64}$/;function Ir(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}function xr(e,t){Sr.test(e)&&t&&Ce(kr,{token:e,orgId:t,createdAt:Date.now()})}function Cr(e,t=Date.now()){const n=xe(kr,Ir);return n?t-n.createdAt>864e5?(Ie(kr),null):n.orgId!==e?null:Sr.test(n.token)?n.token:(Ie(kr),null):null}function Nr(){Ie(kr)}class Pr 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(we(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){ue("[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 _r=()=>({type:"AUTHENTICATION_STARTED"}),Er=()=>({type:"AUTHENTICATION_PROCESSING"}),Ar=()=>({type:"AUTHENTICATION_FAILED"}),Ur=e=>({type:"SET_SESSION",payload:e}),Tr=()=>({type:"REMOVE_SESSION"});function Or(e,t,n,r){const i=s(()=>{const t=n??(e=>e);let i,a,s=!1;return()=>{const n=e();if(!s)return s=!0,i=n,a=t(n),a;if(Object.is(i,n))return a;const o=t(n);i=n;return(r?r(a,o):Object.is(a,o))||(a=o),a}},[e,n,r]);return o(t,i,i)}function Rr({name:e,initialState:n,reducer:r,initializer:a}){const o=c(null);o.displayName=`${e}StoreContext`;const d=i.memo(({children:e})=>{const i=l(null);return null===i.current&&(i.current=function(e,t,n){let r=n?n(e):e;const i=new Set;return{getState:()=>r,dispatch:e=>{const n=t(r,e);Object.is(n,r)||(r=n,i.forEach(e=>e()))},subscribe:e=>(i.add(e),()=>{i.delete(e)})}}(n,r,a)),t(o.Provider,{value:i.current,children:e})});d.displayName=`${e}Provider`;const u=(t="Store")=>{const n=i.useContext(o);if(!n)throw(t=>new Error(`use${e}${t} must be used within a ${e}Provider. Make sure SaaSOSProvider is wrapping your application.`))(t);return n};return{Provider:d,useContext:()=>{const e=u("Context"),t=Or(e.getState,e.subscribe);return s(()=>({state:t,dispatch:e.dispatch}),[t,e])},useState:()=>{const e=u("State");return Or(e.getState,e.subscribe)},useDispatch:()=>u("Dispatch").dispatch,useSelector:(e,t)=>{const n=u("Selector");return Or(n.getState,n.subscribe,e,t)},useStore:u}}function Wr(e,t,n){return{...e,[t]:n}}function Fr(e,t){return{...e,...t}}const{Provider:Lr,useDispatch:$r,useStore:Dr}=Rr({name:"Auth",initialState:{session:null,status:lr.loading},reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return Wr(e,"status",lr.redirecting);case"AUTHENTICATION_PROCESSING":return Wr(e,"status",lr.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return Fr(e,{session:null,status:lr.unauthenticated});case"SET_SESSION":return Fr(e,{session:t.payload,status:lr.authenticated});default:return e}}}),Mr=Lr,jr=$r,qr=Dr,Br=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),Vr=e=>({type:"SET_SETTINGS",payload:e}),zr=(e,t)=>({type:"SET_SETTINGS_STATUS",payload:{status:e,error:t}}),Gr=()=>({serverUrl:"",version:gt.V1,orgId:"",settings:null,settingsStatus:"idle",settingsError:null}),{Provider:Jr,useDispatch:Hr,useStore:Kr}=Rr({name:"OS",initialState:Gr(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return Fr(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return Gr();case"SET_SETTINGS":return Fr(e,{settings:t.payload,settingsStatus:"loaded",settingsError:null});case"SET_SETTINGS_STATUS":return Fr(e,{settingsStatus:t.payload.status,settingsError:t.payload.error??null});default:return e}}}),Yr=Jr,Qr=Hr,Zr=Kr,Xr=e=>({type:"SET_WORKSPACES",payload:e}),ei=e=>({type:"ADD_WORKSPACE",payload:e}),ti=e=>({type:"UPDATE_WORKSPACE",payload:e}),ni=e=>({type:"REMOVE_WORKSPACE",payload:e}),ri=e=>({type:"SET_ALL_FEATURES",payload:e}),ii=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),ai=()=>({type:"RESET_CURRENT_WORKSPACE"}),si=e=>({type:"SET_IS_INITIALIZED",payload:e}),oi=e=>({type:"SET_LOADING",payload:e}),ci=e=>({type:"SET_ERROR",payload:e}),li=e=>({type:"SET_REFRESHING",payload:e}),di=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:ui,useDispatch:pi,useStore:hi}=Rr({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 Wr(e,"workspaces",t.payload);case"ADD_WORKSPACE":return Wr(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return Wr(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return Wr(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return Wr(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return Wr(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return Wr(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return Wr(e,"isInitialized",t.payload);case"SET_LOADING":return Wr(e,"loading",t.payload);case"SET_ERROR":return Wr(e,"error",t.payload);case"SET_REFRESHING":return Wr(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return Wr(e,"switchingToId",t.payload);default:return e}}}),mi=ui,gi=pi,fi=hi,yi=i.memo(({children:e})=>t(Yr,{children:t(Mr,{children:t(mi,{children:e})})}));yi.displayName="SDKContextProvider";const wi=c({});wi.displayName="CheckoutConfigContext";const vi=i.memo(({getCheckoutStripeParams:e,children:n})=>{const r=i.useMemo(()=>({getCheckoutStripeParams:e}),[e]);return t(wi.Provider,{value:r,children:n})});vi.displayName="CheckoutConfigProvider";const bi={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",startFree:"Start free",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:{unlimited:"Unlimited",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}",invitations:{title:"Pending invitations",pendingCount:"{count, plural, =0 {none pending} one {# pending} other {# pending}}",sent:"Invitation sent to {email}",resend:"Resend",resendIn:"Resend in {minutes, plural, one {# minute} other {# minutes}}",revoke:"Revoke",revokeTitle:"Revoke invitation?",revokeConfirm:"Withdraw the invitation to {email}? They will be told it is no longer valid.",sentAt:"Sent {date}",expiresAt:"Expires {date}",seatNote:"{count, plural, one {# pending invitation is billed as a seat} other {# pending invitations are billed as seats}} until accepted, declined, revoked or expired.",formerMember:"a former member",loadFailed:"Could not load invitations",resendFailed:"Could not resend the invitation",revokeFailed:"Could not revoke the invitation",status:{invited:"Pending",accepted:"Accepted",rejected:"Declined",expired:"Expired"}}},invitations:{title:"You have been invited",description:"{inviter} invited you to join {workspace} as {role}.",listDescription:"Workspaces waiting for your answer.",titleJoined:"Welcome to {workspace}",titleUnavailable:"Invitation unavailable",sentTo:"Sent to {email}",invitedAs:"{inviter} invited you as {role}",accept:"Accept",decline:"Decline",accepted:"You joined {workspace}.",declined:"Invitation declined.",expired:"This invitation has expired. Ask {inviter} to send a new one.",revoked:"This invitation is no longer valid.",alreadyAccepted:"You already accepted this invitation.",wrongAccount:"This invitation was sent to {email}. Sign out and sign in with that address.",verifyFirst:"Verify your email address to accept this invitation.",workspaceFull:"This workspace has reached its member limit. Ask an admin to make room.",disabled:"This workspace no longer accepts invitations.",empty:"No invitations waiting for you",signInToAccept:"Sign in to accept",dismiss:"Close",signOut:"Sign out",loadFailed:"Could not load the invitation",acceptFailed:"Could not accept the invitation",declineFailed:"Could not decline the invitation"},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",changePicture:"Upload picture",removePicture:"Remove picture",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",uploadImage:"Upload Image",chooseImage:"Choose an image",updateWorkspace:"Update Workspace"},uploads:{description:"PNG, JPG, GIF, WebP or SVG, up to {max}.",uploading:"Uploading...",errorTooLarge:"This image is too large. Choose one up to {max}.",errorInvalid:"This file type is not supported. Use PNG, JPG, GIF, WebP or SVG.",errorDisabled:"Image uploads are turned off for this app.",errorUserLimit:"You have reached your upload limit for this app.",errorUnavailable:"Uploads are not available right now. Try again later.",errorFailed:"The image could not be uploaded. Check your connection and try again."},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:{inbox:{title:"Notifications",description:"Everything this app has sent you.",bellLabel:"Notifications",bellUnread:"{count, plural, one {# unread notification} other {# unread notifications}}",filterAll:"All",filterUnread:"Unread",markAllRead:"Mark all as read",markRead:"Mark as read",markUnread:"Mark as unread",archive:"Archive",loadMore:"Load more",empty:"You're all caught up.",emptyUnread:"No unread notifications.",loadFailed:"Could not load notifications",updateFailed:"Could not update the notification",channelEmail:"Email",channelPush:"Push",opened:"Opened",clicked:"Clicked",notDelivered:"Not delivered"},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.",prefsSaveFailed:"Could not save your notification settings",yourTitle:"Your notifications",yourDescription:"How you hear about each event in this workspace. Everything still appears in your inbox.",defaultsTitle:"Workspace defaults",defaultsDescription:"What members get unless they choose otherwise. A required event can't be changed by members.",requiredLabel:"Required",requiredHint:"Required by this workspace",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."}},ki={en:async()=>bi,es:async()=>(await import("./es-BD83AlAI.mjs")).es,fr:async()=>(await import("./fr-DUSYz0eM.mjs")).fr,de:async()=>(await import("./de-BjV4j4L8.mjs")).de,ja:async()=>(await import("./ja-CXjz9Ptf.mjs")).ja,zh:async()=>(await import("./zh-BBVxXvHQ.mjs")).zh,hi:async()=>(await import("./hi-BUaHa-qu.mjs")).hi,ar:async()=>(await import("./ar-Bv7MJdID.mjs")).ar},Si=["en","es","fr","de","ja","zh","hi","ar"];const Ii={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function xi(e,t){const n={...e};for(const r of Object.keys(t)){const i=t[r],a=e[r];"string"==typeof i?n[r]=i:i&&"object"==typeof i&&a&&"object"==typeof a&&(n[r]=xi(a,i))}return n}const Ci=c({messages:bi,locale:"en",formattingLocale:"en"});function Ni({locale:e="en",messageOverrides:t,children:n}){const r=function(e){const t=e.toLowerCase().replace("_","-");if(Si.includes(t))return t;const n=t.split("-")[0];return Si.includes(n)?n:"en"}(e),[a,o]=i.useState(bi);i.useEffect(()=>{if("en"===r)return void o(bi);let e=!1;const t=ki[r];return t&&t().then(t=>{e||o(t)}),()=>{e=!0}},[r]);const c=s(()=>t?xi(a,t):a,[a,t]),l=function(e){return Ii[e]??e}(r),d=s(()=>({messages:c,locale:r,formattingLocale:l}),[c,r,l]);return i.createElement(Ci.Provider,{value:d},n)}const Pi=new Map,_i=new Map,Ei=new Map;function Ai(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const Ui={getNumberFormat(e,t){const n=Ai(e,t);let r=Pi.get(n);return r||(r=new Intl.NumberFormat(e,t),Pi.set(n,r)),r},getDateTimeFormat(e,t){const n=Ai(e,t);let r=_i.get(n);return r||(r=new Intl.DateTimeFormat(e,t),_i.set(n,r)),r},getPluralRules(e,t){const n=Ai(e,t);let r=Ei.get(n);return r||(r=new Intl.PluralRules(e,t),Ei.set(n,r)),r}},Ti=new Map;function Oi(){const{messages:e,locale:t,formattingLocale:n}=d(Ci),r=s(()=>{const t=(e,t)=>{let n=e;for(const e of t.split(".")){if(!n||"object"!=typeof n||!(e in n))return;n=n[e]}return"string"==typeof n?n:void 0};return(r,i)=>{const a=t(e,r)??t(bi,r)??r;if(!i)return a;try{const e=function(e,t){const n=`${t}:${e}`;let r=Ti.get(n);return r||(r=new w(e,t,void 0,{formatters:Ui}),Ti.set(n,r)),r}(a,n),t=e.format(i);return"string"==typeof t?t:String(t)}catch{return a.replace(/\{(\w+)\}/g,(e,t)=>String(i[t]??`{${t}}`))}}},[e,n]),i="ar"===t?"rtl":"ltr",a=s(()=>e=>e.toLocaleString(n),[n]),o=s(()=>(e,t)=>ln(e,t,n),[n]);return{t:r,locale:t,formattingLocale:n,dir:i,fmtNum:a,fmtCents:o,messages:e}}const Ri=new Map;function Wi(e,t){const n=Ri.get(e);if(n)return n;const r=t().finally(()=>{Ri.get(e)===r&&Ri.delete(e)});return Ri.set(e,r),r}function Fi(){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 Li="bb_attr",$i=["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"],Di=/^[\w.~-]{1,200}$/;function Mi(){return"undefined"==typeof window?null:window}function ji(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??Mi()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),i=`__bb_probe_${Date.now()}`;n.cookie=`${i}=1; domain=${t}; path=/; SameSite=Lax`;const a=n.cookie.includes(`${i}=1`);if(n.cookie=`${i}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,a)return t}return""}const qi="$t",Bi="$l";function Vi(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${Li}=`));if(!t)return{params:{}};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));if("object"!=typeof e||!e)return{params:{}};const{[qi]:n,[Bi]:r,...i}=e;return{params:i,..."number"==typeof n&&n>0?{capturedAt:n}:{},..."string"==typeof r&&r?{landingUrl:r}:{}}}catch{return{params:{}}}}function zi(e){try{const{origin:t,pathname:n}=e.location;return t&&"null"!==t?`${t}${n}`.slice(0,300):void 0}catch{return}}const Gi=$i.filter(e=>!e.startsWith("utm_")),Ji=e=>Gi.some(t=>!!e[t]);function Hi(){const e=Mi();if(!e)return{};const t=e.document,n=function(e){return Vi(e).params}(t),r=function(e){const t=new URLSearchParams(e),n={};for(const e of $i){const r=t.get(e);r&&(r.length>200||Di.test(r)&&(n[e]=r))}return n}(e.location.search),i=Object.keys(r).length>0&&(Ji(r)||!Ji(n)),a=i?r:n;return 0===Object.keys(a).length?{}:(i&&!function(e,t){const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const r of n)if(e[r]!==t[r])return!1;return!0}(r,n)&&function(e,t,n,r){const i=encodeURIComponent(JSON.stringify({...t,[qi]:r.capturedAt,...r.landingUrl?{[Bi]:r.landingUrl}:{}}));e.cookie=`${Li}=${i}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,a,ji(e.location.hostname,t),{capturedAt:Date.now(),landingUrl:zi(e)}),a)}function Ki(){const e=Mi();return e?Vi(e.document):{params:{}}}function Yi(){const e=Ki(),t={};for(const[n,r]of Object.entries(e.params))"string"==typeof r&&r&&/^[a-z_]{2,32}$/.test(n)&&(t[n]=r);if(Object.keys(t).length)return{params:t,...e.capturedAt?{capturedAt:e.capturedAt}:{},...e.landingUrl?{landingUrl:e.landingUrl}:{}}}function Qi(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const Zi="bb_pending_checkout",Xi=216e5;function ea(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}function ta(e){try{ea()?.setItem(Zi,JSON.stringify(e))}catch{}!function(e){if(!e.sessionId)return;const t=ra();if(!t)return;try{const n=ji(window.location?.hostname??"",t);t.cookie=`${na}=${encodeURIComponent(JSON.stringify(e))}; path=/; max-age=21600; SameSite=Lax`+(n?`; domain=${n}`:"")}catch{}}(e)}const na="bb_co";function ra(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function ia(){const e=ra();if(e)try{const t=ji(window.location?.hostname??"",e);e.cookie=`${na}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function aa(e,t){if(!e)return null;try{const n=JSON.parse(e);return n&&"string"==typeof n.eventId&&n.eventId?"number"!=typeof n.startedAt||t-n.startedAt>Xi?null:n:null}catch{return null}}function sa(e=Date.now()){const t=ea();if(!t)return null;let n=null;try{n=t.getItem(Zi),t.removeItem(Zi)}catch{return null}const r=aa(n,e);return r&&ia(),r}function oa(e){try{return aa(ea()?.getItem(Zi)??null,e)}catch{return null}}function ca(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=oa(t);if(r?.sessionId===n)return sa(t);const i=function(e){const t=ra();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${na}=`));return n?aa(decodeURIComponent(n.slice(na.length+1)),e):null}(t);return i?.sessionId!==n?null:(ia(),i)}function la(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 n={};for(const e of t.split(",")){const t=e.indexOf(":");if(-1!==t)try{n[decodeURIComponent(e.slice(0,t))]=decodeURIComponent(e.slice(t+1))}catch{}}return"checkout"===n.action&&"cancel"===n.status}(e)&&oa(t)?sa(t):null}const da=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),ua=new Set(["bhd","jod","kwd","omr","tnd"]);function pa(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return da.has(n)?e:e/(ua.has(n)?1e3:100)}const ha=["AT","BE","BG","HR","CY","CZ","DK","EE","FI","FR","DE","GR","HU","IE","IT","LV","LT","LU","MT","NL","PL","PT","RO","SK","SI","ES","SE","IS","LI","NO"],ma=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/;function ga(e){const t=new Set;for(const n of e??[]){const e=String(n).trim().toUpperCase();if("EEA"===e)for(const e of ha)t.add(e);else ma.test(e)&&t.add(e)}return[...t]}function fa(e,t,n){return e.includes(t)}function ya(e,t,n){const r=(t??"").trim().toUpperCase();if(!/^[A-Z]{2}$/.test(r)||"XX"===r||"T1"===r)return"denied";const i=(n??"").trim().toUpperCase()||void 0,a=ga(e.regions?.denied),s=ga(e.regions?.granted);if(i){if(a.includes(`${r}-${i}`))return"denied";if(s.includes(`${r}-${i}`))return"granted"}return fa(a,r)?"denied":fa(s,r)||"granted"===e.default?"granted":"denied"}function wa(){return"undefined"==typeof window?null:window}const va=["ad_storage","ad_user_data","ad_personalization","analytics_storage"];function ba(e){const t={};for(const n of va)t[n]=e;return t}function ka(e){const t=wa();if(!t)return;const n=t.gtag;n?.("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"}),n?.("set","ads_data_redaction",!e.marketing);const r=t.fbq;r?.("consent",e.marketing?"grant":"revoke")}const Sa="bb_cid";function Ia(){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const e=document.cookie.split("; ").find(e=>e.startsWith(`${Sa}=`)),t=e?.slice(7);if(t&&/^[\w-]{16,64}$/.test(t))return t;const n=function(){const e=globalThis.crypto;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();const t=new Uint8Array(16);if(e&&"function"==typeof e.getRandomValues)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(256*Math.random());return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}(),r=ji(window.location.hostname,document);return document.cookie=`${Sa}=${n}; path=/; max-age=34128000; SameSite=Lax`+(r?`; domain=${r}`:""),n}catch{return}}const xa="bb_consent_recorded";function Ca(e){if("function"!=typeof fetch||!e.serverUrl||!e.orgId||!e.clientId)return;const t=JSON.stringify([e.orgId,e.clientId,!!e.state.analytics,!!e.state.marketing,e.manifestVersion??"",e.consentString??"",e.headers?.["x-session-id"]?"account":"anonymous"]);if(!e.source&&function(e){try{return window.localStorage.getItem(xa)===e}catch{return!1}}(t))return;!function(e){try{window.localStorage.setItem(xa,e)}catch{}}(t);const n=Ia();if(!n)return;const r=`${e.serverUrl.replace(/\/$/,"")}/api/v1/public/${e.orgId}/consent`;try{fetch(r,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",...e.headers??{}},body:JSON.stringify({clientId:e.clientId,visitorId:n,choices:{analytics:!!e.state.analytics,marketing:!!e.state.marketing},...e.manifestVersion?{manifestVersion:e.manifestVersion}:{},...e.source?{source:e.source.slice(0,40)}:{},...e.consentString?{consentString:e.consentString.slice(0,2e3)}:{}})}).catch(()=>{})}catch{}}const Na=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pa=(e,t)=>e>>>t|e<<32-t;function _a(e){return function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(function(e){let t=1779033703,n=3144134277,r=1013904242,i=2773480762,a=1359893119,s=2600822924,o=528734635,c=1541459225;const l=e.length,d=l+1,u=d+(56-d%64+64)%64+8,p=new Uint8Array(u);p.set(e,0),p[l]=128;const h=8*l,m=Math.floor(h/4294967296),g=h>>>0;p[u-8]=m>>>24&255,p[u-7]=m>>>16&255,p[u-6]=m>>>8&255,p[u-5]=255&m,p[u-4]=g>>>24&255,p[u-3]=g>>>16&255,p[u-2]=g>>>8&255,p[u-1]=255&g;const f=new Uint32Array(64);for(let e=0;e<u;e+=64){for(let t=0;t<16;t++){const n=e+4*t;f[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=Pa(f[e-15],7)^Pa(f[e-15],18)^f[e-15]>>>3,n=Pa(f[e-2],17)^Pa(f[e-2],19)^f[e-2]>>>10;f[e]=f[e-16]+t+f[e-7]+n>>>0}let l=t,d=n,u=r,h=i,m=a,g=s,y=o,w=c;for(let e=0;e<64;e++){const t=w+(Pa(m,6)^Pa(m,11)^Pa(m,25))+(m&g^~m&y)+Na[e]+f[e]>>>0,n=l&d^l&u^d&u;w=y,y=g,g=m,m=h+t>>>0,h=u,u=d,d=l,l=t+((Pa(l,2)^Pa(l,13)^Pa(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+d>>>0,r=r+u>>>0,i=i+h>>>0,a=a+m>>>0,s=s+g>>>0,o=o+y>>>0,c=c+w>>>0}const y=new Uint8Array(32),w=[t,n,r,i,a,s,o,c];for(let e=0;e<8;e++)y[4*e]=w[e]>>>24&255,y[4*e+1]=w[e]>>>16&255,y[4*e+2]=w[e]>>>8&255,y[4*e+3]=255&w[e];return y}(e))}async function Ea(e){const t=globalThis.crypto?.subtle;if(t&&"function"==typeof t.digest)try{const n=await t.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return _a((n=e,(new TextEncoder).encode(n)));var n}async function Aa(e){const t=function(e){const t=String(e??"").trim().toLowerCase(),n=t.lastIndexOf("@");if(n<1||n===t.length-1)return"";let r=t.slice(0,n);const i=t.slice(n+1);return"gmail.com"!==i&&"googlemail.com"!==i||(r=r.replace(/\./g,"")),`${r}@${i}`}(e.email),n=function(e){const t=String(e??"").trim();if(!t.startsWith("+"))return"";const n=t.replace(/[^\d]/g,"");return n.length>=8&&n.length<=15?`+${n}`:""}(e.phone),r={};return t&&(r.emailHash=await Ea(t)),n&&(r.phoneHash=await Ea(n)),r}function Ua(e,t){if("undefined"==typeof window)return;if(!t.emailHash&&!t.phoneHash)return;const n=window;e.some(e=>"google_ads"===e.provider||"ga4"===e.provider||"gtm"===e.provider)&&n.gtag?.("set","user_data",{...t.emailHash?{sha256_email_address:t.emailHash}:{},...t.phoneHash?{sha256_phone_number:t.phoneHash}:{}});for(const r of e)"meta_pixel"===r.provider&&r.providerId&&n.fbq?.("init",r.providerId,{...t.emailHash?{em:t.emailHash}:{},...t.phoneHash?{ph:t.phoneHash}:{}})}function Ta(){const e={};try{if("undefined"==typeof document||"string"!=typeof document.cookie)return e;for(const t of document.cookie.split("; ")){const n=t.indexOf("=");n>0&&(e[t.slice(0,n)]=t.slice(n+1))}}catch{}return e}function Oa(e){if(!e)return;const t=e.split(".");if(t.length<4)return;const n=t.slice(-2).join(".");return/^\d+\.\d+$/.test(n)?n:void 0}function Ra(e){if(!e)return;const t=/^GS2\.\d+\.(?:.*?\$)?s(\d+)/.exec(e)??/^GS2\.\d+\.s(\d+)/.exec(e);if(t)return t[1];const n=/^GS1\.\d+\.(\d+)\./.exec(e);return n?n[1]:void 0}function Wa(e){const t={},n=(e,n)=>{n&&(t[`bb_${e}`]=n.slice(0,400))};if("undefined"==typeof window||"undefined"==typeof document)return t;const r=Ta();n("fbp",r._fbp),n("fbc",r._fbc),n("ga_cid",Oa(r._ga));const i=Object.keys(r).find(e=>e.startsWith("_ga_"));n("ga_sid",i?Ra(r[i]):void 0);try{"undefined"!=typeof navigator&&n("ua",navigator.userAgent),"undefined"!=typeof window&&window.location?.origin&&n("url",window.location.origin+window.location.pathname)}catch{}n("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;n("client",e?.clientId)}catch{}return t}function Fa(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}const La=new Set(["workspace_id","workspace_role","workspace_owner","workspace_member_count","workspace_plan","subscription_status"]);function $a(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(e)){if(Object.keys(t).length>=10)break;if(null==r)continue;if(La.has(n))continue;const e=typeof r;"string"!==e&&"number"!==e&&"boolean"!==e||/^[a-z][a-z0-9_]{0,39}$/.test(n)&&(t[`bbp_${n}`]=String(r).slice(0,200))}return t}function Da(...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 Ma(e,t,n,r=30){const i={bb_event_id:e,...Wa(t),...$a(n)},a=Ki();for(const[e,t]of Object.entries(a.params)){if(Object.keys(i).length>=30)break;"string"==typeof t&&t&&(i[`bb_${e}`]=t)}a.capturedAt&&Object.keys(a.params).length&&Object.keys(i).length<30&&(i.bb_attr_ts=String(a.capturedAt));const s=Math.max(0,Math.min(r,30));return Object.fromEntries(Object.entries(i).slice(0,s))}const ja={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}},qa=Object.keys(ja);function Ba(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(ja,e)}function Va(e,t){return!!Ba(e)&&("string"==typeof t&&0!==t.length&&new RegExp(ja[e].idPattern).test(t))}const za=/^[a-z][a-z0-9-]{0,40}$/,Ga=/^[\w.:/@+=-]{1,200}$/;function Ja(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])=>za.test(e)&&"string"==typeof t&&Ga.test(t))}(e.dataAttributes)}Array.from(new Set(qa.map(e=>ja[e].scriptOrigin))).sort();const Ha={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}},Ka=Object.keys(Ha);function Ya(e){return Ka.includes(e)}function Qa(){return"undefined"==typeof window?null:window}const Za={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 Xa(){return"undefined"==typeof window?null:window}function es(e,t={}){const n=Xa();if(!n)return null;const r=n.document.createElement("script");r.async=!0,r.src=e;for(const[e,n]of Object.entries(t))r.setAttribute(e,n);return n.document.head.appendChild(r),r}function ts(e){const t=Xa();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function ns(e){const t=Xa();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const rs=new Set;function is(e){for(const t of rs)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function as(e,t){const n=Xa();if(!n)return!1;if("gtm"===e||"ga4"===e||"google_ads"===e){const e=n.google_tag_manager;return!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t)}const r=Za[e];if(!r)return!1;if(void 0===n[r])return!1;if(rs.has(`${e}:${t}`))return!0;return!ja[e].multiInstance||!is(e)}const ss={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 os(e,t,n){const r=function(e,t,n){const r=Xa();if(!r)return!1;if("external"===e.provider){if(!e.src)return!1;const t={};for(const[n,r]of Object.entries(e.dataAttributes??{}))t[`data-${n}`]=r;return es(e.src,t),!0}const i=e.provider,a=ja[i];if(!a)return!1;const s=e.providerId;if(!s)return!1;const o=ss[i];if(o&&is(i))return ts(o(s)),!0;switch(i){case"gtm":{ns(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return es(`${a.scriptOrigin}/gtm.js?id=${s}${e}`),!0}case"ga4":case"google_ads":{ns(t),es(`${a.scriptOrigin}/gtag/js?id=${s}`);const e=r.gtag;e("js",new Date);const o="ga4"===i&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return o?e("config",s,o):e("config",s),!0}case"meta_pixel":return ts(`!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','${s}');fbq('track','PageView');`),!0;case"x_pixel":return ts(`!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','${s}');`),!0;case"linkedin":return ts(`window._linkedin_partner_id='${s}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${s}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),es(`${a.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return ts(`!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('${s}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return ts(`!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','${s}');rdt('track','PageVisit');`),!0;case"bing_uet":return ts(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${s}',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 ts(`(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','${s}');`),!0;case"hotjar":return ts(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${s},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,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return ts(`!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('${s}',{api_host:'https://${n}'});`),!0}case"plausible":return ts("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),es(`${a.scriptOrigin}/js/script.js`,{"data-domain":s,defer:"true"}),!0;case"ahrefs":return es(`${a.scriptOrigin}/analytics.js`,{"data-key":s}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&rs.add(`${e.provider}:${e.providerId}`),r}const cs=Symbol.for("@buildbase/sdk.tracking.context"),ls=globalThis,ds=ls[cs]??(ls[cs]=c(null)),us={consent:{manifest:[],state:null,effective:null,default:null,country:null,set:()=>{}},track:()=>{},setUser:()=>{},setIdentity:()=>{},setConsentRecordHeaders:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function ps(){return d(ds)??us}function hs(){return null!==d(ds)}const ms=({serverUrl:e,orgId:n,clientId:r,enabled:i=!0,consent:a="auto",autoPageview:o=!0,events:c,onEvent:d,properties:m,enrich:g,identity:f,debug:y=!1,children:w})=>{const v=l(f);v.current=f;const[b,k]=h(null),[S,I]=h(!1),[x,C]=h(!1),N="object"==typeof a?JSON.stringify(a):"",P=s(()=>N?function(e){if(!e||"object"!=typeof e)return null;const t=e;if("granted"!==t.default&&"denied"!==t.default)return null;const n=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):void 0;return{default:t.default,regions:{...n(t.regions?.denied)?{denied:n(t.regions?.denied)}:{},...n(t.regions?.granted)?{granted:n(t.regions?.granted)}:{}}}}(JSON.parse(N)):null,[N]),_="string"==typeof a?a:"auto",E="granted"===_?{analytics:!0,marketing:!0}:"denied"===_?{analytics:!1,marketing:!1}:null,[A,U]=h(E),T=l(null),O=l(d);O.current=d;const R=l(g);R.current=g;const W=l({});W.current=m??{};const F=l({}),L=p(()=>({...W.current,...F.current}),[]),$=p(e=>{const t={...F.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];F.current=t},[]),[D,M]=h({}),j=l({}),[q,B]=h(0),V=l(null),[z,G]=h(0),J=l({}),H=l(null);H.current=b;const K=b?.dataLayerName??"dataLayer",Y=p((...e)=>{y&&console.info("[buildbase:tracking]",...e)},[y]);u(()=>{return e=()=>{0!==Object.keys(j.current).length&&window.dispatchEvent("function"==typeof PageTransitionEvent?new PageTransitionEvent("pagehide",{persisted:!1}):new Event("pagehide"))},qt.add(e),()=>{qt.delete(e)};var e},[]),u(()=>{if(!(i&&e&&n&&r))return void I(!0);let t=!1;const a=`${e.replace(/\/$/,"")}/api/v1/public/${n}/tracking?clientId=${encodeURIComponent(r)}`;return fetch(a).then(e=>e.ok?e.json():null).then(e=>{if(t||!e)return;const n=e.data??e;n&&Array.isArray(n.scripts)&&k(n)}).catch(()=>{Y("config fetch failed; nothing installed")}).finally(()=>{t||I(!0)}),()=>{t=!0}},[i,e,n,r,Y]),u(()=>{i&&M(Hi())},[i]);const Q="auto"===_?P??b?.consent?.defaults??null:null,Z=s(()=>b?"auto"!==_?_:P?ya(P,b.country,b.region):b.consent?.defaults?b.resolvedConsentDefault??ya(b.consent.defaults,b.country,b.region):"denied":null,[b,_,P]),X=A??("granted"===Z?{analytics:!0,marketing:!0}:null),ee=!!b?.enhancedConversions&&!!X?.marketing,te=!!b?.scripts?.some(e=>"ga4"===e.provider||"google_ads"===e.provider||"gtm"===e.provider),ne=Q?JSON.stringify(Q):"";u(()=>{i&&b?.enabled&&(ns(K),function(e,t,n={}){const r=wa();if(!r)return;Array.isArray(r[e])||(r[e]=[]),"function"!=typeof r.gtag&&(r.gtag=function(){r[e].push(arguments)});const i=r.gtag,a="auto"===t?n.regional:null;let s="granted"===t?"granted":"denied";if(a){const e=ga(a.regions?.denied),t=ga(a.regions?.granted).filter(t=>!e.includes(t));e.length&&i("consent","default",{...ba("denied"),region:e,wait_for_update:500}),t.length&&i("consent","default",{...ba("granted"),region:t}),s=a.default}i("consent","default",{...ba(s),..."denied"===s?{wait_for_update:500}:{}}),n.google&&(i("set","url_passthrough",!0),i("set","ads_data_redaction","granted"!==(n.resolved??s)))}(K,_,{regional:ne?JSON.parse(ne):null,resolved:Z,google:te}),T.current&&ka(T.current))},[i,b?.enabled,K,_,ne,te]);const re=s(()=>b?.enabled?b.scripts.filter(e=>{const t=Ba(e.provider)&&ja[e.provider].supportsConsentMode;return function(e,t,n,r){return"denied"!==r&&("granted"===r||!!t||!!n&&("marketing"===e?n.marketing:n.analytics))}(e.consentCategory,t,X,_)}):[],[b,A,Z,_]),[ie,ae]=h(()=>"undefined"==typeof window||!Qi(window.location.search));u(()=>{if(ie)return;const e=setInterval(()=>{Qi(window.location.search)||ae(!0)},50),t=setTimeout(()=>ae(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[ie]),u(()=>{if(!ie)return;if(!i||!b?.enabled)return void(S&&C(!0));let e=0;for(const t of re)if(!j.current[t.key]){if("external"===t.provider){if(!Ja({src:t.src,dataAttributes:t.dataAttributes})){Y("rejected external script",t.key);continue}}else{if(!Ba(t.provider)){Y("rejected unknown provider",t.provider);continue}if(!Va(t.provider,t.providerId)){Y("rejected id for",t.provider);continue}if(as(t.provider,t.providerId??"")){Y(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}os(t,K,v.current)&&(j.current[t.key]=t.providerId??t.src??"",e+=1,Y("installed",t.key))}e&&B(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...j.current},dataLayerName:K,clientId:r};const n=Object.keys(j.current).length>0,a=null!==X||0===b.scripts.length;(n||a)&&C(!0)},[i,b,re,S,A,Z,K,Y,ie,r]),u(()=>{if(!i||!o||!b?.enabled)return;if("undefined"==typeof window)return;if(!ie)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=Qa();if(!n)return;const r=n[t];Array.isArray(r)&&r.push({event:"page_view",page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});for(const t of e)switch(t.provider){case"ga4":n.gtag?.("event","page_view",{send_to:t.providerId,page_path:n.location.pathname,page_location:n.location.href,page_title:n.document.title});break;case"meta_pixel":n.fbq?.("track","PageView");break;case"tiktok":{const e=n.ttq;e?.page?.();break}case"reddit":n.rdt?.("track","PageVisit")}}(re,K),50)},n=window.history,r=n.pushState,a=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=a.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=a,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[i,o,b?.enabled,re,K,ie]),u(()=>{if(!i)return;const e=function(e,t){const n=e?.mode??"auto",r=e?.overrides??{};if(("manual"===n||Object.values(r).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(r))if(!Ya(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)},[i,c,d]);const se=p((e,t={},n)=>{if(!i)return;const r=n?.eventId||Fa(),a=c?.mode??"auto",s=(Ya(e)?c?.overrides?.[e]:void 0)??a,o={...W.current,...F.current,...D,...t},l=R.current?.({name:e,params:o})??{},d={...o,...l},u=O.current?.({name:e,params:d,eventId:r,handledBy:s});"manual"!==s&&!0!==u?(ee&&V.current&&Ua(re,V.current),function(e,t,n,r,i){const a=Qa();if(!a)return;const s=a[i];Array.isArray(s)&&s.push({event:e,...t,event_id:n});const o=Ya(e)?Ha[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const i of r){const r=i.provider,s=ja[r];if(s){if(s.needsConversionIds){const s=i.conversionIds?.[e];if(!s)continue;"google_ads"===r?a.gtag?.("event","conversion",{send_to:`${i.providerId}/${s}`,transaction_id:n,...t}):"x_pixel"===r?a.twq?.("event",s,{...t,conversion_id:n}):"linkedin"===r&&a.lintrk?.("track",{conversion_id:s});continue}switch(r){case"ga4":o.ga4&&a.gtag?.("event",o.ga4,{...t,send_to:i.providerId,event_id:n});break;case"meta_pixel":o.meta&&a.fbq?.("track",o.meta,t,{eventID:n});break;case"tiktok":if(o.tiktok){const e=a.ttq;e?.track?.(o.tiktok,{...t,event_id:n})}break;case"reddit":o.reddit&&a.rdt?.("track",o.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=a.uetq;r?.push?.("event",o.ga4??e,{...t,event_id:n});break}case"clarity":a.clarity?.("event",e);break;case"hotjar":{const t=a.hj;t?.("event",e);break}case"posthog":{const r=a.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":a.plausible?.(e,{props:t})}}}}(e,d,r,re,K),Y("event fired:",e,r)):Y("event handled by app:",e)},[i,c,re,K,D,Y,ee]),oe=p(async(t,r={})=>{const i=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=i.params;if(t.sessionId&&e&&n){const r=await async function(e,t){try{const n=e.serverUrl.replace(/\/$/,""),r=await fetch(`${n}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}`,{credentials:"omit",..."undefined"!=typeof AbortSignal&&AbortSignal.timeout?{signal:AbortSignal.timeout(2e3)}:{}});if(!r.ok)return null;const i=await r.json(),a=i?.data??i;return"number"!=typeof a?.amount?null:{value:pa(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:n},t.sessionId);r&&"number"==typeof r.value&&(a={...a,value:r.value,...r.currency?{currency:r.currency.toUpperCase()}:{},...r.items?.length?{items:r.items}:{}})}if(se(i.name,{...a,...r},{eventId:t.eventId}),"purchase"===i.name&&t.sessionId&&e&&n){const r=(b?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);r&&as("ga4",r.providerId??"")&&function(e,t,n){try{const r=e.serverUrl.replace(/\/$/,"");fetch(`${r}/api/v1/public/${encodeURIComponent(e.orgId)}/checkout/${encodeURIComponent(t)}/reported`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:n}),keepalive:!0,credentials:"omit"}).catch(()=>{})}catch{}}({serverUrl:e,orgId:n},t.sessionId,"ga4")}},[e,n,se,b]),[ce]=h(()=>"undefined"==typeof window?"":window.location.search);u(()=>{if(!i||!x)return;if("undefined"==typeof window)return;const e=ca(window.location.search);if(e)return void oe(e);const t=la(ce);t&&se("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))})},[i,x,oe,ce,se]);const le=p((t,a)=>{T.current=t,U(t),ka(t),i&&Ca({serverUrl:e,orgId:n,clientId:r,state:t,manifestVersion:H.current?.consent?.manifestVersion,source:a?.source,consentString:a?.consentString,headers:J.current})},[i,e,n,r]),de=p(e=>{J.current={...e}},[]),ue=p(e=>{if(!e)return V.current=null,void G(e=>e+1);Aa(e).then(e=>{V.current=e.emailHash||e.phoneHash?e:null,G(e=>e+1)})},[]),pe=p((e,t)=>{const n=function(e){if(!e)return{traits:e,identity:null};const{email:t,phone:n,...r}=e,i={};return"string"==typeof t&&t&&(i.email=t),"string"==typeof n&&n&&(i.phone=n),{traits:r,identity:i.email||i.phone?i:null}}(t);n.identity&&ue(n.identity),function(e,t,n){const r=Qa();if(!r)return;const i=!!n&&Object.keys(n).length>0;for(const a of t)switch(a.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),i&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":a.providerId&&r.fbq?.("init",a.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,i?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),i)for(const[e,t]of Object.entries(n))r.clarity?.("set",e,String(t));break;case"hotjar":r.hj?.("identify",e,{});break;case"tiktok":{const t=r.ttq;t?.identify?.({external_id:e});break}}}(e,re,n.traits)},[re,ue]);u(()=>{ee&&V.current&&0!==Object.keys(j.current).length&&Ua(re,V.current)},[ee,re,z,q]);const he=s(()=>({consent:{manifest:b?.consent?.manifest??[],state:A,effective:X,default:Z,country:b?.country??null,set:le},track:se,setUser:pe,setIdentity:ue,setConsentRecordHeaders:de,setProperties:$,getProperties:L,completeCheckout:oe,installed:{...j.current},ready:x,attribution:D}),[b,A,Z,le,se,pe,ue,de,$,L,oe,x,q,D]);return t(ds.Provider,{value:he,children:w})};function gs(){const e=jr(),t=Qr(),n=gi();return s(()=>({auth:e,os:t,workspaces:n}),[e,t,n])}function fs(e,t){const n=Zr(),r=qr(),i=fi(),a=p(e=>{const t=[n.subscribe(e),r.subscribe(e),i.subscribe(e)];return()=>t.forEach(e=>e())},[n,r,i]);return Or(s(()=>{let e=null;return()=>(null!==e&&e.os===n.getState()&&e.auth===r.getState()&&e.workspaces===i.getState()||(e={os:n.getState(),auth:r.getState(),workspaces:i.getState()}),e)},[n,r,i]),a,e,t)}function ys(e,t,n){u(()=>{const t=new AbortController;return e(t.signal).catch(e=>{he(e)||(n?.onError?n.onError(e):we(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},t)}function ws(){return fs(e=>e.os)}ms.displayName="BuildBaseTracking";const vs=new Map;let bs=null;function ks(){const e=gs(),t=ws(),{serverUrl:n,version:r,orgId:i,settings:a,settingsStatus:o,settingsError:c}=t,l=s(()=>ft(t)?new Qe({serverUrl:n,version:r,orgId:i}):null,[n,r,i]),d=p(async t=>{if(!l)return null;const a=((e,t,n)=>`${e}|${t}|${n}`)(n,r,i);bs=a;const s=vs.get(a);if(s)return s;const o=(async()=>{e.os(zr("loading"));try{const t=await l.getSettings();return bs===a&&e.os(Vr(t)),t}catch(t){return bs===a&&e.os(zr("error",t instanceof Error?t.message:"Failed to load settings")),ve(t,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:n,version:r,orgId:i}}),null}finally{vs.delete(a)}})();return vs.set(a,o),o},[l,e,n,r,i]);ys(async()=>{a||ft(t)&&await d()},[n,r,i],{onError:e=>ve(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:n,version:r,orgId:i}})});const u="loading"===o||("idle"===o||void 0===o)&&ft(t);return s(()=>({settings:a,loading:u,error:c??null,refetch:d,getSettings:d}),[a,u,c,d])}function Ss(){const e=ws(),t=gs(),n=p(()=>{Ue(),t.auth(Tr()),e.auth?.callbacks?.onSessionExpired?.("expired")},[t,e.auth?.callbacks?.onSessionExpired]),r=function(e,t){return s(()=>new mt({...e,onUnauthorized:t}),[e.serverUrl,e.version,e.orgId,t])}(e,n);return s(()=>({os:e,api:r}),[e,r])}const Is=e=>{const{t:t}=Oi(),{os:n,api:r}=Ss(),i=ft(n),[a,s]=h(null),[o,c]=h(!1),[l,d]=h(null),[m,g]=h(null),{begin:f,settle:y}=Fi(),w=p(async()=>{if(!e||!i)return f(),s(null),g(null),void c(!1);const n=f();c(!0),d(null);try{const t=await r.getPublicPlans(e);if(n.signal.aborted)return;s(t),g(e)}catch(r){if(n.signal.aborted)return;g(e);const i=be(r,"errors.fetchPlans",t);d(i),we(r,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{y(n)&&c(!1)}},[r,e,i,f,y]);u(()=>{w()},[w]);const v=!(!e||i&&m===e),b=v||o;return{items:v?[]:a?.items??[],plans:v?[]:a?.plans??[],notes:v?void 0:a?.notes,loading:b,error:l,refetch:w}},xs=e=>{const{t:t}=Oi(),{api:n}=Ss(),[r,i]=h(null),[a,s]=h(!1),[o,c]=h(null),{begin:l,settle:d}=Fi(),m=p(async()=>{if(!e)return l(),i(null),void s(!1);const r=l();s(!0),c(null);try{const t=await n.getPlanGroupVersion(e);if(r.signal.aborted)return;i(t)}catch(n){if(r.signal.aborted)return;const i=be(n,"errors.fetchPlanGroupVersion",t);c(i),we(n,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{d(r)&&s(!1)}},[n,e,l,d]);return u(()=>{m()},[m]),{planGroupVersion:r,loading:a,error:o,refetch:m}},Cs=e=>{const{t:t}=Oi(),{os:n,api:r}=Ss(),[i,a]=h(null),[s,o]=h(!1),[c,l]=h(null),[d,m]=h(null),{begin:g,settle:f}=Fi(),y=p(async()=>{if(!e)return g(),a(null),m(null),void o(!1);const i=g();o(!0),l(null);try{const t=await Wi(`subscription:${n.serverUrl}:${n.orgId}:${e}`,()=>r.getCurrentSubscription(e));if(i.signal.aborted)return;a(t),m(e)}catch(n){if(i.signal.aborted)return;m(e);const r=be(n,"errors.fetchSubscription",t);l(r),we(n,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{f(i)&&o(!1)}},[r,n.serverUrl,n.orgId,e,g,f]);u(()=>{y()},[y]),u(()=>Et(y),[y]);const w=!!e&&d!==e;return{subscription:w?null:i,loading:s||w,error:c,refetch:y}},Ns=(e,t)=>{const{t:n}=Oi(),{api:r}=Ss(),[i,a]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=Fi(),g=p(async()=>{if(!e)return d(),a(null),void o(!1);const i=d();o(!0),l(null);try{const n=t?await r.getPlanGroupByVersion(e,t):await r.getPlanGroup(e);if(i.signal.aborted)return;a(n)}catch(r){if(i.signal.aborted)return;const a=be(r,"errors.fetchPlanGroup",n);l(a),we(r,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:t}})}finally{m(i)&&o(!1)}},[r,e,t,d,m]);return u(()=>{g()},[g]),{planGroup:i,loading:s,error:c,refetch:g}},Ps=e=>{const{t:t}=Oi(),{api:n}=Ss(),[r,i]=h(null),[a,s]=h(!1),[o,c]=h(null),{begin:l,settle:d}=Fi(),m=p(async()=>{if(!e)return l(),i(null),void s(!1);const r=l();s(!0),c(null);try{const t=await n.getPlanGroupVersions(e);if(r.signal.aborted)return;i(t)}catch(n){if(r.signal.aborted)return;const i=be(n,"errors.fetchPlanGroupVersions",t);c(i),we(n,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{d(r)&&s(!1)}},[n,e,l,d]);return u(()=>{m()},[m]),{versions:r,loading:a,error:o,refetch:m}},_s=e=>{const{t:t}=Oi(),{api:n}=Ss(),{getCheckoutStripeParams:r}=d(wi),{track:i,consent:a,getProperties:s}=ps(),o=hs(),[c,l]=h(!1),[u,m]=h(null);return{createCheckoutSession:p(async c=>{if(!e)throw new Error("Workspace ID is required");l(!0),m(null);const d=Fa();try{const t=r?await r(c):void 0,l=o?Ma(d,a.effective,s(),Da({...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 n.createCheckoutSession(e,u),h="checkout"!==p.type&&p.type?void 0:p,m=h?.currency??c.currency,g=pa(h?.amountTotal,m);return h&&o&&ta({eventId:d,workspaceId:e,planVersionId:c.planVersionId,billingInterval:c.billingInterval,currency:m,sessionId:h.sessionId,value:g,kind:h.trial?"trial_started":"purchase",startedAt:Date.now()}),i("trial_started"===p.type?"trial_started":"checkout_started",{plan_version_id:c.planVersionId,...c.billingInterval?{billing_interval:c.billingInterval}:{},...m?{currency:m.toUpperCase()}:{},..."number"==typeof g?{value:g}:{}},{eventId:d}),"trial_started"===p.type&&(At(),Pt()),p}catch(n){const r=be(n,"errors.createCheckout",t);throw m(r),we(n,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:c}}),n}finally{l(!1)}},[n,e,r,i,t,a.effective,o]),loading:c,error:u}},Es=e=>{const{t:t}=Oi(),{api:n}=Ss(),{track:r}=ps(),i=hs(),[a,s]=h(!1),[o,c]=h(null);return{updateSubscription:p(async(a,o)=>{if(!e)throw new Error("Workspace ID is required");s(!0),c(null);try{const t={planVersionId:a,...o?.billingInterval&&{billingInterval:o.billingInterval},...o?.successUrl&&{successUrl:o.successUrl},...o?.cancelUrl&&{cancelUrl:o.cancelUrl}},s=Fa(),c=await n.updateSubscription(e,t),l="checkoutUrl"in c&&c.checkoutUrl?c:null;if(l){const t=l.currency,n=pa(l.amountTotal,t);i&&ta({eventId:s,workspaceId:e,planVersionId:a,billingInterval:o?.billingInterval,currency:t,sessionId:l.sessionId,value:n,kind:l.trial?"trial_started":"purchase",startedAt:Date.now()}),r("checkout_started",{plan_version_id:a,...o?.billingInterval?{billing_interval:o.billingInterval}:{},...t?{currency:t.toUpperCase()}:{},..."number"==typeof n?{value:n}:{}},{eventId:s})}else{const e=c,t=e.invoice?.amount_due;r("subscription_upgraded",{plan_version_id:a,...o?.billingInterval?{billing_interval:o.billingInterval}:{},..."number"==typeof t&&t>0?{value:pa(t,void 0)}:{}},{eventId:s})}return At(),c}catch(n){const r=be(n,"errors.updateSubscription",t);throw c(r),we(n,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:a,options:o}}),n}finally{s(!1)}},[n,e,r,i]),loading:a,error:o}},As=(e,t)=>{const n=Cs(e),r=Ns(e,t),i=Es(e),a=p(async()=>{await Promise.all([n.refetch(),r.refetch()])},[n.refetch,r.refetch]);return{subscription:n.subscription,planGroup:r.planGroup,loading:n.loading||r.loading||i.loading,error:n.error||r.error||i.error,updateSubscription:i.updateSubscription,refetch:a}},Us=(e,t=10,n)=>{const{t:r}=Oi(),{api:i}=Ss(),[a,s]=h([]),[o,c]=h(!1),[l,d]=h(!1),[m,g]=h(null),{begin:f,settle:y}=Fi(),w=p(async()=>{if(!e)return f(),s([]),c(!1),void d(!1);const a=f();d(!0),g(null);try{const r=await i.listInvoices(e,t,n);if(a.signal.aborted)return;s(r.invoices||[]),c(r.has_more||!1)}catch(i){if(a.signal.aborted)return;const s=be(i,"errors.fetchInvoices",r);g(s),we(i,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:t,startingAfter:n}})}finally{y(a)&&d(!1)}},[i,e,t,n,f,y]);return u(()=>{w()},[w]),{invoices:a,hasMore:o,loading:l,error:m,refetch:w}},Ts=e=>{const{t:t}=Oi(),{api:n}=Ss(),[r,i]=h(!1),[a,s]=h(null);return{openBillingPortal:p(async r=>{if(!e)throw new Error("Workspace ID is required");i(!0),s(null);try{const t=r||window.location.href,i=await n.createBillingPortalSession(e,t);return i.url&&window.open(i.url,"_blank","noopener,noreferrer"),i}catch(n){const r=be(n,"errors.openBillingPortal",t);throw s(r),we(n,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),n}finally{i(!1)}},[e,n]),loading:r,error:a}},Os=(e,t)=>{const{t:n}=Oi(),{api:r}=Ss(),[i,a]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=Fi(),g=p(async()=>{if(!e||!t)return d(),a(null),void o(!1);const i=d();o(!0),l(null);try{const n=await r.getInvoice(e,t);if(i.signal.aborted)return;a(n.invoice)}catch(r){if(i.signal.aborted)return;const a=be(r,"errors.fetchInvoice",n);l(a),we(r,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:t}})}finally{m(i)&&o(!1)}},[r,e,t,d,m]);return u(()=>{g()},[g]),{invoice:i,loading:s,error:c,refetch:g}},Rs=e=>{const{t:t}=Oi(),{api:n}=Ss(),[r,i]=h(!1),[a,s]=h(null);return{cancelSubscription:p(async()=>{if(!e)throw new Error("Workspace ID is required");i(!0),s(null);try{const t=await n.cancelSubscriptionAtPeriodEnd(e);return At(),t}catch(n){const r=be(n,"errors.cancelSubscription",t);throw s(r),we(n,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),n}finally{i(!1)}},[n,e]),loading:r,error:a}},Ws=e=>{const{t:t}=Oi(),{api:n}=Ss(),[r,i]=h(!1),[a,s]=h(null);return{resumeSubscription:p(async()=>{if(!e)throw new Error("Workspace ID is required");i(!0),s(null);try{const t=await n.resumeSubscription(e);return At(),t}catch(n){const r=be(n,"errors.resumeSubscription",t);throw s(r),we(n,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),n}finally{i(!1)}},[n,e]),loading:r,error:a}},Fs=e=>{const{t:t}=Oi(),{api:n}=Ss(),[r,i]=h(!1),[a,s]=h(null);return{recordUsage:p(async r=>{if(!e)throw new Error("Workspace ID is required");i(!0),s(null);try{const t=await n.recordUsage(e,r);return Pt(),t}catch(n){const i=be(n,"errors.recordUsage",t);throw s(i),we(n,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:r}}),n}finally{i(!1)}},[n,e]),loading:r,error:a}},Ls=(e,t)=>{const{t:n}=Oi(),{api:r}=Ss(),[i,a]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=Fi(),g=p(async()=>{if(!e||!t)return d(),a(null),void o(!1);const i=d();o(!0),l(null);try{const n=await r.getQuotaUsageStatus(e,t);if(i.signal.aborted)return;a(n)}catch(r){if(i.signal.aborted)return;const a=be(r,"errors.fetchQuotaUsage",n);l(a),we(r,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:t}})}finally{m(i)&&o(!1)}},[r,e,t,d,m]);return u(()=>{g()},[g]),{status:i,loading:s,error:c,refetch:g}},$s=e=>{const{t:t}=Oi(),{os:n,api:r}=Ss(),[i,a]=h(null),[s,o]=h(!1),[c,l]=h(null),[d,m]=h(null),{begin:g,settle:f}=Fi(),y=p(async()=>{if(!e)return g(),a(null),m(null),void o(!1);const i=g();o(!0),l(null);try{const t=await Wi(`quota-usage:${n.serverUrl}:${n.orgId}:${e}`,()=>r.getAllQuotaUsage(e));if(i.signal.aborted)return;a(t.quotas),m(e)}catch(n){if(i.signal.aborted)return;m(e);const r=be(n,"errors.fetchAllQuotaUsage",t);l(r),we(n,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{f(i)&&o(!1)}},[r,n.serverUrl,n.orgId,e,g,f]);u(()=>{y()},[y]),u(()=>Nt(y),[y]);const w=!!e&&d!==e;return{quotas:w?null:i,loading:s||w,error:c,refetch:y}},Ds=(e,t,n)=>{const{t:r}=Oi(),{api:i}=Ss(),[a,s]=h([]),[o,c]=h(0),[l,d]=h(0),[m,g]=h(1),[f,y]=h(!1),[w,v]=h(!1),[b,k]=h(!1),[S,I]=h(null),{begin:x,settle:C}=Fi(),N=n?.from,P=n?.to,_=n?.source,E=n?.page,A=n?.limit,U=p(async()=>{if(!e)return x(),s([]),c(0),d(0),g(1),y(!1),v(!1),void k(!1);const n=x();k(!0),I(null);try{const r={...t&&{quotaSlug:t},...N&&{from:N},...P&&{to:P},..._&&{source:_},...E&&{page:E},...A&&{limit:A}},a=await i.getUsageLogs(e,r);if(n.signal.aborted)return;s(a.docs||[]),c(a.totalDocs||0),d(a.totalPages||0),g(a.page||1),y(a.hasNextPage||!1),v(a.hasPrevPage||!1)}catch(i){if(n.signal.aborted)return;const a=be(i,"errors.fetchUsageLogs",r);I(a),we(i,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:t}})}finally{C(n)&&k(!1)}},[i,e,t,N,P,_,E,A,x,C]);return u(()=>{U()},[U]),{logs:a,totalDocs:o,totalPages:l,page:m,hasNextPage:f,hasPrevPage:w,loading:b,error:S,refetch:U}},Ms=c(null);Ms.displayName="SubscriptionContext";const js=i.memo(function({children:e}){const n=fs(e=>e.workspaces.currentWorkspace),{subscription:r,loading:i,error:a,refetch:o}=Cs(n?._id),c=s(()=>({response:r,loading:i,error:a,refetch:o}),[r,i,a,o]);return t(Ms.Provider,{value:c,children:e})});function qs(){const e=d(Ms);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}js.displayName="SubscriptionContextProvider";const Bs=e=>{const{t:t}=Oi(),{os:n,api:r}=Ss(),[i,a]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=Fi(),g=p(async()=>{if(!e)return d(),a(null),void o(!1);const i=d();o(!0),l(null);try{const t=await Wi(`credit-balance:${n.serverUrl}:${n.orgId}:${e}`,()=>r.getCreditBalance(e));if(i.signal.aborted)return;a(t)}catch(n){if(i.signal.aborted)return;const r=be(n,"errors.fetchCreditBalance",t);l(r),we(n,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{m(i)&&o(!1)}},[r,n.serverUrl,n.orgId,e,d,m]);return u(()=>{g()},[g]),u(()=>It(g),[g]),{balance:i,loading:s,error:c,refetch:g}},Vs=e=>{const{t:t}=Oi(),{api:n}=Ss(),[r,i]=h(!1),[a,s]=h(null);return{consumeCredits:p(async r=>{if(!e)throw new Error("Workspace ID is required");i(!0),s(null);try{const t=await n.consumeCredits(e,r);return xt(),t}catch(n){const i="INSUFFICIENT_CREDITS"===n.code?t("credits.insufficientDetail",{available:n.available,requested:n.requested}):be(n,"errors.consumeCredits",t);throw s(i),we(n,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:r}}),n}finally{i(!1)}},[n,e]),loading:r,error:a}},zs=e=>{const{t:t}=Oi(),{api:n}=Ss(),{track:r,consent:i,getProperties:a}=ps(),s=hs(),[o,c]=h(!1),[l,d]=h(null);return{purchaseCredits:p(async o=>{if(!e)throw new Error("Workspace ID is required");c(!0),d(null);const l=Fa(),u=s?Ma(l,i.effective,a(),Math.min(Da(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 n.purchaseCredits(e,p)}catch(r){const i=r?.status;if(p===o||o.metadata||400!==i)throw r;t=await n.purchaseCredits(e,o)}const i=t.currency??o.currency,a=pa(t.amountTotal,i);return s&&ta({eventId:l,workspaceId:e,creditPackageId:o.creditPackageId,currency:i,sessionId:t.sessionId,value:a,kind:"purchase",startedAt:Date.now()}),r("checkout_started",{credit_package_id:o.creditPackageId,...i?{currency:i.toUpperCase()}:{},..."number"==typeof a?{value:a}:{}},{eventId:l}),t}catch(n){const r=be(n,"errors.purchaseCredits",t);throw d(r),we(n,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:o}}),n}finally{c(!1)}},[n,e,r,i.effective,s]),loading:o,error:l}},Gs=e=>{const{t:t}=Oi(),{api:n}=Ss(),[r,i]=h([]),[a,s]=h(!1),[o,c]=h(null),{begin:l,settle:d}=Fi(),m=p(async()=>{if(!e)return l(),i([]),void s(!1);const r=l();s(!0),c(null);try{const t=await n.getCreditPackages(e);if(r.signal.aborted)return;i(t)}catch(n){if(r.signal.aborted)return;const i=be(n,"errors.fetchCreditPackages",t);c(i),we(n,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{d(r)&&s(!1)}},[n,e,l,d]);return u(()=>{m()},[m]),{packages:r,loading:a,error:o,refetch:m}},Js=(e,t)=>{const{t:n}=Oi(),{api:r}=Ss(),[i,a]=h([]),[s,o]=h(0),[c,l]=h(0),[d,m]=h(1),[g,f]=h(!1),[y,w]=h(!1),[v,b]=h(!1),[k,S]=h(null),{begin:I,settle:x}=Fi(),C=t?.type,N=t?.page,P=t?.limit,_=p(async()=>{if(!e)return I(),a([]),o(0),l(0),m(1),f(!1),w(!1),void b(!1);const t=I();b(!0),S(null);try{const n=await r.getCreditTransactions(e,{type:C,page:N,limit:P});if(t.signal.aborted)return;a(n.docs||[]),o(n.totalDocs||0),l(n.totalPages||0),m(n.page||1),f(n.hasNextPage||!1),w(n.hasPrevPage||!1)}catch(r){if(t.signal.aborted)return;const i=be(r,"errors.fetchCreditTransactions",n);S(i),we(r,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{x(t)&&b(!1)}},[r,e,C,N,P,I,x]);return u(()=>{_()},[_]),{transactions:i,totalDocs:s,totalPages:c,page:d,hasNextPage:g,hasPrevPage:y,loading:v,error:k,refetch:_}},Hs=(e,t)=>{const{t:n}=Oi(),{api:r}=Ss(),[i,a]=h(null),[s,o]=h(!1),[c,l]=h(null),{begin:d,settle:m}=Fi(),g=p(async()=>{if(!e)return d(),a(null),void o(!1);const i=d();o(!0),l(null);try{const n=await r.getExpiringCredits(e,t);if(i.signal.aborted)return;a(n)}catch(r){if(i.signal.aborted)return;const a=be(r,"errors.fetchExpiringCredits",n);l(a),we(r,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:t}})}finally{m(i)&&o(!1)}},[r,e,t,d,m]);return u(()=>{g()},[g]),{expiringCredits:i?.expiringCredits??0,buckets:i?.buckets??[],days:i?.days??t??7,loading:s,error:c,refetch:g}},Ks=()=>{const{t:e}=Oi(),{os:t,api:n}=Ss(),r=ft(t),[i,a]=h([]),[s,o]=h(),[c,l]=h(!1),[d,m]=h(null),{begin:g,settle:f}=Fi(),y=p(async()=>{if(!r)return g(),a([]),void l(!1);const t=g();l(!0),m(null);try{const e=await n.getPublicCreditPackages();if(t.signal.aborted)return;a(e.packages||[]),o(e.notes)}catch(n){if(t.signal.aborted)return;const r=be(n,"errors.fetchCreditPackages",e);m(r),we(n,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{f(t)&&l(!1)}},[n,r,g,f]);u(()=>{y()},[y]);return{packages:i,notes:s,loading:!r||c,error:d,refetch:y}},Ys=c(null);Ys.displayName="CreditBalanceContext";const Qs=i.memo(function({children:e}){const n=fs(e=>e.workspaces.currentWorkspace),{balance:r,loading:i,error:a,refetch:o}=Bs(n?._id),c=s(()=>({balance:r,loading:i,error:a,refetch:o}),[r,i,a,o]);return t(Ys.Provider,{value:c,children:e})});function Zs(){const e=d(Ys);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}Qs.displayName="CreditBalanceContextProvider";const Xs=({message:r})=>e(n,{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:r}),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 "})]}),eo=({children:n,message:r,backgroundColor:i})=>{const{t:a}=Oi(),s=r??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:i??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:s}),n??t(Xs,{message:s}),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 "})]})};eo.displayName="FullScreenLoader";const to=c(null),no=({children:n,loadingComponent:r})=>{const[i,a]=h({visible:!1,message:""}),o=l(null),c=p(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=p(()=>{c(),a({visible:!1,message:""})},[c]),m=p(e=>{c(),a({visible:!0,message:e}),o.current=setTimeout(()=>{we(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),a({visible:!1,message:""})},6e4)},[c]);u(()=>()=>c(),[c]);const g=s(()=>({show:m,hide:d,visible:i.visible,message:i.message}),[m,d,i.visible,i.message]),f="function"==typeof r?r({message:i.message}):r;return e(to.Provider,{value:g,children:[n,i.visible&&t(eo,{message:i.message,children:f})]})};function ro(){const e=d(to);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}no.displayName="FullScreenLoaderProvider";const io=c(null);function ao(e,t){return e?e.replace(/\{\{(\w+)\}\}/g,(e,n)=>n in t?t[n]:e):e}function so(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"app"}function oo({mcp:e,children:n}){const r=s(()=>e?.url?{...e,url:e.url.replace(/\/+$/,"")}:null,[e]);return t(io.Provider,{value:r,children:n})}function co(){return d(io)}const lo=c({appPermissions:void 0});function uo({appPermissions:e,children:n}){const r=s(()=>({appPermissions:e}),[e]);return t(lo.Provider,{value:r,children:n})}function po(){return d(lo)}const ho=c(null);ho.displayName="QuotaUsageContext";const mo=i.memo(function({children:e}){const n=fs(e=>e.workspaces.currentWorkspace),{quotas:r,loading:i,error:a,refetch:o}=$s(n?._id),c=s(()=>({quotas:r,loading:i,error:a,refetch:o}),[r,i,a,o]);return t(ho.Provider,{value:c,children:e})});function go(){const e=d(ho);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}mo.displayName="QuotaUsageContextProvider";const fo=c({});function yo({ui:e,children:n}){const r=s(()=>e??{},[e]);return t(fo.Provider,{value:r,children:n})}function wo(){return d(fo)}function vo(e,t){return t?bo(e,t):e}function bo(e,t){if(!e||!t||"object"!=typeof e||"object"!=typeof t||Array.isArray(e)||Array.isArray(t))return t;const n={...e};for(const[e,r]of Object.entries(t))n[e]=e in n?bo(n[e],r):r;return n}let ko=!1;function So(){ko=!0}const Io="saas-oauth-state";function xo(){Ie(Io)}function Co(e={}){const t={};for(const[n,r]of Object.entries(e))null!=r&&""!==r&&("string"==typeof r?t[n]=r.slice(0,100):("number"==typeof r?Number.isFinite(r):"boolean"==typeof r)&&(t[n]=r));return t}const No=new Set;function Po(e){return!No.has(e)&&(No.add(e),!0)}function _o(e,t,n,r){const{emitOnce:i}=Eo(),a=l(r);a.current=r,u(()=>{e&&i(t,n,a.current)},[e,t,n,i])}function Eo(){const{track:e,ready:t}=ps(),n=p((t,n)=>{try{e(t,Co(n))}catch{}},[e]),r=p((e,r,i)=>{t&&Po(`${r}|${e}`)&&n(r,i)},[n,t]);return{emit:n,emitOnce:r,ready:t}}const Ao={rows:[],loading:!1,error:null,fetchedAt:0};class Uo{constructor(){this.snapshot=Ao,this.listeners=new Set,this.inFlight=null,this.generation=0,this.getSnapshot=()=>this.snapshot,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e))}set(e){this.snapshot={...this.snapshot,...e};for(const e of this.listeners)e()}load(e,t){if(this.inFlight)return this.inFlight;const n=t.maxAgeMs??0;if(n>0&&this.snapshot.fetchedAt&&Date.now()-this.snapshot.fetchedAt<n)return Promise.resolve();const r=this.generation;return this.set({loading:!0,error:null}),this.inFlight=e().then(e=>{r===this.generation&&this.set({rows:mr(e),fetchedAt:Date.now()})}).catch(e=>{r===this.generation&&this.set({error:t.onError(e)})}).finally(()=>{this.inFlight=null,r===this.generation&&this.set({loading:!1})}),this.inFlight}remove(e){this.set({rows:this.snapshot.rows.filter(t=>t._id!==e)})}setError(e){this.set({error:e})}reset(){this.generation++,this.inFlight=null,this.snapshot=Ao;for(const e of this.listeners)e()}}const To=new Map;function Oo(e){const t=e||"unscoped";let n=To.get(t);return n||(n=new Uo,To.set(t,n)),n}const Ro={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"},Wo=new Set(Object.values(Ro));const Fo=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:Ro.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||Ro.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)})}},Lo=c(null);Lo.displayName="WorkspaceActionsContext";const $o=({children:e})=>{const n=gs(),{os:r,api:a}=Ss(),{settings:o}=ks(),{t:c}=Oi(),l=i.useRef(c);u(()=>{l.current=c},[c]);const d=fs(e=>e.workspaces),h=fs(e=>e.auth.session?.user),m=i.useRef(!1),g=i.useRef(!1),f=i.useRef(0),y=p((e,t)=>{if((!(e._id===d.currentWorkspace?._id)||t?.forceEmit)&&e){const t=d.currentWorkspace;zn(e),n.workspaces(ii(e)),vt.emitWorkspaceChanged(e,t).catch(t=>{we(t,{component:"WorkspaceProvider",action:"emitWorkspaceChanged",metadata:{workspaceId:e._id}})})}},[d.currentWorkspace,n]),w=p(async(e,t)=>{const i=++f.current;n.workspaces(di(e._id));try{const n=r.auth?.callbacks?.onWorkspaceChange;if(n){const t=Yn(e,h?.id);try{await n({workspace:e,user:h??null,role:t})}catch(t){throw we(t,{component:"WorkspaceProvider",action:"onWorkspaceChange",metadata:{workspaceId:e._id}}),t}if(i!==f.current)return}y(e,t)}finally{i===f.current&&n.workspaces(di(null))}},[n,r.auth?.callbacks?.onWorkspaceChange,y,h]),v=i.useRef(w);v.current=w,u(()=>{if(!d.isInitialized){const e=Gn();if(n.workspaces(si(!0)),e){const t=d.workspaces.find(t=>t._id===e);t&&v.current(t,{forceEmit:!0}).catch(t=>{we(t,{component:"WorkspaceProvider",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:e}})})}}},[d.isInitialized,d.workspaces,n]);const b=p(()=>{Jn(),n.workspaces(ai())},[n]),k=p(async()=>{if(!d.loading&&!m.current){m.current=!0,n.workspaces(oi(!0)),n.workspaces(ci(null));try{const e=await a.getWorkspaces();if(n.workspaces(Xr(e)),e.length>0){const t=Gn();if(t&&Hn(t,e)){const n=e.find(e=>e._id===t);if(n)try{await w(n,{forceEmit:!0})}catch{}}else{const t=e[0];try{await w(t,{forceEmit:!0})}catch{}}}}catch(e){n.workspaces(ci(be(e,"errors.fetchWorkspaces",l.current)))}finally{n.workspaces(oi(!1)),m.current=!1}}},[a,d.loading,n,w]),S=p(async()=>{if(!d.refreshing&&!m.current){m.current=!0,n.workspaces(li(!0));try{const e=await a.getWorkspaces();n.workspaces(Xr(e))}catch(e){}finally{n.workspaces(li(!1)),m.current=!1}}},[a,d.refreshing,n]),I=i.useRef(null);u(()=>()=>{I.current&&clearTimeout(I.current)},[]);const x=p(async(e,t)=>{const r=Yi(),i=await a.createWorkspace({name:e,...t?{image:t}:{},...r?{trackingAttribution:r}:{}});n.workspaces(ei(i)),await w(i),vt.emitWorkspaceCreated(i).catch(e=>{we(e,{component:"WorkspaceProvider",action:"emitWorkspaceCreated",metadata:{workspaceId:i._id}})}),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{I.current=null,Fo.openWorkspaceSettings(Ro.Subscription)},300)},[a,n,w]),C=p(async(e,t)=>{const r=await a.updateWorkspace(e._id,t);n.workspaces(ti(r)),vt.emitWorkspaceUpdated(r).catch(e=>{we(e,{component:"WorkspaceProvider",action:"emitWorkspaceUpdated",metadata:{workspaceId:r._id}})})},[a,n]),N=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 n.workspaces(ri(e)),e}catch(e){return we(e,{component:"WorkspaceProvider",action:"getFeatures"}),null}finally{g.current=!1}},[a,n,d.allFeatures]),P=p(async(e,t,n)=>await a.updateFeature(e,t,n),[a]),_=p(async e=>a.updateSettings(e),[a]),E=p(async(e,t)=>{const n=await a.updateWorkspacePermissions(e,t);return await S(),n},[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&&(zn(t),n.workspaces(ii(t)));else if(d.workspaces.length>0){const t=d.workspaces[0];t._id!==e&&w(t).catch(e=>{we(e,{component:"WorkspaceProvider",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:t._id}})})}},[d.workspaces,d.currentWorkspace,n,w]);const A=p(async e=>await a.getWorkspaceUsers(e),[a]),U=p(async(e,t,n)=>{const r=d.workspaces.find(t=>t._id===e);if(r){const e=jn({settingsMaxUsers:o?.workspace?.maxWorkspaceUsers}),t=qn({memberCount:r.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessageKey||"users.memberLimitReached")}const i=await a.addUser(e,{email:t,role:n});return r&&vt.emitWorkspaceUserAdded(i.userId,r,n).catch(t=>{we(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:i.userId,role:n}})}),S().catch(e=>{we(e,{component:"WorkspaceProvider",action:"refreshAfterAddUser"})}),At(),i},[a,d.workspaces,S,o]),T=p(async(e,t)=>{const n=d.workspaces.find(t=>t._id===e);if(n&&Kn(n,t))throw new Error("Cannot remove the workspace owner");const r=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),i=await a.removeUser(e,t);if(n&&r){const t=r.role;vt.emitWorkspaceUserRemoved(i.userId,n,t).catch(n=>{we(n,{component:"WorkspaceProvider",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:i.userId,role:t}})})}return S().catch(e=>{we(e,{component:"WorkspaceProvider",action:"refreshAfterRemoveUser"})}),At(),i},[a,d.workspaces,S]),O=p(async(e,t,n)=>{if(n.role){const n=d.workspaces.find(t=>t._id===e);if(n&&Kn(n,t))throw new Error("Cannot change the role of the workspace owner")}let r;if(n.role){const n=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);r=n?.role}const i=await a.updateUser(e,t,n);return n.role&&r&&r!==n.role&&vt.emitWorkspaceUserRoleChanged(i.userId,i.workspace,r,n.role).catch(i=>{we(i,{component:"WorkspaceProvider",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:r,newRole:n.role}})}),i},[a,d.workspaces]),R=p(async e=>{const t=await a.getProfile().catch(()=>null),n=await a.updateUserProfile(e);return vt.emitUserUpdated(n,t||void 0).catch(e=>{we(e,{component:"WorkspaceProvider",action:"emitUserUpdated",metadata:{userId:n._id}})}),n},[a]),W=p(async()=>await a.getProfile(),[a]),F=p(async e=>await a.getWorkspace(e),[a]),L=p(async e=>{if(!h)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(!Kn(t,h.id))throw new Error("Only the workspace creator can delete the workspace");const r=await a.deleteWorkspace(e);return n.workspaces(ni(e)),d.currentWorkspace?._id===e&&(Jn(),n.workspaces(ai())),t&&vt.emitWorkspaceDeleted(t).catch(t=>{we(t,{component:"WorkspaceProvider",action:"emitWorkspaceDeleted",metadata:{workspaceId:e}})}),r},[a,d.workspaces,d.currentWorkspace,n,h]),$=p(e=>a.listInvitations(e),[a]),D=p(async(e,t,n,r)=>{const i=await a.inviteMember(e,{email:t,role:n,landingUrl:r?.landingUrl});return vt.emitWorkspaceInvitationSent(i,e).catch(t=>{we(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationSent",metadata:{workspaceId:e,invitationId:i._id}})}),At(),i},[a]),M=p(async(e,t)=>{const n=await a.resendInvitation(e,t);return At(),n},[a]),j=p(async(e,t)=>{await a.revokeInvitation(e,t),vt.emitWorkspaceInvitationRevoked(t,e).catch(n=>{we(n,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationRevoked",metadata:{workspaceId:e,invitationId:t}})}),At()},[a]),q=p(()=>a.myInvitations(),[a]),B=p(async(e,t)=>{const i=await a.acceptInvitation(e,t),s=i.workspace;s&&!d.workspaces.some(e=>e._id===s._id)&&n.workspaces(ei(s)),S().catch(e=>{we(e,{component:"WorkspaceProvider",action:"refreshAfterAccept"})}),i.workspace&&vt.emitWorkspaceInvitationAccepted(i.invitation,i.workspace).catch(t=>{we(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationAccepted",metadata:{invitationId:e}})});const o=i.workspace;return h?.id&&o&&vt.emitWorkspaceUserAdded(h.id,o,i.invitation.role).catch(t=>{we(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:o._id,invitationId:e}})}),At(),Oo(r.orgId??"").remove(e),{invitation:i.invitation,workspace:i.workspace}},[a,S,h?.id,r.orgId,d.workspaces,n]),V=p(async e=>{const{invitation:t}=await a.declineInvitation(e);return vt.emitWorkspaceInvitationDeclined(t).catch(t=>{we(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationDeclined",metadata:{invitationId:e}})}),Oo(r.orgId??"").remove(e),t},[a,r.orgId]),z=p(e=>a.previewInvitation(e),[a]),G=s(()=>({fetchWorkspaces:k,refreshWorkspaces:S,setCurrentWorkspace:y,switchToWorkspace:w,resetCurrentWorkspace:b,createWorkspace:x,updateWorkspace:C,deleteWorkspace:L,getWorkspace:F,getUsers:A,addUser:U,removeUser:T,updateUser:O,getProfile:W,updateUserProfile:R,getFeatures:N,updateFeature:P,updateWorkspaceSettings:_,updateWorkspacePermissions:E,listInvitations:$,inviteMember:D,resendInvitation:M,revokeInvitation:j,myInvitations:q,acceptInvitation:B,declineInvitation:V,previewInvitation:z}),[k,S,y,w,b,x,C,L,F,A,U,T,O,W,R,N,P,_,E,$,D,M,j,q,B,V,z]);return t(Lo.Provider,{value:G,children:e})};$o.displayName="WorkspaceProviderInner";const Do=({children:e})=>{const r=i.useContext(Lo);return t(r?n:$o,{children:e})};Do.displayName="WorkspaceProvider";const Mo=()=>{const e=i.useContext(Lo);if(!e)throw new Error("useSaaSWorkspaces must be used within a WorkspaceProvider. Make sure SaaSOSProvider is wrapping your application.");const t=fs(e=>e.workspaces);return s(()=>({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 jo(e,t,n){const r=e._id||e.id;if(!r||"string"!=typeof r)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:r,name:e.name||"",org:t,email:e.email,emailVerified:!1!==e.emailVerified,clientId:n,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 qo(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function Bo(){return fs(e=>e.auth)}function Vo(){const{t:e}=Oi(),t=gs(),n=Bo(),r=ws(),{serverUrl:i,orgId:a,auth:o}=r,{resetCurrentWorkspace:c,currentWorkspace:l}=Mo(),d=ro(),{consent:u}=ps(),{emit:h}=Eo(),m=s(()=>new je({serverUrl:i,version:r.version}),[i,r.version]),g=p(async n=>{Jt(n||window.location.href),h("sign_in_started",{from_path:window.location.pathname}),t.auth(_r()),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 Se(Io,t),t}(),{redirectUrl:t}=await m.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=Ta(),t=Object.keys(e).find(e=>e.startsWith("_ga_")),n={},r=Oa(e._ga);r&&(n.gaClientId=r);const i=t?Ra(e[t]):void 0;return i&&(n.gaSessionId=i),n}();return Object.keys(e).length?{trackingIdentity:e}:{}})(),...(()=>{const e=Yi();return e?{trackingAttribution:e}:{}})(),...(()=>{const e=Cr(a);return e?{invitationToken:e}:{}})()});Vt(t)}catch(e){throw d.hide(),t.auth(Ar()),we(e,{component:"useSaaSAuth",action:"signIn"}),e}},[m,a,o,t,d,e,u.state,h]),f=p(e=>async function(e,t){const n=function(e){if(e&&"object"==typeof e)return"everywhere"in e?e:void 0}(t);try{if("function"==typeof e.onSignOut)try{await e.onSignOut()}catch(t){e.onError(t)}try{await e.revoke(n?.everywhere?{all:!0}:void 0)}catch(t){e.onError(t)}}finally{e.clearLocal()}}({onSignOut:o?.callbacks?.onSignOut,revoke:e=>m.logout(Te()??void 0,e),clearLocal:()=>{Ue(),t.auth(Tr()),c()},onError:e=>we(e,{component:"useSaaSAuth",action:"signOut"})},e),[m,t,c,o?.callbacks?.onSignOut]),y=p(e=>{l?Fo.openWorkspaceSettings(e):we(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),w=p(()=>{l?Fo.openWorkspaceSettings(Ro.Credits,{action:Tt.OpenCreditStore}):we(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),v=p(()=>{l?Fo.openWorkspaceSettings(Ro.Subscription,{action:Tt.SelectPlan}):we(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),b=s(()=>dr(n.status),[n.status]);return s(()=>({user:n.session?.user,session:n.session,status:n.status,...b,signIn:g,signOut:f,openWorkspaceSettings:y,openCreditStore:w,openPlanPicker:v}),[n.session,n.status,b,g,f,y,w,v])}const zo=i.memo(({children:e,callbacks:r})=>{const{t:a}=Oi(),s=gs(),o=Bo(),c=ws(),l=dr(o.status).isAuthenticated,d=ro(),h=i.useRef(!1),m=i.useRef(null),g=i.useRef(!1),f=i.useRef(null),y=p(async e=>{try{if(r?.handleAuthentication){d.show(a("loading.signingIn"));const{sessionId:t}=await r.handleAuthentication(e);if(!t||"string"!=typeof t||""===t.trim())throw new Error("Invalid sessionId received from authentication callback");const n=c;if(!ft(n))throw new Error("OS configuration is not available");const{serverUrl:i,version:o,orgId:l}=n;d.show(a("loading.verifyingAccount"));const u=new je({serverUrl:i,version:o}),p=await u.getProfile(t),h=qo(jo(p,l,n.auth?.clientId||""),t);d.show(a("loading.almostThere")),Ae(h.sessionId),u.getDeviceToken(h.sessionId).then(e=>e&&Oe(e)).catch(()=>{}),Fe();const m=Ht(),g=!!m&&m!==window.location.href;g&&So(),s.auth(Ur(h)),g&&Vt(m),d.hide()}}catch(t){throw d.hide(),Ht(),we(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),s.auth(Ar()),t}},[s,r,c,d,a]);return i.useEffect(()=>{if("undefined"==typeof window)return;if(l)return;if(g.current)return;if(f.current)return;if(!ft(c))return;if(We())return;if(!r?.getSession)return g.current=!0,void s.auth(Ar());const e=r.getSession,{serverUrl:t,version:n,orgId:i}=c,o=c.auth?.clientId||"";f.current=(async()=>{d.show(a("loading.restoringSession"));let c=null;try{c=await e()}catch(e){we(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!c)return Ue(),g.current=!0,s.auth(Ar()),d.hide(),"undefined"!=typeof window&&Jt(window.location.href),void r?.onSessionExpired?.("missing");try{d.show(a("loading.verifyingAccount"));const e=new je({serverUrl:t,version:n}),r=await e.getProfile(c),l=qo(jo(r,i,o),c);Ae(l.sessionId),e.getDeviceToken(l.sessionId).then(e=>e&&Oe(e)).catch(()=>{}),g.current=!0;const u=Ht(),p=!!u&&u!==window.location.href;p&&So(),s.auth(Ur(l)),d.hide(),p&&Vt(u)}catch(e){we(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),Ue(),g.current=!0,s.auth(Ar()),d.hide(),"undefined"!=typeof window&&Jt(window.location.href),r?.onSessionExpired?.("expired")}finally{f.current=null}})()},[l,s,c,r]),u(()=>{const e=We();if(!e)return;if(h.current||m.current===e)return;if(!ft(c))return;const t=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(Ee)}catch(e){return we(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:Ee}}),null}}();if(t&&!function(e){if(!e)return!1;const t=ke(Io);if(Ie(Io),!t)return!1;if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return 0===n}(t))return xo(),Fe(),we(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void s.auth(Ar());xo(),h.current=!0,m.current=e;let n=!1;return s.auth(Er()),y(e).then(()=>{n||(m.current=null)}).catch(e=>{n||(we(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),Fe(),m.current=null)}).finally(()=>{h.current=!1}),()=>{n=!0}},[y,c.serverUrl,c.version,c.orgId]),t(n,{children:e})});zo.displayName="AuthProviderWrapper";const Go=i.memo(({config:e,auth:r,children:a})=>{const s=gs();ws();const o=i.useRef(r?.callbacks);o.current=r?.callbacks;const c=Object.keys(r?.callbacks??{}).sort().join(","),l=i.useMemo(()=>{if(!c)return;const e={};for(const t of c.split(","))e[t]=(...e)=>{const n=o.current;return n?.[t]?.(...e)};return e},[c]),d=i.useMemo(()=>({clientId:r?.clientId||"",redirectUrl:r?.redirectUrl||"",callbacks:l}),[r?.clientId,r?.redirectUrl,l]);return u(()=>{s.os(Br({...e,auth:d}))},[e,d,s]),t(n,{children:a})});Go.displayName="ContextConfigProvider";const Jo=c({container:null,setContainer:()=>{}}),Ho=i.memo(({children:n})=>{const[r,a]=i.useState(null),s=i.useMemo(()=>({container:r,setContainer:a}),[r]);return e(Jo.Provider,{value:s,children:[n,t("div",{ref:a,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});Ho.displayName="PortalProvider";const Ko=c(null);function Yo(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}const Qo=i.memo(function({children:e,serviceWorkerPath:n="/push-sw.js",autoSubscribe:r=!1}){const{t:i}=Oi(),a=ws(),{isAuthenticated:o}=Vo(),c=s(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=s(()=>new Ke({serverUrl:a.serverUrl,version:a.version,orgId:a.orgId}),[a.serverUrl,a.version,a.orgId]),[d,m]=h({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(n);if(e)return;if(!t)return void m(e=>({...e,isSubscribed:!1}));const r=await t.pushManager.getSubscription();if(e)return;m(e=>({...e,isSubscribed:!!r,permission:Notification.permission}))}catch{e||m(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[o,c,n]);const g=p(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return m(t=>({...t,permission:e})),"granted"===e},[c]),f=p(async()=>{if(c&&o){m(e=>({...e,loading:!0,error:null}));try{if(!await g())return void m(e=>({...e,loading:!1,error:i("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(n);await navigator.serviceWorker.ready;const r=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Yo(e)})).toJSON();await l.subscribe({endpoint:r.endpoint,keys:{p256dh:r.keys.p256dh,auth:r.keys.auth}},navigator.userAgent),m(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:i("push.failedToSubscribe");m(e=>({...e,loading:!1,error:t})),we(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,o,l,n,g]),y=p(async()=>{if(c){m(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(n);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}m(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:i("push.failedToUnsubscribe");m(e=>({...e,loading:!1,error:t})),we(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,n]),w=s(()=>({...d,requestPermission:g,subscribe:f,unsubscribe:y}),[d,g,f,y]);return t(Ko.Provider,{value:w,children:e})});function Zo(){const e=d(Ko);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e}const Xo="bb_seen_users",ec=12e4;function tc(){try{const e=window.localStorage.getItem(Xo),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function nc(e,t,n=Date.now()){if(!e)return"login";if("undefined"==typeof window)return"login";if(tc().includes(e))return"login";if(function(e){try{const t=[e,...tc().filter(t=>t!==e)].slice(0,20);window.localStorage.setItem(Xo,JSON.stringify(t))}catch{}}(e),!t)return"login";const r=Date.parse(t);return Number.isNaN(r)||r>n||n-r>ec||function(e){try{const t=window.document?.cookie;return"string"==typeof t&&t.split("; ").includes(`${rc}=${e}`)}catch{return!1}}(e)?"login":(function(e){try{const t=window.document;if(!t||!ic.test(e))return;const n=ji(window.location?.hostname??"",t);t.cookie=`${rc}=${e}; path=/; max-age=120; SameSite=Lax`+(n?`; domain=${n}`:"")}catch{}}(e),"sign_up")}const rc="bb_su",ic=/^[\w-]{1,64}$/;const ac="bb_announced_session";const sc={[yt.UserCreated]:"user_created",[yt.UserUpdated]:"user_updated",[yt.WorkspaceCreated]:"workspace_created",[yt.WorkspaceUpdated]:"workspace_updated",[yt.WorkspaceChanged]:"workspace_switched",[yt.WorkspaceDeleted]:"workspace_deleted",[yt.WorkspaceUserAdded]:"workspace_member_added",[yt.WorkspaceUserRemoved]:"workspace_member_removed",[yt.WorkspaceUserRoleChanged]:"workspace_member_role_changed",[yt.WorkspaceInvitationSent]:"workspace_invitation_sent",[yt.WorkspaceInvitationAccepted]:"workspace_invitation_accepted",[yt.WorkspaceInvitationDeclined]:"workspace_invitation_declined",[yt.WorkspaceInvitationRevoked]:"workspace_invitation_revoked"};const oc=Object.keys(sc),cc="undefined"==typeof window?i.useEffect:i.useLayoutEffect;function lc({children:e}){const{track:r,setUser:a,setProperties:s,ready:o,setIdentity:c,setConsentRecordHeaders:l}=ps(),d=Bo().session,u=d?.user?.id,p=d?.sessionId,h=d?.user?.email;i.useEffect(()=>{l(p?{"x-session-id":p}:{})},[p,l]),i.useEffect(()=>{c(h?{email:h}:null)},[h,c]);const{currentWorkspace:m}=Mo(),{response:g,loading:f}=qs(),y=i.useMemo(()=>function(e){const{workspace:t,userId:n,subscription:r,subscriptionLoading:i}=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 s=Array.isArray(t.users)?t.users.length:void 0,o=i?void 0:r?.subscription?r.plan?.slug??void 0:"none";return{workspace_id:String(t._id),workspace_role:Yn(t,n)??void 0,workspace_owner:n?Kn(t,n):void 0,workspace_member_count:s,workspace_plan:o,subscription_status:i?void 0:r?.subscription?.subscriptionStatus??"none"}}({workspace:u?m:null,userId:u,subscription:g,subscriptionLoading:f}),[m,u,g,f]),w=JSON.stringify(y),v=i.useRef(null);cc(()=>{v.current!==w&&(v.current=w,s(y))},[w,s]);const b=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}(y),k=JSON.stringify(b),S=i.useRef(null);i.useEffect(()=>{if(!o||!u||0===Object.keys(b).length)return;const e=`${u}|${k}`;S.current!==e&&(S.current=e,a(u,b))},[o,u,k,a]),i.useEffect(()=>{o&&u&&p&&(ko||function(e){if(!e)return!1;if("undefined"==typeof window)return!1;try{return window.localStorage.getItem(ac)!==e&&(window.localStorage.setItem(ac,e),!0)}catch{return!0}}(p)&&(a(u),r(nc(u,d?.user?.firstAuthAt),{method:"buildbase"})))},[o,u,p,d?.user?.firstAuthAt,r,a]),i.useEffect(()=>{const e=oc.map(e=>vt.on(e,t=>{(function(e,t){if(e!==yt.WorkspaceChanged)return!0;const n=t,r=n.workspace?._id,i=n.previousWorkspace?._id;return!!r&&!!i&&r!==i})(e,t)&&r(sc[e],function(e,t){const n=t,r={},i=n.workspace;i?._id&&(r.workspace_id=i._id);const a=n.previousWorkspace;a?._id&&(r.previous_workspace_id=a._id);const s=n.user;(s?._id||s?.id)&&(r.user_id=s._id??s.id),"string"==typeof n.userId&&(r.member_id=n.userId),"string"==typeof n.workspaceId&&(r.workspace_id=n.workspaceId);const o=n.invitation;o?._id&&(r.invitation_id=o._id),"string"==typeof o?.role&&(r.role=o.role);const c=o?.workspace;return"string"==typeof c?r.workspace_id=c:c?._id&&(r.workspace_id=c._id),"string"==typeof n.invitationId&&(r.invitation_id=n.invitationId),"string"==typeof n.role&&(r.role=n.role),"string"==typeof n.previousRole&&(r.previous_role=n.previousRole),"string"==typeof n.newRole&&(r.new_role=n.newRole),r}(0,t))}));return()=>e.forEach(e=>e())},[r]);const I=i.useRef(o);I.current=o;const x=i.useRef([]);return i.useEffect(()=>ye.subscribe((e,t)=>{if(!Po(`sdk_error|${`${t.component??"unknown"}|${t.action??"unknown"}`}`))return;const n=Co({component:t.component,action:t.action,code:e.code});I.current?r("sdk_error",n):x.current.length<20&&x.current.push(n)}),[r]),i.useEffect(()=>{if(!o||0===x.current.length)return;const e=x.current;x.current=[],e.forEach(e=>r("sdk_error",e))},[o,r]),t(n,{children:e})}lc.displayName="TrackingBridge";const dc=i.createContext(void 0),uc=i.memo(({children:e})=>{const{t:n}=Oi(),r=ws(),a=function(){const e=ws();return s(()=>new ot(e),[e.serverUrl,e.version])}(),{isAuthenticated:o}=Vo(),{serverUrl:c,version:l}=r,[d,u]=h({}),[m,g]=h({}),[f,y]=h(!1),[w,v]=h(!1),[b,k]=h(null),[S,I]=h(null),x=p(async e=>{if(c&&l&&o){k(null);try{const t=await a.getAttributes(e);u(t)}catch(e){if(he(e))return;const t=e instanceof Error?e:new Error(n("errors.generic"));k(t),we(e,{component:"UserProvider",action:"fetchAttributes"})}}else u({})},[a,c,l,o,n]),C=p(async()=>{if(c&&l&&o){y(!0);try{await x()}finally{y(!1)}}},[c,l,o,x]),N=p(async e=>{y(!0),k(null);try{const t=await a.updateAttributes(e);return await x(),t}catch(t){const r=t instanceof Error?t:new Error(n("errors.generic"));throw k(r),we(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{y(!1)}},[a,x,n]),P=p(async(e,t)=>{y(!0),k(null);try{const n=await a.updateAttribute(e,t);return await x(),n}catch(r){const i=r instanceof Error?r:new Error(n("errors.generic"));throw k(i),we(r,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),r}finally{y(!1)}},[a,x,n]),_=p(async e=>{if(c&&l&&o){I(null);try{const t=await a.getFeatures(e);g(t)}catch(e){if(he(e))return;const t=e instanceof Error?e:new Error(n("errors.generic"));I(t),we(e,{component:"UserProvider",action:"fetchFeatures"})}}else g({})},[a,c,l,o,n]),E=p(async()=>{if(c&&l&&o){v(!0);try{await _()}finally{v(!1)}}},[c,l,o,_]);ys(async e=>{if(!o||!c||!l)return u({}),void g({});y(!0),v(!0),await Promise.all([x(e).finally(()=>y(!1)),_(e).finally(()=>v(!1))])},[o,c,l,x,_],{onError:e=>we(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const A=i.useMemo(()=>({attributes:d,features:m,isLoading:f||w,error:b??S,attributesLoading:f,featuresLoading:w,attributesError:b,featuresError:S,updateAttributes:N,updateAttribute:P,refreshAttributes:C,refreshFeatures:E}),[d,m,f,w,b,S,N,P,C,E]);return t(dc.Provider,{value:A,children:e})});uc.displayName="UserProvider";const pc=b("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"}}),hc=r.forwardRef(({className:n,variant:i,progress:a,size:s,startIcon:o,endIcon:c,asChild:l=!1,...d},u)=>{const p=l?v:"button",h=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(s);return e(p,{disabled:a||d.disabled,className:ce(pc({variant:i,size:s,withIcon:null!=a||null!=o||null!=c,className:n})),ref:u,...d,children:[a&&t(k,{size:h,className:"animate-spin"}),o&&r.cloneElement(o,{size:h}),d.children,c&&r.cloneElement(c,{size:h})]})});hc.displayName="Button";const mc=z.Root,gc=z.Trigger,fc=z.Portal,yc=r.forwardRef(({className:e,...n},r)=>t(z.Overlay,{ref:r,className:ce("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),...n}));yc.displayName=z.Overlay.displayName;const wc=r.forwardRef(({className:n,children:i,...a},s)=>{const{container:o}=r.useContext(Jo),{t:c}=Oi();return e(fc,{container:o,children:[t(yc,{}),e(z.Content,{ref:s,className:ce("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",n),...a,children:[i,e(z.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(G,{className:"h-4 w-4"}),t("span",{className:"sr-only",children:c("settings.common.close")})]})]})]})});wc.displayName=z.Content.displayName;const vc=({className:e,...n})=>t("div",{className:ce("flex flex-col space-y-1.5 text-center sm:text-start",e),...n});vc.displayName="DialogHeader";const bc=({className:e,...n})=>t("div",{className:ce("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...n});bc.displayName="DialogFooter";const kc=r.forwardRef(({className:e,...n},r)=>t(z.Title,{ref:r,className:ce("text-lg font-semibold leading-none tracking-tight",e),...n}));kc.displayName=z.Title.displayName;const Sc=r.forwardRef(({className:e,...n},r)=>t(z.Description,{ref:r,className:ce("text-sm text-muted-foreground",e),...n}));Sc.displayName=z.Description.displayName;const Ic={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 xc({variant:n,title:r,message:i,description:a,icon:s,actionLabel:o,onAction:c,actionDisabled:l,className:d}){const u=Ic[n];return e("div",{role:"error"===n?"alert":"status","aria-live":"error"===n?"assertive":"polite","aria-atomic":"true",className:ce("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:[s,e("div",{className:"min-w-0",children:[r&&t("p",{className:"text-sm font-medium",children:r}),i&&t("p",{className:ce("text-sm",r&&"mt-1"),children:i}),a&&t("p",{className:ce("text-xs mt-2",u.sub),children:a})]})]}),o&&t(hc,{variant:"outline",size:"sm",onClick:c,disabled:l,className:ce("flex-shrink-0",u.button),children:o})]})}const Cc=new Set(["alreadyAccepted","expired","revoked","accepted","declined","disabled"]),Nc=new Set(["expired","revoked","disabled"]),Pc=new Set(["accepted"]),_c=new Set(["alreadyAccepted","expired","revoked","declined"]);function Ec(){const{t:r}=Oi(),i=ws(),{isAuthenticated:a,isLoading:s,signIn:o,signOut:c}=Vo(),{previewInvitation:d,acceptInvitation:m,declineInvitation:g,switchToWorkspace:f}=Mo(),y=i.orgId??"",[w,v]=h(null),[b,k]=h(null),[S,I]=h({kind:"none"}),[x,C]=h(!1),N=l(!1),P=Cc.has(S.kind),_="accepted"===S.kind?r("invitations.titleJoined",{workspace:S.workspace}):Nc.has(S.kind)?r("invitations.titleUnavailable"):r("invitations.title"),E="wrongAccount"===S.kind,A=p(e=>{I(e),Cc.has(e.kind)&&Nr()},[]);u(()=>{if(N.current||!y)return;N.current=!0;const e=$t();e?.action===Tt.Invite&&e.token&&(xr(e.token,y),Dt(),v(e.token))},[y]),u(()=>{if(!y||w||s)return;const e=Cr(y);e&&v(e)},[y,w,s,a]),u(()=>{if(!w)return;let e=!1;return k(null),I({kind:"none"}),d(w).then(t=>{e||(k(t),"accepted"===t.status?A({kind:"alreadyAccepted"}):"expired"===t.status?A({kind:"expired",inviter:t.inviterName}):"rejected"===t.status?A({kind:"revoked"}):!1===t.joinable&&A({kind:"disabled"}))}).catch(t=>{e||(we(t,{component:"InvitationLanding",action:"preview"}),ht(t)&&404===t.status?A({kind:"revoked"}):I({kind:"loadFailed"}))}),()=>{e=!0}},[w,d,A]);const U=p(()=>{Nr(),v(null),k(null),I({kind:"none"})},[]);if(!w)return null;const T=function(e,t){switch(e.kind){case"none":return null;case"alreadyAccepted":return t("invitations.alreadyAccepted");case"expired":return t("invitations.expired",{inviter:e.inviter});case"revoked":return t("invitations.revoked");case"loadFailed":return t("invitations.loadFailed");case"accepted":return t("invitations.accepted",{workspace:e.workspace});case"declined":return t("invitations.declined");case"verifyFirst":return t("invitations.verifyFirst");case"wrongAccount":return t("invitations.wrongAccount",{email:e.email});case"workspaceFull":return t("invitations.workspaceFull");case"disabled":return t("invitations.disabled");case"acceptFailed":return t("invitations.acceptFailed");case"declineFailed":return t("invitations.declineFailed");case"raw":return e.message}}(S,r),O=Pc.has(S.kind)?"success":_c.has(S.kind)?"info":"error";return t(mc,{open:!0,onOpenChange:e=>!e&&U(),children:e(wc,{className:"sm:max-w-md",children:[e(vc,{children:[t(kc,{children:_}),b&&t(Sc,{children:r("invitations.description",{inviter:b.inviterName,workspace:b.workspaceName,role:b.role})})]}),b&&t("p",{className:"text-sm text-muted-foreground",children:r("invitations.sentTo",{email:b.email})}),T&&t(xc,{variant:O,message:T}),t(bc,{className:"gap-2 sm:gap-2",children:P?t(hc,{onClick:U,children:r("invitations.dismiss")}):E?e(n,{children:[t(hc,{variant:"outline",onClick:U,children:r("invitations.dismiss")}),t(hc,{onClick:()=>{c().then(()=>I({kind:"none"})).catch(e=>we(e,{component:"InvitationLanding",action:"signOut"}))},children:r("invitations.signOut")})]}):b?s?null:e(n,a?{children:[t(hc,{variant:"outline",disabled:x,onClick:async()=>{if(b){C(!0),I({kind:"none"});try{await g(b.id),A({kind:"declined"})}catch(e){we(e,{component:"InvitationLanding",action:"decline"}),ht(e)&&e.code===ct.EMAIL_MISMATCH?I({kind:"wrongAccount",email:e.invitedEmail??b.email}):ht(e)&&e.code===ct.ALREADY_HANDLED?A("accepted"===e.invitationStatus?{kind:"alreadyAccepted"}:{kind:"revoked"}):I({kind:"declineFailed"})}finally{C(!1)}}},children:r("invitations.decline")}),t(hc,{progress:x,onClick:async()=>{if(b){C(!0),I({kind:"none"});try{const{workspace:e}=await m(b.id,{token:w??void 0});A({kind:"accepted",workspace:b.workspaceName}),e&&await f(e)}catch(e){if(we(e,{component:"InvitationLanding",action:"accept"}),ht(e))switch(e.code){case ct.EMAIL_NOT_VERIFIED:I({kind:"verifyFirst"});break;case ct.EMAIL_MISMATCH:I({kind:"wrongAccount",email:e.invitedEmail??b.email});break;case ct.SEAT_LIMIT:I({kind:"workspaceFull"});break;case ct.INVITES_DISABLED:A({kind:"disabled"});break;case ct.EXPIRED:A({kind:"expired",inviter:b.inviterName});break;case ct.ALREADY_HANDLED:case ct.NOT_FOUND:A("accepted"===e.invitationStatus?{kind:"alreadyAccepted"}:{kind:"revoked"});break;default:I({kind:"raw",message:e.message})}else I({kind:"acceptFailed"})}finally{C(!1)}}},children:r("invitations.accept")})]}:{children:[t(hc,{variant:"outline",onClick:U,children:r("invitations.dismiss")}),t(hc,{onClick:()=>{o(window.location.href).catch(e=>we(e,{component:"InvitationLanding",action:"signIn"}))},children:r("invitations.signInToAccept")})]}):t(hc,{variant:"outline",onClick:U,disabled:!T,children:r("invitations.dismiss")})})]})})}function Ac(e){const{user:t}=Vo(),{currentWorkspace:n}=Mo(),{settings:r}=ks(),{appPermissions:i}=po(),a=e??n??null,o=t?.id??null,c=s(()=>a?Yn(a,o):null,[a,o]),l=s(()=>!!a&&Kn(a,o),[a,o]),d=s(()=>rr({userId:o,workspaceRole:c,workspace:a,settings:r,appPermissions:i}),[o,c,a,r,i]),u=p(e=>Array.isArray(e)?e.every(e=>d.has(e)):d.has(e),[d]),h=s(()=>or(r,i),[r,i]);return{can:u,permissions:d,isOwner:l,role:c,appPermissionDefinitions:h}}function Uc(){const e=wo(),{can:t}=Ac();return{visible:p((n,r)=>!1!==n(e)&&(void 0===r||t(r)),[e,t]),ui:e}}function Tc(){const e=ws();return s(()=>new Ve(e),[e.serverUrl,e.version])}function Oc(){const e=Tc(),{t:t}=Oi(),[n,r]=h([]),[i,a]=h(!0),[o,c]=h(null),[d,m]=h(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 n=await e.list(t.signal);t.signal.aborted||r(n)}catch(e){if(t.signal.aborted)return;ve(e,{component:"useConnectedAgents",action:"list"}),c(be(e,"security.connectedAgentsLoadFailed",f.current))}finally{g.current===t&&(g.current=null,a(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const w=p(async t=>{m(t),c(null);try{await e.revoke(t),r(e=>e.filter(e=>e.clientId!==t))}catch(e){ve(e,{component:"useConnectedAgents",action:"revoke"}),c(be(e,"security.connectedAgentsRevokeFailed",f.current))}finally{m(null)}},[e]);return s(()=>({agents:n,loading:i,error:o,revoking:d,refresh:y,revoke:w}),[n,i,o,d,y,w])}function Rc(e,t="en-US",n){try{const r=new Date(e);return isNaN(r.getTime())?"":new Intl.DateTimeFormat(t,n??{month:"short",day:"numeric",year:"numeric"}).format(r)}catch{return""}}function Wc(e,t="en-US"){return Rc(e,t,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Fc(e,t="en-US"){return e?new Date(1e3*e).toLocaleDateString(t,{year:"numeric",month:"short",day:"numeric"}):""}const Lc=[["second",60],["minute",60],["hour",24],["day",7],["week",4.34524],["month",12],["year",Number.POSITIVE_INFINITY]];function $c(e,t="en-US",n=Date.now()){try{const r=new Date(e).getTime();if(isNaN(r))return"";const i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});let a=(r-n)/1e3;if(Math.abs(a)<60)return i.format(0,"second");for(const[e,t]of Lc){if(Math.abs(a)<t)return i.format(Math.round(a),e);a/=t}return""}catch{return""}}function Dc({icon:n,title:r,description:i,action:a,className:s}){return e("div",{className:ce("flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",s),children:[n&&t("span",{"aria-hidden":"true",children:n}),r&&t("p",{className:"text-sm font-medium",children:r}),i&&t("p",{className:"text-sm text-muted-foreground",children:i}),a]})}function Mc({title:n,description:r,actions:i,className:a,titleClassName:s}){return n||r||i?e("div",{className:ce(a),children:[(n||i)&&e("div",{className:ce("flex items-center gap-2",n?"justify-between":"justify-end"),children:[n&&t("h3",{className:ce("text-sm font-medium",s),children:n}),i]}),r&&t("p",{className:"text-sm text-muted-foreground",children:r})]}):null}function jc({className:e,...n}){return t("div",{className:ce("animate-pulse rounded-md bg-primary/10",e),...n})}const qc=ae.Root,Bc=r.forwardRef(({className:e,...n},r)=>t(ae.Item,{ref:r,className:ce("border-b last:border-b-0",e),...n}));Bc.displayName="AccordionItem";const Vc=r.forwardRef(({className:n,children:r,...i},a)=>t(ae.Header,{className:"flex",children:e(ae.Trigger,{ref:a,className:ce("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",n),...i,children:[t(S,{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:r})]})}));Vc.displayName="AccordionTrigger";const zc=r.forwardRef(({className:e,children:n,...r},i)=>t(ae.Content,{ref:i,className:"overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:t("div",{className:ce("pb-3 pt-0",e),children:n})}));function Gc({value:n,displayValue:i,copyLabel:a,copiedLabel:s,variant:o="inline",className:c}){const l=i??n,[d,u]=r.useState(!1),p=r.useRef(null);r.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const h=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 n=document.execCommand("copy");return document.body.removeChild(t),n}catch{return!1}}(n)&&(u(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>u(!1),2e3))},m=n=>e(hc,{type:"button",variant:"ghost",size:"sm",onClick:h,"aria-label":d?s:a,className:"h-7 shrink-0 gap-1.5 px-2",children:[t(d?I:x,{className:"h-3.5 w-3.5","aria-hidden":"true"}),t("span",{className:ce("text-xs",n&&"hidden sm:inline"),children:d?s:a})]});return e("div","inline"===o?{dir:"ltr",className:ce("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:n,children:l}),m(!0)]}:{dir:"code"===o?"ltr":void 0,className:ce("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:m(!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 Jc({config:n,title:r,description:i,className:a}){const{t:s}=Oi(),o=co(),c=n??o;if(!c?.url)return null;const l=c.name?.trim()||"app",d={url:c.url,name:l,key:so(l)},u=(e,t,n,r)=>({id:e,name:t,instructions:s("security.mcpAddToConfigFile",{path:`${n}`}),snippet:r}),p=[{id:"chatgpt",name:"ChatGPT",instructions:s("security.mcpClientChatgptInstructions")},{id:"claude",name:"Claude",instructions:s("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:s("security.mcpClientClineInstructions")}],h=c.clients??p,m=void 0===r?s("security.mcpGuideTitle"):r,g=void 0===i?s("security.mcpGuideDescription"):i,f=s("security.mcpCopy"),y=s("security.mcpCopied"),w=!1===c.prompt?null:c.prompt??s("security.mcpPromptTemplate"),v=ao(w??void 0,d),b=ao(w??void 0,{...d,url:`${d.url}`,name:`${d.name}`});return e("div",{className:ce("space-y-5",a),children:[t(Mc,{title:m,description:g}),e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:s("security.mcpServerUrlLabel")}),t("p",{className:"text-xs text-muted-foreground",children:s("security.mcpServerUrlHint")}),t(Gc,{value:c.url,copyLabel:f,copiedLabel:y})]}),v&&e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:s("security.mcpPromptLabel")}),t("p",{className:"text-xs text-muted-foreground",children:s("security.mcpPromptHint")}),t(Gc,{value:v,displayValue:b,copyLabel:f,copiedLabel:y,variant:"text"})]}),h.length>0&&e("div",{className:"space-y-1.5",children:[t("p",{className:"text-sm font-medium",children:s("security.mcpClientsLabel")}),t(qc,{type:"single",collapsible:!0,defaultValue:h[0]?.id,className:"rounded-md border px-3",children:h.map(n=>{const r=ao(n.instructions,d),i=ao(n.snippet,d);return e(Bc,{value:n.id,children:[t(Vc,{children:n.name}),t(zc,{children:e("div",{className:"space-y-2",children:[r&&t("p",{className:"text-sm text-muted-foreground",children:r}),i&&t(Gc,{value:i,copyLabel:f,copiedLabel:y,variant:"code"}),n.actionUrl&&e("a",{href:n.actionUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[n.actionLabel??n.actionUrl,t(C,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})})]},n.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:[s("security.mcpLearnMore"),t(C,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}function Hc({className:n,title:r,description:i,disconnectLabel:a,emptyLabel:s,showConnectGuide:o=!0}){const{t:c,formattingLocale:d}=Oi(),{formats:p}=wo(),{agents:m,loading:g,error:f,revoking:y,revoke:w}=Oc(),v=co(),b=o&&Boolean(v?.url),[k,S]=h(!1),I=l(!1);u(()=>{if(I.current||!b)return;const e=Fo.getState().params;e?.action===Tt.OpenConnectGuide&&(I.current=!0,Fo.clearParams(),S(!0))},[b]);const x=void 0===r?c("security.connectedAgentsTitle"):r,C=void 0===i?c("security.connectedAgentsDescription"):i,_=a??c("security.connectedAgentsDisconnect"),E=s??c("security.connectedAgentsEmpty"),A=c("security.mcpConnectAction"),U=n=>b?e(hc,{size:"sm",onClick:()=>S(!0),"aria-label":A,className:"shrink-0 gap-1.5",children:[t(P,{className:"h-4 w-4","aria-hidden":"true"}),t("span",{className:n?"hidden sm:inline":void 0,children:A})]}):null;return e("div",{className:ce("space-y-4",n),children:[t(Mc,{title:x,description:C,actions:!g&&m.length>0?U(!0):void 0}),g&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(jc,{className:"h-20 rounded-md"},e))}),f&&!g&&t("p",{className:"text-destructive text-sm",children:f}),!g&&!f&&0===m.length&&t(Dc,{icon:t(N,{className:"h-5 w-5 text-muted-foreground"}),description:E,action:U(!1)??void 0}),!g&&m.length>0&&t("ul",{className:"space-y-3",children:m.map(n=>{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:n.title}),n.scope.length>0&&e("span",{className:"text-muted-foreground text-xs break-words",children:[c("security.connectedAgentsAccess"),": ",n.scope.join(", ")]}),n.lastGrantedAt&&e("span",{className:"text-muted-foreground text-xs",children:[c("security.connectedAgentsGranted"),": ",(r=n.lastGrantedAt,Rc(r,d,p?.date??{dateStyle:"medium"}))]})]}),t(hc,{variant:"outline",size:"sm",progress:y===n.clientId,onClick:()=>w(n.clientId),className:"shrink-0",children:_})]},n.clientId);var r})}),b&&t(mc,{open:k,onOpenChange:S,children:e(wc,{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(vc,{className:"pe-8",children:[t(kc,{children:c("security.mcpGuideTitle")}),t(Sc,{children:c("security.mcpGuideDescription")})]}),t(Jc,{title:null,description:null})]})})]})}function Kc({label:n,className:r}){const{t:i}=Oi();return e("div",{role:"status","aria-live":"polite",className:ce("flex items-center gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground",r),children:[t(k,{className:"h-4 w-4 animate-spin flex-shrink-0"}),t("span",{children:n??i("settings.common.loading")})]})}zc.displayName="AccordionContent";const Yc=se.Root,Qc=se.Trigger,Zc=se.Portal,Xc=r.forwardRef(({className:e,...n},r)=>t(se.Overlay,{className:ce("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),...n,ref:r}));Xc.displayName=se.Overlay.displayName;const el=r.forwardRef(({className:n,...i},a)=>{const{container:s}=r.useContext(Jo);return e(Zc,{container:s,children:[t(Xc,{}),t(se.Content,{ref:a,className:ce("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",n),...i})]})});el.displayName=se.Content.displayName;const tl=({className:e,...n})=>t("div",{className:ce("flex flex-col space-y-2 text-center sm:text-start",e),...n});tl.displayName="AlertDialogHeader";const nl=({className:e,...n})=>t("div",{className:ce("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...n});nl.displayName="AlertDialogFooter";const rl=r.forwardRef(({className:e,...n},r)=>t(se.Title,{ref:r,className:ce("text-lg font-semibold",e),...n}));rl.displayName=se.Title.displayName;const il=r.forwardRef(({className:e,...n},r)=>t(se.Description,{ref:r,className:ce("text-sm text-muted-foreground",e),...n}));il.displayName=se.Description.displayName;const al=r.forwardRef(({className:e,...n},r)=>t(se.Action,{ref:r,className:ce(pc(),e),...n}));al.displayName=se.Action.displayName;const sl=r.forwardRef(({className:e,...n},r)=>t(se.Cancel,{ref:r,className:ce(pc({variant:"outline"}),"mt-2 sm:mt-0",e),...n}));function ol(){const e=ws();return s(()=>new ze(e),[e.serverUrl,e.version])}function cl(){const e=ol(),{t:t}=Oi(),[n,r]=h([]),[i,a]=h(!0),[o,c]=h(null),[d,m]=h(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 n=await e.list(t.signal);t.signal.aborted||r(n)}catch(e){if(t.signal.aborted)return;ve(e,{component:"useDevices",action:"list"}),c(be(e,"security.devicesLoadFailed",f.current))}finally{g.current===t&&(g.current=null,a(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const w=p(async(t,n)=>{m(t),c(null);try{await e.rename(t,n),r(e=>e.map(e=>e.deviceId===t?{...e,name:n}:e))}catch(e){ve(e,{component:"useDevices",action:"rename"}),c(be(e,"security.deviceRenameFailed",f.current))}finally{m(null)}},[e]),v=p(async t=>{m(t),c(null);try{await e.signOut(t),r(e=>e.map(e=>e.deviceId===t?{...e,activeSessions:0}:e))}catch(e){ve(e,{component:"useDevices",action:"signOut"}),c(be(e,"security.deviceSignOutFailed",f.current))}finally{m(null)}},[e]),b=p(async t=>{m(t),c(null);try{await e.forget(t),r(e=>e.filter(e=>e.deviceId!==t))}catch(e){ve(e,{component:"useDevices",action:"forget"}),c(be(e,"security.deviceForgetFailed",f.current))}finally{m(null)}},[e]);return s(()=>({devices:n,loading:i,error:o,busyId:d,refresh:y,rename:w,signOut:v,forget:b}),[n,i,o,d,y,w,v,b])}function ll(e){return!!e&&/Mobi|Android|iPhone|iPad|iPod|Windows Phone/i.test(e)}function dl(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 ul(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":""),dl(e)].filter(Boolean).join(" · "):"";var t}sl.displayName=se.Cancel.displayName;const pl=r.forwardRef(({className:e,type:n,...r},i)=>t("input",{type:n,className:ce("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:i,...r}));function hl({className:r,title:i,description:a,showRename:s,showSignOut:o,showRemove:c,renameLabel:l,signOutLabel:d,removeLabel:u,emptyLabel:p}){const{t:m,formattingLocale:g}=Oi(),{formats:f}=wo(),{visible:y}=Uc(),{devices:w,loading:v,error:b,busyId:k,rename:S,signOut:x,forget:C}=cl(),[N,P]=h(null),[O,R]=h(""),[W,F]=h(null),L=s??y(e=>e.settings?.devices?.rename),$=o??y(e=>e.settings?.devices?.signOut),D=c??y(e=>e.settings?.devices?.forget),M=L||$||D,j=void 0===i?m("security.devicesTitle"):i,q=void 0===a?m("security.devicesDescription"):a,B=l??m("security.deviceRename"),V=d??m("security.deviceSignOut"),z=u??m("security.deviceForget"),G=p??m("security.devicesEmpty"),J=async e=>{const t=O.trim();t&&await S(e,t),P(null)};return e("div",{className:ce("space-y-4",r),children:[t(Mc,{title:j,description:q}),v&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(jc,{className:"h-24 rounded-md"},e))}),b&&!v&&t("p",{className:"text-destructive text-sm",children:b}),!v&&!b&&0===w.length&&t(Dc,{icon:t(_,{className:"h-5 w-5 text-muted-foreground"}),description:G}),!v&&w.length>0&&t("ul",{className:"space-y-3",children:w.map(r=>{const i=N===r.deviceId,a=k===r.deviceId,s=ul(r.userAgent),o=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(r),c=ll(r.userAgent)?E:_;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",i?{className:"flex items-center gap-x-2",children:[t(pl,{value:O,onChange:e=>R(e.target.value),placeholder:m("security.deviceRenamePlaceholder"),className:"h-8 w-48",autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&J(r.deviceId),"Escape"===e.key&&P(null)}}),t(hc,{size:"sm",variant:"ghost","aria-label":m("security.deviceSave"),progress:a,onClick:()=>J(r.deviceId),children:t(I,{className:"h-4 w-4","aria-hidden":"true"})}),t(hc,{size:"sm",variant:"ghost","aria-label":m("security.deviceCancel"),onClick:()=>P(null),children:t(A,{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:r.name}),r.current&&t("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:m("security.deviceCurrent")}),r.trusted&&e("span",{className:"text-primary inline-flex items-center gap-x-1 text-xs",children:[t(U,{className:"h-3.5 w-3.5","aria-hidden":"true"}),m("security.deviceTrusted")]}),r.pushEnabled&&t("span",{className:"text-muted-foreground inline-flex","aria-label":m("security.devicePushEnabled"),title:m("security.devicePushEnabled"),children:t(T,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),s&&t("span",{className:"text-muted-foreground text-xs break-words",children:s}),o&&t("span",{className:"text-muted-foreground text-xs break-words",children:o}),e("span",{className:"text-muted-foreground text-xs",children:[r.lastActiveAt&&m("security.deviceLastActive",{date:(l=r.lastActiveAt,Rc(l,g,f?.date??{dateStyle:"medium"}))}),r.activeSessions>0&&e(n,{children:[r.lastActiveAt&&" · ",m("security.deviceActiveSessions",{count:r.activeSessions})]})]})]})]}),!i&&M&&e("div",{className:"flex shrink-0 flex-col items-end gap-y-1.5",children:[(L||$)&&e("div",{className:"flex items-center gap-x-1.5",children:[L&&t(hc,{variant:"ghost",size:"sm",disabled:a,onClick:()=>(e=>{P(e.deviceId),R(e.name)})(r),children:B}),$&&r.activeSessions>0&&t(hc,{variant:"outline",size:"sm",progress:a,onClick:()=>x(r.deviceId),children:V})]}),D&&t(hc,{variant:"ghost",size:"sm",className:"text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:a,onClick:()=>F(r),children:z})]})]},r.deviceId);var l})}),t(Yc,{open:null!==W,onOpenChange:e=>{e||F(null)},children:e(el,{children:[e(tl,{children:[t(rl,{children:m("security.deviceForgetConfirmTitle")}),t(il,{children:m("security.deviceForgetConfirmBody")})]}),e(nl,{children:[t(sl,{children:m("security.deviceCancel")}),t(al,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{if(!W)return;const{deviceId:e}=W;F(null),await C(e)},children:z})]})]})})]})}function ml(){const e=ws();return s(()=>new Ye(e),[e.serverUrl,e.version])}function gl(){const e=ml(),{t:t}=Oi(),[n,r]=h([]),[i,a]=h(!0),[o,c]=h(null),[d,m]=h(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 n=await e.list(t.signal);t.signal.aborted||r(n)}catch(e){if(t.signal.aborted)return;ve(e,{component:"useSessions",action:"list"}),c(be(e,"security.sessionsLoadFailed",f.current))}finally{g.current===t&&(g.current=null,a(!1))}},[e]);u(()=>(y(),()=>g.current?.abort()),[y]);const w=p(async t=>{m(t),c(null);try{await e.revoke(t),r(e=>e.filter(e=>e.id!==t))}catch(e){ve(e,{component:"useSessions",action:"revoke"}),c(be(e,"security.sessionSignOutFailed",f.current))}finally{m(null)}},[e]);return s(()=>({sessions:n,loading:i,error:o,revoking:d,refresh:y,revoke:w}),[n,i,o,d,y,w])}function fl({className:r,title:i,description:a,showSignOut:s,signOutLabel:o,emptyLabel:c}){const{t:l,formattingLocale:d}=Oi(),{formats:u}=wo(),{visible:p}=Uc(),{sessions:h,loading:m,error:g,revoking:f,revoke:y}=gl(),w=s??p(e=>e.settings?.devices?.sessionSignOut),v=void 0===i?l("security.sessionsTitle"):i,b=void 0===a?l("security.sessionsDescription"):a,k=o??l("security.sessionSignOut"),S=c??l("security.sessionsEmpty"),I=e=>Rc(e,d,u?.date??{dateStyle:"medium"});return e("div",{className:ce("space-y-4",r),children:[t(Mc,{title:v,description:b}),m&&t("div",{className:"space-y-3",children:[0,1].map(e=>t(jc,{className:"h-20 rounded-md"},e))}),g&&!m&&t("p",{className:"text-destructive text-sm",children:g}),!m&&!g&&0===h.length&&t(Dc,{icon:t(O,{className:"h-5 w-5 text-muted-foreground"}),description:S}),!m&&h.length>0&&t("ul",{className:"space-y-3",children:h.map(r=>{const i=ul(r.userAgent),a=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(r),s=r.device?.name||i||l("security.sessionsTitle"),o=ll(r.userAgent)?E:_;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:s}),r.current&&t("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:l("security.sessionCurrent")})]}),i&&s!==i&&t("span",{className:"text-muted-foreground text-xs break-words",children:i}),a&&t("span",{className:"text-muted-foreground text-xs break-words",children:a}),e("span",{className:"text-muted-foreground text-xs",children:[r.lastActiveAt&&e(n,{children:[l("security.sessionLastActive",{date:I(r.lastActiveAt)}),r.expiresAt&&" · "]}),r.expiresAt&&l("security.sessionExpires",{date:I(r.expiresAt)})]})]})]}),!r.current&&w&&t(hc,{variant:"ghost",size:"sm",progress:f===r.id,onClick:()=>y(r.id),className:"text-destructive hover:bg-destructive/10 hover:text-destructive shrink-0",children:k})]},r.id)})})]})}pl.displayName="Input";const yl=b("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),wl=r.forwardRef(({className:e,...n},r)=>t(X.Root,{ref:r,className:ce(yl(),e),...n}));wl.displayName=X.Root.displayName;const vl=Y,bl=r.createContext({}),kl=({...e})=>t(bl.Provider,{value:{name:e.name},children:t(K,{...e})}),Sl=()=>{const e=r.useContext(bl),t=r.useContext(Il),{getFieldState:n,formState:i}=Q(),a=n(e.name,i);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:s}=t;return{id:s,name:e.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...a}},Il=r.createContext({}),xl=r.forwardRef(({className:e,...n},i)=>{const a=r.useId();return t(Il.Provider,{value:{id:a},children:t("div",{ref:i,className:ce("space-y-2",e),...n})})});xl.displayName="FormItem";const Cl=r.forwardRef(({className:e,...n},r)=>{const{error:i,formItemId:a}=Sl();return t(wl,{ref:r,className:ce(i&&"text-destructive",e),htmlFor:a,...n})});Cl.displayName="FormLabel";const Nl=r.forwardRef(({...e},n)=>{const{error:r,formItemId:i,formDescriptionId:a,formMessageId:s}=Sl();return t(v,{ref:n,id:i,"aria-describedby":r?`${a} ${s}`:`${a}`,"aria-invalid":!!r,...e})});Nl.displayName="FormControl";const Pl=r.forwardRef(({className:e,...n},r)=>{const{formDescriptionId:i}=Sl();return t("p",{ref:r,id:i,className:ce("text-sm text-muted-foreground",e),...n})});Pl.displayName="FormDescription";const _l=r.forwardRef(({className:e,children:n,...r},i)=>{const{error:a,formMessageId:s}=Sl(),o=a?String(a?.message):n;return o?t("p",{ref:i,id:s,className:ce("text-sm font-medium text-destructive",e),...r,children:o}):null});_l.displayName="FormMessage";const El=r.forwardRef(({className:e,...n},r)=>t(ne.Root,{className:ce("grid gap-2",e),...n,ref:r}));El.displayName=ne.Root.displayName;const Al=r.forwardRef(({className:e,...n},r)=>t(ne.Item,{ref:r,className:ce("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),...n,children:t(ne.Indicator,{className:"flex items-center justify-center",children:t(J,{className:"h-3.5 w-3.5 fill-primary"})})}));Al.displayName=ne.Item.displayName;const Ul=r.forwardRef(({className:n,children:r,...i},a)=>e(re.Root,{ref:a,className:ce("relative overflow-hidden",n),...i,children:[t(re.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),t(Tl,{}),t(re.Corner,{})]}));Ul.displayName=re.Root.displayName;const Tl=r.forwardRef(({className:e,orientation:n="vertical",...r},i)=>t(re.ScrollAreaScrollbar,{ref:i,orientation:n,className:ce("flex touch-none select-none transition-colors","vertical"===n&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===n&&"h-2.5 border-t border-t-transparent p-[1px]",e),...r,children:t(re.ScrollAreaThumb,{className:ce("relative rounded-full bg-border","vertical"===n&&"flex-1")})}));function Ol(){const e=ws();return s(()=>new st(e),[e.serverUrl,e.version])}Tl.displayName=re.ScrollAreaScrollbar.displayName;const Rl={tooLarge:"uploads.errorTooLarge",invalid:"uploads.errorInvalid",disabled:"uploads.errorDisabled",userLimit:"uploads.errorUserLimit",unavailable:"uploads.errorUnavailable",failed:"uploads.errorFailed"};function Wl(e){const t=Ol(),{settings:n}=ks(),{t:r,formattingLocale:i}=Oi(),[a,o]=h(!1),[c,d]=h(null),m=l(null),g=l(!0),f=s(()=>rt(n),[n]),y=s(()=>at(f.maxFileBytes,i),[f.maxFileBytes,i]);u(()=>(g.current=!0,()=>{g.current=!1,m.current?.abort()}),[]);const w=p(()=>m.current?.abort(),[]),v=p(async n=>{m.current?.abort();const r=it(n,f);if(r)throw d(r),Object.assign(new Error(`The upload was refused: ${r}.`),{code:"disabled"===r?"UPLOADS_DISABLED":"UPLOAD_TOO_LARGE",status:"disabled"===r?403:413});const i=new AbortController;m.current=i,o(!0),d(null);try{return await t.upload(n,{purpose:e,signal:i.signal})}catch(e){throw!he(e)&&g.current&&d(nt(e)),ve(e,{component:"useUpload",action:"upload"}),e}finally{m.current===i&&(m.current=null,g.current&&o(!1))}},[t,e,f]),b=c?r(Rl[c],{max:y}):null;return s(()=>({upload:v,cancel:w,loading:a,error:b,failure:c,enabled:f.enabled,maxBytes:f.maxFileBytes,maxLabel:y}),[v,w,a,b,c,f,y])}function Fl(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</text></svg>`}const Ll=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑💻","👨💻","👩💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨💼","👩💼","👨🏫","👩🏫","👨🔬","👩🔬","👨🎨","👩🎨","👨🔧","👩🔧","👨🚀","👩🚀","👨⚖️","👩⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️🌈","🎟️","🎫"],$l=oe.Root,Dl=oe.Trigger,Ml=r.forwardRef(({className:e,align:n="center",sideOffset:i=4,...a},s)=>{const{container:o}=r.useContext(Jo);return t(oe.Portal,{container:o,children:t(oe.Content,{ref:s,align:n,sideOffset:i,className:ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...a})})});Ml.displayName=oe.Content.displayName;const jl=r.forwardRef(({className:e,...n},r)=>t(te.Root,{ref:r,className:ce("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...n}));jl.displayName=te.Root.displayName;const ql=r.forwardRef(({className:e,...n},r)=>t(te.Image,{ref:r,className:ce("aspect-square h-full w-full",e),...n}));ql.displayName=te.Image.displayName;const Bl=r.forwardRef(({className:e,...n},r)=>t(te.Fallback,{ref:r,className:ce("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...n}));function Vl(e,t){const{response:n}=qs(),{settings:r}=ks(),i=t?.settingsMaxUsers??r?.workspace?.maxWorkspaceUsers;return s(()=>{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 r=(e.users?.length??0)+(t?.pendingInvitations??0),a=n?.planVersion,s=n?.subscription,o=e.billingCurrency||"usd",c=jn({planVersion:a,currency:o,settingsMaxUsers:i}),{maxUsers:l,hasSeatPricing:d,includedSeats:u}=c,p=d?Math.max(0,r-u):0,h=l>0?Math.max(0,l-r):1/0,m=l>0&&r>=l,g=l>0&&r>=.8*l&&!m,f=d&&a?Ln(a,o,s?.billingInterval??"monthly"):null,y=qn({memberCount:r,maxUsersConfig:c});return{hasSeatPricing:d,memberCount:r,includedSeats:u,maxUsers:l,maxSeats:l,limitSource:c.source,billableSeats:p,availableSeats:h,isAtMax:m,isNearMax:g,perSeatPriceCents:f,currency:o,canInvite:y.canInvite,inviteBlockReason:y.blockReason,inviteBlockMessageKey:y.blockMessageKey,inviteBlockMessageValues:y.blockMessageValues}},[n,e,i,t?.pendingInvitations])}function zl(e){const{listInvitations:t,resendInvitation:n,revokeInvitation:r}=Mo(),{t:i}=Oi(),{begin:a,settle:o}=Fi(),[c,d]=h([]),[m,g]=h(Boolean(e)),[f,y]=h(null),[w,v]=h(null),b=l(i);u(()=>{b.current=i},[i]);const k=p(async()=>{if(!e)return d([]),void g(!1);const n=a();g(!0),y(null);try{const r=await t(e);if(n.signal.aborted)return;d(pr(r))}catch(e){if(n.signal.aborted)return;ve(e,{component:"useWorkspaceInvitations",action:"list"}),y(be(e,"users.invitations.loadFailed",b.current))}finally{o(n)&&g(!1)}},[e,t,a,o]);u(()=>{k()},[k]);const S=p(async t=>{if(!e)throw new Error("No workspace");v(t),y(null);try{const r=await n(e,t);return d(e=>pr(e.map(e=>e._id===t?{...e,...r}:e))),r}catch(e){throw ve(e,{component:"useWorkspaceInvitations",action:"resend"}),y(be(e,"users.invitations.resendFailed",b.current)),e}finally{v(null)}},[e,n]),I=p(async t=>{if(!e)throw new Error("No workspace");v(t),y(null);try{await r(e,t),d(e=>e.filter(e=>e._id!==t))}catch(e){throw ve(e,{component:"useWorkspaceInvitations",action:"revoke"}),y(be(e,"users.invitations.revokeFailed",b.current)),e}finally{v(null)}},[e,r]),x=s(()=>c.filter(e=>hr(e)).length,[c]);return s(()=>({invitations:c,pendingCount:x,loading:m,error:f,busy:w,refresh:k,resend:S,revoke:I}),[c,x,m,f,w,k,S,I])}function Gl(e){return e?.workspace}function Jl(e){return!1!==Gl(e)?.canInviteMembers}function Hl(e){return 1!==Gl(e)?.maxWorkspacesPerUser}function Kl({title:n,children:r,className:i}){return e("div",{className:ce("px-2 flex flex-col gap-1",i),children:[t("div",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wide px-2 pb-1 shrink-0 whitespace-nowrap",children:n}),r]})}function Yl({icon:n,label:r,active:i=!1,onClick:a,className:s}){return e("button",{className:ce("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",i?"bg-primary/10 text-primary font-medium":"hover:bg-muted hover:text-foreground",s),onClick:a,"aria-current":i?"true":void 0,children:[n,t("span",{className:"min-w-0 truncate",children:r}),t(R,{"aria-hidden":"true",className:"h-4 w-4 ms-auto opacity-40 sm:hidden rtl:rotate-180"})]})}Bl.displayName=te.Fallback.displayName;const Ql=g(()=>import("./SettingsDialog-DuqMmX00.mjs").then(e=>({default:e.default})));const Zl=({children:r})=>{const{currentWorkspace:i,switchToWorkspace:a,workspaces:s}=Mo(),[o,c]=h(!1),[d,p]=h(Ro.Profile),g=l(!1);return u(()=>{const e=Fo.getState();c(e.open),p(e.section);return Fo.subscribe(e=>{c(e.open),p(e.section)})},[]),u(()=>{if(g.current)return;if(!i)return;const e=$t();if(!e)return;const t=function(e){if(e.screen&&Wo.has(e.screen))return e.screen;switch(e.action){case Tt.Checkout:case Tt.Billing:case Tt.SelectPlan:return Ro.Subscription;case Tt.CreditPurchase:return Ro.Credits;case Tt.OpenConnectGuide:return Ro.ConnectedAgents;default:return null}}(e);if(!t)return g.current=!0,void Dt();const n=e.ws;if(n&&n!==i._id){const e=s.find(e=>e._id===n);return e?void a(e).catch(e=>{we(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:n}}),g.current=!0,Dt()}):(g.current=!0,void Dt())}g.current=!0,Fo.openWorkspaceSettings(t,e),Dt()},[i,s,a]),e(n,{children:[r,t(Ec,{}),i&&o&&t(Pr,{fallback:null,children:t(m,{fallback:null,children:t(Ql,{workspace:i,open:o,onOpenChange:e=>{e||Fo.closeSettings()},section:d,onSectionChange:e=>{Fo.setSection(e)},showTrigger:!1})})})]})},Xl=(e,t,n)=>{if(t!==gt.V1)throw new Error(`Invalid version: "${t}". Only "${gt.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(!n||"string"!=typeof n)throw new Error("orgId is required and must be a string");if(!/^[0-9a-fA-F]{24}$/.test(n))throw new Error(`Invalid orgId: "${n}". Must be a valid MongoDB ObjectId (24 hexadecimal characters).`)},ed=i.memo(({serverUrl:e,version:n,orgId:r,region:a,auth:s,locale:o,defaultPermissions:c,getCheckoutStripeParams:l,loadingComponent:d,ui:p,mcp:h,tracking:m,children:g})=>{Xl(e,n,r);const f=i.useMemo(()=>({serverUrl:e,version:n,orgId:r,...void 0!==a&&{region:a}}),[e,n,r,a]),y=i.useMemo(()=>s?.callbacks,[s?.callbacks?.handleAuthentication,s?.callbacks?.onSignOut,s?.callbacks?.getSession,s?.callbacks?.onSessionExpired,s?.callbacks?.handleEvent,s?.callbacks?.onWorkspaceChange]),w=s?.callbacks?.handleEvent;return u(()=>(vt.setCallbacks(w?{handleEvent:w}:null),()=>{vt.setCallbacks(null)}),[w]),t(Ni,{locale:o,messageOverrides:p?.messages,children:t(yi,{children:t(no,{loadingComponent:d,children:t(zo,{callbacks:y,children:t(Ho,{children:t(Go,{config:f,auth:s,children:t(Do,{children:t(vi,{getCheckoutStripeParams:l,children:t(uo,{appPermissions:c,children:t(yo,{ui:p,children:t(oo,{mcp:h,children:t(uc,{children:t(js,{children:t(mo,{children:t(Qs,{children:t(Qo,{children:m&&s?.clientId?t(ms,{serverUrl:e,orgId:r,clientId:s.clientId,...m,children:t(Zl,{children:t(lc,{children:g})})}):t(Zl,{children:g})})})})})})})})})})})})})})})})})});ed.displayName="SaaSOSProviderInner";const td=({children:e,...n})=>t(Pr,{errorTitle:n.ui?.errorBoundary?.title,retryLabel:n.ui?.errorBoundary?.retryLabel,children:t(ed,{...n,children:e})});td.displayName="SaaSOSProvider";const nd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{status:i}=Vo();return dr(i).isLoading?n??null:i!==lr.authenticated?r??null:t},rd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{status:i}=Vo();return dr(i).isLoading?n??null:i!==lr.unauthenticated?r??null:t};nd.displayName="WhenAuthenticated",rd.displayName="WhenUnauthenticated";function id(){const{isAuthenticated:e}=Vo(),{orgId:t}=ws(),{settings:n}=ks(),r=Jl(n),{myInvitations:i,acceptInvitation:a,declineInvitation:c}=Mo(),{t:d}=Oi(),m=s(()=>Oo(t??""),[t]),g=o(m.subscribe,m.getSnapshot,m.getSnapshot),[f,y]=h(null),w=l(d);u(()=>{w.current=d},[d]);const v=p(e=>m.load(i,{maxAgeMs:e,onError:e=>(ve(e,{component:"useMyInvitations",action:"list"}),be(e,"invitations.loadFailed",w.current))}),[m,i]),b=p(()=>v(0),[v]);u(()=>{e&&r?v(15e3).catch(()=>{}):m.reset()},[e,r,m,v]);const k=p(async(e,t)=>{y(e),m.setError(null);try{const{workspace:n}=await a(e,t);return m.remove(e),n}catch(e){throw ve(e,{component:"useMyInvitations",action:"accept"}),m.setError(be(e,"invitations.acceptFailed",w.current)),e}finally{y(null)}},[m,a]),S=p(async e=>{y(e),m.setError(null);try{await c(e),m.remove(e)}catch(e){throw ve(e,{component:"useMyInvitations",action:"decline"}),m.setError(be(e,"invitations.declineFailed",w.current)),e}finally{y(null)}},[m,c]);return s(()=>({invitations:g.rows,loading:g.loading,error:g.error,busy:f,refresh:b,accept:k,decline:S}),[g,f,b,k,S])}function ad({className:r,title:i,description:a,emptyLabel:s,hideWhenEmpty:o=!1,switchOnAccept:c=!0,onAccepted:l}){const{t:d,formattingLocale:u}=Oi(),{formats:p}=wo(),{invitations:h,loading:m,error:g,busy:f,accept:y,decline:w}=id(),{switchToWorkspace:v}=Mo(),b=void 0===i?d("invitations.title"):i,k=void 0===a?d("invitations.listDescription"):a,S=s??d("invitations.empty");return m||0!==h.length||!o||g?t("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e("div",{className:ce("space-y-4",r),children:[t(Mc,{title:b,description:k}),g&&t(xc,{variant:"error",message:g}),m?e("div",{className:"space-y-2",children:[t(jc,{className:"h-16 w-full"}),t(jc,{className:"h-16 w-full"})]}):0===h.length?t(Dc,{icon:t(W,{className:"h-5 w-5 text-muted-foreground"}),description:S}):t("ul",{className:"space-y-2",children:h.map(r=>{const i=wr(r),a=f===r._id;return t("li",{className:"rounded-md border bg-card p-3 text-card-foreground",children:e("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e("div",{className:"min-w-0",children:[t("div",{className:"truncate text-sm font-medium",children:fr(r)}),e("div",{className:"text-xs text-muted-foreground",children:[d("invitations.invitedAs",{inviter:i??d("users.invitations.formerMember"),role:r.role}),r.validTill&&e(n,{children:[" · ",d("users.invitations.expiresAt",{date:(s=r.validTill,s?Rc(s,u,p?.date??{dateStyle:"medium"}):"")})]})]})]}),e("div",{className:"flex shrink-0 items-center gap-2",children:[t(hc,{variant:"outline",size:"sm",disabled:a,onClick:()=>w(r._id).catch(()=>{}),children:d("invitations.decline")}),t(hc,{size:"sm",progress:a,onClick:()=>(async e=>{let t;try{t=await y(e)}catch{return}t&&(l?.(t),c&&await v(t))})(r._id),children:d("invitations.accept")})]})]})},r._id);var s})})]})}):null}const sd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{invitations:i,loading:a}=id();return a?n??null:0===i.length?r??null:t},od="https://www.buildbase.app",cd={"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}}},ld={"built-with":"Built with BuildBase","powered-by":"Powered by BuildBase",mark:"BuildBase"};function dd(e,t){return`${od}/badge/v1/${e}.svg?theme=${t}`}function ud(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 pd(e,{refCode:t,params:n}={}){const r=new URLSearchParams({utm_source:"badge",utm_medium:e}),i=ud(t);i&&r.set("ref",i);for(const[e,t]of Object.entries(n??{}))e&&null!=t&&r.set(e,String(t));return`${od}/?${r.toString()}`}const hd=({variant:e="built-with",theme:n="auto",size:r="md",alt:i,className:a,link:s=!0,refCode:o,params:c})=>{const l=cd[e][r],d=t("img",{src:dd(e,n),alt:i??ld[e],width:l.width,height:l.height,loading:"lazy",decoding:"async"});return s?t("a",{href:pd(e,{refCode:o,params:c}),target:"_blank",rel:"noopener",className:ce("inline-block",a),children:d}):t("span",{className:a,children:d})},md=e=>{const{children:t,fallback:n,roles:r}=e,{user:i}=Vo();return r.includes(i?.role??"")?t:n||null},gd=e=>{const{children:t,fallback:n,roles:r}=e,{user:i}=Vo(),{currentWorkspace:a}=Mo(),s=a?.users.find(e=>e._id===i?.id);return s&&r.includes(s?.role??"")?t:n||null};md.displayName="WhenRoles",gd.displayName="WhenWorkspaceRoles";const fd=e=>{const{children:t,fallback:n,permission:r}=e,{can:i}=Ac();return i(r)?t:n??null};function yd(){const e=ws();return s(()=>new He(e),[e.serverUrl,e.version])}fd.displayName="WhenPermission";const wd=async(e,t)=>{const{io:n}=await import("socket.io-client");return n(e,t)};let vd=null;function bd(e){e.timer&&clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null;for(const t of e.listeners)try{t()}catch{}},500)}function kd(e){e.closed=!0,e.timer&&clearTimeout(e.timer),e.socket?.disconnect(),e.socket=null}function Sd(e,t,n,r=wd){const i=`${e}|${t}`;if(vd&&vd.key!==i&&(kd(vd),vd=null),!vd){const n={key:i,listeners:new Set,socket:null,closed:!1,timer:null};vd=n,Promise.resolve(r(`${e.replace(/\/$/,"")}/inbox`,{auth:{sessionId:t},transports:["websocket"],reconnectionDelay:2e3,reconnectionDelayMax:6e4})).then(e=>{n.closed?e.disconnect():(n.socket=e,e.on("notifications:changed",()=>bd(n)),e.on("connect",()=>bd(n)))}).catch(()=>{})}const a=vd;a.listeners.add(n);let s=!1;return()=>{s||(s=!0,a.listeners.delete(n),0===a.listeners.size&&(kd(a),vd===a&&(vd=null)))}}const Id={items:[],counts:{unread:0,unseen:0},loading:!1,loadingMore:!1,error:null,hasNextPage:!1,page:0,fetchedAt:0},xd=e=>!e.readAt,Cd=e=>!e.readAt&&!e.seenAt;function Nd(e,t){const n=new Map(e.map(e=>[e.id,e]));for(const e of t)n.set(e.id,e);return[...n.values()].sort((e,t)=>new Date(t.createdAt??0).getTime()-new Date(e.createdAt??0).getTime())}class Pd{constructor(){this.snapshot=Id,this.listeners=new Set,this.inFlight=null,this.moreInFlight=null,this.generation=0,this.pollers=0,this.pollTimer=null,this.pollTick=null,this.getSnapshot=()=>this.snapshot,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e))}set(e){this.snapshot={...this.snapshot,...e};for(const e of this.listeners)e()}load(e,t,n){if(this.inFlight)return this.inFlight;const r=n.maxAgeMs??0;if(r>0&&this.snapshot.fetchedAt&&Date.now()-this.snapshot.fetchedAt<r)return Promise.resolve();const i=this.generation;return this.set({loading:0===this.snapshot.fetchedAt,error:null}),this.inFlight=Promise.all([e(1),t()]).then(([e,t])=>{if(i!==this.generation)return;const n=this.snapshot.page<=1;this.set({items:n?e.notifications:Nd(this.snapshot.items,e.notifications),counts:t,hasNextPage:n?e.hasNextPage:this.snapshot.hasNextPage,page:Math.max(this.snapshot.page,1),fetchedAt:Date.now()})}).catch(e=>{i===this.generation&&this.set({error:n.onError(e)})}).finally(()=>{this.inFlight=null,i===this.generation&&this.set({loading:!1})}),this.inFlight}loadMore(e,t){if(this.moreInFlight)return this.moreInFlight;if(!this.snapshot.hasNextPage)return Promise.resolve();const n=this.generation,r=this.snapshot.page+1;return this.set({loadingMore:!0,error:null}),this.moreInFlight=e(r).then(e=>{n===this.generation&&this.set({items:Nd(this.snapshot.items,e.notifications),hasNextPage:e.hasNextPage,page:r})}).catch(e=>{n===this.generation&&this.set({error:t.onError(e)})}).finally(()=>{this.moreInFlight=null,n===this.generation&&this.set({loadingMore:!1})}),this.moreInFlight}async poll(e,t,n){if(this.inFlight)return;const r=this.generation;try{const i=await t();if(r!==this.generation)return;const a=this.snapshot.counts;if(i.unread===a.unread&&i.unseen===a.unseen)return;this.set({counts:i}),await this.load(e,t,{onError:n})}catch{}}retainPoll(e,t){this.pollers++,this.pollTick=t,!this.pollTimer&&e>0&&(this.pollTimer=setInterval(()=>this.pollTick?.(),e));let n=!1;return()=>{n||(n=!0,this.pollers--,this.pollers<=0&&this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null,this.pollTick=null))}}replace(e){const t=this.snapshot.items.find(t=>t.id===e.id);this.set({items:this.snapshot.items.map(t=>t.id===e.id?e:t),counts:t?this.adjustCounts(t,e):this.snapshot.counts})}optimistic(e,t){const n=this.snapshot.items.find(t=>t.id===e);if(!n)return()=>{};const r=this.snapshot.counts;return this.replace({...n,...t}),()=>{this.set({items:this.snapshot.items.map(t=>t.id===e?n:t),counts:r})}}remove(e){const t=this.snapshot.items.findIndex(t=>t.id===e);if(-1===t)return()=>{};const n=this.snapshot.items[t],r=this.snapshot.counts;return this.set({items:this.snapshot.items.filter(t=>t.id!==e),counts:{unread:Math.max(0,r.unread-(xd(n)?1:0)),unseen:Math.max(0,r.unseen-(Cd(n)?1:0))}}),()=>{const e=[...this.snapshot.items];e.splice(Math.min(t,e.length),0,n),this.set({items:e,counts:r})}}markAll(e,t=(new Date).toISOString()){const{items:n,counts:r}=this.snapshot;return this.set({items:n.map(n=>"readAt"===e?n.readAt?n:{...n,readAt:t,readVia:"inbox",seenAt:n.seenAt??t}:n.seenAt?n:{...n,seenAt:t}),counts:"readAt"===e?{unread:0,unseen:0}:{...r,unseen:0}}),()=>this.set({items:n,counts:r})}setError(e){this.set({error:e})}reset(){this.generation++,this.inFlight=null,this.moreInFlight=null,this.snapshot=Id;for(const e of this.listeners)e()}adjustCounts(e,t){const{unread:n,unseen:r}=this.snapshot.counts;return{unread:Math.max(0,n+(xd(t)?1:0)-(xd(e)?1:0)),unseen:Math.max(0,r+(Cd(t)?1:0)-(Cd(e)?1:0))}}}const _d=new Map;const Ed=()=>"undefined"==typeof document||"hidden"!==document.visibilityState;function Ad(e={}){const{isAuthenticated:t}=Vo(),{orgId:n,serverUrl:r}=ws(),{currentWorkspace:i}=Mo(),a=yd(),{t:c}=Oi(),d="current"===e.workspaceId?i?._id:e.workspaceId,h="current"===e.workspaceId&&!i?._id,m=Math.max(1,Math.min(e.pageSize??20,100)),g=e.pollIntervalMs??6e4,f=e.live??!0,y=h?"__waiting_for_workspace__":d,w=s(()=>function(e,t){const n=`${e||"unscoped"}|${t??"*"}`;let r=_d.get(n);return r||(r=new Pd,_d.set(n,r)),r}(n??"",y),[n,y]),v=o(w.subscribe,w.getSnapshot,w.getSnapshot),b=l(c);u(()=>{b.current=c},[c]);const k=p(e=>t=>(ve(t,{component:"useNotifications",action:e}),be(t,"notifications.inbox.loadFailed",b.current)),[]),S=p(e=>a.list({workspaceId:d,page:e,limit:m}),[a,d,m]),I=p(()=>a.counts(d),[a,d]),x=p(e=>w.load(S,I,{maxAgeMs:e,onError:k("list")}),[w,S,I,k]),C=p(()=>x(0),[x]);u(()=>{t?h||x(15e3).catch(()=>{}):w.reset()},[t,h,w,x]),u(()=>{if(!t||h||g<=0)return;const e=()=>{Ed()&&w.poll(S,I,k("poll"))},n=w.retainPoll(g,e),r=()=>{Ed()&&e()};return"undefined"!=typeof document&&document.addEventListener("visibilitychange",r),()=>{n(),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",r)}},[t,h,g,w,S,I,k]),u(()=>{if(!t||h||!f||!r)return;const e=Te();return e?Sd(r,e,()=>{x(0).catch(()=>{})}):void 0},[t,h,f,r,x]);const N=p(async(e,t,n)=>{const r=t();w.setError(null);try{const e=await n();e&&"object"==typeof e&&"id"in e&&w.replace(e)}catch(t){throw r(),ve(t,{component:"useNotifications",action:e}),w.setError(be(t,"notifications.inbox.updateFailed",b.current)),t}},[w]),P=p(async e=>{const t=w.getSnapshot().items.find(t=>t.id===e);if(t?.readAt)return;const n=(new Date).toISOString();await N("read",()=>w.optimistic(e,{readAt:n,readVia:"inbox",seenAt:t?.seenAt??n}),()=>a.markRead(e))},[N,a,w]),_=p(e=>N("unread",()=>w.optimistic(e,{readAt:null,readVia:null}),()=>a.markUnread(e)),[N,a,w]),E=p(e=>N("archive",()=>w.remove(e),async()=>{await a.archive(e)}),[N,a,w]),A=p(()=>N("read-all",()=>w.markAll("readAt"),()=>a.markAllRead(d)),[N,a,w,d]),U=p(async()=>{0!==w.getSnapshot().counts.unseen&&await N("seen",()=>w.markAll("seenAt"),()=>a.markSeen(d)).catch(()=>{})},[N,a,w,d]),T=p(()=>w.loadMore(S,{onError:k("load-more")}),[w,S,k]),O=s(()=>v.items.filter(e=>!e.readAt),[v.items]);return s(()=>({notifications:v.items,unread:O,counts:v.counts,loading:v.loading||t&&h,loadingMore:v.loadingMore,hasMore:v.hasNextPage,error:v.error,refresh:C,loadMore:T,markRead:P,markUnread:_,archive:E,markAllRead:A,markSeen:U}),[v,t,h,O,C,T,P,_,E,A,U])}function Ud({className:n,title:r,description:i,showFilter:a=!0,onSelect:s,emptyLabel:o,markSeenOnView:c=!0,compact:l=!1,...d}){const{t:p,formattingLocale:m}=Oi(),{notifications:g,unread:f,counts:y,loading:w,loadingMore:v,hasMore:b,error:k,loadMore:S,markRead:x,markUnread:C,archive:N,markAllRead:P,markSeen:_}=Ad(d),[A,U]=h("all");u(()=>{c&&!w&&y.unseen>0&&_()},[c,w,y.unseen,_]);const T=void 0===r?p("notifications.inbox.title"):r,O=void 0===i?p("notifications.inbox.description"):i,R="unread"===A?f:g,D=o??p("unread"===A?"notifications.inbox.emptyUnread":"notifications.inbox.empty"),M=e=>{x(e.id).catch(()=>{}),s?s(e):function(e){if(e.link&&"undefined"!=typeof window)try{const t=new URL(e.link,window.location.href);"http:"!==t.protocol&&"https:"!==t.protocol||window.location.assign(t.href)}catch{}}(e)};return t("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e("div",{className:ce(l?"space-y-3":"space-y-4",n),children:[t(Mc,{title:T,description:O}),e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[a?t("div",{role:"group",className:"inline-flex rounded-md border p-0.5 text-xs",children:["all","unread"].map(t=>e("button",{type:"button","aria-pressed":A===t,onClick:()=>U(t),className:ce("rounded px-2.5 py-1 font-medium transition-colors",A===t?"bg-secondary text-secondary-foreground":"text-muted-foreground hover:text-foreground"),children:[p("all"===t?"notifications.inbox.filterAll":"notifications.inbox.filterUnread"),"unread"===t&&y.unread>0&&e("span",{className:"ms-1 tabular-nums",children:["(",y.unread,")"]})]},t))}):t("span",{}),t(hc,{variant:"ghost",size:"sm",disabled:0===y.unread,startIcon:t(I,{}),onClick:()=>P().catch(()=>{}),children:p("notifications.inbox.markAllRead")})]}),k&&t(xc,{variant:"error",message:k}),w?e("div",{className:"space-y-2",children:[t(jc,{className:"h-14 w-full"}),t(jc,{className:"h-14 w-full"}),t(jc,{className:"h-14 w-full"})]}):0===R.length?t(Dc,{icon:t(F,{className:"h-5 w-5 text-muted-foreground"}),description:D}):t("ul",{className:"divide-y rounded-md border bg-card text-card-foreground",children:R.map(n=>{const r=!n.readAt,i=function(e,t){const n=[],{email:r,push:i}=e.channels;if("none"!==r.status&&"skipped"!==r.status){const e="failed"===r.status?t("notifications.inbox.notDelivered"):r.clickedAt?t("notifications.inbox.clicked"):r.openedAt?t("notifications.inbox.opened"):null;n.push({key:"email",icon:"email",text:[t("notifications.inbox.channelEmail"),e].filter(Boolean).join(" · ")})}if("none"!==i.status&&"skipped"!==i.status){const e="failed"===i.status?t("notifications.inbox.notDelivered"):i.clickedAt?t("notifications.inbox.clicked"):null;n.push({key:"push",icon:"push",text:[t("notifications.inbox.channelPush"),e].filter(Boolean).join(" · ")})}return n}(n,p);return e("li",{className:"group relative flex gap-3 p-3",children:[t("span",{"aria-hidden":"true",className:ce("mt-1.5 h-2 w-2 shrink-0 rounded-full",r?"bg-primary":"bg-transparent")}),e("button",{type:"button",onClick:()=>M(n),className:"min-w-0 flex-1 text-start outline-none focus-visible:underline",children:[e("div",{className:"flex items-baseline justify-between gap-2",children:[t("span",{className:ce("truncate text-sm",r?"font-semibold":"font-medium text-muted-foreground"),children:n.title}),n.createdAt&&t("time",{dateTime:n.createdAt,className:"shrink-0 text-xs text-muted-foreground tabular-nums",children:$c(n.createdAt,m)})]}),n.body&&t("p",{className:ce("mt-0.5 text-sm text-muted-foreground",l?"line-clamp-2":"line-clamp-3"),children:n.body}),i.length>0&&t("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:i.map(n=>e("span",{className:"inline-flex items-center gap-1",children:["email"===n.icon?t(L,{className:"h-3 w-3","aria-hidden":"true"}):t(E,{className:"h-3 w-3","aria-hidden":"true"}),n.text]},n.key))})]}),e("div",{className:"flex shrink-0 items-start gap-0.5 opacity-100 sm:opacity-0 sm:transition-opacity sm:group-focus-within:opacity-100 sm:group-hover:opacity-100",children:[t(hc,{variant:"ghost",size:"icon",className:"h-7 w-7 sm:h-7 sm:w-7",title:p(r?"notifications.inbox.markRead":"notifications.inbox.markUnread"),"aria-label":p(r?"notifications.inbox.markRead":"notifications.inbox.markUnread"),onClick:()=>(r?x(n.id):C(n.id)).catch(()=>{}),children:t(r?W:L,{className:"h-4 w-4"})}),t(hc,{variant:"ghost",size:"icon",className:"h-7 w-7 sm:h-7 sm:w-7",title:p("notifications.inbox.archive"),"aria-label":p("notifications.inbox.archive"),onClick:()=>N(n.id).catch(()=>{}),children:t($,{className:"h-4 w-4"})})]})]},n.id)})}),b&&!w&&t(hc,{variant:"outline",size:"sm",fullWidth:!0,progress:v,onClick:()=>S().catch(()=>{}),children:p("notifications.inbox.loadMore")})]})})}function Td({className:n,align:r="end",inboxProps:i,maxCount:a=99,...s}){const{t:o}=Oi(),{counts:c}=Ad(s),[l,d]=h(!1),u=c.unread,p=u>a?`${a}+`:String(u),m=u>0?o("notifications.inbox.bellUnread",{count:u}):o("notifications.inbox.bellLabel");return t("div",{className:"saas-os-ui",style:{backgroundColor:"transparent",display:"inline-flex"},children:e($l,{open:l,onOpenChange:d,children:[t(Dl,{asChild:!0,children:e(hc,{variant:"ghost",size:"icon","aria-label":m,title:m,className:ce("relative",n),children:[t(T,{className:"h-5 w-5"}),u>0&&t("span",{"aria-hidden":"true",className:ce("absolute -end-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-semibold leading-none tabular-nums",c.unseen>0?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:p})]})}),t(Ml,{align:r,className:"w-[min(24rem,calc(100vw-2rem))] max-h-[min(32rem,calc(100vh-6rem))] overflow-y-auto p-3",children:l&&t(Ud,{description:null,...i,...s,compact:!0})})]})})}function Od(){const e=d(dc);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return s(()=>({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 Rd(){const e=d(dc);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return s(()=>({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])}const Wd=e=>{const{children:t,slug:n}=e,{currentWorkspace:r}=Mo(),i=r?.features?.[n];return i?t:null},Fd=e=>{const{children:t,slug:n}=e,{currentWorkspace:r}=Mo(),i=r?.features?.[n];return _o(!!r&&!i,`workspace:${n}`,"feature_gate_shown",{feature:n,scope:"workspace"}),i?null:t},Ld=e=>{const{children:t,slug:n}=e,{isFeatureEnabled:r}=Rd();return r(n)?t:null},$d=e=>{const{children:t,slug:n}=e,{isFeatureEnabled:r,loading:i}=Rd(),a=r(n);return _o(!i&&!a,`user:${n}`,"feature_gate_shown",{feature:n,scope:"user"}),a?null:t};Wd.displayName="WhenWorkspaceFeatureEnabled",Fd.displayName="WhenWorkspaceFeatureDisabled",Ld.displayName="WhenUserFeatureEnabled",$d.displayName="WhenUserFeatureDisabled";const Dd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:i,loading:a}=qs();return a?n??null:i?.subscription?t:r??null},Md=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:i,loading:a}=qs();return a?n??null:i?.subscription?r??null:t},jd=e=>{const{children:t,plans:n,loadingComponent:r,fallbackComponent:i}=e,{response:a,loading:s}=qs(),o=a?.subscription?a.plan??a.subscription?.plan:void 0,c=n.map(e=>e.trim().toLowerCase()),l=(o?.slug??"").toLowerCase(),d=!!o&&c.includes(l),{currentWorkspace:u}=Mo();return _o(!!u&&!s&&!d&&null!=i,c.join(","),"plan_gate_shown",{required_plans:c.join(","),current_plan:l||"none"}),s?r??null:d?t:i??null},qd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:i,loading:a}=qs();return a?n??null:"trialing"!==i?.subscription?.subscriptionStatus?r??null:t},Bd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:i,loading:a}=qs();return a?n??null:i?.subscription?.subscriptionStatus===kn.Trialing?r??null:t},Vd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{behavior:i}=wo(),a=e.daysThreshold??i?.trialEndingDays??3,{response:s,loading:o}=qs();if(o)return n??null;const c=s?.subscription;if(!c||"trialing"!==c.subscriptionStatus)return r??null;const l=c.trialEnd||c.stripeCurrentPeriodEnd;if(!l)return r??null;const d=new Date(l);if(isNaN(d.getTime()))return r??null;return Math.max(0,Math.ceil((d.getTime()-Date.now())/864e5))>a?r??null:t};Dd.displayName="WhenSubscription",Md.displayName="WhenNoSubscription",jd.displayName="WhenSubscriptionToPlans",qd.displayName="WhenTrialing",Bd.displayName="WhenNotTrialing",Vd.displayName="WhenTrialEnding";const zd=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:i}=e,{quotas:a,loading:s}=go(),o=s?void 0:a?.[t];return _o(!!o&&o.available<=0&&null!=i,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),s?r??null:o?o.available<=0?i??null:n:i??null},Gd=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:i}=e,{quotas:a,loading:s}=go(),o=s?void 0:a?.[t];return _o(!!o&&o.available<=0,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),s?r??null:o?o.available>0?i??null:n:i??null},Jd=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:i}=e,{quotas:a,loading:s}=go();if(s)return r??null;const o=a?.[t];return o&&o.hasOverage&&!1!==o.allowOverage?n:i??null},Hd=e=>{const{slug:t,threshold:n,children:r,loadingComponent:i,fallbackComponent:a}=e,{quotas:s,loading:o}=go(),c=o?void 0:s?.[t],l=c?c.included>0?c.consumed/c.included*100:c.consumed>0?100:0:0;return _o(!!c&&l>=n,`${t}@${n}`,"quota_threshold_reached",{quota:t,threshold:n,percent_used:Math.round(l)}),o?i??null:c?l<n?a??null:r:a??null};zd.displayName="WhenQuotaAvailable",Gd.displayName="WhenQuotaExhausted",Jd.displayName="WhenQuotaOverage",Hd.displayName="WhenQuotaThreshold";const Kd=({children:e})=>{const{currentWorkspace:t}=Mo(),n=t?._id,{balance:r,loading:i,error:a,refetch:s}=Zs(),{packages:o,loading:c}=Gs(n),{consumeCredits:l,loading:d,error:u}=Vs(n),{purchaseCredits:p,loading:h,error:m}=zs(n);return e({balance:r,loading:i,packages:o,packagesLoading:c,consume:l,consuming:d,purchase:async e=>{if(!n)throw new Error("No workspace selected");const{successUrl:t,cancelUrl:r}=Lt(n),i=await p({creditPackageId:e._id,successUrl:t,cancelUrl:r});i.url&&Vt(i.url)},purchasing:h,refetch:s,error:u||m||a})};Kd.displayName="CreditActionsProvider";const Yd=({children:e})=>{const{balance:t,loading:n,error:r,refetch:i}=Zs();return e({balance:t,loading:n,error:r,refetch:i})};function Qd({children:r,loadingFallback:i,errorFallback:a,redirectBaseUrl:s}){const{packages:o,notes:c,loading:l,error:d,refetch:u}=Ks(),{isAuthenticated:h,signIn:m}=Vo(),g=p(e=>{if(h)Fo.openWorkspaceSettings(Ro.Credits,{action:Tt.CreditPurchase,packageId:e});else if(s){const t=Wt({action:Tt.CreditPurchase,screen:"credits",packageId:e},s);m(t)}else m()},[h,m,s]);return l?void 0!==i?t(n,{children:i}):e("div",{className:"space-y-4",children:[t(jc,{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(jc,{className:"h-48 rounded-lg"},e))})]}):d?a?t(n,{children:a(d)}):t("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:d}):t(n,{children:r({loading:l,error:d,packages:o,notes:c,refetch:u,selectPackage:g})})}Yd.displayName="CreditBalance";const Zd=e=>{const{min:t=1,children:n,loadingComponent:r,fallbackComponent:i}=e,{balance:a,loading:s}=Zs();return s?r??null:a?a.available<t?i??null:n:i??null},Xd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{balance:i,loading:a}=Zs();return a?n??null:i?i.available>0?r??null:t:r??null},eu=e=>{const{threshold:t,children:n,loadingComponent:r,fallbackComponent:i}=e,{balance:a,loading:s}=Zs();return s?r??null:a?a.available>t?i??null:n:i??null};function tu(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}function nu(){const{response:e}=qs();return s(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const n=tu(t.trialEnd)??tu(t.stripeCurrentPeriodEnd),r=tu(t.trialStart),i=n?Math.max(0,Math.ceil((n.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:i,trialEndsAt:n,trialStartedAt:r,isTrialEnding:i<=3}},[e])}Zd.displayName="WhenCreditsAvailable",Xd.displayName="WhenCreditsExhausted",eu.displayName="WhenCreditsLow";const ru=ee.object({name:ee.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:ee.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)")}),iu=({onSuccess:r,onError:i,className:a="w-full",fieldClassName:s="flex flex-col gap-1.5 w-full",autoFocus:o=!0,showSuccessMessage:c=!0,hideLogo:l=!1,hideTitles:d=!1})=>{const{t:m}=Oi(),[g,f]=h(!1),[y,w]=h(!1),{submitBetaForm:v,isLoading:b,isSubmitting:k,error:S,config:I,success:x,message:C}=(()=>{const{t:e}=Oi(),t=ws(),[n,r]=h(null),[i,a]=h(!0),[s,o]=h(!1),[c,l]=h(null),[d,m]=h(!1),[g,f]=h(null);return u(()=>{let n=!1;return(async()=>{a(!0),l(null);try{const e=new Be(t),i=await e.fetchConfig();n||r(i)}catch(t){n||l(t instanceof Error?t.message:e("beta.errorMessage"))}finally{n||a(!1)}})(),()=>{n=!0}},[t]),{isLoading:i,isSubmitting:s,config:n,error:c,success:d,message:g,submitBetaForm:p(async n=>{if(!t){const t=e("errors.generic");return l(t),{success:!1,message:t}}try{o(!0),l(null),m(!1),f(null);const e=new Be(t),r=await e.submitBetaUser({name:n.name||"",email:n.email}),i="success"===r.status;return m(i),f(r.message),{success:i,message:r.message}}catch(t){const n=t instanceof Error?t.message:e("beta.errorMessage");return l(n),m(!1),f(n),{success:!1,message:n}}finally{o(!1)}},[t])}})();u(()=>{x&&c&&(f(!0),w(!0)),S&&w(!0)},[x,c,S]);const N=Z({resolver:H(ru),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});u(()=>{o&&N.setFocus("name")},[o,N]);const P=N.formState.isValid&&!k;return t("div",{className:"saas-os-ui",style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:e("div",b?{className:ce("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(jc,{className:"h-24 w-24 rounded-lg"}),t(jc,{className:"h-6 w-32"}),e("div",{className:"w-full space-y-4",children:[e("div",{className:"space-y-2",children:[t(jc,{className:"h-4 w-16"}),t(jc,{className:"h-10 w-full"})]}),e("div",{className:"space-y-2",children:[t(jc,{className:"h-4 w-16"}),t(jc,{className:"h-10 w-full"})]}),t(jc,{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:[I?.logo&&t(su,{logo:I?.logo}),I?.name&&t("div",{children:I?.name})]}),t(Y,{...N,children:e("form",{onSubmit:N.handleSubmit(async e=>{try{const t=await v(e);t.success?(r?.(),N.reset(),c&&f(!0),w(!0)):(i?.(t.message),w(!0))}catch(e){i?.(e instanceof Error?e.message:m("beta.errorMessage")),w(!0)}}),className:a,noValidate:!0,"aria-busy":k,children:[!y&&e(n,{children:[!d&&I?.screen?.register&&t(au,{screen:I?.screen?.register}),t(kl,{control:N.control,name:"name",render:({field:n})=>e(xl,{className:s,children:[t(Cl,{children:m("beta.nameLabel")}),t(Nl,{children:t(pl,{...n})}),t(Pl,{}),t(_l,{})]})}),t(kl,{control:N.control,name:"email",render:({field:n})=>e(xl,{className:s,children:[t(Cl,{children:m("beta.emailLabel")}),t(Nl,{children:t(pl,{...n})}),t(Pl,{}),t(_l,{})]})}),t(hc,{type:"submit",disabled:!P,className:s,children:m(k?"beta.submittingText":"beta.submitText")})]}),y&&S&&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":m("settings.common.error"),children:"❗"}),S]}),t("div",{className:"mt-4 flex justify-center",children:t(hc,{type:"button",onClick:()=>{w(!1),N.reset()},className:s,children:m("beta.tryAgain")})})]}),y&&g&&C&&t("div",{className:"flex flex-col items-center justify-center w-full text-success border-success/30 text-center",children:I?.screen?.thankYou&&t(au,{screen:I?.screen?.thankYou})})]})}),!y&&t("div",{children:e("div",{children:[m("beta.privacyConsent")," ",t("a",{href:I?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:m("beta.privacyPolicy")})," ",m("beta.and")," ",t("a",{href:I?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:m("beta.termsOfService")}),"."]})})]})})};function au({screen:n}){return e("div",{className:"flex flex-col items-center justify-center w-full",children:[t("p",{className:"text-2xl font-bold",children:n?.title}),t("p",{className:"text-sm text-muted-foreground",children:n?.description})]})}function su({logo:e}){const{t:n}=Oi();return t("img","string"==typeof e?{src:e,alt:n("beta.logoAlt"),className:"max-h-24"}:{src:e.bucket?.url,alt:n("beta.logoAlt"),className:"max-h-24"})}function ou({slug:r,children:i,loadingFallback:a,errorFallback:s,redirectBaseUrl:o}){const{items:c,plans:l,notes:d,loading:u,error:h,refetch:m}=Is(r),{isAuthenticated:g,signIn:f}=Vo(),{currentWorkspace:y,fetchWorkspaces:w}=Mo(),{emit:v}=Eo();_o(!u&&!h&&l.length>0,r,"pricing_viewed",{pricing_slug:r,plan_count:l.length,authenticated:g});const b=p((e,t,n)=>o?Wt({action:"selectPlan",plan:e,interval:t,currency:n},o):null,[o]),k=p((e,t,n)=>{if(v("pricing_plan_selected",{pricing_slug:r,plan_version_id:e,billing_interval:t,currency:n?n.toUpperCase():void 0,authenticated:g}),g)return Fo.openWorkspaceSettings(Ro.Subscription,{action:"selectPlan",plan:e,interval:t,currency:n}),void(y||w());const i=b(e,t,n);f(i??void 0)},[g,f,b,v,r,y,w]);return u?void 0!==a?t(n,{children:a}):e("div",{className:"space-y-4",children:[t(jc,{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(jc,{className:"h-64 rounded-lg"},e))})]}):h?s?t(n,{children:s(h)}):t("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:h}):t(n,{children:i({loading:u,error:h,items:c,plans:l,notes:d,refetch:m,selectPlan:k})})}const cu=r.forwardRef(({className:e,orientation:n="horizontal",decorative:r=!0,...i},a)=>t(ie.Root,{ref:a,decorative:r,orientation:n,className:ce("shrink-0 bg-border","horizontal"===n?"h-[1px] w-full":"h-full w-[1px]",e),...i}));cu.displayName=ie.Root.displayName;const lu=g(()=>import("./SettingsDialog-DuqMmX00.mjs").then(e=>({default:e.default})));function du({message:r}){return e(n,{children:[t(D,{className:"mx-auto h-12 w-12 text-muted-foreground"}),t("p",{className:"mt-2 text-sm text-muted-foreground",children:r})]})}function uu(r){const{t:i,dir:a}=Oi(),{isAuthenticated:s,user:o}=Vo(),c=ft(ws()),{workspaces:l,currentWorkspace:d,loading:p,refreshing:g,switchingToId:f,fetchWorkspaces:y,getFeatures:w,refreshWorkspaces:v,setCurrentWorkspace:b,switchToWorkspace:S}=Mo(),{settings:I,loading:x}=ks(),{visible:C}=Uc(),[N,P]=h(!1),[_,E]=h(0),[A,U]=h(""),T=p||g;u(()=>{s&&c&&(0===l.length?(y(),w()):w())},[s,c]),u(()=>{s&&c&&_>0&&v()},[_,s,c]);const O=l,R=O.filter(e=>e._id!==d?._id).filter(e=>e.name.toLowerCase().includes(A.toLowerCase())),W=(I?.workspace?.canCreateWorkspace??!0)&&C(e=>e.workspaceSwitcher?.createButton),F=(I?.workspace?.showSwitcher??!0)&&C(e=>e.workspaceSwitcher?.show),L=I?.workspace?.maxWorkspacesPerUser??0,$=O?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===o?.id?.toString()).length??0,q=!1!==W&&(0===L||$<L);u(()=>{!F&&l.length>0&&!d&&S(l[0]).catch(e=>{we(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[F,l,d]);const{emit:B}=Eo();return u(()=>{N&&F&&B("workspace_switcher_opened",{workspace_count:l.length})},[N]),x&&!I?t(n,{children:r.trigger?.(!0,d)}):!F&&d?e(n,{children:[t("div",{role:"button",tabIndex:0,"aria-label":i("settings.common.openSettings"),className:"cursor-pointer",onClick:()=>P(!0),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),P(!0))},children:r.trigger?.(T,d)}),t(m,{fallback:null,children:t(lu,{workspace:d,open:N,onOpenChange:P,showTrigger:!1})})]}):e(mc,{open:N,onOpenChange:P,children:[t(gc,{children:r.trigger?.(T,d)}),e(wc,{dir:a,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e(vc,{dir:a,children:[e(kc,{className:"flex items-center gap-2",children:[t(D,{className:"h-5 w-5"}),i("workspace.switchTitle")]}),t(Sc,{children:i("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:i("workspace.notLoggedIn")})}),o&&e("div",{dir:a,className:"flex flex-col gap-4",children:[d&&t(pu,{workspace:d,isCurrentWorkspace:!0,switchToWorkspace:S,switchingToId:f,setCurrentWorkspace:b,setOpen:P,workspacesToUse:O}),t(cu,{}),e("div",{children:[e("div",{className:"flex items-center justify-between",children:[t("div",{className:"text-sm font-medium text-muted-foreground",children:i("workspace.availableWorkspaces",{count:R.length})}),t("div",{children:t(hc,{progress:g,disabled:g,variant:"ghost",onClick:function(){s&&c&&E(e=>e+1)},startIcon:t(M,{}),children:i("settings.common.refreshAction",{loading:String(g)})})})]}),e("div",{className:"relative",children:[t(j,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),t(pl,{placeholder:i("workspace.searchPlaceholder"),value:A,onChange:e=>U(e.target.value),className:"ps-10"})]}),p?e("div",{className:"flex items-center justify-center py-8",children:[t(k,{className:"h-6 w-6 animate-spin text-muted-foreground"}),t("span",{className:"ms-2 text-sm text-muted-foreground",children:i("workspace.loadingWorkspaces")})]}):0===R.length?t("div",{className:"text-center py-8",children:A?t(du,{message:i("workspace.noWorkspacesFound")}):t(sd,{fallbackComponent:t(du,{message:i("workspace.noWorkspacesAvailable")}),children:t(ad,{title:null,description:null,className:"text-start"})})}):t(Ul,{className:"h-64",dir:a,children:t("div",{dir:a,className:"flex flex-col gap-2 my-2.5",children:R.map(e=>{const n=e._id===d?._id;return t(pu,{workspace:e,isCurrentWorkspace:n,switchToWorkspace:S,switchingToId:f,setCurrentWorkspace:b,setOpen:P,workspacesToUse:O},e._id)})})})]}),q&&e(n,{children:[t(cu,{}),t(hu,{onCreated:()=>{y()}})]})]})]})]})}function pu(n){const{t:r}=Oi(),{visible:i}=Uc(),a=i(e=>e.workspaceSwitcher?.memberCount),s=i(e=>e.workspaceSwitcher?.planBadge),{workspace:o,setCurrentWorkspace:c,setOpen:l,workspacesToUse:d,switchingToId:u}=n,p=n.isCurrentWorkspace??!1,h=u===o._id,g=o.subscription??null,f=null!=g&&"object"==typeof g?g.plan??null:null,y=f?.name??"";return e("div",{className:ce("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":p}),children:[e(jl,{className:"h-8 w-8 flex items-center justify-center",children:[t("div",{children:t(ql,{src:o.image&&o.image.trim()?o.image:void 0})}),t(Bl,{children:(w=o.name,w.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(q,{className:"h-3 w-3"}),t("span",{children:r("workspace.membersCount",{count:o.users?.length||0})})]}),s&&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(hc,{size:"sm",disabled:null!==u||h,progress:h,onClick:()=>{n.switchToWorkspace(o).then(()=>l(!1)).catch(e=>{we(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:o._id}})})},children:r("workspace.switchTo")}),t(m,{fallback:null,children:t(lu,{workspace:o,onClose:()=>{if(p){const e=d.findIndex(e=>e._id?.toString()===o._id?.toString());-1!==e&&c(d[e])}}})})]})]});var w}function hu(r){const{t:i,dir:a}=Oi(),{switching:s}=Mo(),[o,c]=h(!1),[l,d]=h("emoji"),[u,p]=h("🏢"),[m,g]=h(!1),{createWorkspace:f}=Mo(),y=ee.object({name:ee.string().min(2,{message:i("workspace.workspaceNameMinLength")}),image:ee.string().optional()}),w=Z({resolver:H(y),defaultValues:{name:"",image:""}});return e(mc,{open:o,onOpenChange:c,children:[t(gc,{asChild:!0,children:e(hc,{className:"w-full rounded-none",disabled:s,children:[t(P,{className:"h-4 w-4 me-2"}),i("workspace.createNew")]})}),e(wc,{dir:a,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e(vc,{children:[t(kc,{children:i("workspace.createTitle")}),t(Sc,{children:i("workspace.createDescription")})]}),t(vl,{...w,children:e("form",{onSubmit:w.handleSubmit(async function(e){let t="";if("emoji"===l)t=Fl(u);else if("url"===l&&e.image)try{new URL(e.image),t=e.image}catch{return void w.setError("image",{message:i("workspace.invalidUrl")})}g(!0);try{await f(e.name,t),c(!1),w.reset(),p("🏢"),d("emoji"),r?.onCreated?.()}catch(t){we(t,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{g(!1)}}),children:[t(kl,{control:w.control,name:"name",render:({field:n})=>e(xl,{children:[t(Cl,{children:i("workspace.workspaceName")}),t(Nl,{children:t(pl,{placeholder:i("workspace.workspaceNamePlaceholder"),...n})}),t(_l,{})]})}),e("div",{className:"flex flex-col gap-y-2 my-2",children:[e("div",{children:[t(wl,{className:"text-sm font-medium",children:i("workspace.workspaceIcon")}),t(Pl,{children:i("workspace.iconDescription")})]}),e(El,{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(Al,{value:"emoji",id:"emoji"}),e(wl,{htmlFor:"emoji",className:"flex items-center gap-2",children:[t(B,{className:"h-4 w-4"}),i("workspace.chooseEmoji")]})]}),e("div",{className:"flex items-center gap-x-2 my-1",children:[t(Al,{value:"url",id:"url"}),e(wl,{htmlFor:"url",className:"flex items-center gap-2",children:[t(V,{className:"h-4 w-4"}),i("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:i("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(Ul,{className:"h-32 w-full rounded-md border",children:t("div",{className:"p-4 grid grid-cols-8 gap-2",children:Ll.map((e,n)=>t("button",{type:"button",onClick:()=>(e=>{p(e),w.setValue("image",Fl(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},n))})})]}),"url"===l&&e("div",{className:"flex flex-col gap-y-2",children:[t(kl,{control:w.control,name:"image",render:({field:n})=>e(xl,{children:[t(Cl,{children:i("workspace.imageUrl")}),t(Nl,{children:t(pl,{placeholder:i("workspace.imageUrlPlaceholder"),...n})}),t(Pl,{children:i("workspace.imageUrlDescription")}),t(_l,{})]})}),w.watch("image")&&w.watch("image")?.trim()&&e("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-medium",children:i("general.previewLabel")}),t("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:t("img",{src:w.watch("image")||void 0,alt:i("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(hc,{type:"button",variant:"outline",onClick:()=>{c(!1),w.reset(),p("🏢"),d("emoji")},disabled:m,children:i("settings.common.cancel")}),t(hc,{type:"submit",disabled:m,children:m?e(n,{children:[t(k,{className:"me-2 h-4 w-4 animate-spin"}),i("workspace.creating")]}):i("workspace.createWorkspace")})]})]})})]})]})}export{_l as $,ks as A,hc as B,Hc as C,mc as D,Dc as E,Yc as F,Qc as G,el as H,tl as I,rl as J,il as K,Kc as L,nl as M,sl as N,al as O,Qn as P,we as Q,hl as R,jc as S,fl as T,Wl as U,vl as V,kl as W,xl as X,Cl as Y,Nl as Z,pl as _,wc as a,Yl as a$,wl as a0,Zt as a1,Pl as a2,El as a3,Al as a4,Ze as a5,Ul as a6,Ll as a7,Fl as a8,Zo as a9,Ps as aA,Eo as aB,Wn as aC,En as aD,Fn as aE,Ln as aF,xn as aG,An as aH,Ft as aI,At as aJ,go as aK,qs as aL,Un as aM,Jo as aN,Vo as aO,Jl as aP,zl as aQ,br as aR,Vl as aS,tr as aT,wo as aU,vr as aV,gr as aW,Kn as aX,Hl as aY,Ro as aZ,Kl as a_,Ss as aa,po as ab,or as ac,ir as ad,$l as ae,Dl as af,Ml as ag,jl as ah,ql as ai,Bl as aj,Rc as ak,Us as al,Fc as am,Sn as an,vn as ao,bn as ap,In as aq,Rn as ar,fn as as,kn as at,_o as au,As as av,_s as aw,Rs as ax,Ws as ay,Ts as az,kc as b,Jd as b$,vo as b0,yo as b1,gc as b2,Wo as b3,_n as b4,On as b5,Bn as b6,pa as b7,sr as b8,gt as b9,He as bA,en as bB,tn as bC,cr as bD,ad as bE,ou as bF,Ke as bG,Qo as bH,mo as bI,yt as bJ,Si as bK,Ye as bL,Qe as bM,js as bN,Xe as bO,st as bP,ot as bQ,nd as bR,Zd as bS,Xd as bT,eu as bU,Md as bV,Bd as bW,sd as bX,fd as bY,zd as bZ,Gd as b_,je as ba,lr as bb,Rt as bc,Ut as bd,Me as be,iu as bf,hd as bg,td as bh,Yt as bi,Qt as bj,Jc as bk,Ve as bl,Kd as bm,Yd as bn,Qs as bo,Cn as bp,Nn as bq,Qd as br,Xn as bs,ze as bt,wt as bu,er as bv,eo as bw,ct as bx,Td as by,Ud as bz,Sc as c,Ad as c$,Hd as c0,md as c1,Dd as c2,jd as c3,Vd as c4,qd as c5,rd as c6,$d as c7,Ld as c8,Fd as c9,wr as cA,hr as cB,ht as cC,on as cD,so as cE,cn as cF,xr as cG,it as cH,$t as cI,Cr as cJ,jn as cK,rr as cL,Jt as cM,pr as cN,nt as cO,rt as cP,$s as cQ,Oc as cR,Tc as cS,Vs as cT,Bs as cU,cl as cV,ol as cW,ro as cX,Os as cY,co as cZ,id as c_,Wd as ca,gd as cb,mt as cc,uu as cd,mr as ce,$n as cf,Dn as cg,Mn as ch,Dt as ci,Kt as cj,Nr as ck,ud as cl,Ht as cm,Wt as cn,vt as co,ao as cp,dn as cq,pn as cr,hn as cs,gn as ct,wn as cu,at as cv,Tn as cw,mn as cx,ar as cy,Pt as cz,ce as d,yd as d0,Ns as d1,Ks as d2,xs as d3,Is as d4,Ls as d5,Fs as d6,ws as d7,gl as d8,ml as d9,Cs as da,nu as db,Es as dc,Ol as dd,Ds as de,Od as df,Rd as dg,qn as dh,Bt as di,yr as dj,fr as dk,sn as e,ln as f,Xt as g,Ac as h,Uc as i,Zs as j,Gs as k,Hs as l,Js as m,zs as n,Tt as o,Ot as p,xt as q,xc as r,Mc as s,Wc as t,Oi as u,Lt as v,Fo as w,Vt as x,Pn as y,Mo as z};
|