@buildbase/sdk 0.0.84 → 0.0.86
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/CHANGELOG.md +71 -0
- package/README.md +2 -2
- package/dist/css/styles.css +1 -1
- package/dist/index.d.ts +63 -11
- package/dist/mcp/index.d.ts +53 -10
- package/dist/react/chunks/SettingsDialog-5UVMteCm.cjs +2 -0
- package/dist/react/chunks/SettingsDialog-m6H5KOPb.mjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-DRxm2Eqw.cjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-DpQW6B-9.mjs +2 -0
- package/dist/react/chunks/ar-Be9FdHKa.mjs +2 -0
- package/dist/react/chunks/ar-Duvekqlb.cjs +2 -0
- package/dist/react/chunks/de-BCfdK6nX.mjs +2 -0
- package/dist/react/chunks/de-gbGlHNX-.cjs +2 -0
- package/dist/react/chunks/es-DooSNAdp.mjs +2 -0
- package/dist/react/chunks/es-bwO83jXP.cjs +2 -0
- package/dist/react/chunks/fr-B-7CJcbA.mjs +2 -0
- package/dist/react/chunks/fr-Dil9oJyG.cjs +2 -0
- package/dist/react/chunks/hi-ClmxBL1N.mjs +2 -0
- package/dist/react/chunks/hi-DHQ5Zw6P.cjs +2 -0
- package/dist/react/chunks/ja-BmUgLTyq.cjs +2 -0
- package/dist/react/chunks/ja-BxU6033x.mjs +2 -0
- package/dist/react/chunks/react-CZ0O0dPN.mjs +2 -0
- package/dist/react/chunks/react-Cv_H4lXj.cjs +2 -0
- package/dist/react/chunks/zh-DLtQGGPM.cjs +2 -0
- package/dist/react/chunks/zh-LlU_KAvr.mjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +71 -12
- package/dist/react/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/react/chunks/SettingsDialog-DImZc0fo.cjs +0 -2
- package/dist/react/chunks/SettingsDialog-DuqMmX00.mjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-C4I66PXv.cjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-hXscplmw.mjs +0 -2
- package/dist/react/chunks/ar-Bv7MJdID.mjs +0 -2
- package/dist/react/chunks/ar-UyL2IcEN.cjs +0 -2
- package/dist/react/chunks/de-BjV4j4L8.mjs +0 -2
- package/dist/react/chunks/de-BpFTP77W.cjs +0 -2
- package/dist/react/chunks/es-BD83AlAI.mjs +0 -2
- package/dist/react/chunks/es-Cg0WHGyt.cjs +0 -2
- package/dist/react/chunks/fr-DC4nKToc.cjs +0 -2
- package/dist/react/chunks/fr-DUSYz0eM.mjs +0 -2
- package/dist/react/chunks/hi-BUaHa-qu.mjs +0 -2
- package/dist/react/chunks/hi-LZW4ZZQj.cjs +0 -2
- package/dist/react/chunks/ja-BYVJft1g.cjs +0 -2
- package/dist/react/chunks/ja-CXjz9Ptf.mjs +0 -2
- package/dist/react/chunks/react-BW__KLHg.mjs +0 -2
- package/dist/react/chunks/react-BoHqKQID.cjs +0 -2
- package/dist/react/chunks/zh-BBVxXvHQ.mjs +0 -2
- package/dist/react/chunks/zh-BtxE6oq5.cjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";var e=require("react/jsx-runtime"),t=require("react"),n=require("clsx"),r=require("tailwind-merge"),s=require("intl-messageformat"),i=require("@radix-ui/react-slot"),a=require("class-variance-authority"),o=require("lucide-react"),c=require("@radix-ui/react-dialog"),l=require("@radix-ui/react-icons"),u=require("@hookform/resolvers/zod"),d=require("react-hook-form"),p=require("@radix-ui/react-label"),h=require("zod"),m=require("@radix-ui/react-avatar"),f=require("@radix-ui/react-radio-group"),g=require("@radix-ui/react-scroll-area"),y=require("@radix-ui/react-separator"),v=require("@radix-ui/react-accordion"),b=require("@radix-ui/react-alert-dialog"),w=require("@radix-ui/react-popover");function x(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var k=x(t),S=x(c),C=x(p),I=x(m),N=x(f),P=x(g),j=x(y),E=x(v),A=x(b),_=x(w);function U(...e){return r.twMerge(n.clsx(e))}let T=!0;function R(e,...t){T&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function O(e,...t){console.error(e,...t)}function F(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,s=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){s(n);break}n.addEventListener("abort",()=>s(n),{once:!0})}return r.signal}function W(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function D(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 L(e,t="Request failed"){if(!e.ok){let n,r=t;try{const t=await D(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 D(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class $ 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,$)}}const M=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&&(T=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(W(e))return;const n=e instanceof Error?e:new $("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),r=n instanceof $?n:new $(n.message,"SDK_ERROR",t,n);if(this.config.enableConsoleLogging&&R(`[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){O("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(r,t)}catch(e){O("[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 q(e,t={}){M.handleError(e,t)}function B(e,t={}){return!W(e)&&(M.handleError(e,t),!0)}function V(e,t,n){return e instanceof Error?e.message:n(t)}function z(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return q(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function G(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){q(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function J(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){q(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function H(e,t){const n=z(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(q(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),J(e),null):r}catch(t){return q(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),J(e),null}}function K(e,t){try{G(e,JSON.stringify(t))}catch(t){q(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const Y="saas-session-id",Q="saas-device-id",Z="code",X="state";function ee(e){G(Y,e)}function te(){J(Y)}function ne(){if("undefined"==typeof window)return null;try{return z(Y)}catch(e){return q(e,{component:"auth-utils",action:"getSessionId",metadata:{key:Y}}),null}}function re(e){if("undefined"!=typeof window&&e)try{G(Q,e)}catch(e){q(e,{component:"auth-utils",action:"setDeviceId",metadata:{key:Q}})}}function se(){const e=ne(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return z(Q)??null}catch(e){return q(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:Q}}),null}}();return n&&(t["x-device-id"]=n),t}function ie(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(Z)}catch(e){return q(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:Z}}),null}}function ae(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(Z),e.searchParams.delete(X),window.history.replaceState({},"",e.toString())}catch(e){q(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:Z}})}}const oe=new WeakSet,ce=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),le="SDK is not ready (missing serverUrl, version, or orgId)";class ue{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(le);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(le)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:se()}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){oe.has(e)||(oe.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 s=()=>{clearTimeout(i),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const i=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,n){const r=(t.method??"GET").toUpperCase(),s=n??e,i=this.buildHeaders(t),a={...t,headers:i},o=ce.has(r);let c,l;if(this._timeout>0){l=new AbortController;const e=l;c=setTimeout(()=>e.abort(),this._timeout),a.signal=t.signal?F(t.signal,e.signal):e.signal}const u=e=>{if(l?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${r} ${s}`);return this.reportError(e,{method:r,path:s}),e}return e},d=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),s=await n(e,a);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&o&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await ue.delay(e,a.signal),d(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw u(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 ue.delay(e,a.signal)}catch(e){throw u(e)}return d(t+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:s}),e}};try{return await d(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 L(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 de extends ue{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 s=await r(e);if(400===s.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:i,invitationToken:a,...o}=e;s=await r(o)}return s.ok||await this.throwResponseError(s,n),this.unwrapResponse(s,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 pe extends ue{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 he=class{constructor(e){this.api=new pe(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),s=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),i=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:s,currency:i}})}};class me extends ue{constructor(e){super(e)}async list(e){const t=await this.fetchJson("connected-agents",{signal:e},"Failed to load connected agents");return t?.agents??[]}async revoke(e){await this.fetchJson("connected-agents/revoke",{method:"POST",body:JSON.stringify({clientId:e})},"Failed to disconnect agent")}}class fe extends ue{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 ye=e=>JSON.stringify(e?{workspaceId:e}:{});class ve extends ue{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:ye(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:ye(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 be extends ue{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 we extends ue{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 xe extends ue{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}const ke=5242880,Se={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"};function Ce(e){if(e.type)return e.type;const t=(e.name??"").split(".").pop()?.toLowerCase()??"";return Se[t]??""}function Ie(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 Ne(e){const t=e?.uploads,n=Number(t?.maxFileBytes);return{enabled:!!t&&!1!==t.enabled,maxFileBytes:Number.isFinite(n)&&n>0?Math.min(n,ke):ke}}function Pe(e,t){return t.enabled?e.size>t.maxFileBytes?"tooLarge":null:"disabled"}function je(e,t){const n=1048576,[r,s]=e>=n?[e/n,"megabyte"]:[e/1024,"kilobyte"];try{return new Intl.NumberFormat(t,{style:"unit",unit:s,unitDisplay:"short",maximumFractionDigits:1}).format(r)}catch{return`${Math.round(10*r)/10} ${"megabyte"===s?"MB":"KB"}`}}class Ee extends ue{constructor(e){super(e)}async upload(e,t){const{purpose:n,signal:r}=t,s=await this.fetchJson("uploads",{method:"POST",body:JSON.stringify({purpose:n,name:e.name??"file",size:e.size,contentType:Ce(e)}),signal:r},"Could not start the upload");let i;const a=new AbortController,o=setTimeout(()=>a.abort(),12e4);try{i=await this.fetchForeign(s.url,{method:"PUT",headers:s.headers,body:e,signal:r?F(r,a.signal):a.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(!i.ok)throw Object.assign(new Error(`The upload to storage was refused (HTTP ${i.status}). Try again.`),{status:i.status});return this.fetchJson(this.apiPath`uploads/${s.uploadId}/complete`,{method:"POST",body:"{}",signal:r},"Could not finish the upload")}}class Ae extends ue{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 _e={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"},Ue={402:_e.SEAT_LIMIT,404:_e.NOT_FOUND,409:_e.ALREADY_HANDLED,410:_e.EXPIRED,429:_e.RATE_LIMITED,502:_e.EMAIL_FAILED,503:_e.NO_SENDER_CONFIGURED};function Te(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Re(e){return"string"==typeof e&&e?e:void 0}async function Oe(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:{},s=Re(r.message)??Re(r.error)??n,i={status:e,code:Re(r.code)??Ue[e]??`HTTP_${e}`,currentUserCount:Te(r.currentUserCount),limit:Te(r.limit),retryAfterSeconds:Te(r.retryAfterSeconds),invitedEmail:Re(r.invitedEmail),invitationId:Re(r.invitationId),invitationStatus:Re(r.status)};return Object.assign(new Error(s),i)}(e.status,n,t)}function Fe(e){return e instanceof Error&&"number"==typeof e.status}class We extends ue{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 Oe(r,n);return L(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 s=new URLSearchParams;return s.append("limit",t.toString()),n&&s.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.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 s=r.toString(),i=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,s){const i={event:t};return n&&(i.userId=n),r&&(i.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(i),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,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 s=r.toString(),i=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{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 s=r.toString(),i=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{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")}}function De(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const Le={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 $e{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){q(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){q(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(Le.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(Le.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(Le.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(Le.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(Le.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(Le.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(Le.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(Le.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(Le.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(Le.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(Le.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(Le.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(Le.WorkspaceDeleted,{workspace:e})}}const Me=new $e,qe=globalThis;function Be(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=qe[t]??(qe[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const Ve=Be("credit-balance"),ze=Ve.subscribe,Ge=Ve.invalidate,Je=Be("quota-usage"),He=Je.subscribe,Ke=Je.invalidate,Ye=Be("subscription"),Qe=Ye.subscribe,Ze=Ye.invalidate,Xe="bb",et={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},tt={Success:"success",Cancel:"cancel",Error:"error"},nt={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function rt(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(Xe,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function st(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:rt({action:et.CreditPurchase,status:tt.Success,ws:e,screen:nt.Credits},n),cancelUrl:rt({action:et.CreditPurchase,status:tt.Cancel,ws:e,screen:nt.Credits},n)}}function it(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(Xe);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)),s=decodeURIComponent(e.slice(n+1));r&&(t[r]=s)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function at(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(Xe)&&(e.searchParams.delete(Xe),window.history.replaceState({},"",e.toString()))}catch{}}const ot="__buildbaseBeforeLeave",ct=globalThis,lt=ct[ot]??(ct[ot]=new Set);function ut(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,s="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!s)return null;const{sameOrigin:i,allowedOrigins:a}=t;return i||a?.length?i&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||a?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}function dt(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=ut(e,n)??ut(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===lt.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of lt)try{e()}catch{}}(r),window.location.href=r,!0}const pt="saas-auth-intent";function ht(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function mt(e){ut(e,{sameOrigin:!0})&&K(pt,{returnUrl:e,createdAt:Date.now()})}function ft(){const e=H(pt,ht);return J(pt),e?Date.now()-e.createdAt>6e5?null:ut(e.returnUrl,{sameOrigin:!0}):null}const gt={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:"฿"},yt={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function vt(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return gt[t]??t.toUpperCase()}const bt=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],wt=bt.map(e=>({value:e,label:`${e.toUpperCase()} (${vt(e)})`})),xt=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),kt=new Set(["bhd","jod","kwd","omr","tnd"]),St=new Map;function Ct(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(xt.has(t))return 0;if(kt.has(t))return 3;if("isk"===t)return 2;let n=St.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}St.set(t,n)}return n}function It(e,t){const n=Ct(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function Nt(e,t,n="en-US"){const r=(t??"").trim(),s=Ct(r),i=e/10**s;if(!r)return i.toFixed(s);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:s,maximumFractionDigits:s}).format(i)}catch{return vt(r)+(0===s?i.toLocaleString("en-US"):i.toFixed(s))}}function Pt(e,t){return vt(t)+It(e,t)}const jt={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const Et={included:"included",then:"then",hardLimit:"hard limit"};const At={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},_t={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"};function Ut(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 Tt(e,t,n){const r=Ut(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function Rt(e,t,n,r){const s=Ut(e,t),i=s?.quotaOverages?.[n];if(i)return i[r]}function Ot(e,t){const n=Ut(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Ft(e,t,n){const r=Ot(e,t);return r?.perSeat?r.perSeat[n]??null:null}function Wt(e,t){return Math.max(0,e-(t||0))}function Dt(e,t,n,r){const s=Ot(e,t);if(!s)return null;return Wt(r,s.includedSeats)*(Ft(e,t,n)??0)}function Lt(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=Ot(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 $t(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:i,source:a}=n;if(i<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=i){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[a]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[a]??"users.memberLimitMessage",blockMessageValues:{maxUsers:i}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const Mt="saas-workspace-current",qt=e=>{e?G(Mt,e._id):J(Mt)},Bt=()=>z(Mt),Vt=()=>{J(Mt)},zt=(e,t)=>!!e&&t.some(t=>t._id===e);function Gt(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 Jt(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 Ht={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"},Kt=Object.values(Ht),Yt={admin:Kt.filter(e=>e!==Ht.WORKSPACE_DELETE),editor:[Ht.WORKSPACE_SETTINGS_VIEW,Ht.WORKSPACE_MEMBERS_VIEW,Ht.WORKSPACE_FEATURES_VIEW,Ht.WORKSPACE_BILLING_VIEW,Ht.WORKSPACE_USAGE_VIEW,Ht.WORKSPACE_USAGE_RECORD],viewer:[Ht.WORKSPACE_SETTINGS_VIEW,Ht.WORKSPACE_MEMBERS_VIEW]},Qt="viewer";function Zt(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 Xt(e){const{userId:t,workspace:n,settings:r,appPermissions:s}=e;if(!n||!t)return new Set;if(Gt(n,t)){const e=new Set(Kt);if(s)for(const t of Zt(s))e.add(t);if(n.permissions)for(const t of Zt(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of Zt(r.workspace.permissions))e.add(t);return e}const i=e.workspaceRole??Jt(n,t);return i?en(i,e):new Set}function en(e,t,n={}){const{workspace:r,settings:s,appPermissions:i}=t;if(!r)return new Set;const a=r.permissions,o=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=e=>!!a&&e in a,d=e=>!!o&&e in o,p=e=>u(e)||d(e)||e in Yt;let h,m=e;if(!p(e)){const e=s?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;m=e}h=u(m)?c(a[m]):d(m)?c(o[m]):Yt[m]??[];const f=new Set(h),g=new Set((s?.workspace?.customPermissions??[]).map(e=>e.key)),y=i?.[m]?l(i[m]).filter(e=>!g.has(e)):[];let v;v=u(m)?l(a[m]):d(m)?[...l(o[m]),...y]:i?.[m]?l(i[m]):[];for(const e of v)f.add(e);if("admin"===m){for(const e of Yt.admin)f.add(e);for(const e of g)f.add(e);if(i)for(const e of l(Zt(i)))f.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(Ht.WORKSPACE_MEMBERS_INVITE)}(f,m,s),f}const tn="App";function nn(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||tn});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:tn});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))}var rn;function sn(e){return{isAuthenticated:e===exports.AuthStatus.authenticated,isLoading:e===exports.AuthStatus.loading||e===exports.AuthStatus.redirecting||e===exports.AuthStatus.authenticating,isRedirecting:e===exports.AuthStatus.redirecting}}function an(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function on(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||an(n.invitedAt)-an(e.invitedAt))}function cn(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||an(e.validTill)>t.getTime())}function ln(e,t=new Date){return on(e.filter(e=>cn(e,t)))}function un(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""}function dn(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null}exports.AuthStatus=void 0,(rn=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",rn.redirecting="redirecting",rn.authenticated="authenticated",rn.unauthenticated="unauthenticated",rn.authenticating="authenticating";const pn="saas-pending-invite",hn=/^[0-9a-f]{64}$/;function mn(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}function fn(e,t){hn.test(e)&&t&&K(pn,{token:e,orgId:t,createdAt:Date.now()})}function gn(e,t=Date.now()){const n=H(pn,mn);return n?t-n.createdAt>864e5?(J(pn),null):n.orgId!==e?null:hn.test(n.token)?n.token:(J(pn),null):null}function yn(){J(pn)}class vn extends t.Component{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(q(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){O("[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.jsxs("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:[e.jsx("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:this.props.errorTitle??"Something went wrong"}),e.jsx("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),e.jsx("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 bn=()=>({type:"AUTHENTICATION_STARTED"}),wn=()=>({type:"AUTHENTICATION_PROCESSING"}),xn=()=>({type:"AUTHENTICATION_FAILED"}),kn=e=>({type:"SET_SESSION",payload:e}),Sn=()=>({type:"REMOVE_SESSION"});function Cn(e,n,r,s){const i=t.useMemo(()=>{const t=r??(e=>e);let n,i,a=!1;return()=>{const r=e();if(!a)return a=!0,n=r,i=t(r),i;if(Object.is(n,r))return i;const o=t(r);n=r;return(s?s(i,o):Object.is(i,o))||(i=o),i}},[e,r,s]);return t.useSyncExternalStore(n,i,i)}function In({name:n,initialState:r,reducer:s,initializer:i}){const a=t.createContext(null);a.displayName=`${n}StoreContext`;const o=t.memo(({children:n})=>{const o=t.useRef(null);return null===o.current&&(o.current=function(e,t,n){let r=n?n(e):e;const s=new Set;return{getState:()=>r,dispatch:e=>{const n=t(r,e);Object.is(n,r)||(r=n,s.forEach(e=>e()))},subscribe:e=>(s.add(e),()=>{s.delete(e)})}}(r,s,i)),e.jsx(a.Provider,{value:o.current,children:n})});o.displayName=`${n}Provider`;const c=(e="Store")=>{const r=t.useContext(a);if(!r)throw(e=>new Error(`use${n}${e} must be used within a ${n}Provider. Make sure SaaSOSProvider is wrapping your application.`))(e);return r};return{Provider:o,useContext:()=>{const e=c("Context"),n=Cn(e.getState,e.subscribe);return t.useMemo(()=>({state:n,dispatch:e.dispatch}),[n,e])},useState:()=>{const e=c("State");return Cn(e.getState,e.subscribe)},useDispatch:()=>c("Dispatch").dispatch,useSelector:(e,t)=>{const n=c("Selector");return Cn(n.getState,n.subscribe,e,t)},useStore:c}}function Nn(e,t,n){return{...e,[t]:n}}function Pn(e,t){return{...e,...t}}const{Provider:jn,useDispatch:En,useStore:An}=In({name:"Auth",initialState:{session:null,status:exports.AuthStatus.loading},reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return Nn(e,"status",exports.AuthStatus.redirecting);case"AUTHENTICATION_PROCESSING":return Nn(e,"status",exports.AuthStatus.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return Pn(e,{session:null,status:exports.AuthStatus.unauthenticated});case"SET_SESSION":return Pn(e,{session:t.payload,status:exports.AuthStatus.authenticated});default:return e}}}),_n=jn,Un=En,Tn=An,Rn=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),On=e=>({type:"SET_SETTINGS",payload:e}),Fn=(e,t)=>({type:"SET_SETTINGS_STATUS",payload:{status:e,error:t}}),Wn=()=>({serverUrl:"",version:exports.ApiVersion.V1,orgId:"",settings:null,settingsStatus:"idle",settingsError:null}),{Provider:Dn,useDispatch:Ln,useStore:$n}=In({name:"OS",initialState:Wn(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return Pn(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return Wn();case"SET_SETTINGS":return Pn(e,{settings:t.payload,settingsStatus:"loaded",settingsError:null});case"SET_SETTINGS_STATUS":return Pn(e,{settingsStatus:t.payload.status,settingsError:t.payload.error??null});default:return e}}}),Mn=Dn,qn=Ln,Bn=$n,Vn=e=>({type:"SET_WORKSPACES",payload:e}),zn=e=>({type:"ADD_WORKSPACE",payload:e}),Gn=e=>({type:"UPDATE_WORKSPACE",payload:e}),Jn=e=>({type:"REMOVE_WORKSPACE",payload:e}),Hn=e=>({type:"SET_ALL_FEATURES",payload:e}),Kn=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),Yn=()=>({type:"RESET_CURRENT_WORKSPACE"}),Qn=e=>({type:"SET_IS_INITIALIZED",payload:e}),Zn=e=>({type:"SET_LOADING",payload:e}),Xn=e=>({type:"SET_ERROR",payload:e}),er=e=>({type:"SET_REFRESHING",payload:e}),tr=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:nr,useDispatch:rr,useStore:sr}=In({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 Nn(e,"workspaces",t.payload);case"ADD_WORKSPACE":return Nn(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return Nn(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return Nn(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return Nn(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return Nn(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return Nn(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return Nn(e,"isInitialized",t.payload);case"SET_LOADING":return Nn(e,"loading",t.payload);case"SET_ERROR":return Nn(e,"error",t.payload);case"SET_REFRESHING":return Nn(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return Nn(e,"switchingToId",t.payload);default:return e}}}),ir=nr,ar=rr,or=sr,cr=t.memo(({children:t})=>e.jsx(Mn,{children:e.jsx(_n,{children:e.jsx(ir,{children:t})})}));cr.displayName="SDKContextProvider";const lr=t.createContext({});lr.displayName="CheckoutConfigContext";const ur=t.memo(({getCheckoutStripeParams:n,children:r})=>{const s=t.useMemo(()=>({getCheckoutStripeParams:n}),[n]);return e.jsx(lr.Provider,{value:s,children:r})});ur.displayName="CheckoutConfigProvider";const dr={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!",updateSuccessTrial:"Plan changed. Your trial continues on the new plan until {date}.",paymentRequiredTitle:"Complete payment to finish the upgrade",paymentRequiredMessage:"Your new plan starts once this payment goes through. Until then you stay on your current plan, and the change is dropped if it is not paid in time.",completePayment:"Complete payment",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.",trialKeepAccess:"Your access continues after the trial once a payment method is on file.",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."}},pr={en:async()=>dr,es:async()=>(await Promise.resolve().then(function(){return require("./es-bwO83jXP.cjs")})).es,fr:async()=>(await Promise.resolve().then(function(){return require("./fr-Dil9oJyG.cjs")})).fr,de:async()=>(await Promise.resolve().then(function(){return require("./de-gbGlHNX-.cjs")})).de,ja:async()=>(await Promise.resolve().then(function(){return require("./ja-BmUgLTyq.cjs")})).ja,zh:async()=>(await Promise.resolve().then(function(){return require("./zh-DLtQGGPM.cjs")})).zh,hi:async()=>(await Promise.resolve().then(function(){return require("./hi-DHQ5Zw6P.cjs")})).hi,ar:async()=>(await Promise.resolve().then(function(){return require("./ar-Duvekqlb.cjs")})).ar},hr=["en","es","fr","de","ja","zh","hi","ar"];const mr={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function fr(e,t){const n={...e};for(const r of Object.keys(t)){const s=t[r],i=e[r];"string"==typeof s?n[r]=s:s&&"object"==typeof s&&i&&"object"==typeof i&&(n[r]=fr(i,s))}return n}const gr=t.createContext({messages:dr,locale:"en",formattingLocale:"en"});function yr({locale:e="en",messageOverrides:n,children:r}){const s=function(e){const t=e.toLowerCase().replace("_","-");if(hr.includes(t))return t;const n=t.split("-")[0];return hr.includes(n)?n:"en"}(e),[i,a]=t.useState(dr);t.useEffect(()=>{if("en"===s)return void a(dr);let e=!1;const t=pr[s];return t&&t().then(t=>{e||a(t)}),()=>{e=!0}},[s]);const o=t.useMemo(()=>n?fr(i,n):i,[i,n]),c=function(e){return mr[e]??e}(s),l=t.useMemo(()=>({messages:o,locale:s,formattingLocale:c}),[o,s,c]);return t.createElement(gr.Provider,{value:l},r)}const vr=new Map,br=new Map,wr=new Map;function xr(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const kr={getNumberFormat(e,t){const n=xr(e,t);let r=vr.get(n);return r||(r=new Intl.NumberFormat(e,t),vr.set(n,r)),r},getDateTimeFormat(e,t){const n=xr(e,t);let r=br.get(n);return r||(r=new Intl.DateTimeFormat(e,t),br.set(n,r)),r},getPluralRules(e,t){const n=xr(e,t);let r=wr.get(n);return r||(r=new Intl.PluralRules(e,t),wr.set(n,r)),r}},Sr=new Map;function Cr(){const{messages:e,locale:n,formattingLocale:r}=t.useContext(gr),i=t.useMemo(()=>{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(n,i)=>{const a=t(e,n)??t(dr,n)??n;if(!i)return a;try{const e=function(e,t){const n=`${t}:${e}`;let r=Sr.get(n);return r||(r=new s(e,t,void 0,{formatters:kr}),Sr.set(n,r)),r}(a,r),t=e.format(i);return"string"==typeof t?t:String(t)}catch{return a.replace(/\{(\w+)\}/g,(e,t)=>String(i[t]??`{${t}}`))}}},[e,r]),a="ar"===n?"rtl":"ltr",o=t.useMemo(()=>e=>e.toLocaleString(r),[r]),c=t.useMemo(()=>(e,t)=>Nt(e,t,r),[r]);return{t:i,locale:n,formattingLocale:r,dir:a,fmtNum:o,fmtCents:c,messages:e}}const Ir=new Map;function Nr(e,t){const n=Ir.get(e);if(n)return n;const r=t().finally(()=>{Ir.get(e)===r&&Ir.delete(e)});return Ir.set(e,r),r}function Pr(){const e=t.useRef(null);t.useEffect(()=>()=>e.current?.abort(),[]);return{begin:t.useCallback(()=>{e.current?.abort();const t=new AbortController;return e.current=t,t},[]),settle:t.useCallback(t=>e.current===t&&(e.current=null,!t.signal.aborted),[])}}const jr="bb_attr",Er=["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"],Ar=/^[\w.~-]{1,200}$/;function _r(){return"undefined"==typeof window?null:window}function Ur(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??_r()?.document;if(!n)return"";const r=e.split(".");for(let e=r.length-2;e>=0;e--){const t="."+r.slice(e).join("."),s=`__bb_probe_${Date.now()}`;n.cookie=`${s}=1; domain=${t}; path=/; SameSite=Lax`;const i=n.cookie.includes(`${s}=1`);if(n.cookie=`${s}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,i)return t}return""}const Tr="$t",Rr="$l";function Or(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${jr}=`));if(!t)return{params:{}};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));if("object"!=typeof e||!e)return{params:{}};const{[Tr]:n,[Rr]:r,...s}=e;return{params:s,..."number"==typeof n&&n>0?{capturedAt:n}:{},..."string"==typeof r&&r?{landingUrl:r}:{}}}catch{return{params:{}}}}function Fr(e){try{const{origin:t,pathname:n}=e.location;return t&&"null"!==t?`${t}${n}`.slice(0,300):void 0}catch{return}}const Wr=Er.filter(e=>!e.startsWith("utm_")),Dr=e=>Wr.some(t=>!!e[t]);function Lr(){const e=_r();if(!e)return{};const t=e.document,n=function(e){return Or(e).params}(t),r=function(e){const t=new URLSearchParams(e),n={};for(const e of Er){const r=t.get(e);r&&(r.length>200||Ar.test(r)&&(n[e]=r))}return n}(e.location.search),s=Object.keys(r).length>0&&(Dr(r)||!Dr(n)),i=s?r:n;return 0===Object.keys(i).length?{}:(s&&!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 s=encodeURIComponent(JSON.stringify({...t,[Tr]:r.capturedAt,...r.landingUrl?{[Rr]:r.landingUrl}:{}}));e.cookie=`${jr}=${s}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,i,Ur(e.location.hostname,t),{capturedAt:Date.now(),landingUrl:Fr(e)}),i)}function $r(){const e=_r();return e?Or(e.document):{params:{}}}function Mr(){const e=$r(),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 qr(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const Br="bb_pending_checkout",Vr=216e5;function zr(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}function Gr(e){try{zr()?.setItem(Br,JSON.stringify(e))}catch{}!function(e){if(!e.sessionId)return;const t=Hr();if(!t)return;try{const n=Ur(window.location?.hostname??"",t);t.cookie=`${Jr}=${encodeURIComponent(JSON.stringify(e))}; path=/; max-age=21600; SameSite=Lax`+(n?`; domain=${n}`:"")}catch{}}(e)}const Jr="bb_co";function Hr(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function Kr(){const e=Hr();if(e)try{const t=Ur(window.location?.hostname??"",e);e.cookie=`${Jr}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function Yr(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>Vr?null:n:null}catch{return null}}function Qr(e=Date.now()){const t=zr();if(!t)return null;let n=null;try{n=t.getItem(Br),t.removeItem(Br)}catch{return null}const r=Yr(n,e);return r&&Kr(),r}function Zr(e){try{return Yr(zr()?.getItem(Br)??null,e)}catch{return null}}function Xr(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=Zr(t);if(r?.sessionId===n)return Qr(t);const s=function(e){const t=Hr();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${Jr}=`));return n?Yr(decodeURIComponent(n.slice(Jr.length+1)),e):null}(t);return s?.sessionId!==n?null:(Kr(),s)}function es(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)&&Zr(t)?Qr(t):null}const ts=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),ns=new Set(["bhd","jod","kwd","omr","tnd"]);function rs(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return ts.has(n)?e:e/(ns.has(n)?1e3:100)}const ss=["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"],is=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/;function as(e){const t=new Set;for(const n of e??[]){const e=String(n).trim().toUpperCase();if("EEA"===e)for(const e of ss)t.add(e);else is.test(e)&&t.add(e)}return[...t]}function os(e,t,n){return e.includes(t)}function cs(e,t,n){const r=(t??"").trim().toUpperCase();if(!/^[A-Z]{2}$/.test(r)||"XX"===r||"T1"===r)return"denied";const s=(n??"").trim().toUpperCase()||void 0,i=as(e.regions?.denied),a=as(e.regions?.granted);if(s){if(i.includes(`${r}-${s}`))return"denied";if(a.includes(`${r}-${s}`))return"granted"}return os(i,r)?"denied":os(a,r)||"granted"===e.default?"granted":"denied"}function ls(){return"undefined"==typeof window?null:window}const us=["ad_storage","ad_user_data","ad_personalization","analytics_storage"];function ds(e){const t={};for(const n of us)t[n]=e;return t}function ps(e){const t=ls();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 hs="bb_cid";function ms(){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const e=document.cookie.split("; ").find(e=>e.startsWith(`${hs}=`)),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=Ur(window.location.hostname,document);return document.cookie=`${hs}=${n}; path=/; max-age=34128000; SameSite=Lax`+(r?`; domain=${r}`:""),n}catch{return}}const fs="bb_consent_recorded";function gs(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(fs)===e}catch{return!1}}(t))return;!function(e){try{window.localStorage.setItem(fs,e)}catch{}}(t);const n=ms();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 ys=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]),vs=(e,t)=>e>>>t|e<<32-t;function bs(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,s=2773480762,i=1359893119,a=2600822924,o=528734635,c=1541459225;const l=e.length,u=l+1,d=u+(56-u%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[l]=128;const h=8*l,m=Math.floor(h/4294967296),f=h>>>0;p[d-8]=m>>>24&255,p[d-7]=m>>>16&255,p[d-6]=m>>>8&255,p[d-5]=255&m,p[d-4]=f>>>24&255,p[d-3]=f>>>16&255,p[d-2]=f>>>8&255,p[d-1]=255&f;const g=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;g[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=vs(g[e-15],7)^vs(g[e-15],18)^g[e-15]>>>3,n=vs(g[e-2],17)^vs(g[e-2],19)^g[e-2]>>>10;g[e]=g[e-16]+t+g[e-7]+n>>>0}let l=t,u=n,d=r,h=s,m=i,f=a,y=o,v=c;for(let e=0;e<64;e++){const t=v+(vs(m,6)^vs(m,11)^vs(m,25))+(m&f^~m&y)+ys[e]+g[e]>>>0,n=l&u^l&d^u&d;v=y,y=f,f=m,m=h+t>>>0,h=d,d=u,u=l,l=t+((vs(l,2)^vs(l,13)^vs(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+u>>>0,r=r+d>>>0,s=s+h>>>0,i=i+m>>>0,a=a+f>>>0,o=o+y>>>0,c=c+v>>>0}const y=new Uint8Array(32),v=[t,n,r,s,i,a,o,c];for(let e=0;e<8;e++)y[4*e]=v[e]>>>24&255,y[4*e+1]=v[e]>>>16&255,y[4*e+2]=v[e]>>>8&255,y[4*e+3]=255&v[e];return y}(e))}async function ws(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 bs((n=e,(new TextEncoder).encode(n)));var n}async function xs(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 s=t.slice(n+1);return"gmail.com"!==s&&"googlemail.com"!==s||(r=r.replace(/\./g,"")),`${r}@${s}`}(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 ws(t)),n&&(r.phoneHash=await ws(n)),r}function ks(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 Ss(){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 Cs(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 Is(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 Ns(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=Ss();n("fbp",r._fbp),n("fbc",r._fbc),n("ga_cid",Cs(r._ga));const s=Object.keys(r).find(e=>e.startsWith("_ga_"));n("ga_sid",s?Is(r[s]):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 Ps(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}const js=new Set(["workspace_id","workspace_role","workspace_owner","workspace_member_count","workspace_plan","subscription_status"]);function Es(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(js.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 As(...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 _s(e,t,n,r=30){const s={bb_event_id:e,...Ns(t),...Es(n)},i=$r();for(const[e,t]of Object.entries(i.params)){if(Object.keys(s).length>=30)break;"string"==typeof t&&t&&(s[`bb_${e}`]=t)}i.capturedAt&&Object.keys(i.params).length&&Object.keys(s).length<30&&(s.bb_attr_ts=String(i.capturedAt));const a=Math.max(0,Math.min(r,30));return Object.fromEntries(Object.entries(s).slice(0,a))}const Us={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}},Ts=Object.keys(Us);function Rs(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(Us,e)}function Os(e,t){return!!Rs(e)&&("string"==typeof t&&0!==t.length&&new RegExp(Us[e].idPattern).test(t))}const Fs=/^[a-z][a-z0-9-]{0,40}$/,Ws=/^[\w.:/@+=-]{1,200}$/;function Ds(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])=>Fs.test(e)&&"string"==typeof t&&Ws.test(t))}(e.dataAttributes)}Array.from(new Set(Ts.map(e=>Us[e].scriptOrigin))).sort();const Ls={sign_up:{ga4:"sign_up",meta:"CompleteRegistration",tiktok:"CompleteRegistration",reddit:"SignUp"},login:{ga4:"login",meta:null,tiktok:null,reddit:null},trial_started:{ga4:"begin_checkout",meta:"StartTrial",tiktok:"StartTrial",reddit:"Lead"},checkout_started:{ga4:"begin_checkout",meta:"InitiateCheckout",tiktok:"InitiateCheckout",reddit:"AddToCart"},purchase:{ga4:"purchase",meta:"Purchase",tiktok:"CompletePayment",reddit:"Purchase"},subscription_created:{ga4:"purchase",meta:"Subscribe",tiktok:"Subscribe",reddit:"Purchase"},subscription_upgraded:{ga4:"subscription_upgraded",meta:null,tiktok:null,reddit:null},lead:{ga4:"generate_lead",meta:"Lead",tiktok:"SubmitForm",reddit:"Lead"},workspace_created:{ga4:"workspace_created",meta:null,tiktok:null,reddit:null}},$s=Object.keys(Ls);function Ms(e){return $s.includes(e)}function qs(){return"undefined"==typeof window?null:window}const Bs={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 Vs(){return"undefined"==typeof window?null:window}function zs(e,t={}){const n=Vs();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 Gs(e){const t=Vs();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function Js(e){const t=Vs();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const Hs=new Set;function Ks(e){for(const t of Hs)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function Ys(e,t){const n=Vs();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=Bs[e];if(!r)return!1;if(void 0===n[r])return!1;if(Hs.has(`${e}:${t}`))return!0;return!Us[e].multiInstance||!Ks(e)}const Qs={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 Zs(e,t,n){const r=function(e,t,n){const r=Vs();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 zs(e.src,t),!0}const s=e.provider,i=Us[s];if(!i)return!1;const a=e.providerId;if(!a)return!1;const o=Qs[s];if(o&&Ks(s))return Gs(o(a)),!0;switch(s){case"gtm":{Js(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return zs(`${i.scriptOrigin}/gtm.js?id=${a}${e}`),!0}case"ga4":case"google_ads":{Js(t),zs(`${i.scriptOrigin}/gtag/js?id=${a}`);const e=r.gtag;e("js",new Date);const o="ga4"===s&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return o?e("config",a,o):e("config",a),!0}case"meta_pixel":return Gs(`!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','${i.scriptOrigin}/en_US/fbevents.js');fbq('init','${a}');fbq('track','PageView');`),!0;case"x_pixel":return Gs(`!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='${i.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${a}');`),!0;case"linkedin":return Gs(`window._linkedin_partner_id='${a}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${a}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),zs(`${i.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return Gs(`!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='${i.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('${a}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return Gs(`!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='${i.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${a}');rdt('track','PageVisit');`),!0;case"bing_uet":return Gs(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${a}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${i.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 Gs(`(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='${i.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${a}');`),!0;case"hotjar":return Gs(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${a},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${i.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=i.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return Gs(`!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='${i.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('${a}',{api_host:'https://${n}'});`),!0}case"plausible":return Gs("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),zs(`${i.scriptOrigin}/js/script.js`,{"data-domain":a,defer:"true"}),!0;case"ahrefs":return zs(`${i.scriptOrigin}/analytics.js`,{"data-key":a}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&Hs.add(`${e.provider}:${e.providerId}`),r}const Xs=Symbol.for("@buildbase/sdk.tracking.context"),ei=globalThis,ti=ei[Xs]??(ei[Xs]=t.createContext(null)),ni={consent:{manifest:[],state:null,effective:null,default:null,country:null,set:()=>{}},track:()=>{},setUser:()=>{},setIdentity:()=>{},setConsentRecordHeaders:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function ri(){return t.useContext(ti)??ni}function si(){return null!==t.useContext(ti)}const ii=({serverUrl:n,orgId:r,clientId:s,enabled:i=!0,consent:a="auto",autoPageview:o=!0,events:c,onEvent:l,properties:u,enrich:d,identity:p,debug:h=!1,children:m})=>{const f=t.useRef(p);f.current=p;const[g,y]=t.useState(null),[v,b]=t.useState(!1),[w,x]=t.useState(!1),k="object"==typeof a?JSON.stringify(a):"",S=t.useMemo(()=>k?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(k)):null,[k]),C="string"==typeof a?a:"auto",I="granted"===C?{analytics:!0,marketing:!0}:"denied"===C?{analytics:!1,marketing:!1}:null,[N,P]=t.useState(I),j=t.useRef(null),E=t.useRef(l);E.current=l;const A=t.useRef(d);A.current=d;const _=t.useRef({});_.current=u??{};const U=t.useRef({}),T=t.useCallback(()=>({..._.current,...U.current}),[]),R=t.useCallback(e=>{const t={...U.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];U.current=t},[]),[O,F]=t.useState({}),W=t.useRef({}),[D,L]=t.useState(0),$=t.useRef(null),[M,q]=t.useState(0),B=t.useRef({}),V=t.useRef(null);V.current=g;const z=g?.dataLayerName??"dataLayer",G=t.useCallback((...e)=>{h&&console.info("[buildbase:tracking]",...e)},[h]);t.useEffect(()=>{return e=()=>{0!==Object.keys(W.current).length&&window.dispatchEvent("function"==typeof PageTransitionEvent?new PageTransitionEvent("pagehide",{persisted:!1}):new Event("pagehide"))},lt.add(e),()=>{lt.delete(e)};var e},[]),t.useEffect(()=>{if(!(i&&n&&r&&s))return void b(!0);let e=!1;const t=`${n.replace(/\/$/,"")}/api/v1/public/${r}/tracking?clientId=${encodeURIComponent(s)}`;return fetch(t).then(e=>e.ok?e.json():null).then(t=>{if(e||!t)return;const n=t.data??t;n&&Array.isArray(n.scripts)&&y(n)}).catch(()=>{G("config fetch failed; nothing installed")}).finally(()=>{e||b(!0)}),()=>{e=!0}},[i,n,r,s,G]),t.useEffect(()=>{i&&F(Lr())},[i]);const J="auto"===C?S??g?.consent?.defaults??null:null,H=t.useMemo(()=>g?"auto"!==C?C:S?cs(S,g.country,g.region):g.consent?.defaults?g.resolvedConsentDefault??cs(g.consent.defaults,g.country,g.region):"denied":null,[g,C,S]),K=N??("granted"===H?{analytics:!0,marketing:!0}:null),Y=!!g?.enhancedConversions&&!!K?.marketing,Q=!!g?.scripts?.some(e=>"ga4"===e.provider||"google_ads"===e.provider||"gtm"===e.provider),Z=J?JSON.stringify(J):"";t.useEffect(()=>{i&&g?.enabled&&(Js(z),function(e,t,n={}){const r=ls();if(!r)return;Array.isArray(r[e])||(r[e]=[]),"function"!=typeof r.gtag&&(r.gtag=function(){r[e].push(arguments)});const s=r.gtag,i="auto"===t?n.regional:null;let a="granted"===t?"granted":"denied";if(i){const e=as(i.regions?.denied),t=as(i.regions?.granted).filter(t=>!e.includes(t));e.length&&s("consent","default",{...ds("denied"),region:e,wait_for_update:500}),t.length&&s("consent","default",{...ds("granted"),region:t}),a=i.default}s("consent","default",{...ds(a),..."denied"===a?{wait_for_update:500}:{}}),n.google&&(s("set","url_passthrough",!0),s("set","ads_data_redaction","granted"!==(n.resolved??a)))}(z,C,{regional:Z?JSON.parse(Z):null,resolved:H,google:Q}),j.current&&ps(j.current))},[i,g?.enabled,z,C,Z,Q]);const X=t.useMemo(()=>g?.enabled?g.scripts.filter(e=>{const t=Rs(e.provider)&&Us[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,K,C)}):[],[g,N,H,C]),[ee,te]=t.useState(()=>"undefined"==typeof window||!qr(window.location.search));t.useEffect(()=>{if(ee)return;const e=setInterval(()=>{qr(window.location.search)||te(!0)},50),t=setTimeout(()=>te(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[ee]),t.useEffect(()=>{if(!ee)return;if(!i||!g?.enabled)return void(v&&x(!0));let e=0;for(const t of X)if(!W.current[t.key]){if("external"===t.provider){if(!Ds({src:t.src,dataAttributes:t.dataAttributes})){G("rejected external script",t.key);continue}}else{if(!Rs(t.provider)){G("rejected unknown provider",t.provider);continue}if(!Os(t.provider,t.providerId)){G("rejected id for",t.provider);continue}if(Ys(t.provider,t.providerId??"")){G(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}Zs(t,z,f.current)&&(W.current[t.key]=t.providerId??t.src??"",e+=1,G("installed",t.key))}e&&L(e=>e+1);const t=window;t.__buildbase=t.__buildbase??{},t.__buildbase.tracking={installed:{...W.current},dataLayerName:z,clientId:s};const n=Object.keys(W.current).length>0,r=null!==K||0===g.scripts.length;(n||r)&&x(!0)},[i,g,X,v,N,H,z,G,ee,s]),t.useEffect(()=>{if(!i||!o||!g?.enabled)return;if("undefined"==typeof window)return;if(!ee)return;let e=null;const t=()=>{e&&clearTimeout(e),e=setTimeout(()=>function(e,t){const n=qs();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")}}(X,z),50)},n=window.history,r=n.pushState,s=n.replaceState;return n.pushState=function(...e){const n=r.apply(this,e);return t(),n},n.replaceState=function(...e){const n=s.apply(this,e);return t(),n},window.addEventListener("popstate",t),()=>{n.pushState=r,n.replaceState=s,window.removeEventListener("popstate",t),e&&clearTimeout(e)}},[i,o,g?.enabled,X,z,ee]),t.useEffect(()=>{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(!Ms(e))return`[buildbase:tracking] unknown event "${e}" in events.overrides. Overrides only apply to the events the SDK fires itself.`;return null}(c,!!l);if(e)throw new Error(e)},[i,c,l]);const ne=t.useCallback((e,t={},n)=>{if(!i)return;const r=n?.eventId||Ps(),s=c?.mode??"auto",a=(Ms(e)?c?.overrides?.[e]:void 0)??s,o={..._.current,...U.current,...O,...t},l=A.current?.({name:e,params:o})??{},u={...o,...l},d=E.current?.({name:e,params:u,eventId:r,handledBy:a});"manual"!==a&&!0!==d?(Y&&$.current&&ks(X,$.current),function(e,t,n,r,s){const i=qs();if(!i)return;const a=i[s];Array.isArray(a)&&a.push({event:e,...t,event_id:n});const o=Ms(e)?Ls[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const s of r){const r=s.provider,a=Us[r];if(a){if(a.needsConversionIds){const a=s.conversionIds?.[e];if(!a)continue;"google_ads"===r?i.gtag?.("event","conversion",{send_to:`${s.providerId}/${a}`,transaction_id:n,...t}):"x_pixel"===r?i.twq?.("event",a,{...t,conversion_id:n}):"linkedin"===r&&i.lintrk?.("track",{conversion_id:a});continue}switch(r){case"ga4":o.ga4&&i.gtag?.("event",o.ga4,{...t,send_to:s.providerId,event_id:n});break;case"meta_pixel":o.meta&&i.fbq?.("track",o.meta,t,{eventID:n});break;case"tiktok":if(o.tiktok){const e=i.ttq;e?.track?.(o.tiktok,{...t,event_id:n})}break;case"reddit":o.reddit&&i.rdt?.("track",o.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=i.uetq;r?.push?.("event",o.ga4??e,{...t,event_id:n});break}case"clarity":i.clarity?.("event",e);break;case"hotjar":{const t=i.hj;t?.("event",e);break}case"posthog":{const r=i.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":i.plausible?.(e,{props:t})}}}}(e,u,r,X,z),G("event fired:",e,r)):G("event handled by app:",e)},[i,c,X,z,O,G,Y]),re=t.useCallback(async(e,t={})=>{const s=function(e){return{name:"trial_started"===e.kind?"trial_started":"purchase",params:{...e.workspaceId?{workspace_id:e.workspaceId}:{},...e.planVersionId?{plan_version_id:e.planVersionId}:{},...e.creditPackageId?{credit_package_id:e.creditPackageId}:{},...e.billingInterval?{billing_interval:e.billingInterval}:{},...e.currency?{currency:e.currency.toUpperCase()}:{},..."number"==typeof e.value?{value:e.value}:{},...e.sessionId?{transaction_id:e.sessionId}:{}}}}(e);let i=s.params;if(e.sessionId&&n&&r){const t=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 s=await r.json(),i=s?.data??s;return"number"!=typeof i?.amount?null:{value:rs(i.amount,i.currency),currency:"string"==typeof i.currency?i.currency:void 0,...Array.isArray(i.items)&&i.items.length?{items:i.items}:{}}}catch{return null}}({serverUrl:n,orgId:r},e.sessionId);t&&"number"==typeof t.value&&(i={...i,value:t.value,...t.currency?{currency:t.currency.toUpperCase()}:{},...t.items?.length?{items:t.items}:{}})}if(ne(s.name,{...i,...t},{eventId:e.eventId}),"purchase"===s.name&&e.sessionId&&n&&r){const t=(g?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);t&&Ys("ga4",t.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:n,orgId:r},e.sessionId,"ga4")}},[n,r,ne,g]),[se]=t.useState(()=>"undefined"==typeof window?"":window.location.search);t.useEffect(()=>{if(!i||!w)return;if("undefined"==typeof window)return;const e=Xr(window.location.search);if(e)return void re(e);const t=es(se);t&&ne("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,w,re,se,ne]);const ie=t.useCallback((e,t)=>{j.current=e,P(e),ps(e),i&&gs({serverUrl:n,orgId:r,clientId:s,state:e,manifestVersion:V.current?.consent?.manifestVersion,source:t?.source,consentString:t?.consentString,headers:B.current})},[i,n,r,s]),ae=t.useCallback(e=>{B.current={...e}},[]),oe=t.useCallback(e=>{if(!e)return $.current=null,void q(e=>e+1);xs(e).then(e=>{$.current=e.emailHash||e.phoneHash?e:null,q(e=>e+1)})},[]),ce=t.useCallback((e,t)=>{const n=function(e){if(!e)return{traits:e,identity:null};const{email:t,phone:n,...r}=e,s={};return"string"==typeof t&&t&&(s.email=t),"string"==typeof n&&n&&(s.phone=n),{traits:r,identity:s.email||s.phone?s:null}}(t);n.identity&&oe(n.identity),function(e,t,n){const r=qs();if(!r)return;const s=!!n&&Object.keys(n).length>0;for(const i of t)switch(i.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),s&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":i.providerId&&r.fbq?.("init",i.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,s?n:void 0);break;case"clarity":if(r.clarity?.("identify",e),s)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,X,n.traits)},[X,oe]);t.useEffect(()=>{Y&&$.current&&0!==Object.keys(W.current).length&&ks(X,$.current)},[Y,X,M,D]);const le=t.useMemo(()=>({consent:{manifest:g?.consent?.manifest??[],state:N,effective:K,default:H,country:g?.country??null,set:ie},track:ne,setUser:ce,setIdentity:oe,setConsentRecordHeaders:ae,setProperties:R,getProperties:T,completeCheckout:re,installed:{...W.current},ready:w,attribution:O}),[g,N,H,ie,ne,ce,oe,ae,R,T,re,w,D,O]);return e.jsx(ti.Provider,{value:le,children:m})};function ai(){const e=Un(),n=qn(),r=ar();return t.useMemo(()=>({auth:e,os:n,workspaces:r}),[e,n,r])}function oi(e,n){const r=Bn(),s=Tn(),i=or(),a=t.useCallback(e=>{const t=[r.subscribe(e),s.subscribe(e),i.subscribe(e)];return()=>t.forEach(e=>e())},[r,s,i]);return Cn(t.useMemo(()=>{let e=null;return()=>(null!==e&&e.os===r.getState()&&e.auth===s.getState()&&e.workspaces===i.getState()||(e={os:r.getState(),auth:s.getState(),workspaces:i.getState()}),e)},[r,s,i]),a,e,n)}function ci(e,n,r){t.useEffect(()=>{const t=new AbortController;return e(t.signal).catch(e=>{W(e)||(r?.onError?r.onError(e):q(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},n)}function li(){return oi(e=>e.os)}ii.displayName="BuildBaseTracking";const ui=new Map;let di=null;function pi(){const e=ai(),n=li(),{serverUrl:r,version:s,orgId:i,settings:a,settingsStatus:o,settingsError:c}=n,l=t.useMemo(()=>De(n)?new xe({serverUrl:r,version:s,orgId:i}):null,[r,s,i]),u=t.useCallback(async t=>{if(!l)return null;const n=((e,t,n)=>`${e}|${t}|${n}`)(r,s,i);di=n;const a=ui.get(n);if(a)return a;const o=(async()=>{e.os(Fn("loading"));try{const t=await l.getSettings();return di===n&&e.os(On(t)),t}catch(t){return di===n&&e.os(Fn("error",t instanceof Error?t.message:"Failed to load settings")),B(t,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:r,version:s,orgId:i}}),null}finally{ui.delete(n)}})();return ui.set(n,o),o},[l,e,r,s,i]);ci(async()=>{a||De(n)&&await u()},[r,s,i],{onError:e=>B(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:r,version:s,orgId:i}})});const d="loading"===o||("idle"===o||void 0===o)&&De(n);return t.useMemo(()=>({settings:a,loading:d,error:c??null,refetch:u,getSettings:u}),[a,d,c,u])}function hi(){const e=li(),n=ai(),r=t.useCallback(()=>{te(),n.auth(Sn()),e.auth?.callbacks?.onSessionExpired?.("expired")},[n,e.auth?.callbacks?.onSessionExpired]),s=function(e,n){return t.useMemo(()=>new We({...e,onUnauthorized:n}),[e.serverUrl,e.version,e.orgId,n])}(e,r);return t.useMemo(()=>({os:e,api:s}),[e,s])}const mi=e=>{const{t:n}=Cr(),{os:r,api:s}=hi(),i=De(r),[a,o]=t.useState(null),[c,l]=t.useState(!1),[u,d]=t.useState(null),[p,h]=t.useState(null),{begin:m,settle:f}=Pr(),g=t.useCallback(async()=>{if(!e||!i)return m(),o(null),h(null),void l(!1);const t=m();l(!0),d(null);try{const n=await s.getPublicPlans(e);if(t.signal.aborted)return;o(n),h(e)}catch(r){if(t.signal.aborted)return;h(e);const s=V(r,"errors.fetchPlans",n);d(s),q(r,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{f(t)&&l(!1)}},[s,e,i,m,f]);t.useEffect(()=>{g()},[g]);const y=!(!e||i&&p===e),v=y||c;return{items:y?[]:a?.items??[],plans:y?[]:a?.plans??[],notes:y?void 0:a?.notes,loading:v,error:u,refetch:g}},fi=e=>{const{t:n}=Cr(),{os:r,api:s}=hi(),[i,a]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),[d,p]=t.useState(null),{begin:h,settle:m}=Pr(),f=t.useCallback(async()=>{if(!e)return h(),a(null),p(null),void c(!1);const t=h();c(!0),u(null);try{const n=await Nr(`subscription:${r.serverUrl}:${r.orgId}:${e}`,()=>s.getCurrentSubscription(e));if(t.signal.aborted)return;a(n),p(e)}catch(r){if(t.signal.aborted)return;p(e);const s=V(r,"errors.fetchSubscription",n);u(s),q(r,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{m(t)&&c(!1)}},[s,r.serverUrl,r.orgId,e,h,m]);t.useEffect(()=>{f()},[f]),t.useEffect(()=>Qe(f),[f]);const g=!!e&&d!==e;return{subscription:g?null:i,loading:o||g,error:l,refetch:f}},gi=(e,n)=>{const{t:r}=Cr(),{api:s}=hi(),[i,a]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Pr(),h=t.useCallback(async()=>{if(!e)return d(),a(null),void c(!1);const t=d();c(!0),u(null);try{const r=n?await s.getPlanGroupByVersion(e,n):await s.getPlanGroup(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const i=V(s,"errors.fetchPlanGroup",r);u(i),q(s,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:n}})}finally{p(t)&&c(!1)}},[s,e,n,d,p]);return t.useEffect(()=>{h()},[h]),{planGroup:i,loading:o,error:l,refetch:h}},yi=e=>{const{t:n}=Cr(),{api:r}=hi(),{track:s}=ri(),i=si(),[a,o]=t.useState(!1),[c,l]=t.useState(null);return{updateSubscription:t.useCallback(async(t,a)=>{if(!e)throw new Error("Workspace ID is required");o(!0),l(null);try{const n={planVersionId:t,...a?.billingInterval&&{billingInterval:a.billingInterval},...a?.successUrl&&{successUrl:a.successUrl},...a?.cancelUrl&&{cancelUrl:a.cancelUrl}},o=Ps(),c=await r.updateSubscription(e,n),l="checkoutUrl"in c&&c.checkoutUrl?c:null;if(l){const n=l.currency,r=rs(l.amountTotal,n);i&&Gr({eventId:o,workspaceId:e,planVersionId:t,billingInterval:a?.billingInterval,currency:n,sessionId:l.sessionId,value:r,kind:l.trial?"trial_started":"purchase",startedAt:Date.now()}),s("checkout_started",{plan_version_id:t,...a?.billingInterval?{billing_interval:a.billingInterval}:{},...n?{currency:n.toUpperCase()}:{},..."number"==typeof r?{value:r}:{}},{eventId:o})}else if(!c.paymentRequired){const e=c,n=e.invoice?.amount_due;s("subscription_upgraded",{plan_version_id:t,...a?.billingInterval?{billing_interval:a.billingInterval}:{},..."number"==typeof n&&n>0?{value:rs(n,void 0)}:{}},{eventId:o})}return Ze(),c}catch(r){const s=V(r,"errors.updateSubscription",n);throw l(s),q(r,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:t,options:a}}),r}finally{o(!1)}},[r,e,s,i]),loading:a,error:c}},vi=e=>{const{t:n}=Cr(),{os:r,api:s}=hi(),[i,a]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),[d,p]=t.useState(null),{begin:h,settle:m}=Pr(),f=t.useCallback(async()=>{if(!e)return h(),a(null),p(null),void c(!1);const t=h();c(!0),u(null);try{const n=await Nr(`quota-usage:${r.serverUrl}:${r.orgId}:${e}`,()=>s.getAllQuotaUsage(e));if(t.signal.aborted)return;a(n.quotas),p(e)}catch(r){if(t.signal.aborted)return;p(e);const s=V(r,"errors.fetchAllQuotaUsage",n);u(s),q(r,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{m(t)&&c(!1)}},[s,r.serverUrl,r.orgId,e,h,m]);t.useEffect(()=>{f()},[f]),t.useEffect(()=>He(f),[f]);const g=!!e&&d!==e;return{quotas:g?null:i,loading:o||g,error:l,refetch:f}},bi=t.createContext(null);bi.displayName="SubscriptionContext";const wi=t.memo(function({children:n}){const r=oi(e=>e.workspaces.currentWorkspace),{subscription:s,loading:i,error:a,refetch:o}=fi(r?._id),c=t.useMemo(()=>({response:s,loading:i,error:a,refetch:o}),[s,i,a,o]);return e.jsx(bi.Provider,{value:c,children:n})});function xi(){const e=t.useContext(bi);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}wi.displayName="SubscriptionContextProvider";const ki=e=>{const{t:n}=Cr(),{os:r,api:s}=hi(),[i,a]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Pr(),h=t.useCallback(async()=>{if(!e)return d(),a(null),void c(!1);const t=d();c(!0),u(null);try{const n=await Nr(`credit-balance:${r.serverUrl}:${r.orgId}:${e}`,()=>s.getCreditBalance(e));if(t.signal.aborted)return;a(n)}catch(r){if(t.signal.aborted)return;const s=V(r,"errors.fetchCreditBalance",n);u(s),q(r,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{p(t)&&c(!1)}},[s,r.serverUrl,r.orgId,e,d,p]);return t.useEffect(()=>{h()},[h]),t.useEffect(()=>ze(h),[h]),{balance:i,loading:o,error:l,refetch:h}},Si=e=>{const{t:n}=Cr(),{api:r}=hi(),[s,i]=t.useState(!1),[a,o]=t.useState(null);return{consumeCredits:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");i(!0),o(null);try{const n=await r.consumeCredits(e,t);return Ge(),n}catch(r){const s="INSUFFICIENT_CREDITS"===r.code?n("credits.insufficientDetail",{available:r.available,requested:r.requested}):V(r,"errors.consumeCredits",n);throw o(s),q(r,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:t}}),r}finally{i(!1)}},[r,e]),loading:s,error:a}},Ci=e=>{const{t:n}=Cr(),{api:r}=hi(),{track:s,consent:i,getProperties:a}=ri(),o=si(),[c,l]=t.useState(!1),[u,d]=t.useState(null);return{purchaseCredits:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");l(!0),d(null);const c=Ps(),u=o?_s(c,i.effective,a(),Math.min(As(t.metadata),20-Object.keys(t.metadata??{}).length)):{},p=Object.keys(u).length>0?{...t,metadata:{...u,...t.metadata}}:t;try{let n;try{n=await r.purchaseCredits(e,p)}catch(s){const i=s?.status;if(p===t||t.metadata||400!==i)throw s;n=await r.purchaseCredits(e,t)}const i=n.currency??t.currency,a=rs(n.amountTotal,i);return o&&Gr({eventId:c,workspaceId:e,creditPackageId:t.creditPackageId,currency:i,sessionId:n.sessionId,value:a,kind:"purchase",startedAt:Date.now()}),s("checkout_started",{credit_package_id:t.creditPackageId,...i?{currency:i.toUpperCase()}:{},..."number"==typeof a?{value:a}:{}},{eventId:c}),n}catch(r){const s=V(r,"errors.purchaseCredits",n);throw d(s),q(r,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:t}}),r}finally{l(!1)}},[r,e,s,i.effective,o]),loading:c,error:u}},Ii=e=>{const{t:n}=Cr(),{api:r}=hi(),[s,i]=t.useState([]),[a,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Pr(),p=t.useCallback(async()=>{if(!e)return u(),i([]),void o(!1);const t=u();o(!0),l(null);try{const n=await r.getCreditPackages(e);if(t.signal.aborted)return;i(n)}catch(r){if(t.signal.aborted)return;const s=V(r,"errors.fetchCreditPackages",n);l(s),q(r,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{d(t)&&o(!1)}},[r,e,u,d]);return t.useEffect(()=>{p()},[p]),{packages:s,loading:a,error:c,refetch:p}},Ni=()=>{const{t:e}=Cr(),{os:n,api:r}=hi(),s=De(n),[i,a]=t.useState([]),[o,c]=t.useState(),[l,u]=t.useState(!1),[d,p]=t.useState(null),{begin:h,settle:m}=Pr(),f=t.useCallback(async()=>{if(!s)return h(),a([]),void u(!1);const t=h();u(!0),p(null);try{const e=await r.getPublicCreditPackages();if(t.signal.aborted)return;a(e.packages||[]),c(e.notes)}catch(n){if(t.signal.aborted)return;const r=V(n,"errors.fetchCreditPackages",e);p(r),q(n,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{m(t)&&u(!1)}},[r,s,h,m]);t.useEffect(()=>{f()},[f]);return{packages:i,notes:o,loading:!s||l,error:d,refetch:f}},Pi=t.createContext(null);Pi.displayName="CreditBalanceContext";const ji=t.memo(function({children:n}){const r=oi(e=>e.workspaces.currentWorkspace),{balance:s,loading:i,error:a,refetch:o}=ki(r?._id),c=t.useMemo(()=>({balance:s,loading:i,error:a,refetch:o}),[s,i,a,o]);return e.jsx(Pi.Provider,{value:c,children:n})});function Ei(){const e=t.useContext(Pi);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}ji.displayName="CreditBalanceContextProvider";const Ai=({message:t})=>e.jsxs(e.Fragment,{children:[e.jsx("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"}}),e.jsx("p",{"aria-hidden":"true",style:{marginTop:16,color:"hsl(var(--muted-foreground, 215.4 16.3% 46.9%))",fontSize:14},children:t}),e.jsx("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 "})]}),_i=({children:t,message:n,backgroundColor:r})=>{const{t:s}=Cr(),i=n??s("settings.common.loading");return e.jsxs("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:r??void 0},children:[e.jsx("span",{style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:i}),t??e.jsx(Ai,{message:i}),e.jsx("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 "})]})};_i.displayName="FullScreenLoader";const Ui=t.createContext(null),Ti=({children:n,loadingComponent:r})=>{const[s,i]=t.useState({visible:!1,message:""}),a=t.useRef(null),o=t.useCallback(()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]),c=t.useCallback(()=>{o(),i({visible:!1,message:""})},[o]),l=t.useCallback(e=>{o(),i({visible:!0,message:e}),a.current=setTimeout(()=>{q(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),i({visible:!1,message:""})},6e4)},[o]);t.useEffect(()=>()=>o(),[o]);const u=t.useMemo(()=>({show:l,hide:c,visible:s.visible,message:s.message}),[l,c,s.visible,s.message]),d="function"==typeof r?r({message:s.message}):r;return e.jsxs(Ui.Provider,{value:u,children:[n,s.visible&&e.jsx(_i,{message:s.message,children:d})]})};function Ri(){const e=t.useContext(Ui);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}Ti.displayName="FullScreenLoaderProvider";const Oi=t.createContext(null);function Fi(e,t){return e?e.replace(/\{\{(\w+)\}\}/g,(e,n)=>n in t?t[n]:e):e}function Wi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"app"}function Di({mcp:n,children:r}){const s=t.useMemo(()=>n?.url?{...n,url:n.url.replace(/\/+$/,"")}:null,[n]);return e.jsx(Oi.Provider,{value:s,children:r})}function Li(){return t.useContext(Oi)}const $i=t.createContext({appPermissions:void 0});function Mi({appPermissions:n,children:r}){const s=t.useMemo(()=>({appPermissions:n}),[n]);return e.jsx($i.Provider,{value:s,children:r})}function qi(){return t.useContext($i)}const Bi=t.createContext(null);Bi.displayName="QuotaUsageContext";const Vi=t.memo(function({children:n}){const r=oi(e=>e.workspaces.currentWorkspace),{quotas:s,loading:i,error:a,refetch:o}=vi(r?._id),c=t.useMemo(()=>({quotas:s,loading:i,error:a,refetch:o}),[s,i,a,o]);return e.jsx(Bi.Provider,{value:c,children:n})});function zi(){const e=t.useContext(Bi);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}Vi.displayName="QuotaUsageContextProvider";const Gi=t.createContext({});function Ji({ui:n,children:r}){const s=t.useMemo(()=>n??{},[n]);return e.jsx(Gi.Provider,{value:s,children:r})}function Hi(){return t.useContext(Gi)}function Ki(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?Ki(n[e],r):r;return n}let Yi=!1;function Qi(){Yi=!0}const Zi="saas-oauth-state";function Xi(){J(Zi)}function ea(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 ta=new Set;function na(e){return!ta.has(e)&&(ta.add(e),!0)}function ra(e,n,r,s){const{emitOnce:i}=sa(),a=t.useRef(s);a.current=s,t.useEffect(()=>{e&&i(n,r,a.current)},[e,n,r,i])}function sa(){const{track:e,ready:n}=ri(),r=t.useCallback((t,n)=>{try{e(t,ea(n))}catch{}},[e]),s=t.useCallback((e,t,s)=>{n&&na(`${t}|${e}`)&&r(t,s)},[r,n]);return{emit:r,emitOnce:s,ready:n}}const ia={rows:[],loading:!1,error:null,fetchedAt:0};class aa{constructor(){this.snapshot=ia,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:ln(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=ia;for(const e of this.listeners)e()}}const oa=new Map;function ca(e){const t=e||"unscoped";let n=oa.get(t);return n||(n=new aa,oa.set(t,n)),n}const la={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"},ua=new Set(Object.values(la));const da=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:la.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||la.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)})}},pa=t.createContext(null);pa.displayName="WorkspaceActionsContext";const ha=({children:n})=>{const r=ai(),{os:s,api:i}=hi(),{settings:a}=pi(),{t:o}=Cr(),c=t.useRef(o);t.useEffect(()=>{c.current=o},[o]);const l=oi(e=>e.workspaces),u=oi(e=>e.auth.session?.user),d=t.useRef(!1),p=t.useRef(!1),h=t.useRef(0),m=t.useCallback((e,t)=>{if((!(e._id===l.currentWorkspace?._id)||t?.forceEmit)&&e){const t=l.currentWorkspace;qt(e),r.workspaces(Kn(e)),Me.emitWorkspaceChanged(e,t).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceChanged",metadata:{workspaceId:e._id}})})}},[l.currentWorkspace,r]),f=t.useCallback(async(e,t)=>{const n=++h.current;r.workspaces(tr(e._id));try{const r=s.auth?.callbacks?.onWorkspaceChange;if(r){const t=Jt(e,u?.id);try{await r({workspace:e,user:u??null,role:t})}catch(t){throw q(t,{component:"WorkspaceProvider",action:"onWorkspaceChange",metadata:{workspaceId:e._id}}),t}if(n!==h.current)return}m(e,t)}finally{n===h.current&&r.workspaces(tr(null))}},[r,s.auth?.callbacks?.onWorkspaceChange,m,u]),g=t.useRef(f);g.current=f,t.useEffect(()=>{if(!l.isInitialized){const e=Bt();if(r.workspaces(Qn(!0)),e){const t=l.workspaces.find(t=>t._id===e);t&&g.current(t,{forceEmit:!0}).catch(t=>{q(t,{component:"WorkspaceProvider",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:e}})})}}},[l.isInitialized,l.workspaces,r]);const y=t.useCallback(()=>{Vt(),r.workspaces(Yn())},[r]),v=t.useCallback(async()=>{if(!l.loading&&!d.current){d.current=!0,r.workspaces(Zn(!0)),r.workspaces(Xn(null));try{const e=await i.getWorkspaces();if(r.workspaces(Vn(e)),e.length>0){const t=Bt();if(t&&zt(t,e)){const n=e.find(e=>e._id===t);if(n)try{await f(n,{forceEmit:!0})}catch{}}else{const t=e[0];try{await f(t,{forceEmit:!0})}catch{}}}}catch(e){r.workspaces(Xn(V(e,"errors.fetchWorkspaces",c.current)))}finally{r.workspaces(Zn(!1)),d.current=!1}}},[i,l.loading,r,f]),b=t.useCallback(async()=>{if(!l.refreshing&&!d.current){d.current=!0,r.workspaces(er(!0));try{const e=await i.getWorkspaces();r.workspaces(Vn(e))}catch(e){}finally{r.workspaces(er(!1)),d.current=!1}}},[i,l.refreshing,r]),w=t.useRef(null);t.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const x=t.useCallback(async(e,t)=>{const n=Mr(),s=await i.createWorkspace({name:e,...t?{image:t}:{},...n?{trackingAttribution:n}:{}});r.workspaces(zn(s)),await f(s),Me.emitWorkspaceCreated(s).catch(e=>{q(e,{component:"WorkspaceProvider",action:"emitWorkspaceCreated",metadata:{workspaceId:s._id}})}),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{w.current=null,da.openWorkspaceSettings(la.Subscription)},300)},[i,r,f]),k=t.useCallback(async(e,t)=>{const n=await i.updateWorkspace(e._id,t);r.workspaces(Gn(n)),Me.emitWorkspaceUpdated(n).catch(e=>{q(e,{component:"WorkspaceProvider",action:"emitWorkspaceUpdated",metadata:{workspaceId:n._id}})})},[i,r]),S=t.useCallback(async()=>{if(p.current)return l.allFeatures.length>0?l.allFeatures:null;if(l.allFeatures.length>0)return l.allFeatures;p.current=!0;try{const e=await i.getFeatures();return r.workspaces(Hn(e)),e}catch(e){return q(e,{component:"WorkspaceProvider",action:"getFeatures"}),null}finally{p.current=!1}},[i,r,l.allFeatures]),C=t.useCallback(async(e,t,n)=>await i.updateFeature(e,t,n),[i]),I=t.useCallback(async e=>i.updateSettings(e),[i]),N=t.useCallback(async(e,t)=>{const n=await i.updateWorkspacePermissions(e,t);return await b(),n},[i,b]);t.useEffect(()=>{if(!l.currentWorkspace?._id||0===l.workspaces.length)return;const e=l.currentWorkspace._id,t=l.workspaces.find(t=>t._id===e);if(t)t!==l.currentWorkspace&&(qt(t),r.workspaces(Kn(t)));else if(l.workspaces.length>0){const t=l.workspaces[0];t._id!==e&&f(t).catch(e=>{q(e,{component:"WorkspaceProvider",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:t._id}})})}},[l.workspaces,l.currentWorkspace,r,f]);const P=t.useCallback(async e=>await i.getWorkspaceUsers(e),[i]),j=t.useCallback(async(e,t,n)=>{const r=l.workspaces.find(t=>t._id===e);if(r){const e=Lt({settingsMaxUsers:a?.workspace?.maxWorkspaceUsers}),t=$t({memberCount:r.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessageKey||"users.memberLimitReached")}const s=await i.addUser(e,{email:t,role:n});return r&&Me.emitWorkspaceUserAdded(s.userId,r,n).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:s.userId,role:n}})}),b().catch(e=>{q(e,{component:"WorkspaceProvider",action:"refreshAfterAddUser"})}),Ze(),s},[i,l.workspaces,b,a]),E=t.useCallback(async(e,t)=>{const n=l.workspaces.find(t=>t._id===e);if(n&&Gt(n,t))throw new Error("Cannot remove the workspace owner");const r=(await i.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),s=await i.removeUser(e,t);if(n&&r){const t=r.role;Me.emitWorkspaceUserRemoved(s.userId,n,t).catch(n=>{q(n,{component:"WorkspaceProvider",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:s.userId,role:t}})})}return b().catch(e=>{q(e,{component:"WorkspaceProvider",action:"refreshAfterRemoveUser"})}),Ze(),s},[i,l.workspaces,b]),A=t.useCallback(async(e,t,n)=>{if(n.role){const n=l.workspaces.find(t=>t._id===e);if(n&&Gt(n,t))throw new Error("Cannot change the role of the workspace owner")}let r;if(n.role){const n=(await i.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);r=n?.role}const s=await i.updateUser(e,t,n);return n.role&&r&&r!==n.role&&Me.emitWorkspaceUserRoleChanged(s.userId,s.workspace,r,n.role).catch(s=>{q(s,{component:"WorkspaceProvider",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:r,newRole:n.role}})}),s},[i,l.workspaces]),_=t.useCallback(async e=>{const t=await i.getProfile().catch(()=>null),n=await i.updateUserProfile(e);return Me.emitUserUpdated(n,t||void 0).catch(e=>{q(e,{component:"WorkspaceProvider",action:"emitUserUpdated",metadata:{userId:n._id}})}),n},[i]),U=t.useCallback(async()=>await i.getProfile(),[i]),T=t.useCallback(async e=>await i.getWorkspace(e),[i]),R=t.useCallback(async e=>{if(!u)throw new Error("User must be authenticated to delete a workspace");const t=l.workspaces.find(t=>t._id===e);if(!t)throw new Error("Workspace not found");if(!Gt(t,u.id))throw new Error("Only the workspace creator can delete the workspace");const n=await i.deleteWorkspace(e);return r.workspaces(Jn(e)),l.currentWorkspace?._id===e&&(Vt(),r.workspaces(Yn())),t&&Me.emitWorkspaceDeleted(t).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceDeleted",metadata:{workspaceId:e}})}),n},[i,l.workspaces,l.currentWorkspace,r,u]),O=t.useCallback(e=>i.listInvitations(e),[i]),F=t.useCallback(async(e,t,n,r)=>{const s=await i.inviteMember(e,{email:t,role:n,landingUrl:r?.landingUrl});return Me.emitWorkspaceInvitationSent(s,e).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationSent",metadata:{workspaceId:e,invitationId:s._id}})}),Ze(),s},[i]),W=t.useCallback(async(e,t)=>{const n=await i.resendInvitation(e,t);return Ze(),n},[i]),D=t.useCallback(async(e,t)=>{await i.revokeInvitation(e,t),Me.emitWorkspaceInvitationRevoked(t,e).catch(n=>{q(n,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationRevoked",metadata:{workspaceId:e,invitationId:t}})}),Ze()},[i]),L=t.useCallback(()=>i.myInvitations(),[i]),$=t.useCallback(async(e,t)=>{const n=await i.acceptInvitation(e,t),a=n.workspace;a&&!l.workspaces.some(e=>e._id===a._id)&&r.workspaces(zn(a)),b().catch(e=>{q(e,{component:"WorkspaceProvider",action:"refreshAfterAccept"})}),n.workspace&&Me.emitWorkspaceInvitationAccepted(n.invitation,n.workspace).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationAccepted",metadata:{invitationId:e}})});const o=n.workspace;return u?.id&&o&&Me.emitWorkspaceUserAdded(u.id,o,n.invitation.role).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:o._id,invitationId:e}})}),Ze(),ca(s.orgId??"").remove(e),{invitation:n.invitation,workspace:n.workspace}},[i,b,u?.id,s.orgId,l.workspaces,r]),M=t.useCallback(async e=>{const{invitation:t}=await i.declineInvitation(e);return Me.emitWorkspaceInvitationDeclined(t).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationDeclined",metadata:{invitationId:e}})}),ca(s.orgId??"").remove(e),t},[i,s.orgId]),B=t.useCallback(e=>i.previewInvitation(e),[i]),z=t.useMemo(()=>({fetchWorkspaces:v,refreshWorkspaces:b,setCurrentWorkspace:m,switchToWorkspace:f,resetCurrentWorkspace:y,createWorkspace:x,updateWorkspace:k,deleteWorkspace:R,getWorkspace:T,getUsers:P,addUser:j,removeUser:E,updateUser:A,getProfile:U,updateUserProfile:_,getFeatures:S,updateFeature:C,updateWorkspaceSettings:I,updateWorkspacePermissions:N,listInvitations:O,inviteMember:F,resendInvitation:W,revokeInvitation:D,myInvitations:L,acceptInvitation:$,declineInvitation:M,previewInvitation:B}),[v,b,m,f,y,x,k,R,T,P,j,E,A,U,_,S,C,I,N,O,F,W,D,L,$,M,B]);return e.jsx(pa.Provider,{value:z,children:n})};ha.displayName="WorkspaceProviderInner";const ma=({children:n})=>t.useContext(pa)?e.jsx(e.Fragment,{children:n}):e.jsx(ha,{children:n});ma.displayName="WorkspaceProvider";const fa=()=>{const e=t.useContext(pa);if(!e)throw new Error("useSaaSWorkspaces must be used within a WorkspaceProvider. Make sure SaaSOSProvider is wrapping your application.");const n=oi(e=>e.workspaces);return t.useMemo(()=>({workspaces:n.workspaces,loading:n.loading,error:n.error,refreshing:n.refreshing,currentWorkspace:n.currentWorkspace,allFeatures:n.allFeatures,switching:null!==n.switchingToId,switchingToId:n.switchingToId,...e}),[n,e])};function ga(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 ya(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function va(){return oi(e=>e.auth)}function ba(){const{t:e}=Cr(),n=ai(),r=va(),s=li(),{serverUrl:i,orgId:a,auth:o}=s,{resetCurrentWorkspace:c,currentWorkspace:l}=fa(),u=Ri(),{consent:d}=ri(),{emit:p}=sa(),h=t.useMemo(()=>new de({serverUrl:i,version:s.version}),[i,s.version]),m=t.useCallback(async t=>{mt(t||window.location.href),p("sign_in_started",{from_path:window.location.pathname}),n.auth(bn()),u.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 G(Zi,t),t}(),{redirectUrl:t}=await h.requestAuth({orgId:a,clientId:o?.clientId??"",redirect:{success:o?.redirectUrl||window.location.href,error:o?.redirectUrl||window.location.href},state:e,...d.state?{trackingConsent:{analytics:!!d.state.analytics,marketing:!!d.state.marketing}}:{},...(()=>{const e=function(){const e=Ss(),t=Object.keys(e).find(e=>e.startsWith("_ga_")),n={},r=Cs(e._ga);r&&(n.gaClientId=r);const s=t?Is(e[t]):void 0;return s&&(n.gaSessionId=s),n}();return Object.keys(e).length?{trackingIdentity:e}:{}})(),...(()=>{const e=Mr();return e?{trackingAttribution:e}:{}})(),...(()=>{const e=gn(a);return e?{invitationToken:e}:{}})()});dt(t)}catch(e){throw u.hide(),n.auth(xn()),q(e,{component:"useSaaSAuth",action:"signIn"}),e}},[h,a,o,n,u,e,d.state,p]),f=t.useCallback(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=>h.logout(ne()??void 0,e),clearLocal:()=>{te(),n.auth(Sn()),c()},onError:e=>q(e,{component:"useSaaSAuth",action:"signOut"})},e),[h,n,c,o?.callbacks?.onSignOut]),g=t.useCallback(e=>{l?da.openWorkspaceSettings(e):q(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),y=t.useCallback(()=>{l?da.openWorkspaceSettings(la.Credits,{action:et.OpenCreditStore}):q(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),v=t.useCallback(()=>{l?da.openWorkspaceSettings(la.Subscription,{action:et.SelectPlan}):q(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),b=t.useMemo(()=>sn(r.status),[r.status]);return t.useMemo(()=>({user:r.session?.user,session:r.session,status:r.status,...b,signIn:m,signOut:f,openWorkspaceSettings:g,openCreditStore:y,openPlanPicker:v}),[r.session,r.status,b,m,f,g,y,v])}const wa=t.memo(({children:n,callbacks:r})=>{const{t:s}=Cr(),i=ai(),a=va(),o=li(),c=sn(a.status).isAuthenticated,l=Ri(),u=t.useRef(!1),d=t.useRef(null),p=t.useRef(!1),h=t.useRef(null),m=t.useCallback(async e=>{try{if(r?.handleAuthentication){l.show(s("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=o;if(!De(n))throw new Error("OS configuration is not available");const{serverUrl:a,version:c,orgId:u}=n;l.show(s("loading.verifyingAccount"));const d=new de({serverUrl:a,version:c}),p=await d.getProfile(t),h=ya(ga(p,u,n.auth?.clientId||""),t);l.show(s("loading.almostThere")),ee(h.sessionId),d.getDeviceToken(h.sessionId).then(e=>e&&re(e)).catch(()=>{}),ae();const m=ft(),f=!!m&&m!==window.location.href;f&&Qi(),i.auth(kn(h)),f&&dt(m),l.hide()}}catch(t){throw l.hide(),ft(),q(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),i.auth(xn()),t}},[i,r,o,l,s]);return t.useEffect(()=>{if("undefined"==typeof window)return;if(c)return;if(p.current)return;if(h.current)return;if(!De(o))return;if(ie())return;if(!r?.getSession)return p.current=!0,void i.auth(xn());const e=r.getSession,{serverUrl:t,version:n,orgId:a}=o,u=o.auth?.clientId||"";h.current=(async()=>{l.show(s("loading.restoringSession"));let o=null;try{o=await e()}catch(e){q(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!o)return te(),p.current=!0,i.auth(xn()),l.hide(),"undefined"!=typeof window&&mt(window.location.href),void r?.onSessionExpired?.("missing");try{l.show(s("loading.verifyingAccount"));const e=new de({serverUrl:t,version:n}),r=await e.getProfile(o),c=ya(ga(r,a,u),o);ee(c.sessionId),e.getDeviceToken(c.sessionId).then(e=>e&&re(e)).catch(()=>{}),p.current=!0;const d=ft(),h=!!d&&d!==window.location.href;h&&Qi(),i.auth(kn(c)),l.hide(),h&&dt(d)}catch(e){q(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),te(),p.current=!0,i.auth(xn()),l.hide(),"undefined"!=typeof window&&mt(window.location.href),r?.onSessionExpired?.("expired")}finally{h.current=null}})()},[c,i,o,r]),t.useEffect(()=>{const e=ie();if(!e)return;if(u.current||d.current===e)return;if(!De(o))return;const t=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(X)}catch(e){return q(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:X}}),null}}();if(t&&!function(e){if(!e)return!1;const t=z(Zi);if(J(Zi),!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 Xi(),ae(),q(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void i.auth(xn());Xi(),u.current=!0,d.current=e;let n=!1;return i.auth(wn()),m(e).then(()=>{n||(d.current=null)}).catch(e=>{n||(q(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),ae(),d.current=null)}).finally(()=>{u.current=!1}),()=>{n=!0}},[m,o.serverUrl,o.version,o.orgId]),e.jsx(e.Fragment,{children:n})});wa.displayName="AuthProviderWrapper";const xa=t.memo(({config:n,auth:r,children:s})=>{const i=ai();li();const a=t.useRef(r?.callbacks);a.current=r?.callbacks;const o=Object.keys(r?.callbacks??{}).sort().join(","),c=t.useMemo(()=>{if(!o)return;const e={};for(const t of o.split(","))e[t]=(...e)=>{const n=a.current;return n?.[t]?.(...e)};return e},[o]),l=t.useMemo(()=>({clientId:r?.clientId||"",redirectUrl:r?.redirectUrl||"",callbacks:c}),[r?.clientId,r?.redirectUrl,c]);return t.useEffect(()=>{i.os(Rn({...n,auth:l}))},[n,l,i]),e.jsx(e.Fragment,{children:s})});xa.displayName="ContextConfigProvider";const ka=t.createContext({container:null,setContainer:()=>{}}),Sa=t.memo(({children:n})=>{const[r,s]=t.useState(null),i=t.useMemo(()=>({container:r,setContainer:s}),[r]);return e.jsxs(ka.Provider,{value:i,children:[n,e.jsx("div",{ref:s,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});Sa.displayName="PortalProvider";const Ca=t.createContext(null);function Ia(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 Na=t.memo(function({children:n,serviceWorkerPath:r="/push-sw.js",autoSubscribe:s=!1}){const{t:i}=Cr(),a=li(),{isAuthenticated:o}=ba(),c=t.useMemo(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=t.useMemo(()=>new be({serverUrl:a.serverUrl,version:a.version,orgId:a.orgId}),[a.serverUrl,a.version,a.orgId]),[u,d]=t.useState({permission:c?Notification.permission:"default",isSubscribed:!1,isSupported:c,loading:!1,error:null});t.useEffect(()=>{if(!o||!c)return;let e=!1;return(async()=>{try{const t=await navigator.serviceWorker.getRegistration(r);if(e)return;if(!t)return void d(e=>({...e,isSubscribed:!1}));const n=await t.pushManager.getSubscription();if(e)return;d(e=>({...e,isSubscribed:!!n,permission:Notification.permission}))}catch{e||d(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[o,c,r]);const p=t.useCallback(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return d(t=>({...t,permission:e})),"granted"===e},[c]),h=t.useCallback(async()=>{if(c&&o){d(e=>({...e,loading:!0,error:null}));try{if(!await p())return void d(e=>({...e,loading:!1,error:i("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(r);await navigator.serviceWorker.ready;const n=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Ia(e)})).toJSON();await l.subscribe({endpoint:n.endpoint,keys:{p256dh:n.keys.p256dh,auth:n.keys.auth}},navigator.userAgent),d(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:i("push.failedToSubscribe");d(e=>({...e,loading:!1,error:t})),q(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,o,l,r,p]),m=t.useCallback(async()=>{if(c){d(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(r);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}d(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:i("push.failedToUnsubscribe");d(e=>({...e,loading:!1,error:t})),q(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,r]),f=t.useMemo(()=>({...u,requestPermission:p,subscribe:h,unsubscribe:m}),[u,p,h,m]);return e.jsx(Ca.Provider,{value:f,children:n})});const Pa="bb_seen_users",ja=12e4;function Ea(){try{const e=window.localStorage.getItem(Pa),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function Aa(e,t,n=Date.now()){if(!e)return"login";if("undefined"==typeof window)return"login";if(Ea().includes(e))return"login";if(function(e){try{const t=[e,...Ea().filter(t=>t!==e)].slice(0,20);window.localStorage.setItem(Pa,JSON.stringify(t))}catch{}}(e),!t)return"login";const r=Date.parse(t);return Number.isNaN(r)||r>n||n-r>ja||function(e){try{const t=window.document?.cookie;return"string"==typeof t&&t.split("; ").includes(`${_a}=${e}`)}catch{return!1}}(e)?"login":(function(e){try{const t=window.document;if(!t||!Ua.test(e))return;const n=Ur(window.location?.hostname??"",t);t.cookie=`${_a}=${e}; path=/; max-age=120; SameSite=Lax`+(n?`; domain=${n}`:"")}catch{}}(e),"sign_up")}const _a="bb_su",Ua=/^[\w-]{1,64}$/;const Ta="bb_announced_session";const Ra={[Le.UserCreated]:"user_created",[Le.UserUpdated]:"user_updated",[Le.WorkspaceCreated]:"workspace_created",[Le.WorkspaceUpdated]:"workspace_updated",[Le.WorkspaceChanged]:"workspace_switched",[Le.WorkspaceDeleted]:"workspace_deleted",[Le.WorkspaceUserAdded]:"workspace_member_added",[Le.WorkspaceUserRemoved]:"workspace_member_removed",[Le.WorkspaceUserRoleChanged]:"workspace_member_role_changed",[Le.WorkspaceInvitationSent]:"workspace_invitation_sent",[Le.WorkspaceInvitationAccepted]:"workspace_invitation_accepted",[Le.WorkspaceInvitationDeclined]:"workspace_invitation_declined",[Le.WorkspaceInvitationRevoked]:"workspace_invitation_revoked"};const Oa=Object.keys(Ra),Fa="undefined"==typeof window?t.useEffect:t.useLayoutEffect;function Wa({children:n}){const{track:r,setUser:s,setProperties:i,ready:a,setIdentity:o,setConsentRecordHeaders:c}=ri(),l=va().session,u=l?.user?.id,d=l?.sessionId,p=l?.user?.email;t.useEffect(()=>{c(d?{"x-session-id":d}:{})},[d,c]),t.useEffect(()=>{o(p?{email:p}:null)},[p,o]);const{currentWorkspace:h}=fa(),{response:m,loading:f}=xi(),g=t.useMemo(()=>function(e){const{workspace:t,userId:n,subscription:r,subscriptionLoading:s}=e,i={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 i;const a=Array.isArray(t.users)?t.users.length:void 0,o=s?void 0:r?.subscription?r.plan?.slug??void 0:"none";return{workspace_id:String(t._id),workspace_role:Jt(t,n)??void 0,workspace_owner:n?Gt(t,n):void 0,workspace_member_count:a,workspace_plan:o,subscription_status:s?void 0:r?.subscription?.subscriptionStatus??"none"}}({workspace:u?h:null,userId:u,subscription:m,subscriptionLoading:f}),[h,u,m,f]),y=JSON.stringify(g),v=t.useRef(null);Fa(()=>{v.current!==y&&(v.current=y,i(g))},[y,i]);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}(g),w=JSON.stringify(b),x=t.useRef(null);t.useEffect(()=>{if(!a||!u||0===Object.keys(b).length)return;const e=`${u}|${w}`;x.current!==e&&(x.current=e,s(u,b))},[a,u,w,s]),t.useEffect(()=>{a&&u&&d&&(Yi||function(e){if(!e)return!1;if("undefined"==typeof window)return!1;try{return window.localStorage.getItem(Ta)!==e&&(window.localStorage.setItem(Ta,e),!0)}catch{return!0}}(d)&&(s(u),r(Aa(u,l?.user?.firstAuthAt),{method:"buildbase"})))},[a,u,d,l?.user?.firstAuthAt,r,s]),t.useEffect(()=>{const e=Oa.map(e=>Me.on(e,t=>{(function(e,t){if(e!==Le.WorkspaceChanged)return!0;const n=t,r=n.workspace?._id,s=n.previousWorkspace?._id;return!!r&&!!s&&r!==s})(e,t)&&r(Ra[e],function(e,t){const n=t,r={},s=n.workspace;s?._id&&(r.workspace_id=s._id);const i=n.previousWorkspace;i?._id&&(r.previous_workspace_id=i._id);const a=n.user;(a?._id||a?.id)&&(r.user_id=a._id??a.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 k=t.useRef(a);k.current=a;const S=t.useRef([]);return t.useEffect(()=>M.subscribe((e,t)=>{if(!na(`sdk_error|${`${t.component??"unknown"}|${t.action??"unknown"}`}`))return;const n=ea({component:t.component,action:t.action,code:e.code});k.current?r("sdk_error",n):S.current.length<20&&S.current.push(n)}),[r]),t.useEffect(()=>{if(!a||0===S.current.length)return;const e=S.current;S.current=[],e.forEach(e=>r("sdk_error",e))},[a,r]),e.jsx(e.Fragment,{children:n})}Wa.displayName="TrackingBridge";const Da=t.createContext(void 0),La=t.memo(({children:n})=>{const{t:r}=Cr(),s=li(),i=function(){const e=li();return t.useMemo(()=>new Ae(e),[e.serverUrl,e.version])}(),{isAuthenticated:a}=ba(),{serverUrl:o,version:c}=s,[l,u]=t.useState({}),[d,p]=t.useState({}),[h,m]=t.useState(!1),[f,g]=t.useState(!1),[y,v]=t.useState(null),[b,w]=t.useState(null),x=t.useCallback(async e=>{if(o&&c&&a){v(null);try{const t=await i.getAttributes(e);u(t)}catch(e){if(W(e))return;const t=e instanceof Error?e:new Error(r("errors.generic"));v(t),q(e,{component:"UserProvider",action:"fetchAttributes"})}}else u({})},[i,o,c,a,r]),k=t.useCallback(async()=>{if(o&&c&&a){m(!0);try{await x()}finally{m(!1)}}},[o,c,a,x]),S=t.useCallback(async e=>{m(!0),v(null);try{const t=await i.updateAttributes(e);return await x(),t}catch(t){const n=t instanceof Error?t:new Error(r("errors.generic"));throw v(n),q(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{m(!1)}},[i,x,r]),C=t.useCallback(async(e,t)=>{m(!0),v(null);try{const n=await i.updateAttribute(e,t);return await x(),n}catch(n){const s=n instanceof Error?n:new Error(r("errors.generic"));throw v(s),q(n,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),n}finally{m(!1)}},[i,x,r]),I=t.useCallback(async e=>{if(o&&c&&a){w(null);try{const t=await i.getFeatures(e);p(t)}catch(e){if(W(e))return;const t=e instanceof Error?e:new Error(r("errors.generic"));w(t),q(e,{component:"UserProvider",action:"fetchFeatures"})}}else p({})},[i,o,c,a,r]),N=t.useCallback(async()=>{if(o&&c&&a){g(!0);try{await I()}finally{g(!1)}}},[o,c,a,I]);ci(async e=>{if(!a||!o||!c)return u({}),void p({});m(!0),g(!0),await Promise.all([x(e).finally(()=>m(!1)),I(e).finally(()=>g(!1))])},[a,o,c,x,I],{onError:e=>q(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const P=t.useMemo(()=>({attributes:l,features:d,isLoading:h||f,error:y??b,attributesLoading:h,featuresLoading:f,attributesError:y,featuresError:b,updateAttributes:S,updateAttribute:C,refreshAttributes:k,refreshFeatures:N}),[l,d,h,f,y,b,S,C,k,N]);return e.jsx(Da.Provider,{value:P,children:n})});La.displayName="UserProvider";const $a=a.cva("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"}}),Ma=k.forwardRef(({className:t,variant:n,progress:r,size:s,startIcon:a,endIcon:c,asChild:l=!1,...u},d)=>{const p=l?i.Slot:"button",h=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(s);return e.jsxs(p,{disabled:r||u.disabled,className:U($a({variant:n,size:s,withIcon:null!=r||null!=a||null!=c,className:t})),ref:d,...u,children:[r&&e.jsx(o.Loader2,{size:h,className:"animate-spin"}),a&&k.cloneElement(a,{size:h}),u.children,c&&k.cloneElement(c,{size:h})]})});Ma.displayName="Button";const qa=S.Root,Ba=S.Trigger,Va=S.Portal,za=k.forwardRef(({className:t,...n},r)=>e.jsx(S.Overlay,{ref:r,className:U("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",t),...n}));za.displayName=S.Overlay.displayName;const Ga=k.forwardRef(({className:t,children:n,...r},s)=>{const{container:i}=k.useContext(ka),{t:a}=Cr();return e.jsxs(Va,{container:i,children:[e.jsx(za,{}),e.jsxs(S.Content,{ref:s,className:U("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",t),...r,children:[n,e.jsxs(S.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:[e.jsx(l.Cross2Icon,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:a("settings.common.close")})]})]})]})});Ga.displayName=S.Content.displayName;const Ja=({className:t,...n})=>e.jsx("div",{className:U("flex flex-col space-y-1.5 text-center sm:text-start",t),...n});Ja.displayName="DialogHeader";const Ha=({className:t,...n})=>e.jsx("div",{className:U("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...n});Ha.displayName="DialogFooter";const Ka=k.forwardRef(({className:t,...n},r)=>e.jsx(S.Title,{ref:r,className:U("text-lg font-semibold leading-none tracking-tight",t),...n}));Ka.displayName=S.Title.displayName;const Ya=k.forwardRef(({className:t,...n},r)=>e.jsx(S.Description,{ref:r,className:U("text-sm text-muted-foreground",t),...n}));Ya.displayName=S.Description.displayName;const Qa={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 Za({variant:t,title:n,message:r,description:s,icon:i,actionLabel:a,onAction:o,actionDisabled:c,className:l}){const u=Qa[t];return e.jsxs("div",{role:"error"===t?"alert":"status","aria-live":"error"===t?"assertive":"polite","aria-atomic":"true",className:U("border px-4 py-3 rounded-lg flex items-start justify-between gap-2 sm:gap-4",u.box,l),children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[i,e.jsxs("div",{className:"min-w-0",children:[n&&e.jsx("p",{className:"text-sm font-medium",children:n}),r&&e.jsx("p",{className:U("text-sm",n&&"mt-1"),children:r}),s&&e.jsx("p",{className:U("text-xs mt-2",u.sub),children:s})]})]}),a&&e.jsx(Ma,{variant:"outline",size:"sm",onClick:o,disabled:c,className:U("flex-shrink-0",u.button),children:a})]})}const Xa=new Set(["alreadyAccepted","expired","revoked","accepted","declined","disabled"]),eo=new Set(["expired","revoked","disabled"]),to=new Set(["accepted"]),no=new Set(["alreadyAccepted","expired","revoked","declined"]);function ro(){const{t:n}=Cr(),r=li(),{isAuthenticated:s,isLoading:i,signIn:a,signOut:o}=ba(),{previewInvitation:c,acceptInvitation:l,declineInvitation:u,switchToWorkspace:d}=fa(),p=r.orgId??"",[h,m]=t.useState(null),[f,g]=t.useState(null),[y,v]=t.useState({kind:"none"}),[b,w]=t.useState(!1),x=t.useRef(!1),k=Xa.has(y.kind),S="accepted"===y.kind?n("invitations.titleJoined",{workspace:y.workspace}):eo.has(y.kind)?n("invitations.titleUnavailable"):n("invitations.title"),C="wrongAccount"===y.kind,I=t.useCallback(e=>{v(e),Xa.has(e.kind)&&yn()},[]);t.useEffect(()=>{if(x.current||!p)return;x.current=!0;const e=it();e?.action===et.Invite&&e.token&&(fn(e.token,p),at(),m(e.token))},[p]),t.useEffect(()=>{if(!p||h||i)return;const e=gn(p);e&&m(e)},[p,h,i,s]),t.useEffect(()=>{if(!h)return;let e=!1;return g(null),v({kind:"none"}),c(h).then(t=>{e||(g(t),"accepted"===t.status?I({kind:"alreadyAccepted"}):"expired"===t.status?I({kind:"expired",inviter:t.inviterName}):"rejected"===t.status?I({kind:"revoked"}):!1===t.joinable&&I({kind:"disabled"}))}).catch(t=>{e||(q(t,{component:"InvitationLanding",action:"preview"}),Fe(t)&&404===t.status?I({kind:"revoked"}):v({kind:"loadFailed"}))}),()=>{e=!0}},[h,c,I]);const N=t.useCallback(()=>{yn(),m(null),g(null),v({kind:"none"})},[]);if(!h)return null;const P=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}}(y,n),j=to.has(y.kind)?"success":no.has(y.kind)?"info":"error";return e.jsx(qa,{open:!0,onOpenChange:e=>!e&&N(),children:e.jsxs(Ga,{className:"sm:max-w-md",children:[e.jsxs(Ja,{children:[e.jsx(Ka,{children:S}),f&&e.jsx(Ya,{children:n("invitations.description",{inviter:f.inviterName,workspace:f.workspaceName,role:f.role})})]}),f&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n("invitations.sentTo",{email:f.email})}),P&&e.jsx(Za,{variant:j,message:P}),e.jsx(Ha,{className:"gap-2 sm:gap-2",children:k?e.jsx(Ma,{onClick:N,children:n("invitations.dismiss")}):C?e.jsxs(e.Fragment,{children:[e.jsx(Ma,{variant:"outline",onClick:N,children:n("invitations.dismiss")}),e.jsx(Ma,{onClick:()=>{o().then(()=>v({kind:"none"})).catch(e=>q(e,{component:"InvitationLanding",action:"signOut"}))},children:n("invitations.signOut")})]}):f?i?null:s?e.jsxs(e.Fragment,{children:[e.jsx(Ma,{variant:"outline",disabled:b,onClick:async()=>{if(f){w(!0),v({kind:"none"});try{await u(f.id),I({kind:"declined"})}catch(e){q(e,{component:"InvitationLanding",action:"decline"}),Fe(e)&&e.code===_e.EMAIL_MISMATCH?v({kind:"wrongAccount",email:e.invitedEmail??f.email}):Fe(e)&&e.code===_e.ALREADY_HANDLED?I("accepted"===e.invitationStatus?{kind:"alreadyAccepted"}:{kind:"revoked"}):v({kind:"declineFailed"})}finally{w(!1)}}},children:n("invitations.decline")}),e.jsx(Ma,{progress:b,onClick:async()=>{if(f){w(!0),v({kind:"none"});try{const{workspace:e}=await l(f.id,{token:h??void 0});I({kind:"accepted",workspace:f.workspaceName}),e&&await d(e)}catch(e){if(q(e,{component:"InvitationLanding",action:"accept"}),Fe(e))switch(e.code){case _e.EMAIL_NOT_VERIFIED:v({kind:"verifyFirst"});break;case _e.EMAIL_MISMATCH:v({kind:"wrongAccount",email:e.invitedEmail??f.email});break;case _e.SEAT_LIMIT:v({kind:"workspaceFull"});break;case _e.INVITES_DISABLED:I({kind:"disabled"});break;case _e.EXPIRED:I({kind:"expired",inviter:f.inviterName});break;case _e.ALREADY_HANDLED:case _e.NOT_FOUND:I("accepted"===e.invitationStatus?{kind:"alreadyAccepted"}:{kind:"revoked"});break;default:v({kind:"raw",message:e.message})}else v({kind:"acceptFailed"})}finally{w(!1)}}},children:n("invitations.accept")})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ma,{variant:"outline",onClick:N,children:n("invitations.dismiss")}),e.jsx(Ma,{onClick:()=>{a(window.location.href).catch(e=>q(e,{component:"InvitationLanding",action:"signIn"}))},children:n("invitations.signInToAccept")})]}):e.jsx(Ma,{variant:"outline",onClick:N,disabled:!P,children:n("invitations.dismiss")})})]})})}function so(e){const{user:n}=ba(),{currentWorkspace:r}=fa(),{settings:s}=pi(),{appPermissions:i}=qi(),a=e??r??null,o=n?.id??null,c=t.useMemo(()=>a?Jt(a,o):null,[a,o]),l=t.useMemo(()=>!!a&&Gt(a,o),[a,o]),u=t.useMemo(()=>Xt({userId:o,workspaceRole:c,workspace:a,settings:s,appPermissions:i}),[o,c,a,s,i]),d=t.useCallback(e=>Array.isArray(e)?e.every(e=>u.has(e)):u.has(e),[u]),p=t.useMemo(()=>nn(s,i),[s,i]);return{can:d,permissions:u,isOwner:l,role:c,appPermissionDefinitions:p}}function io(){const e=Hi(),{can:n}=so();return{visible:t.useCallback((t,r)=>!1!==t(e)&&(void 0===r||n(r)),[e,n]),ui:e}}function ao(){const e=li();return t.useMemo(()=>new me(e),[e.serverUrl,e.version])}function oo(){const e=ao(),{t:n}=Cr(),[r,s]=t.useState([]),[i,a]=t.useState(!0),[o,c]=t.useState(null),[l,u]=t.useState(null),d=t.useRef(null),p=t.useRef(n);t.useEffect(()=>{p.current=n},[n]);const h=t.useCallback(async()=>{d.current?.abort();const t=new AbortController;d.current=t,a(!0),c(null);try{const n=await e.list(t.signal);t.signal.aborted||s(n)}catch(e){if(t.signal.aborted)return;B(e,{component:"useConnectedAgents",action:"list"}),c(V(e,"security.connectedAgentsLoadFailed",p.current))}finally{d.current===t&&(d.current=null,a(!1))}},[e]);t.useEffect(()=>(h(),()=>d.current?.abort()),[h]);const m=t.useCallback(async t=>{u(t),c(null);try{await e.revoke(t),s(e=>e.filter(e=>e.clientId!==t))}catch(e){B(e,{component:"useConnectedAgents",action:"revoke"}),c(V(e,"security.connectedAgentsRevokeFailed",p.current))}finally{u(null)}},[e]);return t.useMemo(()=>({agents:r,loading:i,error:o,revoking:l,refresh:h,revoke:m}),[r,i,o,l,h,m])}function co(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""}}const lo=[["second",60],["minute",60],["hour",24],["day",7],["week",4.34524],["month",12],["year",Number.POSITIVE_INFINITY]];function uo(e,t="en-US",n=Date.now()){try{const r=new Date(e).getTime();if(isNaN(r))return"";const s=new Intl.RelativeTimeFormat(t,{numeric:"auto"});let i=(r-n)/1e3;if(Math.abs(i)<60)return s.format(0,"second");for(const[e,t]of lo){if(Math.abs(i)<t)return s.format(Math.round(i),e);i/=t}return""}catch{return""}}function po({icon:t,title:n,description:r,action:s,className:i}){return e.jsxs("div",{className:U("flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",i),children:[t&&e.jsx("span",{"aria-hidden":"true",children:t}),n&&e.jsx("p",{className:"text-sm font-medium",children:n}),r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r}),s]})}function ho({title:t,description:n,actions:r,className:s,titleClassName:i}){return t||n||r?e.jsxs("div",{className:U(s),children:[(t||r)&&e.jsxs("div",{className:U("flex items-center gap-2",t?"justify-between":"justify-end"),children:[t&&e.jsx("h3",{className:U("text-sm font-medium",i),children:t}),r]}),n&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n})]}):null}function mo({className:t,...n}){return e.jsx("div",{className:U("animate-pulse rounded-md bg-primary/10",t),...n})}const fo=E.Root,go=k.forwardRef(({className:t,...n},r)=>e.jsx(E.Item,{ref:r,className:U("border-b last:border-b-0",t),...n}));go.displayName="AccordionItem";const yo=k.forwardRef(({className:t,children:n,...r},s)=>e.jsx(E.Header,{className:"flex",children:e.jsxs(E.Trigger,{ref:s,className:U("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",t),...r,children:[e.jsx(o.ChevronDown,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1",children:n})]})}));yo.displayName="AccordionTrigger";const vo=k.forwardRef(({className:t,children:n,...r},s)=>e.jsx(E.Content,{ref:s,className:"overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e.jsx("div",{className:U("pb-3 pt-0",t),children:n})}));function bo({value:t,displayValue:n,copyLabel:r,copiedLabel:s,variant:i="inline",className:a}){const c=n??t,[l,u]=k.useState(!1),d=k.useRef(null);k.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const p=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}}(t)&&(u(!0),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>u(!1),2e3))},h=t=>e.jsxs(Ma,{type:"button",variant:"ghost",size:"sm",onClick:p,"aria-label":l?s:r,className:"h-7 shrink-0 gap-1.5 px-2",children:[l?e.jsx(o.Check,{className:"h-3.5 w-3.5","aria-hidden":"true"}):e.jsx(o.Copy,{className:"h-3.5 w-3.5","aria-hidden":"true"}),e.jsx("span",{className:U("text-xs",t&&"hidden sm:inline"),children:l?s:r})]});return"inline"===i?e.jsxs("div",{dir:"ltr",className:U("flex items-center gap-2 rounded-md border bg-muted/40 py-1 ps-3 pe-1",a),children:[e.jsx("code",{className:"min-w-0 flex-1 truncate text-xs",title:t,children:c}),h(!0)]}):e.jsxs("div",{dir:"code"===i?"ltr":void 0,className:U("overflow-hidden rounded-md border bg-muted/40",a),children:[e.jsx("div",{className:"flex justify-end border-b bg-muted/30 px-1.5 py-1",children:h(!1)}),"code"===i?e.jsx("pre",{className:"overflow-x-auto p-3 text-start text-xs leading-relaxed",children:e.jsx("code",{children:c})}):e.jsx("p",{className:"p-3 text-sm leading-relaxed",children:c})]})}function wo({config:t,title:n,description:r,className:s}){const{t:i}=Cr(),a=Li(),c=t??a;if(!c?.url)return null;const l=c.name?.trim()||"app",u={url:c.url,name:l,key:Wi(l)},d=(e,t,n,r)=>({id:e,name:t,instructions:i("security.mcpAddToConfigFile",{path:`${n}`}),snippet:r}),p=[{id:"chatgpt",name:"ChatGPT",instructions:i("security.mcpClientChatgptInstructions")},{id:"claude",name:"Claude",instructions:i("security.mcpClientClaudeInstructions")},d("cursor","Cursor","~/.cursor/mcp.json",'{\n "mcpServers": {\n "{{key}}": {\n "url": "{{url}}"\n }\n }\n}'),d("vscode","VS Code",".vscode/mcp.json",'{\n "servers": {\n "{{key}}": {\n "type": "http",\n "url": "{{url}}"\n }\n }\n}'),d("windsurf","Windsurf","~/.codeium/windsurf/mcp_config.json",'{\n "mcpServers": {\n "{{key}}": {\n "serverUrl": "{{url}}"\n }\n }\n}'),{id:"cline",name:"Cline",instructions:i("security.mcpClientClineInstructions")}],h=c.clients??p,m=void 0===n?i("security.mcpGuideTitle"):n,f=void 0===r?i("security.mcpGuideDescription"):r,g=i("security.mcpCopy"),y=i("security.mcpCopied"),v=!1===c.prompt?null:c.prompt??i("security.mcpPromptTemplate"),b=Fi(v??void 0,u),w=Fi(v??void 0,{...u,url:`${u.url}`,name:`${u.name}`});return e.jsxs("div",{className:U("space-y-5",s),children:[e.jsx(ho,{title:m,description:f}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:i("security.mcpServerUrlLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("security.mcpServerUrlHint")}),e.jsx(bo,{value:c.url,copyLabel:g,copiedLabel:y})]}),b&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:i("security.mcpPromptLabel")}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i("security.mcpPromptHint")}),e.jsx(bo,{value:b,displayValue:w,copyLabel:g,copiedLabel:y,variant:"text"})]}),h.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:i("security.mcpClientsLabel")}),e.jsx(fo,{type:"single",collapsible:!0,defaultValue:h[0]?.id,className:"rounded-md border px-3",children:h.map(t=>{const n=Fi(t.instructions,u),r=Fi(t.snippet,u);return e.jsxs(go,{value:t.id,children:[e.jsx(yo,{children:t.name}),e.jsx(vo,{children:e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n}),r&&e.jsx(bo,{value:r,copyLabel:g,copiedLabel:y,variant:"code"}),t.actionUrl&&e.jsxs("a",{href:t.actionUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[t.actionLabel??t.actionUrl,e.jsx(o.ExternalLink,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})})]},t.id)})})]}),c.docsUrl&&e.jsxs("a",{href:c.docsUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",children:[i("security.mcpLearnMore"),e.jsx(o.ExternalLink,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}vo.displayName="AccordionContent";const xo=A.Root,ko=A.Trigger,So=A.Portal,Co=k.forwardRef(({className:t,...n},r)=>e.jsx(A.Overlay,{className:U("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",t),...n,ref:r}));Co.displayName=A.Overlay.displayName;const Io=k.forwardRef(({className:t,...n},r)=>{const{container:s}=k.useContext(ka);return e.jsxs(So,{container:s,children:[e.jsx(Co,{}),e.jsx(A.Content,{ref:r,className:U("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",t),...n})]})});Io.displayName=A.Content.displayName;const No=({className:t,...n})=>e.jsx("div",{className:U("flex flex-col space-y-2 text-center sm:text-start",t),...n});No.displayName="AlertDialogHeader";const Po=({className:t,...n})=>e.jsx("div",{className:U("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...n});Po.displayName="AlertDialogFooter";const jo=k.forwardRef(({className:t,...n},r)=>e.jsx(A.Title,{ref:r,className:U("text-lg font-semibold",t),...n}));jo.displayName=A.Title.displayName;const Eo=k.forwardRef(({className:t,...n},r)=>e.jsx(A.Description,{ref:r,className:U("text-sm text-muted-foreground",t),...n}));Eo.displayName=A.Description.displayName;const Ao=k.forwardRef(({className:t,...n},r)=>e.jsx(A.Action,{ref:r,className:U($a(),t),...n}));Ao.displayName=A.Action.displayName;const _o=k.forwardRef(({className:t,...n},r)=>e.jsx(A.Cancel,{ref:r,className:U($a({variant:"outline"}),"mt-2 sm:mt-0",t),...n}));function Uo(){const e=li();return t.useMemo(()=>new fe(e),[e.serverUrl,e.version])}function To(){const e=Uo(),{t:n}=Cr(),[r,s]=t.useState([]),[i,a]=t.useState(!0),[o,c]=t.useState(null),[l,u]=t.useState(null),d=t.useRef(null),p=t.useRef(n);t.useEffect(()=>{p.current=n},[n]);const h=t.useCallback(async()=>{d.current?.abort();const t=new AbortController;d.current=t,a(!0),c(null);try{const n=await e.list(t.signal);t.signal.aborted||s(n)}catch(e){if(t.signal.aborted)return;B(e,{component:"useDevices",action:"list"}),c(V(e,"security.devicesLoadFailed",p.current))}finally{d.current===t&&(d.current=null,a(!1))}},[e]);t.useEffect(()=>(h(),()=>d.current?.abort()),[h]);const m=t.useCallback(async(t,n)=>{u(t),c(null);try{await e.rename(t,n),s(e=>e.map(e=>e.deviceId===t?{...e,name:n}:e))}catch(e){B(e,{component:"useDevices",action:"rename"}),c(V(e,"security.deviceRenameFailed",p.current))}finally{u(null)}},[e]),f=t.useCallback(async t=>{u(t),c(null);try{await e.signOut(t),s(e=>e.map(e=>e.deviceId===t?{...e,activeSessions:0}:e))}catch(e){B(e,{component:"useDevices",action:"signOut"}),c(V(e,"security.deviceSignOutFailed",p.current))}finally{u(null)}},[e]),g=t.useCallback(async t=>{u(t),c(null);try{await e.forget(t),s(e=>e.filter(e=>e.deviceId!==t))}catch(e){B(e,{component:"useDevices",action:"forget"}),c(V(e,"security.deviceForgetFailed",p.current))}finally{u(null)}},[e]);return t.useMemo(()=>({devices:r,loading:i,error:o,busyId:l,refresh:h,rename:m,signOut:f,forget:g}),[r,i,o,l,h,m,f,g])}function Ro(e){return!!e&&/Mobi|Android|iPhone|iPad|iPod|Windows Phone/i.test(e)}function Oo(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 Fo(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":""),Oo(e)].filter(Boolean).join(" · "):"";var t}_o.displayName=A.Cancel.displayName;const Wo=k.forwardRef(({className:t,type:n,...r},s)=>e.jsx("input",{type:n,className:U("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",t),ref:s,...r}));function Do(){const e=li();return t.useMemo(()=>new we(e),[e.serverUrl,e.version])}function Lo(){const e=Do(),{t:n}=Cr(),[r,s]=t.useState([]),[i,a]=t.useState(!0),[o,c]=t.useState(null),[l,u]=t.useState(null),d=t.useRef(null),p=t.useRef(n);t.useEffect(()=>{p.current=n},[n]);const h=t.useCallback(async()=>{d.current?.abort();const t=new AbortController;d.current=t,a(!0),c(null);try{const n=await e.list(t.signal);t.signal.aborted||s(n)}catch(e){if(t.signal.aborted)return;B(e,{component:"useSessions",action:"list"}),c(V(e,"security.sessionsLoadFailed",p.current))}finally{d.current===t&&(d.current=null,a(!1))}},[e]);t.useEffect(()=>(h(),()=>d.current?.abort()),[h]);const m=t.useCallback(async t=>{u(t),c(null);try{await e.revoke(t),s(e=>e.filter(e=>e.id!==t))}catch(e){B(e,{component:"useSessions",action:"revoke"}),c(V(e,"security.sessionSignOutFailed",p.current))}finally{u(null)}},[e]);return t.useMemo(()=>({sessions:r,loading:i,error:o,revoking:l,refresh:h,revoke:m}),[r,i,o,l,h,m])}Wo.displayName="Input";const $o=a.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Mo=k.forwardRef(({className:t,...n},r)=>e.jsx(C.Root,{ref:r,className:U($o(),t),...n}));Mo.displayName=C.Root.displayName;const qo=d.FormProvider,Bo=k.createContext({}),Vo=({...t})=>e.jsx(Bo.Provider,{value:{name:t.name},children:e.jsx(d.Controller,{...t})}),zo=()=>{const e=k.useContext(Bo),t=k.useContext(Go),{getFieldState:n,formState:r}=d.useFormContext(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...s}},Go=k.createContext({}),Jo=k.forwardRef(({className:t,...n},r)=>{const s=k.useId();return e.jsx(Go.Provider,{value:{id:s},children:e.jsx("div",{ref:r,className:U("space-y-2",t),...n})})});Jo.displayName="FormItem";const Ho=k.forwardRef(({className:t,...n},r)=>{const{error:s,formItemId:i}=zo();return e.jsx(Mo,{ref:r,className:U(s&&"text-destructive",t),htmlFor:i,...n})});Ho.displayName="FormLabel";const Ko=k.forwardRef(({...t},n)=>{const{error:r,formItemId:s,formDescriptionId:a,formMessageId:o}=zo();return e.jsx(i.Slot,{ref:n,id:s,"aria-describedby":r?`${a} ${o}`:`${a}`,"aria-invalid":!!r,...t})});Ko.displayName="FormControl";const Yo=k.forwardRef(({className:t,...n},r)=>{const{formDescriptionId:s}=zo();return e.jsx("p",{ref:r,id:s,className:U("text-sm text-muted-foreground",t),...n})});Yo.displayName="FormDescription";const Qo=k.forwardRef(({className:t,children:n,...r},s)=>{const{error:i,formMessageId:a}=zo(),o=i?String(i?.message):n;return o?e.jsx("p",{ref:s,id:a,className:U("text-sm font-medium text-destructive",t),...r,children:o}):null});Qo.displayName="FormMessage";const Zo=k.forwardRef(({className:t,...n},r)=>e.jsx(N.Root,{className:U("grid gap-2",t),...n,ref:r}));Zo.displayName=N.Root.displayName;const Xo=k.forwardRef(({className:t,...n},r)=>e.jsx(N.Item,{ref:r,className:U("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",t),...n,children:e.jsx(N.Indicator,{className:"flex items-center justify-center",children:e.jsx(l.CheckIcon,{className:"h-3.5 w-3.5 fill-primary"})})}));Xo.displayName=N.Item.displayName;const ec=k.forwardRef(({className:t,children:n,...r},s)=>e.jsxs(P.Root,{ref:s,className:U("relative overflow-hidden",t),...r,children:[e.jsx(P.Viewport,{className:"h-full w-full rounded-[inherit]",children:n}),e.jsx(tc,{}),e.jsx(P.Corner,{})]}));ec.displayName=P.Root.displayName;const tc=k.forwardRef(({className:t,orientation:n="vertical",...r},s)=>e.jsx(P.ScrollAreaScrollbar,{ref:s,orientation:n,className:U("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]",t),...r,children:e.jsx(P.ScrollAreaThumb,{className:U("relative rounded-full bg-border","vertical"===n&&"flex-1")})}));function nc(){const e=li();return t.useMemo(()=>new Ee(e),[e.serverUrl,e.version])}tc.displayName=P.ScrollAreaScrollbar.displayName;const rc={tooLarge:"uploads.errorTooLarge",invalid:"uploads.errorInvalid",disabled:"uploads.errorDisabled",userLimit:"uploads.errorUserLimit",unavailable:"uploads.errorUnavailable",failed:"uploads.errorFailed"};function sc(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 ic=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑💻","👨💻","👩💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨💼","👩💼","👨🏫","👩🏫","👨🔬","👩🔬","👨🎨","👩🎨","👨🔧","👩🔧","👨🚀","👩🚀","👨⚖️","👩⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️🌈","🎟️","🎫"],ac=_.Root,oc=_.Trigger,cc=k.forwardRef(({className:t,align:n="center",sideOffset:r=4,...s},i)=>{const{container:a}=k.useContext(ka);return e.jsx(_.Portal,{container:a,children:e.jsx(_.Content,{ref:i,align:n,sideOffset:r,className:U("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",t),...s})})});cc.displayName=_.Content.displayName;const lc=k.forwardRef(({className:t,...n},r)=>e.jsx(I.Root,{ref:r,className:U("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...n}));lc.displayName=I.Root.displayName;const uc=k.forwardRef(({className:t,...n},r)=>e.jsx(I.Image,{ref:r,className:U("aspect-square h-full w-full",t),...n}));uc.displayName=I.Image.displayName;const dc=k.forwardRef(({className:t,...n},r)=>e.jsx(I.Fallback,{ref:r,className:U("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...n}));function pc(e){return e?.workspace}function hc(e){return!1!==pc(e)?.canInviteMembers}dc.displayName=I.Fallback.displayName;const mc=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-5UVMteCm.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));const fc=({children:n})=>{const{currentWorkspace:r,switchToWorkspace:s,workspaces:i}=fa(),[a,o]=t.useState(!1),[c,l]=t.useState(la.Profile),u=t.useRef(!1);return t.useEffect(()=>{const e=da.getState();o(e.open),l(e.section);return da.subscribe(e=>{o(e.open),l(e.section)})},[]),t.useEffect(()=>{if(u.current)return;if(!r)return;const e=it();if(!e)return;const t=function(e){if(e.screen&&ua.has(e.screen))return e.screen;switch(e.action){case et.Checkout:case et.Billing:case et.SelectPlan:return la.Subscription;case et.CreditPurchase:return la.Credits;case et.OpenConnectGuide:return la.ConnectedAgents;default:return null}}(e);if(!t)return u.current=!0,void at();const n=e.ws;if(n&&n!==r._id){const e=i.find(e=>e._id===n);return e?void s(e).catch(e=>{q(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:n}}),u.current=!0,at()}):(u.current=!0,void at())}u.current=!0,da.openWorkspaceSettings(t,e),at()},[r,i,s]),e.jsxs(e.Fragment,{children:[n,e.jsx(ro,{}),r&&a&&e.jsx(vn,{fallback:null,children:e.jsx(t.Suspense,{fallback:null,children:e.jsx(mc,{workspace:r,open:a,onOpenChange:e=>{e||da.closeSettings()},section:c,onSectionChange:e=>{da.setSection(e)},showTrigger:!1})})})]})},gc=(e,t,n)=>{if(t!==exports.ApiVersion.V1)throw new Error(`Invalid version: "${t}". Only "${exports.ApiVersion.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).`)},yc=t.memo(({serverUrl:n,version:r,orgId:s,region:i,auth:a,locale:o,defaultPermissions:c,getCheckoutStripeParams:l,loadingComponent:u,ui:d,mcp:p,tracking:h,children:m})=>{gc(n,r,s);const f=t.useMemo(()=>({serverUrl:n,version:r,orgId:s,...void 0!==i&&{region:i}}),[n,r,s,i]),g=t.useMemo(()=>a?.callbacks,[a?.callbacks?.handleAuthentication,a?.callbacks?.onSignOut,a?.callbacks?.getSession,a?.callbacks?.onSessionExpired,a?.callbacks?.handleEvent,a?.callbacks?.onWorkspaceChange]),y=a?.callbacks?.handleEvent;return t.useEffect(()=>(Me.setCallbacks(y?{handleEvent:y}:null),()=>{Me.setCallbacks(null)}),[y]),e.jsx(yr,{locale:o,messageOverrides:d?.messages,children:e.jsx(cr,{children:e.jsx(Ti,{loadingComponent:u,children:e.jsx(wa,{callbacks:g,children:e.jsx(Sa,{children:e.jsx(xa,{config:f,auth:a,children:e.jsx(ma,{children:e.jsx(ur,{getCheckoutStripeParams:l,children:e.jsx(Mi,{appPermissions:c,children:e.jsx(Ji,{ui:d,children:e.jsx(Di,{mcp:p,children:e.jsx(La,{children:e.jsx(wi,{children:e.jsx(Vi,{children:e.jsx(ji,{children:e.jsx(Na,{children:h&&a?.clientId?e.jsx(ii,{serverUrl:n,orgId:s,clientId:a.clientId,...h,children:e.jsx(fc,{children:e.jsx(Wa,{children:m})})}):e.jsx(fc,{children:m})})})})})})})})})})})})})})})})})});yc.displayName="SaaSOSProviderInner";const vc=({children:t,...n})=>e.jsx(vn,{errorTitle:n.ui?.errorBoundary?.title,retryLabel:n.ui?.errorBoundary?.retryLabel,children:e.jsx(yc,{...n,children:t})});vc.displayName="SaaSOSProvider";const bc=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{status:s}=ba();return sn(s).isLoading?n??null:s!==exports.AuthStatus.authenticated?r??null:t},wc=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{status:s}=ba();return sn(s).isLoading?n??null:s!==exports.AuthStatus.unauthenticated?r??null:t};bc.displayName="WhenAuthenticated",wc.displayName="WhenUnauthenticated";function xc(){const{isAuthenticated:e}=ba(),{orgId:n}=li(),{settings:r}=pi(),s=hc(r),{myInvitations:i,acceptInvitation:a,declineInvitation:o}=fa(),{t:c}=Cr(),l=t.useMemo(()=>ca(n??""),[n]),u=t.useSyncExternalStore(l.subscribe,l.getSnapshot,l.getSnapshot),[d,p]=t.useState(null),h=t.useRef(c);t.useEffect(()=>{h.current=c},[c]);const m=t.useCallback(e=>l.load(i,{maxAgeMs:e,onError:e=>(B(e,{component:"useMyInvitations",action:"list"}),V(e,"invitations.loadFailed",h.current))}),[l,i]),f=t.useCallback(()=>m(0),[m]);t.useEffect(()=>{e&&s?m(15e3).catch(()=>{}):l.reset()},[e,s,l,m]);const g=t.useCallback(async(e,t)=>{p(e),l.setError(null);try{const{workspace:n}=await a(e,t);return l.remove(e),n}catch(e){throw B(e,{component:"useMyInvitations",action:"accept"}),l.setError(V(e,"invitations.acceptFailed",h.current)),e}finally{p(null)}},[l,a]),y=t.useCallback(async e=>{p(e),l.setError(null);try{await o(e),l.remove(e)}catch(e){throw B(e,{component:"useMyInvitations",action:"decline"}),l.setError(V(e,"invitations.declineFailed",h.current)),e}finally{p(null)}},[l,o]);return t.useMemo(()=>({invitations:u.rows,loading:u.loading,error:u.error,busy:d,refresh:f,accept:g,decline:y}),[u,d,f,g,y])}function kc({className:t,title:n,description:r,emptyLabel:s,hideWhenEmpty:i=!1,switchOnAccept:a=!0,onAccepted:c}){const{t:l,formattingLocale:u}=Cr(),{formats:d}=Hi(),{invitations:p,loading:h,error:m,busy:f,accept:g,decline:y}=xc(),{switchToWorkspace:v}=fa(),b=void 0===n?l("invitations.title"):n,w=void 0===r?l("invitations.listDescription"):r,x=s??l("invitations.empty");return h||0!==p.length||!i||m?e.jsx("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e.jsxs("div",{className:U("space-y-4",t),children:[e.jsx(ho,{title:b,description:w}),m&&e.jsx(Za,{variant:"error",message:m}),h?e.jsxs("div",{className:"space-y-2",children:[e.jsx(mo,{className:"h-16 w-full"}),e.jsx(mo,{className:"h-16 w-full"})]}):0===p.length?e.jsx(po,{icon:e.jsx(o.MailOpen,{className:"h-5 w-5 text-muted-foreground"}),description:x}):e.jsx("ul",{className:"space-y-2",children:p.map(t=>{const n=dn(t),r=f===t._id;return e.jsx("li",{className:"rounded-md border bg-card p-3 text-card-foreground",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:un(t)}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[l("invitations.invitedAs",{inviter:n??l("users.invitations.formerMember"),role:t.role}),t.validTill&&e.jsxs(e.Fragment,{children:[" · ",l("users.invitations.expiresAt",{date:(s=t.validTill,s?co(s,u,d?.date??{dateStyle:"medium"}):"")})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx(Ma,{variant:"outline",size:"sm",disabled:r,onClick:()=>y(t._id).catch(()=>{}),children:l("invitations.decline")}),e.jsx(Ma,{size:"sm",progress:r,onClick:()=>(async e=>{let t;try{t=await g(e)}catch{return}t&&(c?.(t),a&&await v(t))})(t._id),children:l("invitations.accept")})]})]})},t._id);var s})})]})}):null}const Sc=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{invitations:s,loading:i}=xc();return i?n??null:0===s.length?r??null:t},Cc="https://www.buildbase.app",Ic={"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}}},Nc={"built-with":"Built with BuildBase","powered-by":"Powered by BuildBase",mark:"BuildBase"};function Pc(e,t){return`${Cc}/badge/v1/${e}.svg?theme=${t}`}function jc(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 Ec(e,{refCode:t,params:n}={}){const r=new URLSearchParams({utm_source:"badge",utm_medium:e}),s=jc(t);s&&r.set("ref",s);for(const[e,t]of Object.entries(n??{}))e&&null!=t&&r.set(e,String(t));return`${Cc}/?${r.toString()}`}const Ac=e=>{const{children:t,fallback:n,roles:r}=e,{user:s}=ba();return r.includes(s?.role??"")?t:n||null},_c=e=>{const{children:t,fallback:n,roles:r}=e,{user:s}=ba(),{currentWorkspace:i}=fa(),a=i?.users.find(e=>e._id===s?.id);return a&&r.includes(a?.role??"")?t:n||null};Ac.displayName="WhenRoles",_c.displayName="WhenWorkspaceRoles";const Uc=e=>{const{children:t,fallback:n,permission:r}=e,{can:s}=so();return s(r)?t:n??null};function Tc(){const e=li();return t.useMemo(()=>new ve(e),[e.serverUrl,e.version])}Uc.displayName="WhenPermission";const Rc=async(e,t)=>{const{io:n}=await import("socket.io-client");return n(e,t)};let Oc=null;function Fc(e){e.timer&&clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null;for(const t of e.listeners)try{t()}catch{}},500)}function Wc(e){e.closed=!0,e.timer&&clearTimeout(e.timer),e.socket?.disconnect(),e.socket=null}function Dc(e,t,n,r=Rc){const s=`${e}|${t}`;if(Oc&&Oc.key!==s&&(Wc(Oc),Oc=null),!Oc){const n={key:s,listeners:new Set,socket:null,closed:!1,timer:null};Oc=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",()=>Fc(n)),e.on("connect",()=>Fc(n)))}).catch(()=>{})}const i=Oc;i.listeners.add(n);let a=!1;return()=>{a||(a=!0,i.listeners.delete(n),0===i.listeners.size&&(Wc(i),Oc===i&&(Oc=null)))}}const Lc={items:[],counts:{unread:0,unseen:0},loading:!1,loadingMore:!1,error:null,hasNextPage:!1,page:0,fetchedAt:0},$c=e=>!e.readAt,Mc=e=>!e.readAt&&!e.seenAt;function qc(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 Bc{constructor(){this.snapshot=Lc,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 s=this.generation;return this.set({loading:0===this.snapshot.fetchedAt,error:null}),this.inFlight=Promise.all([e(1),t()]).then(([e,t])=>{if(s!==this.generation)return;const n=this.snapshot.page<=1;this.set({items:n?e.notifications:qc(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=>{s===this.generation&&this.set({error:n.onError(e)})}).finally(()=>{this.inFlight=null,s===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:qc(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 s=await t();if(r!==this.generation)return;const i=this.snapshot.counts;if(s.unread===i.unread&&s.unseen===i.unseen)return;this.set({counts:s}),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-($c(n)?1:0)),unseen:Math.max(0,r.unseen-(Mc(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=Lc;for(const e of this.listeners)e()}adjustCounts(e,t){const{unread:n,unseen:r}=this.snapshot.counts;return{unread:Math.max(0,n+($c(t)?1:0)-($c(e)?1:0)),unseen:Math.max(0,r+(Mc(t)?1:0)-(Mc(e)?1:0))}}}const Vc=new Map;const zc=()=>"undefined"==typeof document||"hidden"!==document.visibilityState;function Gc(e={}){const{isAuthenticated:n}=ba(),{orgId:r,serverUrl:s}=li(),{currentWorkspace:i}=fa(),a=Tc(),{t:o}=Cr(),c="current"===e.workspaceId?i?._id:e.workspaceId,l="current"===e.workspaceId&&!i?._id,u=Math.max(1,Math.min(e.pageSize??20,100)),d=e.pollIntervalMs??6e4,p=e.live??!0,h=l?"__waiting_for_workspace__":c,m=t.useMemo(()=>function(e,t){const n=`${e||"unscoped"}|${t??"*"}`;let r=Vc.get(n);return r||(r=new Bc,Vc.set(n,r)),r}(r??"",h),[r,h]),f=t.useSyncExternalStore(m.subscribe,m.getSnapshot,m.getSnapshot),g=t.useRef(o);t.useEffect(()=>{g.current=o},[o]);const y=t.useCallback(e=>t=>(B(t,{component:"useNotifications",action:e}),V(t,"notifications.inbox.loadFailed",g.current)),[]),v=t.useCallback(e=>a.list({workspaceId:c,page:e,limit:u}),[a,c,u]),b=t.useCallback(()=>a.counts(c),[a,c]),w=t.useCallback(e=>m.load(v,b,{maxAgeMs:e,onError:y("list")}),[m,v,b,y]),x=t.useCallback(()=>w(0),[w]);t.useEffect(()=>{n?l||w(15e3).catch(()=>{}):m.reset()},[n,l,m,w]),t.useEffect(()=>{if(!n||l||d<=0)return;const e=()=>{zc()&&m.poll(v,b,y("poll"))},t=m.retainPoll(d,e),r=()=>{zc()&&e()};return"undefined"!=typeof document&&document.addEventListener("visibilitychange",r),()=>{t(),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",r)}},[n,l,d,m,v,b,y]),t.useEffect(()=>{if(!n||l||!p||!s)return;const e=ne();return e?Dc(s,e,()=>{w(0).catch(()=>{})}):void 0},[n,l,p,s,w]);const k=t.useCallback(async(e,t,n)=>{const r=t();m.setError(null);try{const e=await n();e&&"object"==typeof e&&"id"in e&&m.replace(e)}catch(t){throw r(),B(t,{component:"useNotifications",action:e}),m.setError(V(t,"notifications.inbox.updateFailed",g.current)),t}},[m]),S=t.useCallback(async e=>{const t=m.getSnapshot().items.find(t=>t.id===e);if(t?.readAt)return;const n=(new Date).toISOString();await k("read",()=>m.optimistic(e,{readAt:n,readVia:"inbox",seenAt:t?.seenAt??n}),()=>a.markRead(e))},[k,a,m]),C=t.useCallback(e=>k("unread",()=>m.optimistic(e,{readAt:null,readVia:null}),()=>a.markUnread(e)),[k,a,m]),I=t.useCallback(e=>k("archive",()=>m.remove(e),async()=>{await a.archive(e)}),[k,a,m]),N=t.useCallback(()=>k("read-all",()=>m.markAll("readAt"),()=>a.markAllRead(c)),[k,a,m,c]),P=t.useCallback(async()=>{0!==m.getSnapshot().counts.unseen&&await k("seen",()=>m.markAll("seenAt"),()=>a.markSeen(c)).catch(()=>{})},[k,a,m,c]),j=t.useCallback(()=>m.loadMore(v,{onError:y("load-more")}),[m,v,y]),E=t.useMemo(()=>f.items.filter(e=>!e.readAt),[f.items]);return t.useMemo(()=>({notifications:f.items,unread:E,counts:f.counts,loading:f.loading||n&&l,loadingMore:f.loadingMore,hasMore:f.hasNextPage,error:f.error,refresh:x,loadMore:j,markRead:S,markUnread:C,archive:I,markAllRead:N,markSeen:P}),[f,n,l,E,x,j,S,C,I,N,P])}function Jc({className:n,title:r,description:s,showFilter:i=!0,onSelect:a,emptyLabel:c,markSeenOnView:l=!0,compact:u=!1,...d}){const{t:p,formattingLocale:h}=Cr(),{notifications:m,unread:f,counts:g,loading:y,loadingMore:v,hasMore:b,error:w,loadMore:x,markRead:k,markUnread:S,archive:C,markAllRead:I,markSeen:N}=Gc(d),[P,j]=t.useState("all");t.useEffect(()=>{l&&!y&&g.unseen>0&&N()},[l,y,g.unseen,N]);const E=void 0===r?p("notifications.inbox.title"):r,A=void 0===s?p("notifications.inbox.description"):s,_="unread"===P?f:m,T=c??p("unread"===P?"notifications.inbox.emptyUnread":"notifications.inbox.empty"),R=e=>{k(e.id).catch(()=>{}),a?a(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 e.jsx("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e.jsxs("div",{className:U(u?"space-y-3":"space-y-4",n),children:[e.jsx(ho,{title:E,description:A}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[i?e.jsx("div",{role:"group",className:"inline-flex rounded-md border p-0.5 text-xs",children:["all","unread"].map(t=>e.jsxs("button",{type:"button","aria-pressed":P===t,onClick:()=>j(t),className:U("rounded px-2.5 py-1 font-medium transition-colors",P===t?"bg-secondary text-secondary-foreground":"text-muted-foreground hover:text-foreground"),children:[p("all"===t?"notifications.inbox.filterAll":"notifications.inbox.filterUnread"),"unread"===t&&g.unread>0&&e.jsxs("span",{className:"ms-1 tabular-nums",children:["(",g.unread,")"]})]},t))}):e.jsx("span",{}),e.jsx(Ma,{variant:"ghost",size:"sm",disabled:0===g.unread,startIcon:e.jsx(o.Check,{}),onClick:()=>I().catch(()=>{}),children:p("notifications.inbox.markAllRead")})]}),w&&e.jsx(Za,{variant:"error",message:w}),y?e.jsxs("div",{className:"space-y-2",children:[e.jsx(mo,{className:"h-14 w-full"}),e.jsx(mo,{className:"h-14 w-full"}),e.jsx(mo,{className:"h-14 w-full"})]}):0===_.length?e.jsx(po,{icon:e.jsx(o.BellOff,{className:"h-5 w-5 text-muted-foreground"}),description:T}):e.jsx("ul",{className:"divide-y rounded-md border bg-card text-card-foreground",children:_.map(t=>{const n=!t.readAt,r=function(e,t){const n=[],{email:r,push:s}=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"!==s.status&&"skipped"!==s.status){const e="failed"===s.status?t("notifications.inbox.notDelivered"):s.clickedAt?t("notifications.inbox.clicked"):null;n.push({key:"push",icon:"push",text:[t("notifications.inbox.channelPush"),e].filter(Boolean).join(" · ")})}return n}(t,p);return e.jsxs("li",{className:"group relative flex gap-3 p-3",children:[e.jsx("span",{"aria-hidden":"true",className:U("mt-1.5 h-2 w-2 shrink-0 rounded-full",n?"bg-primary":"bg-transparent")}),e.jsxs("button",{type:"button",onClick:()=>R(t),className:"min-w-0 flex-1 text-start outline-none focus-visible:underline",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:U("truncate text-sm",n?"font-semibold":"font-medium text-muted-foreground"),children:t.title}),t.createdAt&&e.jsx("time",{dateTime:t.createdAt,className:"shrink-0 text-xs text-muted-foreground tabular-nums",children:uo(t.createdAt,h)})]}),t.body&&e.jsx("p",{className:U("mt-0.5 text-sm text-muted-foreground",u?"line-clamp-2":"line-clamp-3"),children:t.body}),r.length>0&&e.jsx("div",{className:"mt-1.5 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:r.map(t=>e.jsxs("span",{className:"inline-flex items-center gap-1",children:["email"===t.icon?e.jsx(o.Mail,{className:"h-3 w-3","aria-hidden":"true"}):e.jsx(o.Smartphone,{className:"h-3 w-3","aria-hidden":"true"}),t.text]},t.key))})]}),e.jsxs("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:[e.jsx(Ma,{variant:"ghost",size:"icon",className:"h-7 w-7 sm:h-7 sm:w-7",title:p(n?"notifications.inbox.markRead":"notifications.inbox.markUnread"),"aria-label":p(n?"notifications.inbox.markRead":"notifications.inbox.markUnread"),onClick:()=>(n?k(t.id):S(t.id)).catch(()=>{}),children:n?e.jsx(o.MailOpen,{className:"h-4 w-4"}):e.jsx(o.Mail,{className:"h-4 w-4"})}),e.jsx(Ma,{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:()=>C(t.id).catch(()=>{}),children:e.jsx(o.Archive,{className:"h-4 w-4"})})]})]},t.id)})}),b&&!y&&e.jsx(Ma,{variant:"outline",size:"sm",fullWidth:!0,progress:v,onClick:()=>x().catch(()=>{}),children:p("notifications.inbox.loadMore")})]})})}function Hc(){const e=t.useContext(Da);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return t.useMemo(()=>({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 Kc=e=>{const{children:t,slug:n}=e,{currentWorkspace:r}=fa(),s=r?.features?.[n];return s?t:null},Yc=e=>{const{children:t,slug:n}=e,{currentWorkspace:r}=fa(),s=r?.features?.[n];return ra(!!r&&!s,`workspace:${n}`,"feature_gate_shown",{feature:n,scope:"workspace"}),s?null:t},Qc=e=>{const{children:t,slug:n}=e,{isFeatureEnabled:r}=Hc();return r(n)?t:null},Zc=e=>{const{children:t,slug:n}=e,{isFeatureEnabled:r,loading:s}=Hc(),i=r(n);return ra(!s&&!i,`user:${n}`,"feature_gate_shown",{feature:n,scope:"user"}),i?null:t};Kc.displayName="WhenWorkspaceFeatureEnabled",Yc.displayName="WhenWorkspaceFeatureDisabled",Qc.displayName="WhenUserFeatureEnabled",Zc.displayName="WhenUserFeatureDisabled";const Xc=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:s,loading:i}=xi();return i?n??null:s?.subscription?t:r??null},el=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:s,loading:i}=xi();return i?n??null:s?.subscription?r??null:t},tl=e=>{const{children:t,plans:n,loadingComponent:r,fallbackComponent:s}=e,{response:i,loading:a}=xi(),o=i?.subscription?i.plan??i.subscription?.plan:void 0,c=n.map(e=>e.trim().toLowerCase()),l=(o?.slug??"").toLowerCase(),u=!!o&&c.includes(l),{currentWorkspace:d}=fa();return ra(!!d&&!a&&!u&&null!=s,c.join(","),"plan_gate_shown",{required_plans:c.join(","),current_plan:l||"none"}),a?r??null:u?t:s??null},nl=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:s,loading:i}=xi();return i?n??null:"trialing"!==s?.subscription?.subscriptionStatus?r??null:t},rl=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:s,loading:i}=xi();return i?n??null:s?.subscription?.subscriptionStatus===_t.Trialing?r??null:t},sl=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{behavior:s}=Hi(),i=e.daysThreshold??s?.trialEndingDays??3,{response:a,loading:o}=xi();if(o)return n??null;const c=a?.subscription;if(!c||"trialing"!==c.subscriptionStatus)return r??null;const l=c.trialEnd||c.stripeCurrentPeriodEnd;if(!l)return r??null;const u=new Date(l);if(isNaN(u.getTime()))return r??null;return Math.max(0,Math.ceil((u.getTime()-Date.now())/864e5))>i?r??null:t};Xc.displayName="WhenSubscription",el.displayName="WhenNoSubscription",tl.displayName="WhenSubscriptionToPlans",nl.displayName="WhenTrialing",rl.displayName="WhenNotTrialing",sl.displayName="WhenTrialEnding";const il=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:s}=e,{quotas:i,loading:a}=zi(),o=a?void 0:i?.[t];return ra(!!o&&o.available<=0&&null!=s,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),a?r??null:o?o.available<=0?s??null:n:s??null},al=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:s}=e,{quotas:i,loading:a}=zi(),o=a?void 0:i?.[t];return ra(!!o&&o.available<=0,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),a?r??null:o?o.available>0?s??null:n:s??null},ol=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:s}=e,{quotas:i,loading:a}=zi();if(a)return r??null;const o=i?.[t];return o&&o.hasOverage&&!1!==o.allowOverage?n:s??null},cl=e=>{const{slug:t,threshold:n,children:r,loadingComponent:s,fallbackComponent:i}=e,{quotas:a,loading:o}=zi(),c=o?void 0:a?.[t],l=c?c.included>0?c.consumed/c.included*100:c.consumed>0?100:0:0;return ra(!!c&&l>=n,`${t}@${n}`,"quota_threshold_reached",{quota:t,threshold:n,percent_used:Math.round(l)}),o?s??null:c?l<n?i??null:r:i??null};il.displayName="WhenQuotaAvailable",al.displayName="WhenQuotaExhausted",ol.displayName="WhenQuotaOverage",cl.displayName="WhenQuotaThreshold";const ll=({children:e})=>{const{currentWorkspace:t}=fa(),n=t?._id,{balance:r,loading:s,error:i,refetch:a}=Ei(),{packages:o,loading:c}=Ii(n),{consumeCredits:l,loading:u,error:d}=Si(n),{purchaseCredits:p,loading:h,error:m}=Ci(n);return e({balance:r,loading:s,packages:o,packagesLoading:c,consume:l,consuming:u,purchase:async e=>{if(!n)throw new Error("No workspace selected");const{successUrl:t,cancelUrl:r}=st(n),s=await p({creditPackageId:e._id,successUrl:t,cancelUrl:r});s.url&&dt(s.url)},purchasing:h,refetch:a,error:d||m||i})};ll.displayName="CreditActionsProvider";const ul=({children:e})=>{const{balance:t,loading:n,error:r,refetch:s}=Ei();return e({balance:t,loading:n,error:r,refetch:s})};ul.displayName="CreditBalance";const dl=e=>{const{min:t=1,children:n,loadingComponent:r,fallbackComponent:s}=e,{balance:i,loading:a}=Ei();return a?r??null:i?i.available<t?s??null:n:s??null},pl=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{balance:s,loading:i}=Ei();return i?n??null:s?s.available>0?r??null:t:r??null},hl=e=>{const{threshold:t,children:n,loadingComponent:r,fallbackComponent:s}=e,{balance:i,loading:a}=Ei();return a?r??null:i?i.available>t?s??null:n:s??null};function ml(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}dl.displayName="WhenCreditsAvailable",pl.displayName="WhenCreditsExhausted",hl.displayName="WhenCreditsLow";const fl=h.z.object({name:h.z.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:h.z.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)")});function gl({screen:t}){return e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[e.jsx("p",{className:"text-2xl font-bold",children:t?.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t?.description})]})}function yl({logo:t}){const{t:n}=Cr();return"string"==typeof t?e.jsx("img",{src:t,alt:n("beta.logoAlt"),className:"max-h-24"}):e.jsx("img",{src:t.bucket?.url,alt:n("beta.logoAlt"),className:"max-h-24"})}const vl=k.forwardRef(({className:t,orientation:n="horizontal",decorative:r=!0,...s},i)=>e.jsx(j.Root,{ref:i,decorative:r,orientation:n,className:U("shrink-0 bg-border","horizontal"===n?"h-[1px] w-full":"h-full w-[1px]",t),...s}));vl.displayName=j.Root.displayName;const bl=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-5UVMteCm.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));function wl({message:t}){return e.jsxs(e.Fragment,{children:[e.jsx(o.Building2,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:t})]})}function xl(n){const{t:r}=Cr(),{visible:s}=io(),i=s(e=>e.workspaceSwitcher?.memberCount),a=s(e=>e.workspaceSwitcher?.planBadge),{workspace:c,setCurrentWorkspace:l,setOpen:u,workspacesToUse:d,switchingToId:p}=n,h=n.isCurrentWorkspace??!1,m=p===c._id,f=c.subscription??null,g=null!=f&&"object"==typeof f?f.plan??null:null,y=g?.name??"";return e.jsxs("div",{className:U("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":h}),children:[e.jsxs(lc,{className:"h-8 w-8 flex items-center justify-center",children:[e.jsx("div",{children:e.jsx(uc,{src:c.image&&c.image.trim()?c.image:void 0})}),e.jsx(dc,{children:(v=c.name,v.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2))})]}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-full",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"font-medium line-clamp-1 text-ellipsis overflow-hidden max-w-full",children:c.name})}),i&&e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(o.Users,{className:"h-3 w-3"}),e.jsx("span",{children:r("workspace.membersCount",{count:c.users?.length||0})})]}),a&&y&&e.jsx("div",{className:"max-w-fit",children:e.jsx("div",{className:"flex items-center gap-1 text-sm bg-success text-success-foreground rounded-full px-2 py-0.5",children:e.jsx("span",{className:"text-xs",children:y})})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[h?null:e.jsx(Ma,{size:"sm",disabled:null!==p||m,progress:m,onClick:()=>{n.switchToWorkspace(c).then(()=>u(!1)).catch(e=>{q(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:c._id}})})},children:r("workspace.switchTo")}),e.jsx(t.Suspense,{fallback:null,children:e.jsx(bl,{workspace:c,onClose:()=>{if(h){const e=d.findIndex(e=>e._id?.toString()===c._id?.toString());-1!==e&&l(d[e])}}})})]})]});var v}function kl(n){const{t:r,dir:s}=Cr(),{switching:i}=fa(),[a,c]=t.useState(!1),[l,p]=t.useState("emoji"),[m,f]=t.useState("🏢"),[g,y]=t.useState(!1),{createWorkspace:v}=fa(),b=h.z.object({name:h.z.string().min(2,{message:r("workspace.workspaceNameMinLength")}),image:h.z.string().optional()}),w=d.useForm({resolver:u.zodResolver(b),defaultValues:{name:"",image:""}});return e.jsxs(qa,{open:a,onOpenChange:c,children:[e.jsx(Ba,{asChild:!0,children:e.jsxs(Ma,{className:"w-full rounded-none",disabled:i,children:[e.jsx(o.Plus,{className:"h-4 w-4 me-2"}),r("workspace.createNew")]})}),e.jsxs(Ga,{dir:s,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e.jsxs(Ja,{children:[e.jsx(Ka,{children:r("workspace.createTitle")}),e.jsx(Ya,{children:r("workspace.createDescription")})]}),e.jsx(qo,{...w,children:e.jsxs("form",{onSubmit:w.handleSubmit(async function(e){let t="";if("emoji"===l)t=sc(m);else if("url"===l&&e.image)try{new URL(e.image),t=e.image}catch{return void w.setError("image",{message:r("workspace.invalidUrl")})}y(!0);try{await v(e.name,t),c(!1),w.reset(),f("🏢"),p("emoji"),n?.onCreated?.()}catch(t){q(t,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{y(!1)}}),children:[e.jsx(Vo,{control:w.control,name:"name",render:({field:t})=>e.jsxs(Jo,{children:[e.jsx(Ho,{children:r("workspace.workspaceName")}),e.jsx(Ko,{children:e.jsx(Wo,{placeholder:r("workspace.workspaceNamePlaceholder"),...t})}),e.jsx(Qo,{})]})}),e.jsxs("div",{className:"flex flex-col gap-y-2 my-2",children:[e.jsxs("div",{children:[e.jsx(Mo,{className:"text-sm font-medium",children:r("workspace.workspaceIcon")}),e.jsx(Yo,{children:r("workspace.iconDescription")})]}),e.jsxs(Zo,{value:l,onValueChange:e=>p(e),className:"flex flex-col gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(Xo,{value:"emoji",id:"emoji"}),e.jsxs(Mo,{htmlFor:"emoji",className:"flex items-center gap-2",children:[e.jsx(o.Smile,{className:"h-4 w-4"}),r("workspace.chooseEmoji")]})]}),e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(Xo,{value:"url",id:"url"}),e.jsxs(Mo,{htmlFor:"url",className:"flex items-center gap-2",children:[e.jsx(o.Image,{className:"h-4 w-4"}),r("workspace.customImageUrl")]})]})]}),"emoji"===l&&e.jsxs("div",{className:"flex flex-col gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:r("general.previewLabel")}),e.jsx("div",{className:"w-12 h-12 rounded-lg border-2 border-border flex items-center justify-center text-2xl bg-muted",children:m})]}),e.jsx(ec,{className:"h-32 w-full rounded-md border",children:e.jsx("div",{className:"p-4 grid grid-cols-8 gap-2",children:ic.map((t,n)=>e.jsx("button",{type:"button",onClick:()=>(e=>{f(e),w.setValue("image",sc(e))})(t),"aria-label":t,"aria-pressed":m===t,className:"w-10 h-10 sm:w-8 sm:h-8 rounded flex items-center justify-center text-lg hover:bg-muted transition-colors "+(m===t?"bg-primary text-primary-foreground":""),children:t},n))})})]}),"url"===l&&e.jsxs("div",{className:"flex flex-col gap-y-2",children:[e.jsx(Vo,{control:w.control,name:"image",render:({field:t})=>e.jsxs(Jo,{children:[e.jsx(Ho,{children:r("workspace.imageUrl")}),e.jsx(Ko,{children:e.jsx(Wo,{placeholder:r("workspace.imageUrlPlaceholder"),...t})}),e.jsx(Yo,{children:r("workspace.imageUrlDescription")}),e.jsx(Qo,{})]})}),w.watch("image")&&w.watch("image")?.trim()&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:r("general.previewLabel")}),e.jsx("div",{className:"w-12 h-12 rounded-lg border-2 border-border overflow-hidden bg-muted",children:e.jsx("img",{src:w.watch("image")||void 0,alt:r("general.previewImageAlt"),className:"w-full h-full object-cover",onError:e=>{e.currentTarget.style.display="none"}})})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(Ma,{type:"button",variant:"outline",onClick:()=>{c(!1),w.reset(),f("🏢"),p("emoji")},disabled:g,children:r("settings.common.cancel")}),e.jsx(Ma,{type:"submit",disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(o.Loader2,{className:"me-2 h-4 w-4 animate-spin"}),r("workspace.creating")]}):r("workspace.createWorkspace")})]})]})})]})]})}exports.APP_PERMISSION_FALLBACK_GROUP=tn,exports.AlertDialog=xo,exports.AlertDialogAction=Ao,exports.AlertDialogCancel=_o,exports.AlertDialogContent=Io,exports.AlertDialogDescription=Eo,exports.AlertDialogFooter=Po,exports.AlertDialogHeader=No,exports.AlertDialogTitle=jo,exports.AlertDialogTrigger=ko,exports.AuthApi=de,exports.Avatar=lc,exports.AvatarFallback=dc,exports.AvatarImage=uc,exports.BBAction=et,exports.BBScreen=nt,exports.BBStatus=tt,exports.BB_PARAM=Xe,exports.BaseApi=ue,exports.BetaForm=({onSuccess:n,onError:r,className:s="w-full",fieldClassName:i="flex flex-col gap-1.5 w-full",autoFocus:a=!0,showSuccessMessage:o=!0,hideLogo:c=!1,hideTitles:l=!1})=>{const{t:p}=Cr(),[h,m]=t.useState(!1),[f,g]=t.useState(!1),{submitBetaForm:y,isLoading:v,isSubmitting:b,error:w,config:x,success:k,message:S}=(()=>{const{t:e}=Cr(),n=li(),[r,s]=t.useState(null),[i,a]=t.useState(!0),[o,c]=t.useState(!1),[l,u]=t.useState(null),[d,p]=t.useState(!1),[h,m]=t.useState(null);return t.useEffect(()=>{let t=!1;return(async()=>{a(!0),u(null);try{const e=new he(n),r=await e.fetchConfig();t||s(r)}catch(n){t||u(n instanceof Error?n.message:e("beta.errorMessage"))}finally{t||a(!1)}})(),()=>{t=!0}},[n]),{isLoading:i,isSubmitting:o,config:r,error:l,success:d,message:h,submitBetaForm:t.useCallback(async t=>{if(!n){const t=e("errors.generic");return u(t),{success:!1,message:t}}try{c(!0),u(null),p(!1),m(null);const e=new he(n),r=await e.submitBetaUser({name:t.name||"",email:t.email}),s="success"===r.status;return p(s),m(r.message),{success:s,message:r.message}}catch(t){const n=t instanceof Error?t.message:e("beta.errorMessage");return u(n),p(!1),m(n),{success:!1,message:n}}finally{c(!1)}},[n])}})();t.useEffect(()=>{k&&o&&(m(!0),g(!0)),w&&g(!0)},[k,o,w]);const C=d.useForm({resolver:u.zodResolver(fl),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});t.useEffect(()=>{a&&C.setFocus("name")},[a,C]);const I=C.formState.isValid&&!b;return e.jsx("div",{className:"saas-os-ui",style:{width:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:v?e.jsxs("div",{className:U("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",s),children:[e.jsx(mo,{className:"h-24 w-24 rounded-lg"}),e.jsx(mo,{className:"h-6 w-32"}),e.jsxs("div",{className:"w-full space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(mo,{className:"h-4 w-16"}),e.jsx(mo,{className:"h-10 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mo,{className:"h-4 w-16"}),e.jsx(mo,{className:"h-10 w-full"})]}),e.jsx(mo,{className:"h-10 w-full"})]})]}):e.jsxs("div",{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:[!c&&e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[x?.logo&&e.jsx(yl,{logo:x?.logo}),x?.name&&e.jsx("div",{children:x?.name})]}),e.jsx(d.FormProvider,{...C,children:e.jsxs("form",{onSubmit:C.handleSubmit(async e=>{try{const t=await y(e);t.success?(n?.(),C.reset(),o&&m(!0),g(!0)):(r?.(t.message),g(!0))}catch(e){r?.(e instanceof Error?e.message:p("beta.errorMessage")),g(!0)}}),className:s,noValidate:!0,"aria-busy":b,children:[!f&&e.jsxs(e.Fragment,{children:[!l&&x?.screen?.register&&e.jsx(gl,{screen:x?.screen?.register}),e.jsx(Vo,{control:C.control,name:"name",render:({field:t})=>e.jsxs(Jo,{className:i,children:[e.jsx(Ho,{children:p("beta.nameLabel")}),e.jsx(Ko,{children:e.jsx(Wo,{...t})}),e.jsx(Yo,{}),e.jsx(Qo,{})]})}),e.jsx(Vo,{control:C.control,name:"email",render:({field:t})=>e.jsxs(Jo,{className:i,children:[e.jsx(Ho,{children:p("beta.emailLabel")}),e.jsx(Ko,{children:e.jsx(Wo,{...t})}),e.jsx(Yo,{}),e.jsx(Qo,{})]})}),e.jsx(Ma,{type:"submit",disabled:!I,className:i,children:p(b?"beta.submittingText":"beta.submitText")})]}),f&&w&&e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[e.jsxs("div",{className:"border-destructive/30 text-destructive",role:"alert","aria-live":"assertive","aria-atomic":!0,children:[e.jsx("span",{className:"text-4xl mb-2",role:"img","aria-label":p("settings.common.error"),children:"❗"}),w]}),e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx(Ma,{type:"button",onClick:()=>{g(!1),C.reset()},className:i,children:p("beta.tryAgain")})})]}),f&&h&&S&&e.jsx("div",{className:"flex flex-col items-center justify-center w-full text-success border-success/30 text-center",children:x?.screen?.thankYou&&e.jsx(gl,{screen:x?.screen?.thankYou})})]})}),!f&&e.jsx("div",{children:e.jsxs("div",{children:[p("beta.privacyConsent")," ",e.jsx("a",{href:x?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:p("beta.privacyPolicy")})," ",p("beta.and")," ",e.jsx("a",{href:x?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:p("beta.termsOfService")}),"."]})})]})})},exports.BillingIntervals=At,exports.BuildBaseBadge=({variant:t="built-with",theme:n="auto",size:r="md",alt:s,className:i,link:a=!0,refCode:o,params:c})=>{const l=Ic[t][r],u=e.jsx("img",{src:Pc(t,n),alt:s??Nc[t],width:l.width,height:l.height,loading:"lazy",decoding:"async"});return a?e.jsx("a",{href:Ec(t,{refCode:o,params:c}),target:"_blank",rel:"noopener",className:U("inline-block",i),children:u}):e.jsx("span",{className:i,children:u})},exports.Button=Ma,exports.CURRENCY_DISPLAY=gt,exports.CURRENCY_FLAG=yt,exports.ConnectMcpGuide=wo,exports.ConnectedAgents=function({className:n,title:r,description:s,disconnectLabel:i,emptyLabel:a,showConnectGuide:c=!0}){const{t:l,formattingLocale:u}=Cr(),{formats:d}=Hi(),{agents:p,loading:h,error:m,revoking:f,revoke:g}=oo(),y=Li(),v=c&&Boolean(y?.url),[b,w]=t.useState(!1),x=t.useRef(!1);t.useEffect(()=>{if(x.current||!v)return;const e=da.getState().params;e?.action===et.OpenConnectGuide&&(x.current=!0,da.clearParams(),w(!0))},[v]);const k=void 0===r?l("security.connectedAgentsTitle"):r,S=void 0===s?l("security.connectedAgentsDescription"):s,C=i??l("security.connectedAgentsDisconnect"),I=a??l("security.connectedAgentsEmpty"),N=l("security.mcpConnectAction"),P=t=>v?e.jsxs(Ma,{size:"sm",onClick:()=>w(!0),"aria-label":N,className:"shrink-0 gap-1.5",children:[e.jsx(o.Plus,{className:"h-4 w-4","aria-hidden":"true"}),e.jsx("span",{className:t?"hidden sm:inline":void 0,children:N})]}):null;return e.jsxs("div",{className:U("space-y-4",n),children:[e.jsx(ho,{title:k,description:S,actions:!h&&p.length>0?P(!0):void 0}),h&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mo,{className:"h-20 rounded-md"},t))}),m&&!h&&e.jsx("p",{className:"text-destructive text-sm",children:m}),!h&&!m&&0===p.length&&e.jsx(po,{icon:e.jsx(o.Bot,{className:"h-5 w-5 text-muted-foreground"}),description:I,action:P(!1)??void 0}),!h&&p.length>0&&e.jsx("ul",{className:"space-y-3",children:p.map(t=>{return e.jsxs("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium break-words",children:t.title}),t.scope.length>0&&e.jsxs("span",{className:"text-muted-foreground text-xs break-words",children:[l("security.connectedAgentsAccess"),": ",t.scope.join(", ")]}),t.lastGrantedAt&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:[l("security.connectedAgentsGranted"),": ",(n=t.lastGrantedAt,co(n,u,d?.date??{dateStyle:"medium"}))]})]}),e.jsx(Ma,{variant:"outline",size:"sm",progress:f===t.clientId,onClick:()=>g(t.clientId),className:"shrink-0",children:C})]},t.clientId);var n})}),v&&e.jsx(qa,{open:b,onOpenChange:w,children:e.jsxs(Ga,{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.jsxs(Ja,{className:"pe-8",children:[e.jsx(Ka,{children:l("security.mcpGuideTitle")}),e.jsx(Ya,{children:l("security.mcpGuideDescription")})]}),e.jsx(wo,{title:null,description:null})]})})]})},exports.ConnectedAgentsApi=me,exports.CreditActionsProvider=ll,exports.CreditBalance=ul,exports.CreditBalanceContextProvider=ji,exports.CreditBucketSource={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},exports.CreditBucketStatus={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},exports.CreditStorePage=function({children:n,loadingFallback:r,errorFallback:s,redirectBaseUrl:i}){const{packages:a,notes:o,loading:c,error:l,refetch:u}=Ni(),{isAuthenticated:d,signIn:p}=ba(),h=t.useCallback(e=>{if(d)da.openWorkspaceSettings(la.Credits,{action:et.CreditPurchase,packageId:e});else if(i){const t=rt({action:et.CreditPurchase,screen:"credits",packageId:e},i);p(t)}else p()},[d,p,i]);return c?void 0!==r?e.jsx(e.Fragment,{children:r}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(mo,{className:"h-8 w-48"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(t=>e.jsx(mo,{className:"h-48 rounded-lg"},t))})]}):l?s?e.jsx(e.Fragment,{children:s(l)}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:l}):e.jsx(e.Fragment,{children:n({loading:c,error:l,packages:a,notes:o,refetch:u,selectPackage:h})})},exports.CreditTransactionType={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"},exports.DEFAULT_ROLE_PERMISSIONS=Yt,exports.Devices=function({className:n,title:r,description:s,showRename:i,showSignOut:a,showRemove:c,renameLabel:l,signOutLabel:u,removeLabel:d,emptyLabel:p}){const{t:h,formattingLocale:m}=Cr(),{formats:f}=Hi(),{visible:g}=io(),{devices:y,loading:v,error:b,busyId:w,rename:x,signOut:k,forget:S}=To(),[C,I]=t.useState(null),[N,P]=t.useState(""),[j,E]=t.useState(null),A=i??g(e=>e.settings?.devices?.rename),_=a??g(e=>e.settings?.devices?.signOut),T=c??g(e=>e.settings?.devices?.forget),R=A||_||T,O=void 0===r?h("security.devicesTitle"):r,F=void 0===s?h("security.devicesDescription"):s,W=l??h("security.deviceRename"),D=u??h("security.deviceSignOut"),L=d??h("security.deviceForget"),$=p??h("security.devicesEmpty"),M=async e=>{const t=N.trim();t&&await x(e,t),I(null)};return e.jsxs("div",{className:U("space-y-4",n),children:[e.jsx(ho,{title:O,description:F}),v&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mo,{className:"h-24 rounded-md"},t))}),b&&!v&&e.jsx("p",{className:"text-destructive text-sm",children:b}),!v&&!b&&0===y.length&&e.jsx(po,{icon:e.jsx(o.Monitor,{className:"h-5 w-5 text-muted-foreground"}),description:$}),!v&&y.length>0&&e.jsx("ul",{className:"space-y-3",children:y.map(t=>{const n=C===t.deviceId,r=w===t.deviceId,s=Fo(t.userAgent),i=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(t),a=Ro(t.userAgent)?o.Smartphone:o.Monitor;return e.jsxs("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e.jsxs("div",{className:"flex min-w-0 gap-x-3",children:[e.jsx(a,{className:"text-muted-foreground mt-0.5 h-5 w-5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-y-1",children:[n?e.jsxs("div",{className:"flex items-center gap-x-2",children:[e.jsx(Wo,{value:N,onChange:e=>P(e.target.value),placeholder:h("security.deviceRenamePlaceholder"),className:"h-8 w-48",autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&M(t.deviceId),"Escape"===e.key&&I(null)}}),e.jsx(Ma,{size:"sm",variant:"ghost","aria-label":h("security.deviceSave"),progress:r,onClick:()=>M(t.deviceId),children:e.jsx(o.Check,{className:"h-4 w-4","aria-hidden":"true"})}),e.jsx(Ma,{size:"sm",variant:"ghost","aria-label":h("security.deviceCancel"),onClick:()=>I(null),children:e.jsx(o.X,{className:"h-4 w-4","aria-hidden":"true"})})]}):e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium break-words",children:t.name}),t.current&&e.jsx("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:h("security.deviceCurrent")}),t.trusted&&e.jsxs("span",{className:"text-primary inline-flex items-center gap-x-1 text-xs",children:[e.jsx(o.ShieldCheck,{className:"h-3.5 w-3.5","aria-hidden":"true"}),h("security.deviceTrusted")]}),t.pushEnabled&&e.jsx("span",{className:"text-muted-foreground inline-flex","aria-label":h("security.devicePushEnabled"),title:h("security.devicePushEnabled"),children:e.jsx(o.Bell,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),s&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:s}),i&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:i}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:[t.lastActiveAt&&h("security.deviceLastActive",{date:(c=t.lastActiveAt,co(c,m,f?.date??{dateStyle:"medium"}))}),t.activeSessions>0&&e.jsxs(e.Fragment,{children:[t.lastActiveAt&&" · ",h("security.deviceActiveSessions",{count:t.activeSessions})]})]})]})]}),!n&&R&&e.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-y-1.5",children:[(A||_)&&e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[A&&e.jsx(Ma,{variant:"ghost",size:"sm",disabled:r,onClick:()=>(e=>{I(e.deviceId),P(e.name)})(t),children:W}),_&&t.activeSessions>0&&e.jsx(Ma,{variant:"outline",size:"sm",progress:r,onClick:()=>k(t.deviceId),children:D})]}),T&&e.jsx(Ma,{variant:"ghost",size:"sm",className:"text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:r,onClick:()=>E(t),children:L})]})]},t.deviceId);var c})}),e.jsx(xo,{open:null!==j,onOpenChange:e=>{e||E(null)},children:e.jsxs(Io,{children:[e.jsxs(No,{children:[e.jsx(jo,{children:h("security.deviceForgetConfirmTitle")}),e.jsx(Eo,{children:h("security.deviceForgetConfirmBody")})]}),e.jsxs(Po,{children:[e.jsx(_o,{children:h("security.deviceCancel")}),e.jsx(Ao,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{if(!j)return;const{deviceId:e}=j;E(null),await S(e)},children:L})]})]})})]})},exports.DevicesApi=fe,exports.Dialog=qa,exports.DialogContent=Ga,exports.DialogDescription=Ya,exports.DialogTitle=Ka,exports.DialogTrigger=Ba,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EmptyState=po,exports.EventEmitter=$e,exports.FALLBACK_WORKSPACE_ROLE=Qt,exports.Form=qo,exports.FormControl=Ko,exports.FormDescription=Yo,exports.FormField=Vo,exports.FormItem=Jo,exports.FormLabel=Ho,exports.FormMessage=Qo,exports.FullScreenLoader=_i,exports.INVITATION_ERROR_CODE=_e,exports.Input=Wo,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.Label=Mo,exports.LoadingState=function({label:t,className:n}){const{t:r}=Cr();return e.jsxs("div",{role:"status","aria-live":"polite",className:U("flex items-center gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground",n),children:[e.jsx(o.Loader2,{className:"h-4 w-4 animate-spin flex-shrink-0"}),e.jsx("span",{children:t??r("settings.common.loading")})]})},exports.NotificationBell=function({className:n,align:r="end",inboxProps:s,maxCount:i=99,...a}){const{t:c}=Cr(),{counts:l}=Gc(a),[u,d]=t.useState(!1),p=l.unread,h=p>i?`${i}+`:String(p),m=p>0?c("notifications.inbox.bellUnread",{count:p}):c("notifications.inbox.bellLabel");return e.jsx("div",{className:"saas-os-ui",style:{backgroundColor:"transparent",display:"inline-flex"},children:e.jsxs(ac,{open:u,onOpenChange:d,children:[e.jsx(oc,{asChild:!0,children:e.jsxs(Ma,{variant:"ghost",size:"icon","aria-label":m,title:m,className:U("relative",n),children:[e.jsx(o.Bell,{className:"h-5 w-5"}),p>0&&e.jsx("span",{"aria-hidden":"true",className:U("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",l.unseen>0?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:h})]})}),e.jsx(cc,{align:r,className:"w-[min(24rem,calc(100vw-2rem))] max-h-[min(32rem,calc(100vh-6rem))] overflow-y-auto p-3",children:u&&e.jsx(Jc,{description:null,...s,...a,compact:!0})})]})})},exports.NotificationInbox=Jc,exports.NotificationsApi=ve,exports.PLAN_CURRENCY_CODES=bt,exports.PLAN_CURRENCY_OPTIONS=wt,exports.PUSH_SERVICE_WORKER_SCRIPT="\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",exports.PendingInvitations=kc,exports.Permission=Ht,exports.Popover=ac,exports.PopoverContent=cc,exports.PopoverTrigger=oc,exports.PortalContext=ka,exports.PricingPage=function({slug:n,children:r,loadingFallback:s,errorFallback:i,redirectBaseUrl:a}){const{items:o,plans:c,notes:l,loading:u,error:d,refetch:p}=mi(n),{isAuthenticated:h,signIn:m}=ba(),{currentWorkspace:f,fetchWorkspaces:g}=fa(),{emit:y}=sa();ra(!u&&!d&&c.length>0,n,"pricing_viewed",{pricing_slug:n,plan_count:c.length,authenticated:h});const v=t.useCallback((e,t,n)=>a?rt({action:"selectPlan",plan:e,interval:t,currency:n},a):null,[a]),b=t.useCallback((e,t,r)=>{if(y("pricing_plan_selected",{pricing_slug:n,plan_version_id:e,billing_interval:t,currency:r?r.toUpperCase():void 0,authenticated:h}),h)return da.openWorkspaceSettings(la.Subscription,{action:"selectPlan",plan:e,interval:t,currency:r}),void(f||g());const s=v(e,t,r);m(s??void 0)},[h,m,v,y,n,f,g]);return u?void 0!==s?e.jsx(e.Fragment,{children:s}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(mo,{className:"h-8 w-48"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(t=>e.jsx(mo,{className:"h-64 rounded-lg"},t))})]}):d?i?e.jsx(e.Fragment,{children:i(d)}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:d}):e.jsx(e.Fragment,{children:r({loading:u,error:d,items:o,plans:c,notes:l,refetch:p,selectPlan:b})})},exports.PushApi=be,exports.PushNotificationProvider=Na,exports.QuotaUsageContextProvider=Vi,exports.RadioGroup=Zo,exports.RadioGroupItem=Xo,exports.SDKEvent=Le,exports.SETTINGS_SCREENS=ua,exports.SUPPORTED_LOCALES=hr,exports.SaaSOSProvider=vc,exports.ScrollArea=ec,exports.SectionHeader=ho,exports.Sessions=function({className:t,title:n,description:r,showSignOut:s,signOutLabel:i,emptyLabel:a}){const{t:c,formattingLocale:l}=Cr(),{formats:u}=Hi(),{visible:d}=io(),{sessions:p,loading:h,error:m,revoking:f,revoke:g}=Lo(),y=s??d(e=>e.settings?.devices?.sessionSignOut),v=void 0===n?c("security.sessionsTitle"):n,b=void 0===r?c("security.sessionsDescription"):r,w=i??c("security.sessionSignOut"),x=a??c("security.sessionsEmpty"),k=e=>co(e,l,u?.date??{dateStyle:"medium"});return e.jsxs("div",{className:U("space-y-4",t),children:[e.jsx(ho,{title:v,description:b}),h&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mo,{className:"h-20 rounded-md"},t))}),m&&!h&&e.jsx("p",{className:"text-destructive text-sm",children:m}),!h&&!m&&0===p.length&&e.jsx(po,{icon:e.jsx(o.MonitorSmartphone,{className:"h-5 w-5 text-muted-foreground"}),description:x}),!h&&p.length>0&&e.jsx("ul",{className:"space-y-3",children:p.map(t=>{const n=Fo(t.userAgent),r=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(t),s=t.device?.name||n||c("security.sessionsTitle"),i=Ro(t.userAgent)?o.Smartphone:o.Monitor;return e.jsxs("li",{className:"flex items-start justify-between gap-x-4 rounded-md border p-3",children:[e.jsxs("div",{className:"flex min-w-0 gap-x-3",children:[e.jsx(i,{className:"text-muted-foreground mt-0.5 h-5 w-5 shrink-0","aria-hidden":"true"}),e.jsxs("div",{className:"flex min-w-0 flex-col gap-y-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium break-words",children:s}),t.current&&e.jsx("span",{className:"bg-primary/10 text-primary rounded px-1.5 py-0.5 text-xs font-medium",children:c("security.sessionCurrent")})]}),n&&s!==n&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:n}),r&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:r}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:[t.lastActiveAt&&e.jsxs(e.Fragment,{children:[c("security.sessionLastActive",{date:k(t.lastActiveAt)}),t.expiresAt&&" · "]}),t.expiresAt&&c("security.sessionExpires",{date:k(t.expiresAt)})]})]})]}),!t.current&&y&&e.jsx(Ma,{variant:"ghost",size:"sm",progress:f===t.id,onClick:()=>g(t.id),className:"text-destructive hover:bg-destructive/10 hover:text-destructive shrink-0",children:w})]},t.id)})})]})},exports.SessionsApi=we,exports.SettingsApi=xe,exports.SettingsScreen=la,exports.SidebarNavItem=function({icon:t,label:n,active:r=!1,onClick:s,className:i}){return e.jsxs("button",{className:U("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",r?"bg-primary/10 text-primary font-medium":"hover:bg-muted hover:text-foreground",i),onClick:s,"aria-current":r?"true":void 0,children:[t,e.jsx("span",{className:"min-w-0 truncate",children:n}),e.jsx(o.ChevronRight,{"aria-hidden":"true",className:"h-4 w-4 ms-auto opacity-40 sm:hidden rtl:rotate-180"})]})},exports.SidebarNavSection=function({title:t,children:n,className:r}){return e.jsxs("div",{className:U("px-2 flex flex-col gap-1",r),children:[e.jsx("div",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wide px-2 pb-1 shrink-0 whitespace-nowrap",children:t}),n]})},exports.Skeleton=mo,exports.StatusBanner=Za,exports.SubscriptionContextProvider=wi,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus=_t,exports.UIConfigProvider=Ji,exports.UPLOAD_ACCEPT="image/png,image/jpeg,image/gif,image/webp,image/svg+xml",exports.UPLOAD_MAX_BYTES=ke,exports.UploadsApi=Ee,exports.UserApi=Ae,exports.WhenAuthenticated=bc,exports.WhenCreditsAvailable=dl,exports.WhenCreditsExhausted=pl,exports.WhenCreditsLow=hl,exports.WhenNoSubscription=el,exports.WhenNotTrialing=rl,exports.WhenPendingInvitations=Sc,exports.WhenPermission=Uc,exports.WhenQuotaAvailable=il,exports.WhenQuotaExhausted=al,exports.WhenQuotaOverage=ol,exports.WhenQuotaThreshold=cl,exports.WhenRoles=Ac,exports.WhenSubscription=Xc,exports.WhenSubscriptionToPlans=tl,exports.WhenTrialEnding=sl,exports.WhenTrialing=nl,exports.WhenUnauthenticated=wc,exports.WhenUserFeatureDisabled=Zc,exports.WhenUserFeatureEnabled=Qc,exports.WhenWorkspaceFeatureDisabled=Yc,exports.WhenWorkspaceFeatureEnabled=Kc,exports.WhenWorkspaceRoles=_c,exports.WorkspaceApi=We,exports.WorkspaceSwitcher=function(n){const{t:r,dir:s}=Cr(),{isAuthenticated:i,user:a}=ba(),c=De(li()),{workspaces:l,currentWorkspace:u,loading:d,refreshing:p,switchingToId:h,fetchWorkspaces:m,getFeatures:f,refreshWorkspaces:g,setCurrentWorkspace:y,switchToWorkspace:v}=fa(),{settings:b,loading:w}=pi(),{visible:x}=io(),[k,S]=t.useState(!1),[C,I]=t.useState(0),[N,P]=t.useState(""),j=d||p;t.useEffect(()=>{i&&c&&(0===l.length?(m(),f()):f())},[i,c]),t.useEffect(()=>{i&&c&&C>0&&g()},[C,i,c]);const E=l,A=E.filter(e=>e._id!==u?._id).filter(e=>e.name.toLowerCase().includes(N.toLowerCase())),_=(b?.workspace?.canCreateWorkspace??!0)&&x(e=>e.workspaceSwitcher?.createButton),U=(b?.workspace?.showSwitcher??!0)&&x(e=>e.workspaceSwitcher?.show),T=b?.workspace?.maxWorkspacesPerUser??0,R=E?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===a?.id?.toString()).length??0,O=!1!==_&&(0===T||R<T);t.useEffect(()=>{!U&&l.length>0&&!u&&v(l[0]).catch(e=>{q(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[U,l,u]);const{emit:F}=sa();return t.useEffect(()=>{k&&U&&F("workspace_switcher_opened",{workspace_count:l.length})},[k]),w&&!b?e.jsx(e.Fragment,{children:n.trigger?.(!0,u)}):!U&&u?e.jsxs(e.Fragment,{children:[e.jsx("div",{role:"button",tabIndex:0,"aria-label":r("settings.common.openSettings"),className:"cursor-pointer",onClick:()=>S(!0),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),S(!0))},children:n.trigger?.(j,u)}),e.jsx(t.Suspense,{fallback:null,children:e.jsx(bl,{workspace:u,open:k,onOpenChange:S,showTrigger:!1})})]}):e.jsxs(qa,{open:k,onOpenChange:S,children:[e.jsx(Ba,{children:n.trigger?.(j,u)}),e.jsxs(Ga,{dir:s,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e.jsxs(Ja,{dir:s,children:[e.jsxs(Ka,{className:"flex items-center gap-2",children:[e.jsx(o.Building2,{className:"h-5 w-5"}),r("workspace.switchTitle")]}),e.jsx(Ya,{children:r("workspace.switchDescription")})]}),!a&&e.jsx("div",{className:"flex flex-col items-center justify-center h-full py-4 sm:py-8",children:e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:r("workspace.notLoggedIn")})}),a&&e.jsxs("div",{dir:s,className:"flex flex-col gap-4",children:[u&&e.jsx(xl,{workspace:u,isCurrentWorkspace:!0,switchToWorkspace:v,switchingToId:h,setCurrentWorkspace:y,setOpen:S,workspacesToUse:E}),e.jsx(vl,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:r("workspace.availableWorkspaces",{count:A.length})}),e.jsx("div",{children:e.jsx(Ma,{progress:p,disabled:p,variant:"ghost",onClick:function(){i&&c&&I(e=>e+1)},startIcon:e.jsx(o.RefreshCcw,{}),children:r("settings.common.refreshAction",{loading:String(p)})})})]}),e.jsxs("div",{className:"relative",children:[e.jsx(o.Search,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(Wo,{placeholder:r("workspace.searchPlaceholder"),value:N,onChange:e=>P(e.target.value),className:"ps-10"})]}),d?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(o.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ms-2 text-sm text-muted-foreground",children:r("workspace.loadingWorkspaces")})]}):0===A.length?e.jsx("div",{className:"text-center py-8",children:N?e.jsx(wl,{message:r("workspace.noWorkspacesFound")}):e.jsx(Sc,{fallbackComponent:e.jsx(wl,{message:r("workspace.noWorkspacesAvailable")}),children:e.jsx(kc,{title:null,description:null,className:"text-start"})})}):e.jsx(ec,{className:"h-64",dir:s,children:e.jsx("div",{dir:s,className:"flex flex-col gap-2 my-2.5",children:A.map(t=>{const n=t._id===u?._id;return e.jsx(xl,{workspace:t,isCurrentWorkspace:n,switchToWorkspace:v,switchingToId:h,setCurrentWorkspace:y,setOpen:S,workspacesToUse:E},t._id)})})})]}),O&&e.jsxs(e.Fragment,{children:[e.jsx(vl,{}),e.jsx(kl,{onCreated:()=>{m()}})]})]})]})]})},exports.actionableInvitations=ln,exports.appPermissionCatalogue=nn,exports.calculateBillableSeats=Wt,exports.calculateSeatOverageCents=Dt,exports.calculateTotalSubscriptionCents=function(e,t,n,r){const s=Tt(e,t,n);return null===s?null:void 0===r?s:s+(Dt(e,t,n,r)??0)},exports.cleanBBParams=at,exports.clearAuthIntent=function(){J(pt)},exports.clearPendingInvite=yn,exports.cn=U,exports.coerceBadgeRef=jc,exports.consumeAuthIntent=ft,exports.createBBUrl=rt,exports.createCheckoutRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:rt({action:et.Checkout,status:tt.Success,ws:e,screen:nt.Subscription},n),cancelUrl:rt({action:et.Checkout,status:tt.Cancel,ws:e,screen:nt.Subscription},n)}},exports.createCreditPurchaseRedirectUrls=st,exports.eventEmitter=Me,exports.fillMcpTemplate=Fi,exports.formatCents=Pt,exports.formatDate=co,exports.formatDateTime=function(e,t="en-US"){return co(e,t,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})},exports.formatMinorAmountIntl=Nt,exports.formatOverageRate=function(e,t,n,r,s){if(null==e||e<0)return null;const i={...jt,...r},a=null!=t&&t>=1?t:1,o=vt(n),c=It(e,n);return 1===a?`${o}${c}/${i.unit}`:`${o}${c}/${a.toLocaleString(s)} ${i.units}`},exports.formatOverageRateWithLabel=function(e,t,n,r,s,i,a){if(null==e||e<0)return null;const o={...jt,...i},c=null!=t&&t>=1?t:1,l=vt(r),u=It(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${u}/${c.toLocaleString(a)} ${e}`:`${l}${u}/${n}`}return 1===c?`${l}${u}/${o.unit}`:`${l}${u}/${c.toLocaleString(a)} ${o.units}`},exports.formatQuotaIncludedOverage=function(e,t,n,r,s,i,a,o,c){const l={...jt,...a};if(!1===o)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:a?.hardLimit??"Hard limit";const u=i??(n.endsWith("s")?n:`${n}s`),d=null!=s&&s>=2?`${s.toLocaleString(c)} ${u}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${Pt(t,r)}/${d}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${Pt(t,r)}/${d}`:"—"},exports.formatQuotaWithPrice=function(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,i={...Et,...n.labels},a=n.currencySymbol??vt(s??"");if(null==e)return"—";const{included:o,overage:c}=e,l=`${o} ${i.included}`;if(!1===e.allowOverage)return`${l} (${i.hardLimit})`;if(null==c)return l;const u=Ct(s),d=r&&u>0?c/10**u:c,p="number"==typeof d&&Number.isFinite(d)?0===u?d.toLocaleString("en-US"):d.toFixed(u):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${i.then} ${a}${p}${h}`},exports.formatUnixDate=function(e,t="en-US"){return e?new Date(1e3*e).toLocaleDateString(t,{year:"numeric",month:"short",day:"numeric"}):""},exports.formatUploadLimit=je,exports.getAvailableBillingIntervals=function(e,t){return[At.Monthly,At.Quarterly,At.Yearly].filter(n=>n===At.Monthly||e.some(e=>null!=Tt(e,t,n)))},exports.getAvailableCurrenciesFromPlans=function(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()},exports.getBasePriceCents=Tt,exports.getBillingIntervalAndCurrencyFromPriceId=function(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},exports.getCurrencyDecimals=Ct,exports.getCurrencyFlag=function(e){return e&&e.trim()?yt[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=vt,exports.getDisplayCurrency=function(e,t){const n=Ut(e,t);return n?n.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=Ft,exports.getPricingVariant=Ut,exports.getQuotaDisplayParts=function(e,t,n={}){if(null==e)return null;const{overageInCents:r=!0,currency:s,locale:i="en"}=n,{included:a,overage:o}=e;if(!(!1!==e.allowOverage))return{included:a,hasOverage:!1,allowOverage:!1,price:"",unit:""};if(null==o)return{included:a,hasOverage:!1,allowOverage:!0,price:"",unit:""};const c=Ct(s),l=r&&c>0?o/10**c:o,u=(s??"").trim().toUpperCase();let d;if(u&&"number"==typeof l&&Number.isFinite(l))try{d=new Intl.NumberFormat(i,{style:"currency",currency:u,minimumFractionDigits:c,maximumFractionDigits:c}).format(l)}catch{d=`${n.currencySymbol??vt(s??"")}${l.toFixed(c)}`}else{d=`${n.currencySymbol??vt(s??"")}${"number"==typeof l?l.toFixed(c):String(o)}`}return{included:a,hasOverage:!0,allowOverage:!0,price:d,unit:t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(i)} ${t}`:t||""}},exports.getQuotaDisplayValue=function(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},exports.getQuotaDisplayWithVariant=function(e,t,n,r){const s=e.quotas?.[n];if(null==s)return null;const i=s[r];if(!i)return null;const a=Rt(e,t,n,r);return{included:i.included,...void 0!==i.unitSize&&{unitSize:i.unitSize},...void 0!==a&&{overage:a},allowOverage:!1!==s.allowOverage}},exports.getQuotaOverageCents=Rt,exports.getQuotaUnitLabelFromName=function(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},exports.getSeatPricing=Ot,exports.getStripePriceIdForInterval=function(e,t,n){const r=Ut(e,t);if(!r?.stripePrices)return null;const s=n===At.Monthly?"monthlyPriceId":n===At.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===At.Monthly?"monthly":n===At.Yearly?"yearly":void 0;return r.stripePrices[s]??(i?r.stripePrices[i]:void 0)??null},exports.getSvgImage=sc,exports.handleError=q,exports.hasPermission=function(e,t){const n=Xt(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)},exports.invalidateCreditBalance=Ge,exports.invalidateQuotaUsage=Ke,exports.invalidateSubscription=Ze,exports.inviterNameOf=dn,exports.isInvitationActionable=cn,exports.isInvitationError=Fe,exports.isInvitationLapsed=function(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!cn(e,t)},exports.isWorkspaceOwner=Gt,exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===Ct(e)},exports.mcpServerKey=Wi,exports.mergeUIConfig=function(e,t){return t?Ki(e,t):e},exports.minorAmountToDisplay=It,exports.parkPendingInvite=fn,exports.pickDefaultRole=function(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(Qt)?Qt:e.find(e=>"admin"!==e)??""},exports.preflightUpload=Pe,exports.readBBParams=it,exports.readPendingInvite=gn,exports.resendCooldownSeconds=function(e,t=new Date){const n=an(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0},exports.resolveMaxUsers=Lt,exports.resolvePermissions=Xt,exports.resolveRolePermissions=en,exports.safeRedirect=dt,exports.saveAuthIntent=mt,exports.shouldLoadWorkspaceInvitations=function(e){return e.canView},exports.sortInvitations=on,exports.toMajorUnits=rs,exports.uploadFailureOf=Ie,exports.uploadPolicyOf=Ne,exports.useAllQuotaUsage=vi,exports.useBillingPortal=e=>{const{t:n}=Cr(),{api:r}=hi(),[s,i]=t.useState(!1),[a,o]=t.useState(null);return{openBillingPortal:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");i(!0),o(null);try{const n=t||window.location.href,s=await r.createBillingPortalSession(e,n);return s.url&&window.open(s.url,"_blank","noopener,noreferrer"),s}catch(t){const r=V(t,"errors.openBillingPortal",n);throw o(r),q(t,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),t}finally{i(!1)}},[e,r]),loading:s,error:a}},exports.useCancelSubscription=e=>{const{t:n}=Cr(),{api:r}=hi(),[s,i]=t.useState(!1),[a,o]=t.useState(null);return{cancelSubscription:t.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");i(!0),o(null);try{const t=await r.cancelSubscriptionAtPeriodEnd(e);return Ze(),t}catch(t){const r=V(t,"errors.cancelSubscription",n);throw o(r),q(t,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),t}finally{i(!1)}},[r,e]),loading:s,error:a}},exports.useConnectedAgents=oo,exports.useConnectedAgentsApi=ao,exports.useConsumeCredits=Si,exports.useCreateCheckoutSession=e=>{const{t:n}=Cr(),{api:r}=hi(),{getCheckoutStripeParams:s}=t.useContext(lr),{track:i,consent:a,getProperties:o}=ri(),c=si(),[l,u]=t.useState(!1),[d,p]=t.useState(null);return{createCheckoutSession:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");u(!0),p(null);const l=Ps();try{const n=s?await s(t):void 0,u=c?_s(l,a.effective,o(),As({...t.stripeOptions?.metadata,...n?.metadata},{...t.stripeOptions?.subscriptionMetadata,...n?.subscriptionMetadata})):{},d=Object.keys(u).length>0||n?{...t,stripeOptions:{...t.stripeOptions,...n,metadata:{...u,...t.stripeOptions?.metadata,...n?.metadata},subscriptionMetadata:{...u,...t.stripeOptions?.subscriptionMetadata,...n?.subscriptionMetadata}}}:t,p=await r.createCheckoutSession(e,d),h="checkout"!==p.type&&p.type?void 0:p,m=h?.currency??t.currency,f=rs(h?.amountTotal,m);return h&&c&&Gr({eventId:l,workspaceId:e,planVersionId:t.planVersionId,billingInterval:t.billingInterval,currency:m,sessionId:h.sessionId,value:f,kind:h.trial?"trial_started":"purchase",startedAt:Date.now()}),i("trial_started"===p.type?"trial_started":"checkout_started",{plan_version_id:t.planVersionId,...t.billingInterval?{billing_interval:t.billingInterval}:{},...m?{currency:m.toUpperCase()}:{},..."number"==typeof f?{value:f}:{}},{eventId:l}),"trial_started"===p.type&&(Ze(),Ke()),p}catch(r){const s=V(r,"errors.createCheckout",n);throw p(s),q(r,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:t}}),r}finally{u(!1)}},[r,e,s,i,n,a.effective,c]),loading:l,error:d}},exports.useCreditBalance=ki,exports.useCreditBalanceContext=Ei,exports.useCreditPackages=Ii,exports.useCreditTransactions=(e,n)=>{const{t:r}=Cr(),{api:s}=hi(),[i,a]=t.useState([]),[o,c]=t.useState(0),[l,u]=t.useState(0),[d,p]=t.useState(1),[h,m]=t.useState(!1),[f,g]=t.useState(!1),[y,v]=t.useState(!1),[b,w]=t.useState(null),{begin:x,settle:k}=Pr(),S=n?.type,C=n?.page,I=n?.limit,N=t.useCallback(async()=>{if(!e)return x(),a([]),c(0),u(0),p(1),m(!1),g(!1),void v(!1);const t=x();v(!0),w(null);try{const n=await s.getCreditTransactions(e,{type:S,page:C,limit:I});if(t.signal.aborted)return;a(n.docs||[]),c(n.totalDocs||0),u(n.totalPages||0),p(n.page||1),m(n.hasNextPage||!1),g(n.hasPrevPage||!1)}catch(n){if(t.signal.aborted)return;const s=V(n,"errors.fetchCreditTransactions",r);w(s),q(n,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{k(t)&&v(!1)}},[s,e,S,C,I,x,k]);return t.useEffect(()=>{N()},[N]),{transactions:i,totalDocs:o,totalPages:l,page:d,hasNextPage:h,hasPrevPage:f,loading:y,error:b,refetch:N}},exports.useDevices=To,exports.useDevicesApi=Uo,exports.useExpiringCredits=(e,n)=>{const{t:r}=Cr(),{api:s}=hi(),[i,a]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Pr(),h=t.useCallback(async()=>{if(!e)return d(),a(null),void c(!1);const t=d();c(!0),u(null);try{const r=await s.getExpiringCredits(e,n);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const i=V(s,"errors.fetchExpiringCredits",r);u(i),q(s,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:n}})}finally{p(t)&&c(!1)}},[s,e,n,d,p]);return t.useEffect(()=>{h()},[h]),{expiringCredits:i?.expiringCredits??0,buckets:i?.buckets??[],days:i?.days??n??7,loading:o,error:l,refetch:h}},exports.useFullScreenLoader=Ri,exports.useFunnel=sa,exports.useGateReport=ra,exports.useInvoice=(e,n)=>{const{t:r}=Cr(),{api:s}=hi(),[i,a]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Pr(),h=t.useCallback(async()=>{if(!e||!n)return d(),a(null),void c(!1);const t=d();c(!0),u(null);try{const r=await s.getInvoice(e,n);if(t.signal.aborted)return;a(r.invoice)}catch(s){if(t.signal.aborted)return;const i=V(s,"errors.fetchInvoice",r);u(i),q(s,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:n}})}finally{p(t)&&c(!1)}},[s,e,n,d,p]);return t.useEffect(()=>{h()},[h]),{invoice:i,loading:o,error:l,refetch:h}},exports.useInvoices=(e,n=10,r)=>{const{t:s}=Cr(),{api:i}=hi(),[a,o]=t.useState([]),[c,l]=t.useState(!1),[u,d]=t.useState(!1),[p,h]=t.useState(null),{begin:m,settle:f}=Pr(),g=t.useCallback(async()=>{if(!e)return m(),o([]),l(!1),void d(!1);const t=m();d(!0),h(null);try{const s=await i.listInvoices(e,n,r);if(t.signal.aborted)return;o(s.invoices||[]),l(s.has_more||!1)}catch(i){if(t.signal.aborted)return;const a=V(i,"errors.fetchInvoices",s);h(a),q(i,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:n,startingAfter:r}})}finally{f(t)&&d(!1)}},[i,e,n,r,m,f]);return t.useEffect(()=>{g()},[g]),{invoices:a,hasMore:c,loading:u,error:p,refetch:g}},exports.useMcpConnection=Li,exports.useMyInvitations=xc,exports.useNotifications=Gc,exports.useNotificationsApi=Tc,exports.usePermissionConfig=qi,exports.usePermissions=so,exports.usePlanGroup=gi,exports.usePlanGroupVersions=e=>{const{t:n}=Cr(),{api:r}=hi(),[s,i]=t.useState(null),[a,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Pr(),p=t.useCallback(async()=>{if(!e)return u(),i(null),void o(!1);const t=u();o(!0),l(null);try{const n=await r.getPlanGroupVersions(e);if(t.signal.aborted)return;i(n)}catch(r){if(t.signal.aborted)return;const s=V(r,"errors.fetchPlanGroupVersions",n);l(s),q(r,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{d(t)&&o(!1)}},[r,e,u,d]);return t.useEffect(()=>{p()},[p]),{versions:s,loading:a,error:c,refetch:p}},exports.usePublicCreditPackages=Ni,exports.usePublicPlanGroupVersion=e=>{const{t:n}=Cr(),{api:r}=hi(),[s,i]=t.useState(null),[a,o]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Pr(),p=t.useCallback(async()=>{if(!e)return u(),i(null),void o(!1);const t=u();o(!0),l(null);try{const n=await r.getPlanGroupVersion(e);if(t.signal.aborted)return;i(n)}catch(r){if(t.signal.aborted)return;const s=V(r,"errors.fetchPlanGroupVersion",n);l(s),q(r,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{d(t)&&o(!1)}},[r,e,u,d]);return t.useEffect(()=>{p()},[p]),{planGroupVersion:s,loading:a,error:c,refetch:p}},exports.usePublicPlans=mi,exports.usePurchaseCredits=Ci,exports.usePushNotifications=function(){const e=t.useContext(Ca);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e},exports.useQuotaUsageContext=zi,exports.useQuotaUsageStatus=(e,n)=>{const{t:r}=Cr(),{api:s}=hi(),[i,a]=t.useState(null),[o,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Pr(),h=t.useCallback(async()=>{if(!e||!n)return d(),a(null),void c(!1);const t=d();c(!0),u(null);try{const r=await s.getQuotaUsageStatus(e,n);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const i=V(s,"errors.fetchQuotaUsage",r);u(i),q(s,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:n}})}finally{p(t)&&c(!1)}},[s,e,n,d,p]);return t.useEffect(()=>{h()},[h]),{status:i,loading:o,error:l,refetch:h}},exports.useRecordUsage=e=>{const{t:n}=Cr(),{api:r}=hi(),[s,i]=t.useState(!1),[a,o]=t.useState(null);return{recordUsage:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");i(!0),o(null);try{const n=await r.recordUsage(e,t);return Ke(),n}catch(r){const s=V(r,"errors.recordUsage",n);throw o(s),q(r,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:t}}),r}finally{i(!1)}},[r,e]),loading:s,error:a}},exports.useResumeSubscription=e=>{const{t:n}=Cr(),{api:r}=hi(),[s,i]=t.useState(!1),[a,o]=t.useState(null);return{resumeSubscription:t.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");i(!0),o(null);try{const t=await r.resumeSubscription(e);return Ze(),t}catch(t){const r=V(t,"errors.resumeSubscription",n);throw o(r),q(t,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),t}finally{i(!1)}},[r,e]),loading:s,error:a}},exports.useSaaSAuth=ba,exports.useSaaSOs=li,exports.useSaaSSettings=pi,exports.useSaaSWorkspaces=fa,exports.useSeatStatus=function(e,n){const{response:r}=xi(),{settings:s}=pi(),i=n?.settingsMaxUsers??s?.workspace?.maxWorkspaceUsers;return t.useMemo(()=>{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 t=(e.users?.length??0)+(n?.pendingInvitations??0),s=r?.planVersion,a=r?.subscription,o=e.billingCurrency||"usd",c=Lt({planVersion:s,currency:o,settingsMaxUsers:i}),{maxUsers:l,hasSeatPricing:u,includedSeats:d}=c,p=u?Math.max(0,t-d):0,h=l>0?Math.max(0,l-t):1/0,m=l>0&&t>=l,f=l>0&&t>=.8*l&&!m,g=u&&s?Ft(s,o,a?.billingInterval??"monthly"):null,y=$t({memberCount:t,maxUsersConfig:c});return{hasSeatPricing:u,memberCount:t,includedSeats:d,maxUsers:l,maxSeats:l,limitSource:c.source,billableSeats:p,availableSeats:h,isAtMax:m,isNearMax:f,perSeatPriceCents:g,currency:o,canInvite:y.canInvite,inviteBlockReason:y.blockReason,inviteBlockMessageKey:y.blockMessageKey,inviteBlockMessageValues:y.blockMessageValues}},[r,e,i,n?.pendingInvitations])},exports.useSessions=Lo,exports.useSessionsApi=Do,exports.useSubscription=fi,exports.useSubscriptionContext=xi,exports.useSubscriptionManagement=(e,n)=>{const r=fi(e),s=gi(e,n),i=yi(e),a=t.useCallback(async()=>{await Promise.all([r.refetch(),s.refetch()])},[r.refetch,s.refetch]);return{subscription:r.subscription,planGroup:s.planGroup,loading:r.loading||s.loading||i.loading,error:r.error||s.error||i.error,updateSubscription:i.updateSubscription,refetch:a}},exports.useTranslation=Cr,exports.useTrialStatus=function(){const{response:e}=xi();return t.useMemo(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const n=ml(t.trialEnd)??ml(t.stripeCurrentPeriodEnd),r=ml(t.trialStart),s=n?Math.max(0,Math.ceil((n.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:s,trialEndsAt:n,trialStartedAt:r,isTrialEnding:s<=3}},[e])},exports.useUIConfig=Hi,exports.useUIVisibility=io,exports.useUpdateSubscription=yi,exports.useUpload=function(e){const n=nc(),{settings:r}=pi(),{t:s,formattingLocale:i}=Cr(),[a,o]=t.useState(!1),[c,l]=t.useState(null),u=t.useRef(null),d=t.useRef(!0),p=t.useMemo(()=>Ne(r),[r]),h=t.useMemo(()=>je(p.maxFileBytes,i),[p.maxFileBytes,i]);t.useEffect(()=>(d.current=!0,()=>{d.current=!1,u.current?.abort()}),[]);const m=t.useCallback(()=>u.current?.abort(),[]),f=t.useCallback(async t=>{u.current?.abort();const r=Pe(t,p);if(r)throw l(r),Object.assign(new Error(`The upload was refused: ${r}.`),{code:"disabled"===r?"UPLOADS_DISABLED":"UPLOAD_TOO_LARGE",status:"disabled"===r?403:413});const s=new AbortController;u.current=s,o(!0),l(null);try{return await n.upload(t,{purpose:e,signal:s.signal})}catch(e){throw!W(e)&&d.current&&l(Ie(e)),B(e,{component:"useUpload",action:"upload"}),e}finally{u.current===s&&(u.current=null,d.current&&o(!1))}},[n,e,p]),g=c?s(rc[c],{max:h}):null;return t.useMemo(()=>({upload:f,cancel:m,loading:a,error:g,failure:c,enabled:p.enabled,maxBytes:p.maxFileBytes,maxLabel:h}),[f,m,a,g,c,p,h])},exports.useUploadsApi=nc,exports.useUsageLogs=(e,n,r)=>{const{t:s}=Cr(),{api:i}=hi(),[a,o]=t.useState([]),[c,l]=t.useState(0),[u,d]=t.useState(0),[p,h]=t.useState(1),[m,f]=t.useState(!1),[g,y]=t.useState(!1),[v,b]=t.useState(!1),[w,x]=t.useState(null),{begin:k,settle:S}=Pr(),C=r?.from,I=r?.to,N=r?.source,P=r?.page,j=r?.limit,E=t.useCallback(async()=>{if(!e)return k(),o([]),l(0),d(0),h(1),f(!1),y(!1),void b(!1);const t=k();b(!0),x(null);try{const r={...n&&{quotaSlug:n},...C&&{from:C},...I&&{to:I},...N&&{source:N},...P&&{page:P},...j&&{limit:j}},s=await i.getUsageLogs(e,r);if(t.signal.aborted)return;o(s.docs||[]),l(s.totalDocs||0),d(s.totalPages||0),h(s.page||1),f(s.hasNextPage||!1),y(s.hasPrevPage||!1)}catch(r){if(t.signal.aborted)return;const i=V(r,"errors.fetchUsageLogs",s);x(i),q(r,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:n}})}finally{S(t)&&b(!1)}},[i,e,n,C,I,N,P,j,k,S]);return t.useEffect(()=>{E()},[E]),{logs:a,totalDocs:c,totalPages:u,page:p,hasNextPage:m,hasPrevPage:g,loading:v,error:w,refetch:E}},exports.useUserAttributes=function(){const e=t.useContext(Da);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return t.useMemo(()=>({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])},exports.useUserFeatures=Hc,exports.useWorkspaceApiWithOs=hi,exports.useWorkspaceInvitations=function(e){const{listInvitations:n,resendInvitation:r,revokeInvitation:s}=fa(),{t:i}=Cr(),{begin:a,settle:o}=Pr(),[c,l]=t.useState([]),[u,d]=t.useState(Boolean(e)),[p,h]=t.useState(null),[m,f]=t.useState(null),g=t.useRef(i);t.useEffect(()=>{g.current=i},[i]);const y=t.useCallback(async()=>{if(!e)return l([]),void d(!1);const t=a();d(!0),h(null);try{const r=await n(e);if(t.signal.aborted)return;l(on(r))}catch(e){if(t.signal.aborted)return;B(e,{component:"useWorkspaceInvitations",action:"list"}),h(V(e,"users.invitations.loadFailed",g.current))}finally{o(t)&&d(!1)}},[e,n,a,o]);t.useEffect(()=>{y()},[y]);const v=t.useCallback(async t=>{if(!e)throw new Error("No workspace");f(t),h(null);try{const n=await r(e,t);return l(e=>on(e.map(e=>e._id===t?{...e,...n}:e))),n}catch(e){throw B(e,{component:"useWorkspaceInvitations",action:"resend"}),h(V(e,"users.invitations.resendFailed",g.current)),e}finally{f(null)}},[e,r]),b=t.useCallback(async t=>{if(!e)throw new Error("No workspace");f(t),h(null);try{await s(e,t),l(e=>e.filter(e=>e._id!==t))}catch(e){throw B(e,{component:"useWorkspaceInvitations",action:"revoke"}),h(V(e,"users.invitations.revokeFailed",g.current)),e}finally{f(null)}},[e,s]),w=t.useMemo(()=>c.filter(e=>cn(e)).length,[c]);return t.useMemo(()=>({invitations:c,pendingCount:w,loading:u,error:p,busy:m,refresh:y,resend:v,revoke:b}),[c,w,u,p,m,y,v,b])},exports.validateInvite=$t,exports.validateRedirectUrl=ut,exports.workspaceCanBeDeleted=function(e){return 1!==pc(e)?.maxWorkspacesPerUser},exports.workspaceEmojis=ic,exports.workspaceIdOf=function(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace},exports.workspaceInvitesEnabled=hc,exports.workspaceNameOf=un,exports.workspaceSettingsManager=da;
|