@buildbase/sdk 0.0.88 → 0.0.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +7 -3
- package/CHANGELOG.md +515 -0
- package/README.md +120 -3
- package/dist/cli.mjs +1 -1
- package/dist/css/styles.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1351 -12
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -1
- package/dist/mcp/index.d.ts +120 -2
- package/dist/mcp/index.mjs +1 -1
- package/dist/react/chunks/SettingsDialog-BVyV5Zfm.mjs +2 -0
- package/dist/react/chunks/SettingsDialog-Ch8X6WXy.cjs +2 -0
- package/dist/react/chunks/{SubscriptionDialog-B8FTFRtp.cjs → SubscriptionDialog-CGIvMKpT.cjs} +1 -1
- package/dist/react/chunks/SubscriptionDialog-g0LwHhbe.mjs +2 -0
- package/dist/react/chunks/ar-3aqWucom.mjs +2 -0
- package/dist/react/chunks/ar-DQVB89r8.cjs +2 -0
- package/dist/react/chunks/de-DO10bhnU.cjs +2 -0
- package/dist/react/chunks/de-HXQk5D6k.mjs +2 -0
- package/dist/react/chunks/es-BZsmhBN3.mjs +2 -0
- package/dist/react/chunks/es-Cxg-qhUh.cjs +2 -0
- package/dist/react/chunks/fr-COCMy3vW.cjs +2 -0
- package/dist/react/chunks/fr-rdnNHzxy.mjs +2 -0
- package/dist/react/chunks/hi-BB0Z-Dgn.cjs +2 -0
- package/dist/react/chunks/hi-t3RH7ITu.mjs +2 -0
- package/dist/react/chunks/ja-CDyla2g0.mjs +2 -0
- package/dist/react/chunks/ja-D92JgUlk.cjs +2 -0
- package/dist/react/chunks/react-DTq7A_PT.mjs +2 -0
- package/dist/react/chunks/react-DeapSbq6.cjs +2 -0
- package/dist/react/chunks/zh-C5HABZZV.mjs +2 -0
- package/dist/react/chunks/zh-DK2yA5wB.cjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +1517 -14
- package/dist/react/index.mjs +1 -1
- package/docs/ERROR_CODES.md +218 -0
- package/docs/THEMING.md +89 -21
- package/docs/UI-CONFIG.md +23 -4
- package/docs/USER-IMPORT.md +320 -0
- package/package.json +2 -1
- package/dist/react/chunks/SettingsDialog-CKVE1PpH.mjs +0 -2
- package/dist/react/chunks/SettingsDialog-DrDmxFEj.cjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-UN7o9Hqb.mjs +0 -2
- package/dist/react/chunks/ar-B2l90OZJ.cjs +0 -2
- package/dist/react/chunks/ar-DVVNZhXD.mjs +0 -2
- package/dist/react/chunks/de-BspJtvAC.mjs +0 -2
- package/dist/react/chunks/de-dURUqbl0.cjs +0 -2
- package/dist/react/chunks/es-DArjREi5.cjs +0 -2
- package/dist/react/chunks/es-vu4BmI3g.mjs +0 -2
- package/dist/react/chunks/fr-DVm5WCvZ.mjs +0 -2
- package/dist/react/chunks/fr-DhYDaYrX.cjs +0 -2
- package/dist/react/chunks/hi-C_nv_c1T.cjs +0 -2
- package/dist/react/chunks/hi-VW8xCj_K.mjs +0 -2
- package/dist/react/chunks/ja-C-b88dvw.mjs +0 -2
- package/dist/react/chunks/ja-CqtDkLHr.cjs +0 -2
- package/dist/react/chunks/react-CHivaJhA.mjs +0 -2
- package/dist/react/chunks/react-Ch_Suxxy.cjs +0 -2
- package/dist/react/chunks/zh-D1yfhUf0.mjs +0 -2
- package/dist/react/chunks/zh-D_tMpsNt.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("lucide-react"),a=require("intl-messageformat"),i=require("@radix-ui/react-slot"),o=require("class-variance-authority"),c=require("@radix-ui/react-dialog"),l=require("@radix-ui/react-icons"),d=require("@hookform/resolvers/zod"),u=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"),w=require("@radix-ui/react-accordion"),b=require("@radix-ui/react-alert-dialog"),v=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),A=x(g),E=x(y),j=x(w),P=x(b),_=x(v);function T(...e){return r.twMerge(n.clsx(e))}let U=!0;function R(e,...t){U&&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&&(U=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 Y(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 H(e,t){try{G(e,JSON.stringify(t))}catch(t){q(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const K="saas-session-id",Q="saas-device-id",Z="code",X="state";function ee(e){G(K,e)}function te(){J(K)}function ne(){if("undefined"==typeof window)return null;try{return z(K)}catch(e){return q(e,{component:"auth-utils",action:"getSessionId",metadata:{key:K}}),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 ae(){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 ie(){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=Symbol.for("@buildbase/sdk/unreachable"),ce=/^(failed to fetch|networkerror when attempting to fetch resource\.?|load failed|fetch failed|network request failed)$/i;function le(e){return Object.defineProperty(e,oe,{value:!0}),e}function de(e){if(!e||"object"!=typeof e)return!1;if(!0===e[oe])return!0;const{name:t,message:n}=e;return"TypeError"===t&&"string"==typeof n&&ce.test(n)}const ue=new WeakSet,pe=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),he="SDK is not ready (missing serverUrl, version, or orgId)";class me{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(he);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(he)}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){ue.has(e)||(ue.add(e),this._onError?.(e,t))}async executeFetch(e,t,n={}){return this.executeFetchUrl(this.url(e),t,e,n)}notifyUnauthorized(){this._onUnauthorized?.()}static delay(e,t){return new Promise((n,r)=>{const s=()=>{clearTimeout(a),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const a=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,n,r={}){const s=(t.method??"GET").toUpperCase(),a=n??e,i=this.buildHeaders(t),o={...t,headers:i},c=pe.has(s);let l,d;if(this._timeout>0){d=new AbortController;const e=d;l=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?F(t.signal,e.signal):e.signal}const u=e=>{if(d?.signal.aborted&&!t.signal?.aborted){const e=le(new Error(`Request timeout after ${this._timeout}ms: ${s} ${a}`));return this.reportError(e,{method:s,path:a}),e}return e},p=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),a=await n(e,o);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${a.status}`),401===a.status&&this._onUnauthorized&&!r.deferUnauthorized&&this._onUnauthorized(),a.status>=500&&c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await me.delay(e,o.signal),p(t+1)}return a}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw u(e);if(c&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await me.delay(e,o.signal)}catch(e){throw u(e)}return p(t+1)}throw e instanceof TypeError&&le(e),e instanceof Error&&this.reportError(e,{method:s,path:a}),e}};try{return await p(0)}finally{void 0!==l&&clearTimeout(l)}}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={},n={}){return this.ensureReady(),this.executeFetch(e,t,n)}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,r=!1;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`,r=!0}const s=Object.assign(new Error(n),{status:e.status});throw r?le(s):s}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 fe extends me{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let s=await r(e);if(400===s.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken||e.locale)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:a,invitationToken:i,locale:o,...c}=e;s=await r(c)}return s.ok||await this.throwResponseError(s,n),this.unwrapResponse(s,n)}async getUsernamePolicy(e,t){const n=`${this.serverUrl}/api/${this.version}/auth/config?org=${encodeURIComponent(e)}`,r="Failed to fetch the sign-in settings",s=await this.fetchAbsoluteUrl(n,{signal:t});s.ok||await this.throwResponseError(s,r);const a=await this.unwrapResponse(s,r),i=a?.username??{},o=!0===i.enabled;return{enabled:o,required:o&&!0===i.required}}async getAccountDeletionGraceDays(e,t){const n=`${this.serverUrl}/api/${this.version}/auth/config?org=${encodeURIComponent(e)}`,r="Failed to fetch the sign-in settings",s=await this.fetchAbsoluteUrl(n,{signal:t});s.ok||await this.throwResponseError(s,r);const a=await this.unwrapResponse(s,r),i=Number((a?.security??{}).accountDeletionGraceDays);return Number.isFinite(i)?Math.min(30,Math.max(0,Math.floor(i))):7}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 ge extends me{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}let ye=class{constructor(e){this.api=new ge(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),a=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:s,currency:a}})}};class we extends me{constructor(e){super(e)}async list(e){const t=await this.fetchJson("connected-agents",{signal:e},"Failed to load connected agents");return t?.agents??[]}async revoke(e){await this.fetchJson("connected-agents/revoke",{method:"POST",body:JSON.stringify({clientId:e})},"Failed to disconnect agent")}}class be extends me{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,n){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}function ve(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 xe=e=>JSON.stringify(e?{workspaceId:e}:{});class ke extends me{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${ve({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${ve({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:xe(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:xe(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 Se extends me{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class Ce extends me{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class Ie extends me{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}const Ne=5242880,Ae={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"};function Ee(e){if(e.type)return e.type;const t=(e.name??"").split(".").pop()?.toLowerCase()??"";return Ae[t]??""}function je(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 Pe(e){const t=e?.uploads,n=Number(t?.maxFileBytes);return{enabled:!!t&&!1!==t.enabled,maxFileBytes:Number.isFinite(n)&&n>0?Math.min(n,Ne):Ne}}function _e(e,t){return t.enabled?e.size>t.maxFileBytes?"tooLarge":null:"disabled"}function Te(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 Ue extends me{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:Ee(e)}),signal:r},"Could not start the upload");let a;const i=new AbortController,o=setTimeout(()=>i.abort(),12e4);try{a=await this.fetchForeign(s.url,{method:"PUT",headers:s.headers,body:e,signal:r?F(r,i.signal):i.signal})}catch(e){if(r?.aborted)throw e;throw new Error("The upload to storage did not finish. Check the connection and try again.")}finally{clearTimeout(o)}if(!a.ok)throw Object.assign(new Error(`The upload to storage was refused (HTTP ${a.status}). Try again.`),{status:a.status});return this.fetchJson(this.apiPath`uploads/${s.uploadId}/complete`,{method:"POST",body:"{}",signal:r},"Could not finish the upload")}}class Re extends me{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}const Oe={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"},Fe={402:Oe.SEAT_LIMIT,404:Oe.NOT_FOUND,409:Oe.ALREADY_HANDLED,410:Oe.EXPIRED,429:Oe.RATE_LIMITED,502:Oe.EMAIL_FAILED,503:Oe.NO_SENDER_CONFIGURED};function We(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function De(e){return"string"==typeof e&&e?e:void 0}async function Le(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=De(r.message)??De(r.error)??n,a={status:e,code:De(r.code)??Fe[e]??`HTTP_${e}`,currentUserCount:We(r.currentUserCount),limit:We(r.limit),retryAfterSeconds:We(r.retryAfterSeconds),invitedEmail:De(r.invitedEmail),invitationId:De(r.invitationId),invitationStatus:De(r.status)};return Object.assign(new Error(s),a)}(e.status,n,t)}function $e(e){return e instanceof Error&&"number"==typeof e.status}function Me(e){return"string"==typeof e&&e.length>0}function qe(e){return"number"==typeof e&&Number.isInteger(e)&&e>0}function Be(e){return"number"==typeof e&&Number.isFinite(e)?Math.max(0,Math.ceil(e)):void 0}class Ve extends me{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await Le(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 changePassword(e,t,n){await this.fetchWithReason("profile/password",{method:"POST",body:JSON.stringify({currentPassword:e,newPassword:t}),signal:n},"Failed to change password")}async fetchWithReason(e,t,n,r=[]){const s=r.length>0,a=await this.fetchResponse(e,t,{deferUnauthorized:s});if(!a.ok){let e,t,i=n,o={},c=!1;try{const n=await a.json();"string"==typeof n?.message&&n.message&&(i=n.message),"string"==typeof n?.reason&&n.reason&&(e=n.reason),t=Be(n?.retryAfter),o=function(e){if(!e||"object"!=typeof e)return{};const{maxAgeSeconds:t,factors:n,workspaces:r}=e,s={},a=Be(t);if(void 0!==a&&(s.maxAgeSeconds=a),Array.isArray(n)){const e=n.filter(e=>"mfa"===e);e.length&&(s.factors=e)}return Array.isArray(r)&&(s.workspaces=r.filter(e=>!!e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.name).map(({id:e,name:t})=>({id:e,name:t}))),s}(n)}catch{i=`${n} (${a.status}: ${a.statusText})`,c=!0}!s||401!==a.status||void 0!==e&&r.includes(e)||this.notifyUnauthorized();const l=Object.assign(new Error(i),{status:a.status,...e?{code:e}:{},...void 0!==t?{retryAfter:t}:{},...o});throw c?le(l):l}return this.unwrapResponse(a,n)}static compactCode(e){return e.replace(/\s+/g,"")}async requestEmailChange(e,t){const n=await this.fetchWithReason("profile/email",{method:"POST",body:JSON.stringify({newEmail:e.trim()}),signal:t},"Failed to send the code");return{retryAfter:Be(n?.retryAfter)??0}}async confirmEmailChange(e,t){return this.fetchWithReason("profile/email/confirm",{method:"POST",body:JSON.stringify({code:Ve.compactCode(e)}),signal:t},"Failed to change email",["code_expired"])}async addPhone(e,t,n){const r=await this.fetchWithReason("profile/phone",{method:"POST",body:JSON.stringify({phone:e.trim(),...t?{channel:t}:{}}),signal:n},"Failed to send the code");return{retryAfter:Be(r?.retryAfter)??0}}async confirmPhone(e,t){const n=await this.fetchWithReason("profile/phone/confirm",{method:"POST",body:JSON.stringify({code:Ve.compactCode(e)}),signal:t},"Failed to verify the phone number");return{phone:"string"==typeof n?.phone?n.phone:"",phoneVerified:!0}}async removePhone(e){await this.fetchWithReason("profile/phone",{method:"DELETE",signal:e},"Failed to remove the phone number")}async getMfaStatus(e){return this.fetchWithReason("mfa",{signal:e},"Failed to fetch two-step sign-in status")}async startTotpEnrollment(e){return this.fetchWithReason("mfa/totp/enroll",{method:"POST",signal:e},"Failed to start authenticator app setup")}async confirmTotpEnrollment(e,t){return this.fetchWithReason("mfa/totp/confirm",{method:"POST",body:JSON.stringify({code:Ve.compactCode(e)}),signal:t},"Failed to confirm authenticator app")}async disableTotp(e,t){await this.fetchWithReason("mfa/totp/disable",{method:"POST",body:JSON.stringify({code:Ve.compactCode(e)}),signal:t},"Failed to turn off two-step sign-in")}async regenerateBackupCodes(e,t){return this.fetchWithReason("mfa/backup-codes/regenerate",{method:"POST",body:JSON.stringify({code:Ve.compactCode(e)}),signal:t},"Failed to make new backup codes")}async startSmsEnrollment(e){const t=await this.fetchWithReason("mfa/sms/enroll",{method:"POST",signal:e},"Failed to send the code");return{retryAfter:Be(t?.retryAfter)??0,..."string"==typeof t?.phone&&t.phone?{phone:t.phone}:{}}}async confirmSmsEnrollment(e,t){const n=await this.fetchWithReason("mfa/sms/enroll/confirm",{method:"POST",body:JSON.stringify({code:Ve.compactCode(e)}),signal:t},"Failed to turn on text message codes"),r=n?.backupCodes;return Array.isArray(r)&&r.length>0&&r.every(e=>"string"==typeof e)?{backupCodes:r}:{}}async disableSms(e){await this.fetchWithReason("mfa/sms/disable",{method:"POST",signal:e},"Failed to turn off text message codes")}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.fetchWithReason(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchWithReason(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getConnectedAccounts(e){const t=await this.fetchWithReason("accounts",{signal:e},"Failed to fetch connected accounts"),n=Array.isArray(t?.accounts)?t.accounts:[],r=Array.isArray(t?.available)?t.available:[],s=function(e){if(!e||"object"!=typeof e)return;const{ethereumChainIds:t,solana:n}=e,r=Array.isArray(t)?t.filter(qe):[];return 0!==r.length||!0===n?{ethereumChainIds:r,solana:!0===n}:void 0}(t?.wallet);return{accounts:n.filter(e=>"string"==typeof e?._id&&!!e._id).map(({detail:e,...t})=>({...t,label:"string"==typeof t.label&&t.label?t.label:t.provider,..."string"==typeof e&&e?{detail:e}:{},canUnlink:!0===t.canUnlink})),available:r.filter(e=>"string"==typeof e?.methodId&&!!e.methodId).map(e=>({...e,label:"string"==typeof e.label&&e.label?e.label:e.provider})),...s?{wallet:s}:{},signInWays:"number"==typeof t?.signInWays&&Number.isFinite(t.signInWays)?t.signInWays:0,recentSignIn:!0===t?.recentSignIn}}async linkAccount(e,t,n){const r=await this.fetchWithReason("accounts",{method:"POST",body:JSON.stringify({methodId:e,redirect:t}),signal:n},"Failed to start connecting the account");if("string"!=typeof r?.url||!r.url)throw new Error("Failed to start connecting the account: the server sent no URL");return{url:r.url}}async unlinkAccount(e,t){await this.fetchWithReason(this.apiPath`accounts/${e}`,{method:"DELETE",signal:t},"Failed to remove the connected account")}async requestWalletNonce(e,t){const n=await this.fetchWithReason("accounts/wallet/nonce",{method:"POST",body:JSON.stringify({chain:e}),signal:t},"Failed to start connecting the wallet"),{nonce:r,domain:s,uri:a,issuedAt:i}=n??{};if(!(Me(r)&&Me(s)&&Me(a)&&Me(i)))throw new Error("Failed to start connecting the wallet: the server sent no nonce");const o=Array.isArray(n?.chainIds)?n.chainIds.filter(qe):void 0;return{nonce:r,domain:s,uri:a,issuedAt:i,...o?{chainIds:o}:{}}}async linkWallet(e,t){const{chain:n,message:r,signature:s}=e,a=await this.fetchWithReason("accounts/wallet",{method:"POST",body:JSON.stringify({chain:n,message:r,signature:s}),signal:t},"Failed to connect the wallet",["nonce_expired"]);if(!Me(a?._id))throw new Error("Failed to connect the wallet: the server sent no account");const i=Me(a.provider)?a.provider:n;return{_id:a._id,provider:i,label:Me(a.label)?a.label:i,...Me(a.icon)?{icon:a.icon}:{},...Me(a.detail)?{detail:a.detail}:{},canUnlink:!1}}async startReverification(e,t){const{returnUrl:n,factors:r}=e,s=await this.fetchWithReason("session/reverify",{method:"POST",body:JSON.stringify({returnUrl:n,...r?.length?{factors:r}:{}}),signal:t},"Failed to start confirming it is you");if(!Me(s?.url))throw new Error("Failed to start confirming it is you: the server sent no URL");return{url:s.url}}async requestAccountDeletion(e){const t=await this.fetchWithReason("account/delete",{method:"POST",signal:e},"Failed to delete the account");return{deleteAfter:Me(t?.deleteAfter)?t.deleteAfter:null,deleted:!0===t?.deleted||null===t?.deleteAfter}}async cancelAccountDeletion(e){const t=await this.fetchWithReason("account/delete/cancel",{method:"POST",signal:e},"Failed to cancel the deletion");return{cancelled:!0===t?.cancelled}}async setUsername(e,t){const n=e.trim(),r=await this.fetchWithReason("profile/username",{method:"PUT",body:JSON.stringify({username:n}),signal:t},"Failed to save the username");return{username:Me(r?.username)?r.username:n.toLowerCase()}}async removeUsername(e){await this.fetchWithReason("profile/username",{method:"DELETE",signal:e},"Failed to remove the username")}async requestGuestUpgrade(e,t){const n=e.name?.trim(),r=await this.fetchWithReason("guest/upgrade",{method:"POST",body:JSON.stringify({email:e.email.trim(),...n?{name:n}:{},...e.password?{password:e.password}:{}}),signal:t},"Failed to send the code");return{retryAfter:Be(r?.retryAfter)??0}}async confirmGuestUpgrade(e,t){return this.fetchWithReason("guest/upgrade/confirm",{method:"POST",body:JSON.stringify({code:Ve.compactCode(e)}),signal:t},"Failed to create your account")}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(),a=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(a,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,s){const a={event:t};return n&&(a.userId=n),r&&(a.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(a),signal: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(),a=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(a,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),a=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(a,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}function ze(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const Ge={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 Je{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(Ge.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(Ge.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(Ge.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(Ge.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(Ge.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(Ge.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(Ge.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(Ge.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(Ge.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(Ge.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(Ge.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(Ge.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(Ge.WorkspaceDeleted,{workspace:e})}}const Ye=new Je,He=globalThis;function Ke(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=He[t]??(He[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const Qe=Ke("credit-balance"),Ze=Qe.subscribe,Xe=Qe.invalidate,et=Ke("quota-usage"),tt=et.subscribe,nt=et.invalidate,rt=Ke("subscription"),st=rt.subscribe,at=rt.invalidate,it="bb",ot={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},ct={Success:"success",Cancel:"cancel",Error:"error"},lt={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",Security:"security",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function dt(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(it,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function ut(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:dt({action:ot.CreditPurchase,status:ct.Success,ws:e,screen:lt.Credits},n),cancelUrl:dt({action:ot.CreditPurchase,status:ct.Cancel,ws:e,screen:lt.Credits},n)}}function pt(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(it);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 ht(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(it)&&(e.searchParams.delete(it),window.history.replaceState({},"",e.toString()))}catch{}}const mt="__buildbaseBeforeLeave",ft=globalThis,gt=ft[mt]??(ft[mt]=new Set);function yt(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:a,allowedOrigins:i}=t;return a||i?.length?a&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||i?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}function wt(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=yt(e,n)??yt(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===gt.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of gt)try{e()}catch{}}(r),window.location.href=r,!0}const bt="saas-auth-intent";function vt(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function xt(e){yt(e,{sameOrigin:!0})&&H(bt,{returnUrl:e,createdAt:Date.now()})}function kt(){const e=Y(bt,vt);return J(bt),e?Date.now()-e.createdAt>6e5?null:yt(e.returnUrl,{sameOrigin:!0}):null}function St(){J(bt)}const Ct={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},It={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function Nt(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Ct[t]??t.toUpperCase()}const At=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Et=At.map(e=>({value:e,label:`${e.toUpperCase()} (${Nt(e)})`})),jt=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),Pt=new Set(["bhd","jod","kwd","omr","tnd"]),_t=new Map;function Tt(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(jt.has(t))return 0;if(Pt.has(t))return 3;if("isk"===t)return 2;let n=_t.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}_t.set(t,n)}return n}function Ut(e,t){const n=Tt(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function Rt(e,t,n="en-US"){const r=(t??"").trim(),s=Tt(r),a=e/10**s;if(!r)return a.toFixed(s);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:s,maximumFractionDigits:s}).format(a)}catch{return Nt(r)+(0===s?a.toLocaleString("en-US"):a.toFixed(s))}}function Ot(e,t){return Nt(t)+Ut(e,t)}const Ft={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const Wt={included:"included",then:"then",hardLimit:"hard limit"};const Dt={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},Lt={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"};function $t(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 Mt(e,t,n){const r=$t(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function qt(e,t,n,r){const s=$t(e,t),a=s?.quotaOverages?.[n];if(a)return a[r]}function Bt(e,t){const n=$t(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Vt(e,t,n){const r=Bt(e,t);return r?.perSeat?r.perSeat[n]??null:null}function zt(e,t){return Math.max(0,e-(t||0))}function Gt(e,t,n,r){const s=Bt(e,t);if(!s)return null;return zt(r,s.includedSeats)*(Vt(e,t,n)??0)}function Jt(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=Bt(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 Yt(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:a,source:i}=n;if(a<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=a){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:a}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const Ht="saas-workspace-current",Kt=e=>{e?G(Ht,e._id):J(Ht)},Qt=()=>z(Ht),Zt=()=>{J(Ht)},Xt=(e,t)=>!!e&&t.some(t=>t._id===e);function en(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 tn(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 nn={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"},rn=Object.values(nn),sn={admin:rn.filter(e=>e!==nn.WORKSPACE_DELETE),editor:[nn.WORKSPACE_SETTINGS_VIEW,nn.WORKSPACE_MEMBERS_VIEW,nn.WORKSPACE_FEATURES_VIEW,nn.WORKSPACE_BILLING_VIEW,nn.WORKSPACE_USAGE_VIEW,nn.WORKSPACE_USAGE_RECORD],viewer:[nn.WORKSPACE_SETTINGS_VIEW,nn.WORKSPACE_MEMBERS_VIEW]},an="viewer";function on(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 cn(e){const{userId:t,workspace:n,settings:r,appPermissions:s}=e;if(!n||!t)return new Set;if(en(n,t)){const e=new Set(rn);if(s)for(const t of on(s))e.add(t);if(n.permissions)for(const t of on(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of on(r.workspace.permissions))e.add(t);return e}const a=e.workspaceRole??tn(n,t);return a?ln(a,e):new Set}function ln(e,t,n={}){const{workspace:r,settings:s,appPermissions:a}=t;if(!r)return new Set;const i=r.permissions,o=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),d=e=>!!i&&e in i,u=e=>!!o&&e in o,p=e=>d(e)||u(e)||e in sn;let h,m=e;if(!p(e)){const e=s?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;m=e}h=d(m)?c(i[m]):u(m)?c(o[m]):sn[m]??[];const f=new Set(h),g=new Set((s?.workspace?.customPermissions??[]).map(e=>e.key)),y=a?.[m]?l(a[m]).filter(e=>!g.has(e)):[];let w;w=d(m)?l(i[m]):u(m)?[...l(o[m]),...y]:a?.[m]?l(a[m]):[];for(const e of w)f.add(e);if("admin"===m){for(const e of sn.admin)f.add(e);for(const e of g)f.add(e);if(a)for(const e of l(on(a)))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(nn.WORKSPACE_MEMBERS_INVITE)}(f,m,s),f}const dn="App";function un(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||dn});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:dn});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))}var pn;function hn(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}}exports.AuthStatus=void 0,(pn=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",pn.redirecting="redirecting",pn.authenticated="authenticated",pn.unauthenticated="unauthenticated",pn.authenticating="authenticating";const mn="reverified",fn="bb-reverified-at";function gn(e){let t;try{t=new URL(e)}catch{return null}return t.searchParams.has(mn)?(t.searchParams.delete(mn),t.toString()):null}async function yn(e,t={}){const n=t.factors?.length?t.factors:void 0;if("number"==typeof t.maxAgeSeconds&&function(e,t,n=[],r=Date.now()){const s=e?.authTime?Date.parse(e.authTime):NaN;return!(!Number.isFinite(s)||s>r+6e4)&&!(r-s>=1e3*t)&&n.every(t=>e?.amr?.includes(t))}(e.session,t.maxAgeSeconds,n,e.now))return"recent";const r=t.returnUrl??gn(e.currentHref)??e.currentHref;let s;try{s=await e.start({returnUrl:r,...n?{factors:n}:{}})}catch(t){const a=e.redirectUrl;if(!("invalid_return_url"===t?.code&&!!a&&a!==r))throw t;e.saveIntent(r);try{s=await e.start({returnUrl:a,...n?{factors:n}:{}})}catch(t){throw e.clearIntent(),t}}if(!yt(s.url))throw e.clearIntent(),new Error("Failed to start confirming it is you: the server sent an unsafe URL");return e.redirect(s.url),"redirecting"}const wn=/^[a-z0-9](?:[a-z0-9_.-]{1,28})[a-z0-9]$/,bn=new Set(["admin","administrator","root","support","help","system","api","null","undefined","owner","staff","security","billing","moderator","buildbase"]);function vn(e){if("string"!=typeof e)return null;const t=e.trim().toLowerCase();return wn.test(t)?t.includes("..")||bn.has(t)?null:t:null}const xn=new Uint32Array([1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648]),kn=[0,1,62,28,27,36,44,6,55,20,3,10,43,25,39,41,45,15,21,8,18,2,61,56,14],Sn=136;function Cn(e,t,n){if(0===n)return[e,t];if(32===n)return[t,e];if(n<32)return[(e<<n|t>>>32-n)>>>0,(t<<n|e>>>32-n)>>>0];const r=n-32;return[(t<<r|e>>>32-r)>>>0,(e<<r|t>>>32-r)>>>0]}function In(e){const t=new Uint32Array(10),n=new Uint32Array(50);for(let r=0;r<24;r++){for(let n=0;n<5;n++){let r=0,s=0;for(let t=0;t<5;t++)r^=e[2*(n+5*t)],s^=e[2*(n+5*t)+1];t[2*n]=r,t[2*n+1]=s}for(let n=0;n<5;n++){const r=(n+4)%5,s=(n+1)%5,[a,i]=Cn(t[2*s],t[2*s+1],1),o=t[2*r]^a,c=t[2*r+1]^i;for(let t=0;t<5;t++)e[2*(n+5*t)]^=o,e[2*(n+5*t)+1]^=c}for(let t=0;t<5;t++)for(let r=0;r<5;r++){const s=t+5*r,a=r+(2*t+3*r)%5*5,[i,o]=Cn(e[2*s],e[2*s+1],kn[s]);n[2*a]=i,n[2*a+1]=o}for(let t=0;t<5;t++){const r=(t+1)%5,s=(t+2)%5;for(let a=0;a<5;a++){const i=t+5*a,o=r+5*a,c=s+5*a;e[2*i]=n[2*i]^~n[2*o]&n[2*c],e[2*i+1]=n[2*i+1]^~n[2*o+1]&n[2*c+1]}}e[0]^=xn[2*r],e[1]^=xn[2*r+1]}}function Nn(e,t){for(let n=0;n<34;n++)e[n]^=t[4*n]|t[4*n+1]<<8|t[4*n+2]<<16|t[4*n+3]<<24}const An="0123456789abcdef";function En(e){let t="";for(const n of e)t+=An[n>>4]+An[15&n];return t}function jn(e){if("string"!=typeof(t=e)||!/^0x[0-9a-fA-F]{40}$/.test(t))return null;var t;const n=e.slice(2).toLowerCase(),r=En(function(e){const t=new Uint32Array(50);let n=0;for(;n+Sn<=e.length;n+=Sn)Nn(t,e.subarray(n,n+Sn)),In(t);const r=new Uint8Array(Sn);r.set(e.subarray(n)),r[e.length-n]^=1,r[135]^=128,Nn(t,r),In(t);const s=new Uint8Array(32);for(let e=0;e<8;e++){const n=t[e];s[4*e]=255&n,s[4*e+1]=n>>>8&255,s[4*e+2]=n>>>16&255,s[4*e+3]=n>>>24&255}return s}((new TextEncoder).encode(n)));let s="0x";for(let e=0;e<40;e++)s+=parseInt(r[e],16)>=8?n[e].toUpperCase():n[e];return s}const Pn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function _n(e){let t=0;for(;t<e.length&&0===e[t];)t++;const n=[];for(const t of e){let e=t;for(let t=n.length-1;t>=0;t--)e+=256*n[t],n[t]=e%58,e=Math.floor(e/58);for(;e>0;)n.unshift(e%58),e=Math.floor(e/58)}return"1".repeat(t)+n.map(e=>Pn[e]).join("")}function Tn(e){return!("string"!=typeof e||e.length>64)&&32===function(e){if(!e)return null;let t=0;for(;t<e.length&&"1"===e[t];)t++;const n=[];for(const t of e){const e=Pn.indexOf(t);if(e<0)return null;let r=e;for(let e=n.length-1;e>=0;e--)r+=58*n[e],n[e]=255&r,r>>=8;for(;r>0;)n.unshift(255&r),r>>=8}return Uint8Array.from([...new Array(t).fill(0),...n])}(e)?.length}const Un="Connect this wallet to your account.";function Rn(e){const t=e.statement??Un;if([e.domain,e.address,t,e.uri,String(e.chainId),e.nonce,e.issuedAt].some(e=>!e||/[\r\n]/.test(e)))throw new Error("A wallet message field is empty or spans lines");const n="ethereum"===e.chain?"Ethereum":"Solana";return[`${e.domain} wants you to sign in with your ${n} account:`,e.address,"",t,"",`URI: ${e.uri}`,"Version: 1",`Chain ID: ${e.chainId}`,`Nonce: ${e.nonce}`,`Issued At: ${e.issuedAt}`].join("\n")}class On extends Error{constructor(e,t){super(t),this.name="WalletFlowError",this.code=e}}function Fn(e,t){if(e instanceof On)return e;const n=e?.code,r=e instanceof Error&&e.message?e.message:"The wallet did not answer";return new On(4001===n?"rejected":-32002===n?"wallet_busy":t,r)}function Wn(e){return"number"==typeof e&&Number.isInteger(e)?e:"string"==typeof e&&/^0x[0-9a-fA-F]+$/.test(e)?parseInt(e,16):"string"==typeof e&&/^\d+$/.test(e)?Number(e):null}async function Dn(e){const t=void 0===e.ethereum?function(){if("undefined"==typeof window)return null;const e=window.ethereum;return e&&"function"==typeof e.request?e:null}():e.ethereum;if(!t)throw new On("no_wallet","No Ethereum wallet in this browser");let n;try{const e=await t.request({method:"eth_requestAccounts"});n=jn(Array.isArray(e)?e[0]:void 0)}catch(e){throw Fn(e,"wallet_failed")}if(!n)throw new On("no_account","The wallet gave no address");const r=await e.api.requestWalletNonce("ethereum"),s=r.chainIds?.length?r.chainIds:e.ethereumChainIds??[];let a;try{if(a=Wn(await t.request({method:"eth_chainId"})),null===a||!s.includes(a)){if(!s.length)throw new On("wrong_network","The app takes no Ethereum network");await t.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${s[0].toString(16)}`}]}),a=Wn(await t.request({method:"eth_chainId"}))}}catch(e){throw Fn(e,"wrong_network")}if(null===a||!s.includes(a))throw new On("wrong_network","The wallet is on a network the app does not take");const i=Rn({chain:"ethereum",domain:r.domain,address:n,statement:e.statement,uri:r.uri,chainId:a,nonce:r.nonce,issuedAt:r.issuedAt});let o;try{o=await t.request({method:"personal_sign",params:[(c=i,`0x${En((new TextEncoder).encode(c))}`),n]})}catch(e){throw Fn(e,"wallet_failed")}var c;if("string"!=typeof o||!/^0x[0-9a-fA-F]+$/.test(o))throw new On("wallet_failed","The wallet sent no signature");return e.api.linkWallet({chain:"ethereum",message:i,signature:o})}async function Ln(e){const t=void 0===e.solana?function(){if("undefined"==typeof window)return null;const e=window,t=e.phantom?.solana??e.solana;return t&&"function"==typeof t.connect&&"function"==typeof t.signMessage?t:null}():e.solana;if(!t)throw new On("no_wallet","No Solana wallet in this browser");let n;try{const e=await t.connect();n=(e&&e.publicKey?e.publicKey:t.publicKey)?.toString()}catch(e){throw Fn(e,"wallet_failed")}if(!Tn(n))throw new On("no_account","The wallet gave no address");const r=await e.api.requestWalletNonce("solana"),s=Rn({chain:"solana",domain:r.domain,address:n,statement:e.statement,uri:r.uri,chainId:"mainnet",nonce:r.nonce,issuedAt:r.issuedAt});let a;try{a=await t.signMessage((new TextEncoder).encode(s),"utf8")}catch(e){throw Fn(e,"wallet_failed")}const i=a instanceof Uint8Array?a:a?.signature;if(!(i instanceof Uint8Array)||64!==i.length)throw new On("wallet_failed","The wallet sent no signature");return e.api.linkWallet({chain:"solana",message:s,signature:_n(i)})}const $n=["ethereum","solana"];function Mn(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function qn(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||Mn(n.invitedAt)-Mn(e.invitedAt))}function Bn(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||Mn(e.validTill)>t.getTime())}function Vn(e,t=new Date){return qn(e.filter(e=>Bn(e,t)))}function zn(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""}function Gn(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null}const Jn="saas-pending-invite",Yn=/^[0-9a-f]{64}$/;function Hn(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}function Kn(e,t){Yn.test(e)&&t&&H(Jn,{token:e,orgId:t,createdAt:Date.now()})}function Qn(e,t=Date.now()){const n=Y(Jn,Hn);return n?t-n.createdAt>864e5?(J(Jn),null):n.orgId!==e?null:Yn.test(n.token)?n.token:(J(Jn),null):null}function Zn(){J(Jn)}class Xn 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",{className:"saas-os-ui",style:{padding:"1rem",border:"1px solid hsl(var(--destructive, 0 72% 45%))",borderRadius:"0.5rem",backgroundColor:"hsl(var(--destructive, 0 72% 45%) / 0.08)",color:"hsl(var(--destructive-text, 0 72% 36%))"},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 72% 45%))",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 er={authenticationStarted:()=>({type:"AUTHENTICATION_STARTED"}),authenticationProcessing:()=>({type:"AUTHENTICATION_PROCESSING"}),authenticationFailed:()=>({type:"AUTHENTICATION_FAILED"}),setSession:e=>({type:"SET_SESSION",payload:e}),removeSession:()=>({type:"REMOVE_SESSION"})};function tr(e,n,r,s){const a=t.useMemo(()=>{const t=r??(e=>e);let n,a,i=!1;return()=>{const r=e();if(!i)return i=!0,n=r,a=t(r),a;if(Object.is(n,r))return a;const o=t(r);n=r;return(s?s(a,o):Object.is(a,o))||(a=o),a}},[e,r,s]);return t.useSyncExternalStore(n,a,a)}function nr({name:n,initialState:r,reducer:s,initializer:a}){const i=t.createContext(null);i.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,a)),e.jsx(i.Provider,{value:o.current,children:n})});o.displayName=`${n}Provider`;const c=(e="Store")=>{const r=t.useContext(i);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=tr(e.getState,e.subscribe);return t.useMemo(()=>({state:n,dispatch:e.dispatch}),[n,e])},useState:()=>{const e=c("State");return tr(e.getState,e.subscribe)},useDispatch:()=>c("Dispatch").dispatch,useSelector:(e,t)=>{const n=c("Selector");return tr(n.getState,n.subscribe,e,t)},useStore:c}}function rr(e,t,n){return{...e,[t]:n}}function sr(e,t){return{...e,...t}}const{Provider:ar,useDispatch:ir,useSelector:or,useStore:cr}=nr({name:"Auth",initialState:{session:null,status:exports.AuthStatus.loading},reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return rr(e,"status",exports.AuthStatus.redirecting);case"AUTHENTICATION_PROCESSING":return rr(e,"status",exports.AuthStatus.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return sr(e,{session:null,status:exports.AuthStatus.unauthenticated});case"SET_SESSION":return sr(e,{session:t.payload,status:exports.AuthStatus.authenticated});default:return e}}}),lr=ar,dr=ir,ur=or,pr=cr,hr=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),mr=e=>({type:"SET_SETTINGS",payload:e}),fr=(e,t)=>({type:"SET_SETTINGS_STATUS",payload:{status:e,error:t}}),gr=()=>({serverUrl:"",version:exports.ApiVersion.V1,orgId:"",settings:null,settingsStatus:"idle",settingsError:null}),{Provider:yr,useDispatch:wr,useStore:br}=nr({name:"OS",initialState:gr(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return sr(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return gr();case"SET_SETTINGS":return sr(e,{settings:t.payload,settingsStatus:"loaded",settingsError:null});case"SET_SETTINGS_STATUS":return sr(e,{settingsStatus:t.payload.status,settingsError:t.payload.error??null});default:return e}}}),vr=yr,xr=wr,kr=br,Sr=e=>({type:"SET_WORKSPACES",payload:e}),Cr=e=>({type:"ADD_WORKSPACE",payload:e}),Ir=e=>({type:"UPDATE_WORKSPACE",payload:e}),Nr=e=>({type:"REMOVE_WORKSPACE",payload:e}),Ar=e=>({type:"SET_ALL_FEATURES",payload:e}),Er=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),jr=()=>({type:"RESET_CURRENT_WORKSPACE"}),Pr=e=>({type:"SET_IS_INITIALIZED",payload:e}),_r=e=>({type:"SET_LOADING",payload:e}),Tr=e=>({type:"SET_ERROR",payload:e}),Ur=e=>({type:"SET_REFRESHING",payload:e}),Rr=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:Or,useDispatch:Fr,useStore:Wr}=nr({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 rr(e,"workspaces",t.payload);case"ADD_WORKSPACE":return rr(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return rr(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return rr(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return rr(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return rr(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return rr(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return rr(e,"isInitialized",t.payload);case"SET_LOADING":return rr(e,"loading",t.payload);case"SET_ERROR":return rr(e,"error",t.payload);case"SET_REFRESHING":return rr(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return rr(e,"switchingToId",t.payload);default:return e}}}),Dr=Or,Lr=Fr,$r=Wr,Mr=t.memo(({children:t})=>e.jsx(vr,{children:e.jsx(lr,{children:e.jsx(Dr,{children:t})})}));Mr.displayName="SDKContextProvider";const qr=t.createContext({});qr.displayName="CheckoutConfigContext";const Br=t.memo(({getCheckoutStripeParams:n,children:r})=>{const s=t.useMemo(()=>({getCheckoutStripeParams:n}),[n]);return e.jsx(qr.Provider,{value:s,children:r})});Br.displayName="CheckoutConfigProvider";const Vr={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:"Done",error:"Something went wrong",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, and 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",changeEmail:"Change",changeEmailNewLabel:"New email address",changeEmailNewHint:"We'll email a code to the new address. Your email changes only once you enter it.",changeEmailInvalid:"Enter a valid email address.",changeEmailSame:"That is already your email address.",changeEmailSend:"Send code",changeEmailSentTo:"We sent a code to {email}.",changeEmailCodeLabel:"6-digit code from the email",changeEmailCodeInvalid:"Enter the 6-digit code from the email.",changeEmailConfirm:"Change email",changeEmailResend:"Resend code",changeEmailResendIn:"Resend in {seconds, plural, one {# second} other {# seconds}}",changeEmailResent:"We sent a new code to {email}.",changeEmailChanged:"Your email is now {email}. We let your old address know.",changeEmailBlockedSocial:"You sign in with Google or another provider, which finds your account by this address, so it cannot be changed here. Changing it would leave you with a second account.",username:"Username",usernameHint:"You can sign in with it instead of your email address.",usernameInvalid:"Use 3 to 30 characters: letters a to z, digits, dots, dashes or underscores. Start and end with a letter or digit.",usernameSave:"Save username",usernameRemove:"Remove",usernameSaved:"Your username is now {username}.",usernameRemoved:"Your username was removed.",usernameRequiredNote:"This app requires a username, so you can change it but not remove it.",loadFailed:"Your profile couldn't be loaded. Please try again."},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:"It looks like you are not signed in. Please sign in 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}"},guest:{title:"Create your account",description:"You are using the app as a guest. Add your email address to keep what you have done here and sign in again later.",emailLabel:"Email",nameLabel:"Name (optional)",passwordLabel:"Password (optional)",passwordHint:"At least 8 characters. Leave it empty to sign in another way the app offers.",emailInvalid:"Enter a valid email address.",passwordMinLength:"Use at least 8 characters.",send:"Send code",sentTo:"We sent a code to {email}.",codeLabel:"Code from the email",codeInvalid:"Enter the 6-digit code from the email.",resend:"Resend code",resendIn:"Resend in {seconds, plural, one {# second} other {# seconds}}",resent:"We sent a new code to {email}.",confirm:"Create account",done:"Your account is ready. You can sign in with {email} from now on."},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",unreachable:"The server could not be reached. Check your connection and try again.",unauthorized:"Your session has ended. Sign in again.",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. Disconnecting revokes access immediately.",connectedAgentsDisconnect:"Disconnect",connectedAgentsEmpty:"No connected agents.",connectedAgentsAccess:"Access",connectedAgentsGranted:"Granted",connectedAgentsLoadFailed:"Failed to load connected agents",connectedAgentsRevokeFailed:"Failed to disconnect",connectedAgentsConfirmTitle:"Disconnect {name}?",connectedAgentsConfirmBody:"It loses access to your account at once. You can connect it again at any time.",connectedAgentsCancel:"Cancel",connectedAgentsDisconnected:"{name} was disconnected.",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:"After you sign in, the sign-in page offers to add a passkey on that device, but only while your account has none.",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",passwordTitle:"Password",passwordDescription:"Change the password you sign in with. Every other session is signed out.",currentPassword:"Current password",newPassword:"New password",passwordRequired:"Enter your current password.",passwordMinLength:"Use at least 8 characters.",changePassword:"Change password",passwordChanged:"Password changed. You were signed out on every other device.",passwordSocialHint:'If you signed up with Google or another provider, or with a code or link, you have no password yet. To set one, sign out and use "Forgot password?" on the sign-in page.',passwordNone:"You sign in without a password.",passwordNoneHint:'To set one, sign out and use "Forgot password?" on the sign-in page.',twoStepTitle:"Two-step sign-in",twoStepDescription:"Ask for a code from an authenticator app when you sign in, so a stolen password alone is not enough.",twoStepSetUp:"Set up",twoStepRequiredSetup:"This app requires two-step sign-in. Set it up now, or you will be asked to at your next sign-in.",twoStepScan:"Scan this QR code with your authenticator app.",twoStepQrAlt:"QR code for your authenticator app",twoStepManualKey:"Can't scan it? Type this key into the app instead.",twoStepCodeLabel:"6-digit code from the app",twoStepCodeInvalid:"Enter the 6-digit code the app shows.",twoStepTurnOn:"Turn on",twoStepEnabled:"Two-step sign-in is on.",twoStepBackupTitle:"Save your backup codes",twoStepBackupDescription:"Each code signs you in once if you lose your phone. Keep them somewhere safe. They will not be shown again.",twoStepCopy:"Copy",twoStepCopied:"Copied",twoStepDone:"Done",twoStepAppName:"Authenticator app",twoStepBackupLeft:"{count, plural, =0 {No backup codes left} one {# backup code left} other {# backup codes left}}",twoStepNewCodes:"New backup codes",twoStepTurnOff:"Turn off",twoStepRequiredNote:"This app requires two-step sign-in, so it cannot be turned off.",twoStepCurrentCodeLabel:"Code from your authenticator app, or a backup code",twoStepCurrentCodeRequired:"Enter a code to continue.",twoStepTurnOffHint:"Enter a current code to turn off two-step sign-in.",twoStepNewCodesHint:"Enter a current code to make new backup codes. The old ones stop working.",twoStepDisabled:"Two-step sign-in is off.",twoStepCodesRegenerated:"New backup codes made. The old ones no longer work.",twoStepOffDescription:"This app has two-step sign-in turned off, so signing in does not ask for a code. You can still remove what you set up before.",twoStepRemoveHint:"Enter a current code to remove the authenticator app.",twoStepRemoved:"The authenticator app was removed.",connectedAccountsTitle:"Connected accounts",connectedAccountsDescription:"Sign in with any of these accounts. Connect another, or remove one you no longer use.",connectedAccountsEmpty:"No accounts connected yet.",connectedAccountsAvailable:"Connect another account",connectedAccountsConnect:"Connect {provider}",connectedAccountsLastWay:"This is the only way you can sign in. Add another sign-in method before removing it.",connectedAccountsRemoveTitle:"Remove {provider}?",connectedAccountsRemoveDescription:"You will no longer be able to sign in with this {provider} account. You can connect it again later.",connectedAccountsRemoved:"{provider} was removed from your account.",connectedAccountsLinked:"{provider} is connected. You can sign in with it from now on.",connectedAccountsLinkedGeneric:"The account is connected. You can sign in with it from now on.",connectedAccountsReauth:"For your security, confirm it's you before removing a connected account.",connectedAccountsSignInAgain:"Sign in again",connectedAccountsLinkConflict:"That account is already connected to a different account here, so it was not connected to this one.",connectedAccountsProviderError:"The provider did not allow the connection, or it was cancelled. Nothing was changed.",connectedAccountsProviderFailed:"The account could not be connected. Please try again.",connectedAccountsSessionEnded:"Your session ended before the account was connected. Sign in and try again.",connectedAccountsNoVerifiedEmail:"That account has no verified email address. Verify an email address with the provider, then try again.",connectedAccountsEmailUnverified:"That account has no verified email address to create your account with. Nothing was changed.",connectedAccountsEmailUnavailable:"The email address of that account cannot be used here. Connect another account, or if that address already has an account here, sign in to that account instead.",connectedAccountsDisposableEmail:"That account uses a disposable email address. Connect an account with a permanent address.",connectedAccountsSignupClosed:"Sign-up is not enabled for this app, so your account cannot be created.",connectedAccountsSignupRestricted:"Sign-up isn't available for the email address of that account.",connectedAccountsWaitlistRequired:"This app signs people up from its waitlist. Join it with that address, and you can create your account once you're approved.",connectedAccountsNotAGuest:"Your account already has an email address.",twoStepGuest:"Create your account before setting up two-step sign-in.",phoneTitle:"Phone number",phoneDescription:"Add a phone number to get sign-in codes by text message.",phoneEmpty:"No phone number added yet.",phoneAdd:"Add phone number",phoneChange:"Change",phoneCountryLabel:"Country",phoneNumberHint:"We will text a code to this number to check it is yours. Message rates may apply.",phoneNumberInvalid:"Enter a phone number with its area code.",phoneSendCode:"Send code",phoneSentTo:"We sent a code to {phone}.",phoneCodeLabel:"Code from the text message",phoneCodeInvalid:"Enter the code from the text message.",phoneResend:"Resend code",phoneResendIn:"Resend in {seconds, plural, one {# second} other {# seconds}}",phoneWait:"A code was sent moments ago. You can send another in {seconds, plural, one {# second} other {# seconds}}.",phoneResent:"We sent a new code to {phone}.",phoneVerify:"Verify",phoneVerified:"Verified",phoneNotVerified:"Not verified",phoneSaved:"{phone} is verified and on your account.",phoneRemoveTitle:"Remove your phone number?",phoneRemoveDescription:"Codes will no longer be sent to {phone}. You can add a number again later.",phoneRemoved:"Your phone number was removed.",phoneReauth:"For your security, confirm it's you before removing your phone number.",phoneLastWay:"This is the only way you can sign in. Add another sign-in method before removing your phone number.",phoneUsedForTwoStep:"Two-step sign-in sends codes to this number. Turn off text message codes before removing it.",phoneSmsUnavailable:"Text messages cannot be sent right now. Try again later.",phoneCheckUnavailable:"The code cannot be checked right now. Try again later.",phoneTextUnavailable:"This app does not send codes by text message, so a phone number cannot be added here.",twoStepSmsName:"Text message",twoStepSmsWeaker:"Less secure than an authenticator app, because a phone number can be moved to someone else's SIM card.",twoStepSmsTo:"Codes go to {phone}.",twoStepSmsNeedsPhone:"Add and verify a phone number first, then turn on text message codes.",twoStepSmsGoToPhone:"Go to phone number",twoStepSmsSentGeneric:"We sent a code to your phone.",twoStepSmsEnabled:"Text message codes are on.",twoStepSmsDisabled:"Text message codes are off.",twoStepSmsTurnOffTitle:"Turn off text message codes?",twoStepSmsTurnOffDescription:"Sign-in will no longer send a code to your phone.",twoStepSmsReauth:"For your security, confirm it's you before turning off text message codes.",reauthConfirm:"Confirm it's you",reauthConfirmed:"Thanks, that's confirmed. You can go ahead now.",reauthImpersonating:"You are signed in as this person from the console, so you can't confirm it's them here. Only they can make this change.",deleteAccountTitle:"Delete account",deleteAccountDescription:"Delete your account and the personal data in it. Workspaces only you use are deleted with it.",deleteAccountWarning:"Your other sessions end now. Depending on the app, the account is deleted straight away or after up to 30 days in which you can change your mind. After that, the account and its personal data are gone for good.",deleteAccountWarningNow:"Your account and its personal data are deleted straight away, and you are signed out. This cannot be undone.",deleteAccountWarningDays:"Your other sessions end now. You have {days, plural, one {# day} other {# days}} to change your mind; after that, the account and its personal data are gone for good.",deleteAccountTypeLabel:"Type {word} to confirm",deleteAccountWord:"DELETE",deleteAccountConfirm:"Delete my account",deleteAccountScheduled:"Your account will be deleted on {date}. You can cancel until then.",deleteAccountNotice:"Your account will be deleted on {date}.",deleteAccountCancel:"Cancel deletion",deleteAccountCancelled:"Your account will not be deleted.",deleteAccountReauth:"For your security, confirm it's you before deleting your account.",deleteAccountOwnsWorkspaces:"{count, plural, one {This workspace has other members or a subscription, so it cannot be deleted with your account. Remove the other members and cancel the subscription, or delete the workspace, then try again:} other {These workspaces have other members or a subscription, so they cannot be deleted with your account. Remove the other members and cancel the subscriptions, or delete those workspaces, then try again:}}",impersonationReadOnly:"You are viewing as {name}. {actor} signed in as this person, read-only until {time}.",impersonationFull:"You are viewing as {name}. {actor} signed in as this person until {time}. Changes are saved to their account.",impersonationSignInLocked:"How they sign in can't be changed.",impersonationExit:"Exit",impersonationRegion:"Viewing as another person",walletConnectEthereum:"Connect an Ethereum wallet",walletConnectSolana:"Connect a Solana wallet",walletNotFound:"No {chain} wallet was found in this browser. Install a wallet extension and try again.",walletRejected:"The request was cancelled in your wallet.",walletBusy:"Your wallet is already waiting for you. Open it to continue.",walletWrongNetwork:"Switch your wallet to a network this app accepts, then try again.",walletNoAccount:"Your wallet did not share an address. Unlock it and try again.",walletFailed:"Your wallet could not sign the request. Please try again.",walletHint:"Connecting asks your wallet to sign a message. It is free and sends no transaction.",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."},help:{button:"Help: {label}",linkNewTab:"{link} (opens in a new tab)",twoStep:"When you sign in, you also enter a short code that only you can get. Someone who learns your password still cannot get in.",twoStepApp:"An authenticator app shows a new 6-digit code every 30 seconds, even without signal. For example Google Authenticator, Microsoft Authenticator, 1Password or Authy. You scan the QR code with it once.",twoStepSms:"With text message codes, the code comes by text to your verified phone number. They are more convenient, but less safe than an app.",twoStepLostPhone:"Lost your phone? Sign in with one of your backup codes, then turn the app off here and set it up on your new phone. If you have no backup codes left, or cannot turn it off, ask this app's support team to reset your two-step sign-in.",twoStepKeyPrivate:"Keep this key private, like a password. Anyone who has it can make your sign-in codes.",backupCodesLabel:"Backup codes",backupCodes:"Backup codes let you sign in when you cannot use your authenticator app, for example after losing your phone. Each code works only once.",backupCodesKeep:"Keep them somewhere safe and private, such as a password manager or a printed copy at home. Anyone who has them and your password can sign in as you.",backupCodesNew:"Making new backup codes replaces all the old ones: they stop working at once, used or not.",passkeys:"A passkey lets you sign in with your fingerprint, your face or your screen lock (the PIN or pattern that unlocks your device), instead of a password.",passkeysWhere:"It stays on your device or in your password manager, such as iCloud Keychain or Google Password Manager. This app never receives the passkey itself.",passkeysRemove:"Removing a passkey here means it can no longer sign you in. Your device or password manager may still list it, and you can delete it there too.",devicesThis:"{label}: the phone or computer you are using now.",devicesTrusted:"{label}: you chose to remember this device when you signed in, so it may skip the two-step code for a while.",devicesSignOut:"{label}: ends every sign-in on that device, so whoever uses it next has to sign in again. On this device, it signs you out here too.",devicesRemove:"{label}: signs the device out and takes it off this list. It comes back if you sign in on it again.",sessionsWhat:"Each one is a place where you are signed in, such as a browser or an app.",sessionsThis:"{label}: where you are signed in right now.",sessionsSignOut:"{label}: ends that sign-in straight away.",sessionsEverywhere:"Changing your password signs you out everywhere except here. Do it if you see a sign-in you do not recognize.",connectedAccounts:"Connecting another account lets you sign in here with it, without a password. You confirm on its own sign-in page, then come back here.",connectedAccountsRemove:"Removing one only means it can no longer sign you in here. The account itself does not change.",connectedAccountsLastWay:"You always need at least one way to sign in, so the last one cannot be removed. A way to sign in can be a connected account, a passkey, a password, or a code sent to your verified email or phone, where this app offers them.",phone:"Your phone number can get codes by text message: to sign in, if this app offers that, and for two-step sign-in, if you turn text message codes on.",phoneCheck:"We text a code to the number first, to check it is yours. Sign-in codes only go to a verified number.",reauth:"Some changes, such as removing a way to sign in or deleting your account, need a sign-in from the last 10 minutes. That stops someone else making them on a device you left signed in.",reauthHow:"You confirm on the sign-in page, then come straight back here. Then make the change again.",email:"Your email address is how this app knows you, and where it sends messages about your account.",emailChange:"To change it, enter the new address, then the 6-digit code we email there. We let your old address know, and you stay signed in.",password:"You enter your current password first, so nobody else can change it on a device you left open. The new one needs at least 8 characters. A few unrelated words together are hard to guess, and you will remember them.",passwordLeaks:"Passwords found in known data leaks are refused. After the change, you stay signed in here and are signed out everywhere else.",passwordForgot:'Forgot your current password? Sign out, then choose "Forgot password?" on the sign-in page.',deleteAccountDays:"Your account is deleted {days, plural, one {# day} other {# days}} after you confirm. Until then it keeps working: you can still sign in, and {cancel}, here or at the top of the settings, keeps your account.",deleteAccountNow:"This app deletes accounts as soon as you confirm. There is no waiting time, and it cannot be undone.",deleteAccountRange:"Depending on the app, your account is deleted as soon as you confirm, or after a waiting time of up to 30 days. During that time it keeps working: you can still sign in, and {cancel} keeps your account."}},zr={en:async()=>Vr,es:async()=>(await Promise.resolve().then(function(){return require("./es-Cxg-qhUh.cjs")})).es,fr:async()=>(await Promise.resolve().then(function(){return require("./fr-COCMy3vW.cjs")})).fr,de:async()=>(await Promise.resolve().then(function(){return require("./de-DO10bhnU.cjs")})).de,ja:async()=>(await Promise.resolve().then(function(){return require("./ja-D92JgUlk.cjs")})).ja,zh:async()=>(await Promise.resolve().then(function(){return require("./zh-DK2yA5wB.cjs")})).zh,hi:async()=>(await Promise.resolve().then(function(){return require("./hi-BB0Z-Dgn.cjs")})).hi,ar:async()=>(await Promise.resolve().then(function(){return require("./ar-DQVB89r8.cjs")})).ar},Gr=["en","es","fr","de","ja","zh","hi","ar"];function Jr(e){if("string"!=typeof e||!e)return;const t=e.toLowerCase().replace("_","-");if(Gr.includes(t))return t;const n=t.split("-")[0];return Gr.includes(n)?n:void 0}const Yr={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function Hr(e,t){const n={...e};for(const r of Object.keys(t)){const s=t[r],a=e[r];"string"==typeof s?n[r]=s:s&&"object"==typeof s&&a&&"object"==typeof a&&(n[r]=Hr(a,s))}return n}const Kr=t.createContext({messages:Vr,locale:"en",formattingLocale:"en"});function Qr({locale:e,messageOverrides:n,children:r}){const s=Jr(e??"en")??"en";const[a,i]=t.useState(Vr);t.useEffect(()=>{if("en"===s)return void i(Vr);let e=!1;const t=zr[s];return t&&t().then(t=>{e||i(t)}),()=>{e=!0}},[s]);const o=t.useMemo(()=>n?Hr(a,n):a,[a,n]),c=function(e){return Yr[e]??e}(s),l=t.useMemo(()=>({messages:o,locale:s,formattingLocale:c,requestedLocale:e}),[o,s,c,e]);return t.createElement(Kr.Provider,{value:l},r)}const Zr=new Map,Xr=new Map,es=new Map;function ts(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const ns={getNumberFormat(e,t){const n=ts(e,t);let r=Zr.get(n);return r||(r=new Intl.NumberFormat(e,t),Zr.set(n,r)),r},getDateTimeFormat(e,t){const n=ts(e,t);let r=Xr.get(n);return r||(r=new Intl.DateTimeFormat(e,t),Xr.set(n,r)),r},getPluralRules(e,t){const n=ts(e,t);let r=es.get(n);return r||(r=new Intl.PluralRules(e,t),es.set(n,r)),r}},rs=new Map;function ss(){const{messages:e,locale:n,formattingLocale:r}=t.useContext(Kr),s=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,s)=>{const i=t(e,n)??t(Vr,n)??n;if(!s)return i;try{const e=function(e,t){const n=`${t}:${e}`;let r=rs.get(n);return r||(r=new a(e,t,void 0,{formatters:ns}),rs.set(n,r)),r}(i,r),t=e.format(s);return"string"==typeof t?t:String(t)}catch{return i.replace(/\{(\w+)\}/g,(e,t)=>String(s[t]??`{${t}}`))}}},[e,r]),i="ar"===n?"rtl":"ltr",o=t.useMemo(()=>e=>e.toLocaleString(r),[r]),c=t.useMemo(()=>(e,t)=>Rt(e,t,r),[r]);return{t:s,locale:n,formattingLocale:r,dir:i,fmtNum:o,fmtCents:c,messages:e}}const as=new Map;function is(e,t){const n=as.get(e);if(n)return n;const r=t().finally(()=>{as.get(e)===r&&as.delete(e)});return as.set(e,r),r}function os(){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 cs="bb_attr",ls=["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"],ds=/^[\w.~-]{1,200}$/;function us(){return"undefined"==typeof window?null:window}function ps(e,t){if(!e||!e.includes("."))return"";if(/^\d{1,3}(\.\d{1,3}){3}$/.test(e))return"";const n=t??us()?.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 a=n.cookie.includes(`${s}=1`);if(n.cookie=`${s}=; domain=${t}; path=/; max-age=0; SameSite=Lax`,a)return t}return""}const hs="$t",ms="$l";function fs(e){const t=e.cookie.split("; ").find(e=>e.startsWith(`${cs}=`));if(!t)return{params:{}};try{const e=JSON.parse(decodeURIComponent(t.slice(8)));if("object"!=typeof e||!e)return{params:{}};const{[hs]:n,[ms]:r,...s}=e;return{params:s,..."number"==typeof n&&n>0?{capturedAt:n}:{},..."string"==typeof r&&r?{landingUrl:r}:{}}}catch{return{params:{}}}}function gs(e){try{const{origin:t,pathname:n}=e.location;return t&&"null"!==t?`${t}${n}`.slice(0,300):void 0}catch{return}}const ys=ls.filter(e=>!e.startsWith("utm_")),ws=e=>ys.some(t=>!!e[t]);function bs(){const e=us();if(!e)return{};const t=e.document,n=function(e){return fs(e).params}(t),r=function(e){const t=new URLSearchParams(e),n={};for(const e of ls){const r=t.get(e);r&&(r.length>200||ds.test(r)&&(n[e]=r))}return n}(e.location.search),s=Object.keys(r).length>0&&(ws(r)||!ws(n)),a=s?r:n;return 0===Object.keys(a).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,[hs]:r.capturedAt,...r.landingUrl?{[ms]:r.landingUrl}:{}}));e.cookie=`${cs}=${s}; path=/; max-age=7776000; SameSite=Lax`+(n?`; domain=${n}`:"")}(t,a,ps(e.location.hostname,t),{capturedAt:Date.now(),landingUrl:gs(e)}),a)}function vs(){const e=us();return e?fs(e.document):{params:{}}}function xs(){const e=vs(),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 ks(e){try{const t=new URLSearchParams(e);return t.has("code")&&t.has("state")}catch{return!1}}const Ss="bb_pending_checkout",Cs=216e5;function Is(){try{return"undefined"==typeof window?null:window.sessionStorage}catch{return null}}function Ns(e){try{Is()?.setItem(Ss,JSON.stringify(e))}catch{}!function(e){if(!e.sessionId)return;const t=Es();if(!t)return;try{const n=ps(window.location?.hostname??"",t);t.cookie=`${As}=${encodeURIComponent(JSON.stringify(e))}; path=/; max-age=21600; SameSite=Lax`+(n?`; domain=${n}`:"")}catch{}}(e)}const As="bb_co";function Es(){try{return"undefined"==typeof window?null:window.document??null}catch{return null}}function js(){const e=Es();if(e)try{const t=ps(window.location?.hostname??"",e);e.cookie=`${As}=; path=/; max-age=0; SameSite=Lax`+(t?`; domain=${t}`:"")}catch{}}function Ps(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>Cs?null:n:null}catch{return null}}function _s(e=Date.now()){const t=Is();if(!t)return null;let n=null;try{n=t.getItem(Ss),t.removeItem(Ss)}catch{return null}const r=Ps(n,e);return r&&js(),r}function Ts(e){try{return Ps(Is()?.getItem(Ss)??null,e)}catch{return null}}function Us(e,t=Date.now()){let n=null;try{n=new URLSearchParams(e).get("session_id")}catch{return null}if(!n)return null;const r=Ts(t);if(r?.sessionId===n)return _s(t);const s=function(e){const t=Es();if(!t||"string"!=typeof t.cookie)return null;const n=t.cookie.split("; ").find(e=>e.startsWith(`${As}=`));return n?Ps(decodeURIComponent(n.slice(As.length+1)),e):null}(t);return s?.sessionId!==n?null:(js(),s)}function Rs(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)&&Ts(t)?_s(t):null}const Os=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),Fs=new Set(["bhd","jod","kwd","omr","tnd"]);function Ws(e,t){if("number"!=typeof e||!Number.isFinite(e))return;const n=(t??"").toLowerCase();return Os.has(n)?e:e/(Fs.has(n)?1e3:100)}const Ds=["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"],Ls=/^[A-Z]{2}(-[A-Z0-9]{1,3})?$/;function $s(e){const t=new Set;for(const n of e??[]){const e=String(n).trim().toUpperCase();if("EEA"===e)for(const e of Ds)t.add(e);else Ls.test(e)&&t.add(e)}return[...t]}function Ms(e,t,n){return e.includes(t)}function qs(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,a=$s(e.regions?.denied),i=$s(e.regions?.granted);if(s){if(a.includes(`${r}-${s}`))return"denied";if(i.includes(`${r}-${s}`))return"granted"}return Ms(a,r)?"denied":Ms(i,r)||"granted"===e.default?"granted":"denied"}function Bs(){return"undefined"==typeof window?null:window}const Vs=["ad_storage","ad_user_data","ad_personalization","analytics_storage"];function zs(e){const t={};for(const n of Vs)t[n]=e;return t}function Gs(e){const t=Bs();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 Js="bb_cid";function Ys(){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const e=document.cookie.split("; ").find(e=>e.startsWith(`${Js}=`)),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=ps(window.location.hostname,document);return document.cookie=`${Js}=${n}; path=/; max-age=34128000; SameSite=Lax`+(r?`; domain=${r}`:""),n}catch{return}}const Hs="bb_consent_recorded";function Ks(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(Hs)===e}catch{return!1}}(t))return;!function(e){try{window.localStorage.setItem(Hs,e)}catch{}}(t);const n=Ys();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 Qs=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]),Zs=(e,t)=>e>>>t|e<<32-t;function Xs(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,a=1359893119,i=2600822924,o=528734635,c=1541459225;const l=e.length,d=l+1,u=d+(56-d%64+64)%64+8,p=new Uint8Array(u);p.set(e,0),p[l]=128;const h=8*l,m=Math.floor(h/4294967296),f=h>>>0;p[u-8]=m>>>24&255,p[u-7]=m>>>16&255,p[u-6]=m>>>8&255,p[u-5]=255&m,p[u-4]=f>>>24&255,p[u-3]=f>>>16&255,p[u-2]=f>>>8&255,p[u-1]=255&f;const g=new Uint32Array(64);for(let e=0;e<u;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=Zs(g[e-15],7)^Zs(g[e-15],18)^g[e-15]>>>3,n=Zs(g[e-2],17)^Zs(g[e-2],19)^g[e-2]>>>10;g[e]=g[e-16]+t+g[e-7]+n>>>0}let l=t,d=n,u=r,h=s,m=a,f=i,y=o,w=c;for(let e=0;e<64;e++){const t=w+(Zs(m,6)^Zs(m,11)^Zs(m,25))+(m&f^~m&y)+Qs[e]+g[e]>>>0,n=l&d^l&u^d&u;w=y,y=f,f=m,m=h+t>>>0,h=u,u=d,d=l,l=t+((Zs(l,2)^Zs(l,13)^Zs(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+d>>>0,r=r+u>>>0,s=s+h>>>0,a=a+m>>>0,i=i+f>>>0,o=o+y>>>0,c=c+w>>>0}const y=new Uint8Array(32),w=[t,n,r,s,a,i,o,c];for(let e=0;e<8;e++)y[4*e]=w[e]>>>24&255,y[4*e+1]=w[e]>>>16&255,y[4*e+2]=w[e]>>>8&255,y[4*e+3]=255&w[e];return y}(e))}async function ea(e){const t=globalThis.crypto?.subtle;if(t&&"function"==typeof t.digest)try{const n=await t.digest("SHA-256",(new TextEncoder).encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch{}return Xs((n=e,(new TextEncoder).encode(n)));var n}async function ta(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 ea(t)),n&&(r.phoneHash=await ea(n)),r}function na(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 ra(){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 sa(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 aa(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 ia(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=ra();n("fbp",r._fbp),n("fbc",r._fbc),n("ga_cid",sa(r._ga));const s=Object.keys(r).find(e=>e.startsWith("_ga_"));n("ga_sid",s?aa(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 oa(){const e=globalThis.crypto;return e?.randomUUID?e.randomUUID():`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}const ca=new Set(["workspace_id","workspace_role","workspace_owner","workspace_member_count","workspace_plan","subscription_status"]);function la(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(ca.has(n))continue;const e=typeof r;"string"!==e&&"number"!==e&&"boolean"!==e||/^[a-z][a-z0-9_]{0,39}$/.test(n)&&(t[`bbp_${n}`]=String(r).slice(0,200))}return t}function da(...e){const t=Math.max(0,...e.map(e=>e?Object.keys(e).length:0));return Math.max(0,Math.min(30,40-t))}function ua(e,t,n,r=30){const s={bb_event_id:e,...ia(t),...la(n)},a=vs();for(const[e,t]of Object.entries(a.params)){if(Object.keys(s).length>=30)break;"string"==typeof t&&t&&(s[`bb_${e}`]=t)}a.capturedAt&&Object.keys(a.params).length&&Object.keys(s).length<30&&(s.bb_attr_ts=String(a.capturedAt));const i=Math.max(0,Math.min(r,30));return Object.fromEntries(Object.entries(s).slice(0,i))}const pa={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}},ha=Object.keys(pa);function ma(e){return"string"==typeof e&&Object.prototype.hasOwnProperty.call(pa,e)}function fa(e,t){return!!ma(e)&&("string"==typeof t&&0!==t.length&&new RegExp(pa[e].idPattern).test(t))}const ga=/^[a-z][a-z0-9-]{0,40}$/,ya=/^[\w.:/@+=-]{1,200}$/;function wa(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])=>ga.test(e)&&"string"==typeof t&&ya.test(t))}(e.dataAttributes)}Array.from(new Set(ha.map(e=>pa[e].scriptOrigin))).sort();const ba={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}},va=Object.keys(ba);function xa(e){return va.includes(e)}function ka(){return"undefined"==typeof window?null:window}const Sa={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 Ca(){return"undefined"==typeof window?null:window}function Ia(e,t={}){const n=Ca();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 Na(e){const t=Ca();if(!t)return;const n=t.document.createElement("script");n.text=e,t.document.head.appendChild(n)}function Aa(e){const t=Ca();t&&(Array.isArray(t[e])||(t[e]=[]),"function"!=typeof t.gtag&&(t.gtag=function(){t[e].push(arguments)}))}const Ea=new Set;function ja(e){for(const t of Ea)if(t.slice(0,t.indexOf(":"))===e)return!0;return!1}function Pa(e,t){const n=Ca();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=Sa[e];if(!r)return!1;if(void 0===n[r])return!1;if(Ea.has(`${e}:${t}`))return!0;return!pa[e].multiInstance||!ja(e)}const _a={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 Ta(e,t,n){const r=function(e,t,n){const r=Ca();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 Ia(e.src,t),!0}const s=e.provider,a=pa[s];if(!a)return!1;const i=e.providerId;if(!i)return!1;const o=_a[s];if(o&&ja(s))return Na(o(i)),!0;switch(s){case"gtm":{Aa(t),r[t].push({"gtm.start":Date.now(),event:"gtm.js"});const e="dataLayer"===t?"":`&l=${t}`;return Ia(`${a.scriptOrigin}/gtm.js?id=${i}${e}`),!0}case"ga4":case"google_ads":{Aa(t),Ia(`${a.scriptOrigin}/gtag/js?id=${i}`);const e=r.gtag;e("js",new Date);const o="ga4"===s&&n?.gaClientId?{client_id:n.gaClientId}:void 0;return o?e("config",i,o):e("config",i),!0}case"meta_pixel":return Na(`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','${a.scriptOrigin}/en_US/fbevents.js');fbq('init','${i}');fbq('track','PageView');`),!0;case"x_pixel":return Na(`!function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments)},s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='${a.scriptOrigin}/uwt.js',a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');twq('config','${i}');`),!0;case"linkedin":return Na(`window._linkedin_partner_id='${i}';window._linkedin_data_partner_ids=window._linkedin_data_partner_ids||[];window._linkedin_data_partner_ids.push('${i}');window.lintrk=window.lintrk||function(a,b){(window.lintrk.q=window.lintrk.q||[]).push([a,b])};window.lintrk.q=window.lintrk.q||[];`),Ia(`${a.scriptOrigin}/li.lms-analytics/insight.min.js`),!0;case"tiktok":return Na(`!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=['page','track','identify','instances','debug','on','off','once','ready','alias','group','enableCookie','disableCookie'];ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.load=function(e,n){var r='${a.scriptOrigin}/i18n/pixel/events.js';ttq._i=ttq._i||{};ttq._i[e]=[];ttq._i[e]._u=r;ttq._t=ttq._t||{};ttq._t[e]=+new Date;ttq._o=ttq._o||{};ttq._o[e]=n||{};var o=d.createElement('script');o.type='text/javascript';o.async=!0;o.src=r+'?sdkid='+e+'&lib='+t;var a=d.getElementsByTagName('script')[0];a.parentNode.insertBefore(o,a)};ttq.load('${i}');ttq.page()}(window,document,'ttq');`),!0;case"reddit":return Na(`!function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement('script');t.src='${a.scriptOrigin}/ads/pixel.js';t.async=!0;var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','${i}');rdt('track','PageVisit');`),!0;case"bing_uet":return Na(`(function(w,d,t,r,u){w[u]=w[u]||[];w[u].push({ti:'${i}',enableAutoSpaTracking:false});var o=d.createElement(t);o.src='${a.scriptOrigin}/bat.js';o.async=1;var i=d.getElementsByTagName(t)[0];i.parentNode.insertBefore(o,i)})(window,document,'script',0,'uetq');`),!0;case"clarity":return Na(`(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src='${a.scriptOrigin}/tag/'+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,'clarity','script','${i}');`),!0;case"hotjar":return Na(`(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:${i},hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src='${a.scriptOrigin}/hotjar-'+h._hjSettings.hjid+'.js?sv='+h._hjSettings.hjsv;a.appendChild(r)})(window,document);`),!0;case"posthog":{const t=a.hosts,n=t?.includes(e.host??"")?e.host:t?.[0]??"us.i.posthog.com";return Na(`!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split('.');2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement('script')).type='text/javascript',p.async=!0,p.src='${a.scriptOrigin}/static/array.js',(r=t.getElementsByTagName('script')[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a='posthog',u.people=u.people||[],u.toString=function(t){var e='posthog';return'posthog'!==a&&(e+='.'+a),t||(e+=' (stub)'),e},u.people.toString=function(){return u.toString(1)+'.people (stub)'},o='init capture register register_once identify alias people.set people.set_once set_config get_distinct_id getFeatureFlag isFeatureEnabled onFeatureFlags reloadFeatureFlags group reset'.split(' '),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('${i}',{api_host:'https://${n}'});`),!0}case"plausible":return Na("window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)};"),Ia(`${a.scriptOrigin}/js/script.js`,{"data-domain":i,defer:"true"}),!0;case"ahrefs":return Ia(`${a.scriptOrigin}/analytics.js`,{"data-key":i}),r.__ahrefs_loaded=!0,!0;default:return!1}}(e,t,n);return r&&"external"!==e.provider&&e.providerId&&Ea.add(`${e.provider}:${e.providerId}`),r}const Ua=Symbol.for("@buildbase/sdk.tracking.context"),Ra=globalThis,Oa=Ra[Ua]??(Ra[Ua]=t.createContext(null)),Fa={consent:{manifest:[],state:null,effective:null,default:null,country:null,set:()=>{}},track:()=>{},setUser:()=>{},setIdentity:()=>{},setConsentRecordHeaders:()=>{},setProperties:()=>{},getProperties:()=>({}),completeCheckout:async()=>{},installed:{},ready:!0,attribution:{}};function Wa(){return t.useContext(Oa)??Fa}function Da(){return null!==t.useContext(Oa)}const La=({serverUrl:n,orgId:r,clientId:s,enabled:a=!0,consent:i="auto",autoPageview:o=!0,events:c,onEvent:l,properties:d,enrich:u,identity:p,debug:h=!1,children:m})=>{const f=t.useRef(p);f.current=p;const[g,y]=t.useState(null),[w,b]=t.useState(!1),[v,x]=t.useState(!1),k="object"==typeof i?JSON.stringify(i):"",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 i?i:"auto",I="granted"===C?{analytics:!0,marketing:!0}:"denied"===C?{analytics:!1,marketing:!1}:null,[N,A]=t.useState(I),E=t.useRef(null),j=t.useRef(l);j.current=l;const P=t.useRef(u);P.current=u;const _=t.useRef({});_.current=d??{};const T=t.useRef({}),U=t.useCallback(()=>({..._.current,...T.current}),[]),R=t.useCallback(e=>{const t={...T.current,...e};for(const[e,n]of Object.entries(t))void 0===n&&delete t[e];T.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"))},gt.add(e),()=>{gt.delete(e)};var e},[]),t.useEffect(()=>{if(!(a&&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}},[a,n,r,s,G]),t.useEffect(()=>{a&&F(bs())},[a]);const J="auto"===C?S??g?.consent?.defaults??null:null,Y=t.useMemo(()=>g?"auto"!==C?C:S?qs(S,g.country,g.region):g.consent?.defaults?g.resolvedConsentDefault??qs(g.consent.defaults,g.country,g.region):"denied":null,[g,C,S]),H=N??("granted"===Y?{analytics:!0,marketing:!0}:null),K=!!g?.enhancedConversions&&!!H?.marketing,Q=!!g?.scripts?.some(e=>"ga4"===e.provider||"google_ads"===e.provider||"gtm"===e.provider),Z=J?JSON.stringify(J):"";t.useEffect(()=>{a&&g?.enabled&&(Aa(z),function(e,t,n={}){const r=Bs();if(!r)return;Array.isArray(r[e])||(r[e]=[]),"function"!=typeof r.gtag&&(r.gtag=function(){r[e].push(arguments)});const s=r.gtag,a="auto"===t?n.regional:null;let i="granted"===t?"granted":"denied";if(a){const e=$s(a.regions?.denied),t=$s(a.regions?.granted).filter(t=>!e.includes(t));e.length&&s("consent","default",{...zs("denied"),region:e,wait_for_update:500}),t.length&&s("consent","default",{...zs("granted"),region:t}),i=a.default}s("consent","default",{...zs(i),..."denied"===i?{wait_for_update:500}:{}}),n.google&&(s("set","url_passthrough",!0),s("set","ads_data_redaction","granted"!==(n.resolved??i)))}(z,C,{regional:Z?JSON.parse(Z):null,resolved:Y,google:Q}),E.current&&Gs(E.current))},[a,g?.enabled,z,C,Z,Q]);const X=t.useMemo(()=>g?.enabled?g.scripts.filter(e=>{const t=ma(e.provider)&&pa[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,H,C)}):[],[g,N,Y,C]),[ee,te]=t.useState(()=>"undefined"==typeof window||!ks(window.location.search));t.useEffect(()=>{if(ee)return;const e=setInterval(()=>{ks(window.location.search)||te(!0)},50),t=setTimeout(()=>te(!0),5e3);return()=>{clearInterval(e),clearTimeout(t)}},[ee]),t.useEffect(()=>{if(!ee)return;if(!a||!g?.enabled)return void(w&&x(!0));let e=0;for(const t of X)if(!W.current[t.key]){if("external"===t.provider){if(!wa({src:t.src,dataAttributes:t.dataAttributes})){G("rejected external script",t.key);continue}}else{if(!ma(t.provider)){G("rejected unknown provider",t.provider);continue}if(!fa(t.provider,t.providerId)){G("rejected id for",t.provider);continue}if(Pa(t.provider,t.providerId??"")){G(`${t.provider} ${t.providerId} is already on the page; skipping. Configure each tag in exactly one place.`);continue}}Ta(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!==H||0===g.scripts.length;(n||r)&&x(!0)},[a,g,X,w,N,Y,z,G,ee,s]),t.useEffect(()=>{if(!a||!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=ka();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)}},[a,o,g?.enabled,X,z,ee]),t.useEffect(()=>{if(!a)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(!xa(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)},[a,c,l]);const ne=t.useCallback((e,t={},n)=>{if(!a)return;const r=n?.eventId||oa(),s=c?.mode??"auto",i=(xa(e)?c?.overrides?.[e]:void 0)??s,o={..._.current,...T.current,...O,...t},l=P.current?.({name:e,params:o})??{},d={...o,...l},u=j.current?.({name:e,params:d,eventId:r,handledBy:i});"manual"!==i&&!0!==u?(K&&$.current&&na(X,$.current),function(e,t,n,r,s){const a=ka();if(!a)return;const i=a[s];Array.isArray(i)&&i.push({event:e,...t,event_id:n});const o=xa(e)?ba[e]:{ga4:e,meta:null,tiktok:null,reddit:null};for(const s of r){const r=s.provider,i=pa[r];if(i){if(i.needsConversionIds){const i=s.conversionIds?.[e];if(!i)continue;"google_ads"===r?a.gtag?.("event","conversion",{send_to:`${s.providerId}/${i}`,transaction_id:n,...t}):"x_pixel"===r?a.twq?.("event",i,{...t,conversion_id:n}):"linkedin"===r&&a.lintrk?.("track",{conversion_id:i});continue}switch(r){case"ga4":o.ga4&&a.gtag?.("event",o.ga4,{...t,send_to:s.providerId,event_id:n});break;case"meta_pixel":o.meta&&a.fbq?.("track",o.meta,t,{eventID:n});break;case"tiktok":if(o.tiktok){const e=a.ttq;e?.track?.(o.tiktok,{...t,event_id:n})}break;case"reddit":o.reddit&&a.rdt?.("track",o.reddit,{...t,conversionId:n});break;case"bing_uet":{const r=a.uetq;r?.push?.("event",o.ga4??e,{...t,event_id:n});break}case"clarity":a.clarity?.("event",e);break;case"hotjar":{const t=a.hj;t?.("event",e);break}case"posthog":{const r=a.posthog;r?.capture?.(e,{...t,event_id:n});break}case"plausible":a.plausible?.(e,{props:t})}}}}(e,d,r,X,z),G("event fired:",e,r)):G("event handled by app:",e)},[a,c,X,z,O,G,K]),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 a=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(),a=s?.data??s;return"number"!=typeof a?.amount?null:{value:Ws(a.amount,a.currency),currency:"string"==typeof a.currency?a.currency:void 0,...Array.isArray(a.items)&&a.items.length?{items:a.items}:{}}}catch{return null}}({serverUrl:n,orgId:r},e.sessionId);t&&"number"==typeof t.value&&(a={...a,value:t.value,...t.currency?{currency:t.currency.toUpperCase()}:{},...t.items?.length?{items:t.items}:{}})}if(ne(s.name,{...a,...t},{eventId:e.eventId}),"purchase"===s.name&&e.sessionId&&n&&r){const t=(g?.scripts??[]).find(e=>"ga4"===e.provider&&e.providerId);t&&Pa("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(!a||!v)return;if("undefined"==typeof window)return;const e=Us(window.location.search);if(e)return void re(e);const t=Rs(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))})},[a,v,re,se,ne]);const ae=t.useCallback((e,t)=>{E.current=e,A(e),Gs(e),a&&Ks({serverUrl:n,orgId:r,clientId:s,state:e,manifestVersion:V.current?.consent?.manifestVersion,source:t?.source,consentString:t?.consentString,headers:B.current})},[a,n,r,s]),ie=t.useCallback(e=>{B.current={...e}},[]),oe=t.useCallback(e=>{if(!e)return $.current=null,void q(e=>e+1);ta(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=ka();if(!r)return;const s=!!n&&Object.keys(n).length>0;for(const a of t)switch(a.provider){case"ga4":case"google_ads":r.gtag?.("set",{user_id:e}),s&&r.gtag?.("set",{user_properties:n});break;case"meta_pixel":a.providerId&&r.fbq?.("init",a.providerId,{external_id:e});break;case"posthog":r.posthog?.identify?.(e,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(()=>{K&&$.current&&0!==Object.keys(W.current).length&&na(X,$.current)},[K,X,M,D]);const le=t.useMemo(()=>({consent:{manifest:g?.consent?.manifest??[],state:N,effective:H,default:Y,country:g?.country??null,set:ae},track:ne,setUser:ce,setIdentity:oe,setConsentRecordHeaders:ie,setProperties:R,getProperties:U,completeCheckout:re,installed:{...W.current},ready:v,attribution:O}),[g,N,Y,ae,ne,ce,oe,ie,R,U,re,v,D,O]);return e.jsx(Oa.Provider,{value:le,children:m})};function $a(){const e=dr(),n=xr(),r=Lr();return t.useMemo(()=>({auth:e,os:n,workspaces:r}),[e,n,r])}function Ma(e,n){const r=kr(),s=pr(),a=$r(),i=t.useCallback(e=>{const t=[r.subscribe(e),s.subscribe(e),a.subscribe(e)];return()=>t.forEach(e=>e())},[r,s,a]);return tr(t.useMemo(()=>{let e=null;return()=>(null!==e&&e.os===r.getState()&&e.auth===s.getState()&&e.workspaces===a.getState()||(e={os:r.getState(),auth:s.getState(),workspaces:a.getState()}),e)},[r,s,a]),i,e,n)}function qa(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 Ba(){return Ma(e=>e.os)}La.displayName="BuildBaseTracking";const Va=new Map;let za=null;function Ga(){const e=$a(),n=Ba(),{serverUrl:r,version:s,orgId:a,settings:i,settingsStatus:o,settingsError:c}=n,l=t.useMemo(()=>ze(n)?new Ie({serverUrl:r,version:s,orgId:a}):null,[r,s,a]),d=t.useCallback(async t=>{if(!l)return null;const n=((e,t,n)=>`${e}|${t}|${n}`)(r,s,a);za=n;const i=Va.get(n);if(i)return i;const o=(async()=>{e.os(fr("loading"));try{const t=await l.getSettings();return za===n&&e.os(mr(t)),t}catch(t){return za===n&&e.os(fr("error",t instanceof Error?t.message:"Failed to load settings")),B(t,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:r,version:s,orgId:a}}),null}finally{Va.delete(n)}})();return Va.set(n,o),o},[l,e,r,s,a]);qa(async()=>{i||ze(n)&&await d()},[r,s,a],{onError:e=>B(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:r,version:s,orgId:a}})});const u="loading"===o||("idle"===o||void 0===o)&&ze(n);return t.useMemo(()=>({settings:i,loading:u,error:c??null,refetch:d,getSettings:d}),[i,u,c,d])}function Ja(){const e=Ba(),n=$a(),r=t.useCallback(()=>{te(),n.auth(er.removeSession()),e.auth?.callbacks?.onSessionExpired?.("expired")},[n,e.auth?.callbacks?.onSessionExpired]),s=function(e,n){return t.useMemo(()=>new Ve({...e,onUnauthorized:n}),[e.serverUrl,e.version,e.orgId,n])}(e,r);return t.useMemo(()=>({os:e,api:s}),[e,s])}const Ya=e=>{const{t:n}=ss(),{os:r,api:s}=Ja(),a=ze(r),[i,o]=t.useState(null),[c,l]=t.useState(!1),[d,u]=t.useState(null),[p,h]=t.useState(null),{begin:m,settle:f}=os(),g=t.useCallback(async()=>{if(!e||!a)return m(),o(null),h(null),void l(!1);const t=m();l(!0),u(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);u(s),q(r,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{f(t)&&l(!1)}},[s,e,a,m,f]);t.useEffect(()=>{g()},[g]);const y=!(!e||a&&p===e),w=y||c;return{items:y?[]:i?.items??[],plans:y?[]:i?.plans??[],notes:y?void 0:i?.notes,loading:w,error:d,refetch:g}},Ha=e=>{const{t:n}=ss(),{os:r,api:s}=Ja(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,d]=t.useState(null),[u,p]=t.useState(null),{begin:h,settle:m}=os(),f=t.useCallback(async()=>{if(!e)return h(),i(null),p(null),void c(!1);const t=h();c(!0),d(null);try{const n=await is(`subscription:${r.serverUrl}:${r.orgId}:${e}`,()=>s.getCurrentSubscription(e));if(t.signal.aborted)return;i(n),p(e)}catch(r){if(t.signal.aborted)return;p(e);const s=V(r,"errors.fetchSubscription",n);d(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(()=>st(f),[f]);const g=!!e&&u!==e;return{subscription:g?null:a,loading:o||g,error:l,refetch:f}},Ka=(e,n)=>{const{t:r}=ss(),{api:s}=Ja(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,d]=t.useState(null),{begin:u,settle:p}=os(),h=t.useCallback(async()=>{if(!e)return u(),i(null),void c(!1);const t=u();c(!0),d(null);try{const r=n?await s.getPlanGroupByVersion(e,n):await s.getPlanGroup(e);if(t.signal.aborted)return;i(r)}catch(s){if(t.signal.aborted)return;const a=V(s,"errors.fetchPlanGroup",r);d(a),q(s,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:n}})}finally{p(t)&&c(!1)}},[s,e,n,u,p]);return t.useEffect(()=>{h()},[h]),{planGroup:a,loading:o,error:l,refetch:h}},Qa=e=>{const{t:n}=ss(),{api:r}=Ja(),{track:s}=Wa(),a=Da(),[i,o]=t.useState(!1),[c,l]=t.useState(null);return{updateSubscription:t.useCallback(async(t,i)=>{if(!e)throw new Error("Workspace ID is required");o(!0),l(null);try{const n={planVersionId:t,...i?.billingInterval&&{billingInterval:i.billingInterval},...i?.successUrl&&{successUrl:i.successUrl},...i?.cancelUrl&&{cancelUrl:i.cancelUrl}},o=oa(),c=await r.updateSubscription(e,n),l="checkoutUrl"in c&&c.checkoutUrl?c:null;if(l){const n=l.currency,r=Ws(l.amountTotal,n);a&&Ns({eventId:o,workspaceId:e,planVersionId:t,billingInterval:i?.billingInterval,currency:n,sessionId:l.sessionId,value:r,kind:l.trial?"trial_started":"purchase",startedAt:Date.now()}),s("checkout_started",{plan_version_id:t,...i?.billingInterval?{billing_interval:i.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,...i?.billingInterval?{billing_interval:i.billingInterval}:{},..."number"==typeof n&&n>0?{value:Ws(n,void 0)}:{}},{eventId:o})}return at(),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:i}}),r}finally{o(!1)}},[r,e,s,a]),loading:i,error:c}},Za=e=>{const{t:n}=ss(),{os:r,api:s}=Ja(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,d]=t.useState(null),[u,p]=t.useState(null),{begin:h,settle:m}=os(),f=t.useCallback(async()=>{if(!e)return h(),i(null),p(null),void c(!1);const t=h();c(!0),d(null);try{const n=await is(`quota-usage:${r.serverUrl}:${r.orgId}:${e}`,()=>s.getAllQuotaUsage(e));if(t.signal.aborted)return;i(n.quotas),p(e)}catch(r){if(t.signal.aborted)return;p(e);const s=V(r,"errors.fetchAllQuotaUsage",n);d(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(()=>tt(f),[f]);const g=!!e&&u!==e;return{quotas:g?null:a,loading:o||g,error:l,refetch:f}},Xa=t.createContext(null);Xa.displayName="SubscriptionContext";const ei=t.memo(function({children:n}){const r=Ma(e=>e.workspaces.currentWorkspace),{subscription:s,loading:a,error:i,refetch:o}=Ha(r?._id),c=t.useMemo(()=>({response:s,loading:a,error:i,refetch:o}),[s,a,i,o]);return e.jsx(Xa.Provider,{value:c,children:n})});function ti(){const e=t.useContext(Xa);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}ei.displayName="SubscriptionContextProvider";const ni=({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 "})]}),ri=({children:t,message:n,backgroundColor:r})=>{const{t:s}=ss(),a=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:a}),t??e.jsx(ni,{message:a}),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 "})]})};ri.displayName="FullScreenLoader";const si=t.createContext(null),ai=({children:n,loadingComponent:r})=>{const[s,a]=t.useState({visible:!1,message:""}),i=t.useRef(null),o=t.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null)},[]),c=t.useCallback(()=>{o(),a({visible:!1,message:""})},[o]),l=t.useCallback(e=>{o(),a({visible:!0,message:e}),i.current=setTimeout(()=>{q(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),a({visible:!1,message:""})},6e4)},[o]);t.useEffect(()=>()=>o(),[o]);const d=t.useMemo(()=>({show:l,hide:c,visible:s.visible,message:s.message}),[l,c,s.visible,s.message]),u="function"==typeof r?r({message:s.message}):r;return e.jsxs(si.Provider,{value:d,children:[n,s.visible&&e.jsx(ri,{message:s.message,children:u})]})};function ii(){const e=t.useContext(si);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}ai.displayName="FullScreenLoaderProvider";const oi="saas-oauth-state";function ci(){J(oi)}function li(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 di=new Set;function ui(e){return!di.has(e)&&(di.add(e),!0)}function pi(e,n,r,s){const{emitOnce:a}=hi(),i=t.useRef(s);i.current=s,t.useEffect(()=>{e&&a(n,r,i.current)},[e,n,r,a])}function hi(){const{track:e,ready:n}=Wa(),r=t.useCallback((t,n)=>{try{e(t,li(n))}catch{}},[e]),s=t.useCallback((e,t,s)=>{n&&ui(`${t}|${e}`)&&r(t,s)},[r,n]);return{emit:r,emitOnce:s,ready:n}}const mi=t.createContext({});function fi({ui:n,children:r}){const s=t.useMemo(()=>n??{},[n]);return e.jsx(mi.Provider,{value:s,children:r})}function gi(){return t.useContext(mi)}function yi(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?yi(n[e],r):r;return n}const wi={rows:[],loading:!1,error:null,fetchedAt:0};class bi{constructor(){this.snapshot=wi,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:Vn(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=wi;for(const e of this.listeners)e()}}const vi=new Map;function xi(e){const t=e||"unscoped";let n=vi.get(t);return n||(n=new bi,vi.set(t,n)),n}const ki={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"},Si=new Set(Object.values(ki));const Ci=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:ki.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||ki.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)})}},Ii=t.createContext(null);Ii.displayName="WorkspaceActionsContext";const Ni=({children:n})=>{const r=$a(),{os:s,api:a}=Ja(),{settings:i}=Ga(),{t:o}=ss(),c=t.useRef(o);t.useEffect(()=>{c.current=o},[o]);const l=Ma(e=>e.workspaces),d=Ma(e=>e.auth.session?.user),u=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;Kt(e),r.workspaces(Er(e)),Ye.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(Rr(e._id));try{const r=s.auth?.callbacks?.onWorkspaceChange;if(r){const t=tn(e,d?.id);try{await r({workspace:e,user:d??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(Rr(null))}},[r,s.auth?.callbacks?.onWorkspaceChange,m,d]),g=t.useRef(f);g.current=f,t.useEffect(()=>{if(!l.isInitialized){const e=Qt();if(r.workspaces(Pr(!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(()=>{Zt(),r.workspaces(jr())},[r]),w=t.useCallback(async()=>{if(!l.loading&&!u.current){u.current=!0,r.workspaces(_r(!0)),r.workspaces(Tr(null));try{const e=await a.getWorkspaces();if(r.workspaces(Sr(e)),e.length>0){const t=Qt();if(t&&Xt(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(Tr(V(e,"errors.fetchWorkspaces",c.current)))}finally{r.workspaces(_r(!1)),u.current=!1}}},[a,l.loading,r,f]),b=t.useCallback(async()=>{if(!l.refreshing&&!u.current){u.current=!0,r.workspaces(Ur(!0));try{const e=await a.getWorkspaces();r.workspaces(Sr(e))}catch(e){}finally{r.workspaces(Ur(!1)),u.current=!1}}},[a,l.refreshing,r]),v=t.useRef(null),x=gi(),k=!1!==x.behavior?.autoOpenPlanDialog&&!1!==x.settings?.sections?.subscription,S=t.useRef(k);S.current=k,t.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const C=t.useCallback(async(e,t)=>{const n=xs(),s=await a.createWorkspace({name:e,...t?{image:t}:{},...n?{trackingAttribution:n}:{}});r.workspaces(Cr(s)),await f(s),Ye.emitWorkspaceCreated(s).catch(e=>{q(e,{component:"WorkspaceProvider",action:"emitWorkspaceCreated",metadata:{workspaceId:s._id}})}),v.current&&clearTimeout(v.current),v.current=null,S.current&&(v.current=setTimeout(()=>{v.current=null,Ci.openWorkspaceSettings(ki.Subscription)},300))},[a,r,f]),I=t.useCallback(async(e,t)=>{const n=await a.updateWorkspace(e._id,t);r.workspaces(Ir(n)),Ye.emitWorkspaceUpdated(n).catch(e=>{q(e,{component:"WorkspaceProvider",action:"emitWorkspaceUpdated",metadata:{workspaceId:n._id}})})},[a,r]),N=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 a.getFeatures();return r.workspaces(Ar(e)),e}catch(e){return q(e,{component:"WorkspaceProvider",action:"getFeatures"}),null}finally{p.current=!1}},[a,r,l.allFeatures]),A=t.useCallback(async(e,t,n)=>await a.updateFeature(e,t,n),[a]),E=t.useCallback(async e=>a.updateSettings(e),[a]),j=t.useCallback(async(e,t)=>{const n=await a.updateWorkspacePermissions(e,t);return await b(),n},[a,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&&(Kt(t),r.workspaces(Er(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 a.getWorkspaceUsers(e),[a]),_=t.useCallback(async(e,t,n)=>{const r=l.workspaces.find(t=>t._id===e);if(r){const e=Jt({settingsMaxUsers:i?.workspace?.maxWorkspaceUsers}),t=Yt({memberCount:r.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessageKey||"users.memberLimitReached")}const s=await a.addUser(e,{email:t,role:n});return r&&Ye.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"})}),at(),s},[a,l.workspaces,b,i]),T=t.useCallback(async(e,t)=>{const n=l.workspaces.find(t=>t._id===e);if(n&&en(n,t))throw new Error("Cannot remove the workspace owner");const r=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),s=await a.removeUser(e,t);if(n&&r){const t=r.role;Ye.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"})}),at(),s},[a,l.workspaces,b]),U=t.useCallback(async(e,t,n)=>{if(n.role){const n=l.workspaces.find(t=>t._id===e);if(n&&en(n,t))throw new Error("Cannot change the role of the workspace owner")}let r;if(n.role){const n=(await a.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);r=n?.role}const s=await a.updateUser(e,t,n);return n.role&&r&&r!==n.role&&Ye.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},[a,l.workspaces]),R=t.useCallback(async e=>{const t=await a.getProfile().catch(()=>null),n=await a.updateUserProfile(e);return Ye.emitUserUpdated(n,t||void 0).catch(e=>{q(e,{component:"WorkspaceProvider",action:"emitUserUpdated",metadata:{userId:n._id}})}),n},[a]),O=t.useCallback(async()=>await a.getProfile(),[a]),F=t.useCallback(async e=>await a.getWorkspace(e),[a]),W=t.useCallback(async e=>{if(!d)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(!en(t,d.id))throw new Error("Only the workspace creator can delete the workspace");const n=await a.deleteWorkspace(e);return r.workspaces(Nr(e)),l.currentWorkspace?._id===e&&(Zt(),r.workspaces(jr())),t&&Ye.emitWorkspaceDeleted(t).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceDeleted",metadata:{workspaceId:e}})}),n},[a,l.workspaces,l.currentWorkspace,r,d]),D=t.useCallback(e=>a.listInvitations(e),[a]),L=t.useCallback(async(e,t,n,r)=>{const s=await a.inviteMember(e,{email:t,role:n,landingUrl:r?.landingUrl});return Ye.emitWorkspaceInvitationSent(s,e).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationSent",metadata:{workspaceId:e,invitationId:s._id}})}),at(),s},[a]),$=t.useCallback(async(e,t)=>{const n=await a.resendInvitation(e,t);return at(),n},[a]),M=t.useCallback(async(e,t)=>{await a.revokeInvitation(e,t),Ye.emitWorkspaceInvitationRevoked(t,e).catch(n=>{q(n,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationRevoked",metadata:{workspaceId:e,invitationId:t}})}),at()},[a]),B=t.useCallback(()=>a.myInvitations(),[a]),z=t.useCallback(async(e,t)=>{const n=await a.acceptInvitation(e,t),i=n.workspace;i&&!l.workspaces.some(e=>e._id===i._id)&&r.workspaces(Cr(i)),b().catch(e=>{q(e,{component:"WorkspaceProvider",action:"refreshAfterAccept"})}),n.workspace&&Ye.emitWorkspaceInvitationAccepted(n.invitation,n.workspace).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationAccepted",metadata:{invitationId:e}})});const o=n.workspace;return d?.id&&o&&Ye.emitWorkspaceUserAdded(d.id,o,n.invitation.role).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceUserAdded",metadata:{workspaceId:o._id,invitationId:e}})}),at(),xi(s.orgId??"").remove(e),{invitation:n.invitation,workspace:n.workspace}},[a,b,d?.id,s.orgId,l.workspaces,r]),G=t.useCallback(async e=>{const{invitation:t}=await a.declineInvitation(e);return Ye.emitWorkspaceInvitationDeclined(t).catch(t=>{q(t,{component:"WorkspaceProvider",action:"emitWorkspaceInvitationDeclined",metadata:{invitationId:e}})}),xi(s.orgId??"").remove(e),t},[a,s.orgId]),J=t.useCallback(e=>a.previewInvitation(e),[a]),Y=t.useMemo(()=>({fetchWorkspaces:w,refreshWorkspaces:b,setCurrentWorkspace:m,switchToWorkspace:f,resetCurrentWorkspace:y,createWorkspace:C,updateWorkspace:I,deleteWorkspace:W,getWorkspace:F,getUsers:P,addUser:_,removeUser:T,updateUser:U,getProfile:O,updateUserProfile:R,getFeatures:N,updateFeature:A,updateWorkspaceSettings:E,updateWorkspacePermissions:j,listInvitations:D,inviteMember:L,resendInvitation:$,revokeInvitation:M,myInvitations:B,acceptInvitation:z,declineInvitation:G,previewInvitation:J}),[w,b,m,f,y,C,I,W,F,P,_,T,U,O,R,N,A,E,j,D,L,$,M,B,z,G,J]);return e.jsx(Ii.Provider,{value:Y,children:n})};Ni.displayName="WorkspaceProviderInner";const Ai=({children:n})=>t.useContext(Ii)?e.jsx(e.Fragment,{children:n}):e.jsx(Ni,{children:n});Ai.displayName="WorkspaceProvider";const Ei=()=>{const e=t.useContext(Ii);if(!e)throw new Error("useSaaSWorkspaces must be used within a WorkspaceProvider. Make sure SaaSOSProvider is wrapping your application.");const n=Ma(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])},ji=/^\+[1-9]\d{6,14}$/;function Pi(e){return"string"==typeof e&&ji.test(e)}function _i(e){return!0===e.isAnonymous||"string"==typeof e.email&&e.email.endsWith("@anonymous.invalid")}function Ti(e){return"string"==typeof e&&e&&Number.isFinite(Date.parse(e))?e:void 0}function Ui(e){const t=Ti(e.authTime),n=Array.isArray(e.amr)?e.amr.filter(e=>"string"==typeof e&&e.length>0):void 0,r=e.impersonation,s=Ti(r?.expiresAt),a=r&&"object"==typeof r&&s?{actorName:"string"==typeof r.actorName?r.actorName:"",readOnly:!1!==r.readOnly,expiresAt:s}:void 0;return{...t?{authTime:t}:{},...n?{amr:n}:{},...a?{impersonation:a}:{}}}function Ri(e){return!0===e.canChangeEmail?{canChangeEmail:!0}:"linked_social_account"===e.changeEmailBlockedBy?{canChangeEmail:!1,changeEmailBlockedBy:"linked_social_account"}:{canChangeEmail:!1}}function Oi(e){return Pi(e.phone)?{phone:e.phone,phoneVerified:!0===e.phoneVerified}:{}}function Fi(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");const s=_i(e),a="string"==typeof e.username?e.username:"",i=Ti(e.deleteAfter);return{id:r,name:e.name||"",org:t,email:s?"":e.email,emailVerified:!s&&!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,mfaEnabled:!0===e.mfaEnabled,...Ri(e),..."string"==typeof e.externalId&&e.externalId?{externalId:e.externalId}:{},...Oi(e),...a?{username:a}:{},claims:(o=e.claims,o&&"object"==typeof o&&!Array.isArray(o)?o:{}),isAnonymous:s,...i?{deleteAfter:i}:{}};var o}function Wi(e,t,n={}){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString(),...n}}function Di(){return Ma(e=>e.auth)}function Li(){const{t:e}=ss(),n=$a(),r=Di(),s=Ba(),{serverUrl:a,orgId:i,auth:o}=s,{resetCurrentWorkspace:c,currentWorkspace:l}=Ei(),d=ii(),{consent:u}=Wa(),{emit:p}=hi(),h=t.useContext(Kr).requestedLocale,m=t.useMemo(()=>new fe({serverUrl:a,version:s.version}),[a,s.version]),{api:f}=Ja(),g=t.useCallback(async t=>{xt(t||window.location.href),p("sign_in_started",{from_path:window.location.pathname}),n.auth(er.authenticationStarted()),d.show(e("loading.redirecting"));try{const e=function(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return G(oi,t),t}(),{redirectUrl:t}=await m.requestAuth({orgId:i,clientId:o?.clientId??"",redirect:{success:o?.redirectUrl||window.location.href,error:o?.redirectUrl||window.location.href},state:e,...u.state?{trackingConsent:{analytics:!!u.state.analytics,marketing:!!u.state.marketing}}:{},...(()=>{const e=function(){const e=ra(),t=Object.keys(e).find(e=>e.startsWith("_ga_")),n={},r=sa(e._ga);r&&(n.gaClientId=r);const s=t?aa(e[t]):void 0;return s&&(n.gaSessionId=s),n}();return Object.keys(e).length?{trackingIdentity:e}:{}})(),...(()=>{const e=xs();return e?{trackingAttribution:e}:{}})(),...(()=>{const e=Qn(i);return e?{invitationToken:e}:{}})(),...(()=>{const e=Jr(o?.locale)??Jr(h);return e?{locale:e}:{}})()});wt(t)}catch(e){throw d.hide(),n.auth(er.authenticationFailed()),q(e,{component:"useSaaSAuth",action:"signIn"}),e}},[m,i,o,n,d,e,u.state,p,h]),y=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=>m.logout(ne()??void 0,e),clearLocal:()=>{te(),n.auth(er.removeSession()),c()},onError:e=>q(e,{component:"useSaaSAuth",action:"signOut"})},e),[m,n,c,o?.callbacks?.onSignOut]),w=r.session,b=t.useCallback(t=>yn({currentHref:window.location.href,redirectUrl:o?.redirectUrl||void 0,session:w,start:e=>f.startReverification(e),saveIntent:xt,clearIntent:St,redirect:t=>{d.show(e("loading.redirecting")),wt(t)}},t).catch(e=>{throw d.hide(),q(e,{component:"useSaaSAuth",action:"requireReverification"}),e}),[f,o?.redirectUrl,w,d,e]),v=t.useCallback(e=>{l?Ci.openWorkspaceSettings(e):q(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),x=t.useCallback(()=>{l?Ci.openWorkspaceSettings(ki.Credits,{action:ot.OpenCreditStore}):q(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),k=t.useCallback(()=>{l?Ci.openWorkspaceSettings(ki.Subscription,{action:ot.SelectPlan}):q(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),S=t.useMemo(()=>hn(r.status),[r.status]);return t.useMemo(()=>({user:r.session?.user,session:r.session,status:r.status,...S,signIn:g,signOut:y,requireReverification:b,openWorkspaceSettings:v,openCreditStore:x,openPlanPicker:k}),[r.session,r.status,S,g,y,b,v,x,k])}const $i=o.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"}}),Mi=k.forwardRef(({className:t,variant:n,progress:r,size:a,startIcon:o,endIcon:c,asChild:l=!1,...d},u)=>{const p=l?i.Slot:"button",h=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(a);return e.jsxs(p,{disabled:r||d.disabled,className:T($i({variant:n,size:a,withIcon:null!=r||null!=o||null!=c,className:t})),ref:u,...d,children:[r&&e.jsx(s.Loader2,{size:h,className:"animate-spin"}),o&&k.cloneElement(o,{size:h}),d.children,c&&k.cloneElement(c,{size:h})]})});function qi({className:n,fixed:r=!0}){const{t:a,formattingLocale:i}=ss(),o=Di().session,{signOut:c}=Li(),[l,d]=t.useState(!1),u=o?.impersonation;if(!o||!u)return null;let p="";try{p=new Intl.DateTimeFormat(i,{timeStyle:"short"}).format(new Date(u.expiresAt))}catch{p=u.expiresAt}const h={name:o.user.name||o.user.email,actor:u.actorName,time:p};return e.jsx("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e.jsxs("div",{role:"region","aria-label":a("security.impersonationRegion"),className:T("flex flex-col gap-2 border-t border-warning/40 bg-background px-4 py-3 text-sm shadow-lg sm:flex-row sm:items-center sm:justify-between",r&&"fixed inset-x-0 bottom-0 z-[2147483000]",n),children:[e.jsxs("p",{className:"flex min-w-0 items-start gap-2 text-warning",children:[e.jsx(s.Eye,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 break-words",children:u.readOnly?a("security.impersonationReadOnly",h):e.jsxs(e.Fragment,{children:[a("security.impersonationFull",h),e.jsx("span",{className:"block",children:a("security.impersonationSignInLocked")})]})})]}),e.jsx(Mi,{size:"sm",variant:"outline",className:"shrink-0 self-end sm:self-auto",progress:l,disabled:l,onClick:async()=>{d(!0),await c(),d(!1)},children:a("security.impersonationExit")})]})})}Mi.displayName="Button";const Bi=e=>{const{t:n}=ss(),{os:r,api:s}=Ja(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,d]=t.useState(null),{begin:u,settle:p}=os(),h=t.useCallback(async()=>{if(!e)return u(),i(null),void c(!1);const t=u();c(!0),d(null);try{const n=await is(`credit-balance:${r.serverUrl}:${r.orgId}:${e}`,()=>s.getCreditBalance(e));if(t.signal.aborted)return;i(n)}catch(r){if(t.signal.aborted)return;const s=V(r,"errors.fetchCreditBalance",n);d(s),q(r,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{p(t)&&c(!1)}},[s,r.serverUrl,r.orgId,e,u,p]);return t.useEffect(()=>{h()},[h]),t.useEffect(()=>Ze(h),[h]),{balance:a,loading:o,error:l,refetch:h}},Vi=e=>{const{t:n}=ss(),{api:r}=Ja(),[s,a]=t.useState(!1),[i,o]=t.useState(null);return{consumeCredits:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const n=await r.consumeCredits(e,t);return Xe(),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{a(!1)}},[r,e]),loading:s,error:i}},zi=e=>{const{t:n}=ss(),{api:r}=Ja(),{track:s,consent:a,getProperties:i}=Wa(),o=Da(),[c,l]=t.useState(!1),[d,u]=t.useState(null);return{purchaseCredits:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");l(!0),u(null);const c=oa(),d=o?ua(c,a.effective,i(),Math.min(da(t.metadata),20-Object.keys(t.metadata??{}).length)):{},p=Object.keys(d).length>0?{...t,metadata:{...d,...t.metadata}}:t;try{let n;try{n=await r.purchaseCredits(e,p)}catch(s){const a=s?.status;if(p===t||t.metadata||400!==a)throw s;n=await r.purchaseCredits(e,t)}const a=n.currency??t.currency,i=Ws(n.amountTotal,a);return o&&Ns({eventId:c,workspaceId:e,creditPackageId:t.creditPackageId,currency:a,sessionId:n.sessionId,value:i,kind:"purchase",startedAt:Date.now()}),s("checkout_started",{credit_package_id:t.creditPackageId,...a?{currency:a.toUpperCase()}:{},..."number"==typeof i?{value:i}:{}},{eventId:c}),n}catch(r){const s=V(r,"errors.purchaseCredits",n);throw u(s),q(r,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:t}}),r}finally{l(!1)}},[r,e,s,a.effective,o]),loading:c,error:d}},Gi=e=>{const{t:n}=ss(),{api:r}=Ja(),[s,a]=t.useState([]),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:d,settle:u}=os(),p=t.useCallback(async()=>{if(!e)return d(),a([]),void o(!1);const t=d();o(!0),l(null);try{const n=await r.getCreditPackages(e);if(t.signal.aborted)return;a(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{u(t)&&o(!1)}},[r,e,d,u]);return t.useEffect(()=>{p()},[p]),{packages:s,loading:i,error:c,refetch:p}},Ji=()=>{const{t:e}=ss(),{os:n,api:r}=Ja(),s=ze(n),[a,i]=t.useState([]),[o,c]=t.useState(),[l,d]=t.useState(!1),[u,p]=t.useState(null),{begin:h,settle:m}=os(),f=t.useCallback(async()=>{if(!s)return h(),i([]),void d(!1);const t=h();d(!0),p(null);try{const e=await r.getPublicCreditPackages();if(t.signal.aborted)return;i(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)&&d(!1)}},[r,s,h,m]);t.useEffect(()=>{f()},[f]);return{packages:a,notes:o,loading:!s||l,error:u,refetch:f}},Yi=t.createContext(null);Yi.displayName="CreditBalanceContext";const Hi=t.memo(function({children:n}){const r=Ma(e=>e.workspaces.currentWorkspace),{balance:s,loading:a,error:i,refetch:o}=Bi(r?._id),c=t.useMemo(()=>({balance:s,loading:a,error:i,refetch:o}),[s,a,i,o]);return e.jsx(Yi.Provider,{value:c,children:n})});function Ki(){const e=t.useContext(Yi);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}Hi.displayName="CreditBalanceContextProvider";const Qi=t.createContext(null);function Zi(e,t){return e?e.replace(/\{\{(\w+)\}\}/g,(e,n)=>n in t?t[n]:e):e}function Xi(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"app"}function eo({mcp:n,children:r}){const s=t.useMemo(()=>n?.url?{...n,url:n.url.replace(/\/+$/,"")}:null,[n]);return e.jsx(Qi.Provider,{value:s,children:r})}function to(){return t.useContext(Qi)}const no=t.createContext({appPermissions:void 0});function ro({appPermissions:n,children:r}){const s=t.useMemo(()=>({appPermissions:n}),[n]);return e.jsx(no.Provider,{value:s,children:r})}function so(){return t.useContext(no)}const ao=t.createContext(null);ao.displayName="QuotaUsageContext";const io=t.memo(function({children:n}){const r=Ma(e=>e.workspaces.currentWorkspace),{quotas:s,loading:a,error:i,refetch:o}=Za(r?._id),c=t.useMemo(()=>({quotas:s,loading:a,error:i,refetch:o}),[s,a,i,o]);return e.jsx(ao.Provider,{value:c,children:n})});function oo(){const e=t.useContext(ao);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}io.displayName="QuotaUsageContextProvider";let co=!1;function lo(){co=!0}const uo=t.memo(({children:n,callbacks:r})=>{const{t:s}=ss(),a=$a(),i=Di(),o=Ba(),c=hn(i.status).isAuthenticated,l=ii(),d=t.useRef(!1),u=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(!ze(n))throw new Error("OS configuration is not available");const{serverUrl:i,version:c,orgId:d}=n;l.show(s("loading.verifyingAccount"));const u=new fe({serverUrl:i,version:c}),p=await u.getProfile(t),h=Wi(Fi(p,d,n.auth?.clientId||""),t,Ui(p));l.show(s("loading.almostThere")),ee(h.sessionId),u.getDeviceToken(h.sessionId).then(e=>e&&re(e)).catch(()=>{}),ie();const m=kt(),f=!!m&&m!==window.location.href;f&&lo(),a.auth(er.setSession(h)),f&&wt(m),l.hide()}}catch(t){throw l.hide(),kt(),q(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),a.auth(er.authenticationFailed()),t}},[a,r,o,l,s]);return t.useEffect(()=>{if("undefined"==typeof window)return;const e=gn(window.location.href);e&&(window.history.replaceState(window.history.state,"",e),function(e=Date.now()){try{sessionStorage.setItem(fn,String(e))}catch{}}())},[]),t.useEffect(()=>{if("undefined"==typeof window)return;if(c)return;if(p.current)return;if(h.current)return;if(!ze(o))return;if(ae())return;if(!r?.getSession)return p.current=!0,void a.auth(er.authenticationFailed());const e=r.getSession,{serverUrl:t,version:n,orgId:i}=o,d=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,a.auth(er.authenticationFailed()),l.hide(),"undefined"!=typeof window&&xt(window.location.href),void r?.onSessionExpired?.("missing");try{l.show(s("loading.verifyingAccount"));const e=new fe({serverUrl:t,version:n}),r=await e.getProfile(o),c=Wi(Fi(r,i,d),o,Ui(r));ee(c.sessionId),e.getDeviceToken(c.sessionId).then(e=>e&&re(e)).catch(()=>{}),p.current=!0;const u=kt(),h=!!u&&u!==window.location.href;h&&lo(),a.auth(er.setSession(c)),l.hide(),h&&wt(u)}catch(e){q(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),te(),p.current=!0,a.auth(er.authenticationFailed()),l.hide(),"undefined"!=typeof window&&xt(window.location.href),r?.onSessionExpired?.("expired")}finally{h.current=null}})()},[c,a,o,r]),t.useEffect(()=>{const e=ae();if(!e)return;if(d.current||u.current===e)return;if(!ze(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(oi);if(J(oi),!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 ci(),ie(),q(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void a.auth(er.authenticationFailed());ci(),d.current=!0,u.current=e;let n=!1;return a.auth(er.authenticationProcessing()),m(e).then(()=>{n||(u.current=null)}).catch(e=>{n||(q(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),ie(),u.current=null)}).finally(()=>{d.current=!1}),()=>{n=!0}},[m,o.serverUrl,o.version,o.orgId]),e.jsx(e.Fragment,{children:n})});uo.displayName="AuthProviderWrapper";const po=t.memo(({config:n,auth:r,children:s})=>{const a=$a();Ba();const i=t.useRef(r?.callbacks);i.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=i.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(()=>{a.os(hr({...n,auth:l}))},[n,l,a]),e.jsx(e.Fragment,{children:s})});po.displayName="ContextConfigProvider";const ho=t.createContext({container:null,setContainer:()=>{}}),mo=t.memo(({children:n})=>{const[r,s]=t.useState(null),a=t.useMemo(()=>({container:r,setContainer:s}),[r]);return e.jsxs(ho.Provider,{value:a,children:[n,e.jsx("div",{ref:s,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});mo.displayName="PortalProvider";const fo=t.createContext(null);function go(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 yo=t.memo(function({children:n,serviceWorkerPath:r="/push-sw.js",autoSubscribe:s=!1}){const{t:a}=ss(),i=Ba(),{isAuthenticated:o}=Li(),c=t.useMemo(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=t.useMemo(()=>new Se({serverUrl:i.serverUrl,version:i.version,orgId:i.orgId}),[i.serverUrl,i.version,i.orgId]),[d,u]=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 u(e=>({...e,isSubscribed:!1}));const n=await t.pushManager.getSubscription();if(e)return;u(e=>({...e,isSubscribed:!!n,permission:Notification.permission}))}catch{e||u(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[o,c,r]);const p=t.useCallback(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return u(t=>({...t,permission:e})),"granted"===e},[c]),h=t.useCallback(async()=>{if(c&&o){u(e=>({...e,loading:!0,error:null}));try{if(!await p())return void u(e=>({...e,loading:!1,error:a("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:go(e)})).toJSON();await l.subscribe({endpoint:n.endpoint,keys:{p256dh:n.keys.p256dh,auth:n.keys.auth}},navigator.userAgent),u(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:a("push.failedToSubscribe");u(e=>({...e,loading:!1,error:t})),q(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,o,l,r,p]),m=t.useCallback(async()=>{if(c){u(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)}}u(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:a("push.failedToUnsubscribe");u(e=>({...e,loading:!1,error:t})),q(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,r]),f=t.useMemo(()=>({...d,requestPermission:p,subscribe:h,unsubscribe:m}),[d,p,h,m]);return e.jsx(fo.Provider,{value:f,children:n})});const wo="bb_seen_users",bo=12e4;function vo(){try{const e=window.localStorage.getItem(wo),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}function xo(e,t,n=Date.now()){if(!e)return"login";if("undefined"==typeof window)return"login";if(vo().includes(e))return"login";if(function(e){try{const t=[e,...vo().filter(t=>t!==e)].slice(0,20);window.localStorage.setItem(wo,JSON.stringify(t))}catch{}}(e),!t)return"login";const r=Date.parse(t);return Number.isNaN(r)||r>n||n-r>bo||function(e){try{const t=window.document?.cookie;return"string"==typeof t&&t.split("; ").includes(`${ko}=${e}`)}catch{return!1}}(e)?"login":(function(e){try{const t=window.document;if(!t||!So.test(e))return;const n=ps(window.location?.hostname??"",t);t.cookie=`${ko}=${e}; path=/; max-age=120; SameSite=Lax`+(n?`; domain=${n}`:"")}catch{}}(e),"sign_up")}const ko="bb_su",So=/^[\w-]{1,64}$/;const Co="bb_announced_session";const Io={[Ge.UserCreated]:"user_created",[Ge.UserUpdated]:"user_updated",[Ge.WorkspaceCreated]:"workspace_created",[Ge.WorkspaceUpdated]:"workspace_updated",[Ge.WorkspaceChanged]:"workspace_switched",[Ge.WorkspaceDeleted]:"workspace_deleted",[Ge.WorkspaceUserAdded]:"workspace_member_added",[Ge.WorkspaceUserRemoved]:"workspace_member_removed",[Ge.WorkspaceUserRoleChanged]:"workspace_member_role_changed",[Ge.WorkspaceInvitationSent]:"workspace_invitation_sent",[Ge.WorkspaceInvitationAccepted]:"workspace_invitation_accepted",[Ge.WorkspaceInvitationDeclined]:"workspace_invitation_declined",[Ge.WorkspaceInvitationRevoked]:"workspace_invitation_revoked"};const No=Object.keys(Io),Ao="undefined"==typeof window?t.useEffect:t.useLayoutEffect;function Eo({children:n}){const{track:r,setUser:s,setProperties:a,ready:i,setIdentity:o,setConsentRecordHeaders:c}=Wa(),l=Di().session,d=l?.user?.id,u=l?.sessionId,p=l?.user?.email;t.useEffect(()=>{c(u?{"x-session-id":u}:{})},[u,c]),t.useEffect(()=>{o(p?{email:p}:null)},[p,o]);const{currentWorkspace:h}=Ei(),{response:m,loading:f}=ti(),g=t.useMemo(()=>function(e){const{workspace:t,userId:n,subscription:r,subscriptionLoading:s}=e,a={workspace_id:void 0,workspace_role:void 0,workspace_owner:void 0,workspace_member_count:void 0,workspace_plan:void 0,subscription_status:void 0};if(!t?._id)return a;const i=Array.isArray(t.users)?t.users.length:void 0,o=s?void 0:r?.subscription?r.plan?.slug??void 0:"none";return{workspace_id:String(t._id),workspace_role:tn(t,n)??void 0,workspace_owner:n?en(t,n):void 0,workspace_member_count:i,workspace_plan:o,subscription_status:s?void 0:r?.subscription?.subscriptionStatus??"none"}}({workspace:d?h:null,userId:d,subscription:m,subscriptionLoading:f}),[h,d,m,f]),y=JSON.stringify(g),w=t.useRef(null);Ao(()=>{w.current!==y&&(w.current=y,a(g))},[y,a]);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),v=JSON.stringify(b),x=t.useRef(null);t.useEffect(()=>{if(!i||!d||0===Object.keys(b).length)return;const e=`${d}|${v}`;x.current!==e&&(x.current=e,s(d,b))},[i,d,v,s]),t.useEffect(()=>{i&&d&&u&&(co||function(e){if(!e)return!1;if("undefined"==typeof window)return!1;try{return window.localStorage.getItem(Co)!==e&&(window.localStorage.setItem(Co,e),!0)}catch{return!0}}(u)&&(s(d),r(xo(d,l?.user?.firstAuthAt),{method:"buildbase"})))},[i,d,u,l?.user?.firstAuthAt,r,s]),t.useEffect(()=>{const e=No.map(e=>Ye.on(e,t=>{(function(e,t){if(e!==Ge.WorkspaceChanged)return!0;const n=t,r=n.workspace?._id,s=n.previousWorkspace?._id;return!!r&&!!s&&r!==s})(e,t)&&r(Io[e],function(e,t){const n=t,r={},s=n.workspace;s?._id&&(r.workspace_id=s._id);const a=n.previousWorkspace;a?._id&&(r.previous_workspace_id=a._id);const i=n.user;(i?._id||i?.id)&&(r.user_id=i._id??i.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(i);k.current=i;const S=t.useRef([]);return t.useEffect(()=>M.subscribe((e,t)=>{if(!ui(`sdk_error|${`${t.component??"unknown"}|${t.action??"unknown"}`}`))return;const n=li({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(!i||0===S.current.length)return;const e=S.current;S.current=[],e.forEach(e=>r("sdk_error",e))},[i,r]),e.jsx(e.Fragment,{children:n})}Eo.displayName="TrackingBridge";const jo=t.createContext(void 0),Po=t.memo(({children:n})=>{const{t:r}=ss(),s=Ba(),a=function(){const e=Ba();return t.useMemo(()=>new Re(e),[e.serverUrl,e.version])}(),{isAuthenticated:i}=Li(),{serverUrl:o,version:c}=s,[l,d]=t.useState({}),[u,p]=t.useState({}),[h,m]=t.useState(!1),[f,g]=t.useState(!1),[y,w]=t.useState(null),[b,v]=t.useState(null),x=t.useCallback(async e=>{if(o&&c&&i){w(null);try{const t=await a.getAttributes(e);d(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:"fetchAttributes"})}}else d({})},[a,o,c,i,r]),k=t.useCallback(async()=>{if(o&&c&&i){m(!0);try{await x()}finally{m(!1)}}},[o,c,i,x]),S=t.useCallback(async e=>{m(!0),w(null);try{const t=await a.updateAttributes(e);return await x(),t}catch(t){const n=t instanceof Error?t:new Error(r("errors.generic"));throw w(n),q(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{m(!1)}},[a,x,r]),C=t.useCallback(async(e,t)=>{m(!0),w(null);try{const n=await a.updateAttribute(e,t);return await x(),n}catch(n){const s=n instanceof Error?n:new Error(r("errors.generic"));throw w(s),q(n,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),n}finally{m(!1)}},[a,x,r]),I=t.useCallback(async e=>{if(o&&c&&i){v(null);try{const t=await a.getFeatures(e);p(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:"fetchFeatures"})}}else p({})},[a,o,c,i,r]),N=t.useCallback(async()=>{if(o&&c&&i){g(!0);try{await I()}finally{g(!1)}}},[o,c,i,I]);qa(async e=>{if(!i||!o||!c)return d({}),void p({});m(!0),g(!0),await Promise.all([x(e).finally(()=>m(!1)),I(e).finally(()=>g(!1))])},[i,o,c,x,I],{onError:e=>q(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const A=t.useMemo(()=>({attributes:l,features:u,isLoading:h||f,error:y??b,attributesLoading:h,featuresLoading:f,attributesError:y,featuresError:b,updateAttributes:S,updateAttribute:C,refreshAttributes:k,refreshFeatures:N}),[l,u,h,f,y,b,S,C,k,N]);return e.jsx(jo.Provider,{value:A,children:n})});Po.displayName="UserProvider";const _o=S.Root,To=S.Trigger,Uo=S.Portal,Ro=k.forwardRef(({className:t,...n},r)=>e.jsx(S.Overlay,{ref:r,className:T("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}));Ro.displayName=S.Overlay.displayName;const Oo=k.forwardRef(({className:t,children:n,...r},s)=>{const{container:a}=k.useContext(ho),{t:i}=ss();return e.jsxs(Uo,{container:a,children:[e.jsx(Ro,{}),e.jsxs(S.Content,{ref:s,className:T("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:i("settings.common.close")})]})]})]})});Oo.displayName=S.Content.displayName;const Fo=({className:t,...n})=>e.jsx("div",{className:T("flex flex-col space-y-1.5 text-center sm:text-start",t),...n});Fo.displayName="DialogHeader";const Wo=({className:t,...n})=>e.jsx("div",{className:T("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...n});Wo.displayName="DialogFooter";const Do=k.forwardRef(({className:t,...n},r)=>e.jsx(S.Title,{ref:r,className:T("text-lg font-semibold leading-none tracking-tight",t),...n}));Do.displayName=S.Title.displayName;const Lo=k.forwardRef(({className:t,...n},r)=>e.jsx(S.Description,{ref:r,className:T("text-sm text-muted-foreground",t),...n}));Lo.displayName=S.Description.displayName;const $o={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 Mo({variant:t,title:n,message:r,description:s,icon:a,actionLabel:i,onAction:o,actionDisabled:c,actionProgress:l,className:d}){const u=$o[t];return e.jsxs("div",{role:"error"===t?"alert":"status","aria-live":"error"===t?"assertive":"polite","aria-atomic":"true",className:T("border px-4 py-3 rounded-lg flex items-start justify-between gap-2 sm:gap-4",u.box,d),children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[a,e.jsxs("div",{className:"min-w-0",children:[n&&e.jsx("p",{className:"text-sm font-medium",children:n}),r&&e.jsx("p",{className:T("text-sm",n&&"mt-1"),children:r}),s&&e.jsx("p",{className:T("text-xs mt-2",u.sub),children:s})]})]}),i&&e.jsx(Mi,{variant:"outline",size:"sm",onClick:o,progress:l,disabled:c||l,className:T("flex-shrink-0",u.button),children:i})]})}const qo=new Set(["alreadyAccepted","expired","revoked","accepted","declined","disabled"]),Bo=new Set(["expired","revoked","disabled"]),Vo=new Set(["accepted"]),zo=new Set(["alreadyAccepted","expired","revoked","declined"]);function Go(){const{t:n}=ss(),r=Ba(),{isAuthenticated:s,isLoading:a,signIn:i,signOut:o}=Li(),{previewInvitation:c,acceptInvitation:l,declineInvitation:d,switchToWorkspace:u}=Ei(),p=r.orgId??"",[h,m]=t.useState(null),[f,g]=t.useState(null),[y,w]=t.useState({kind:"none"}),[b,v]=t.useState(!1),x=t.useRef(!1),k=qo.has(y.kind),S="accepted"===y.kind?n("invitations.titleJoined",{workspace:y.workspace}):Bo.has(y.kind)?n("invitations.titleUnavailable"):n("invitations.title"),C="wrongAccount"===y.kind,I=t.useCallback(e=>{w(e),qo.has(e.kind)&&Zn()},[]);t.useEffect(()=>{if(x.current||!p)return;x.current=!0;const e=pt();e?.action===ot.Invite&&e.token&&(Kn(e.token,p),ht(),m(e.token))},[p]),t.useEffect(()=>{if(!p||h||a)return;const e=Qn(p);e&&m(e)},[p,h,a,s]),t.useEffect(()=>{if(!h)return;let e=!1;return g(null),w({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"}),$e(t)&&404===t.status?I({kind:"revoked"}):w({kind:"loadFailed"}))}),()=>{e=!0}},[h,c,I]);const N=t.useCallback(()=>{Zn(),m(null),g(null),w({kind:"none"})},[]);if(!h)return null;const A=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),E=Vo.has(y.kind)?"success":zo.has(y.kind)?"info":"error";return e.jsx(_o,{open:!0,onOpenChange:e=>!e&&N(),children:e.jsxs(Oo,{className:"sm:max-w-md",children:[e.jsxs(Fo,{children:[e.jsx(Do,{children:S}),f&&e.jsx(Lo,{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})}),A&&e.jsx(Mo,{variant:E,message:A}),e.jsx(Wo,{className:"gap-2 sm:gap-2",children:k?e.jsx(Mi,{onClick:N,children:n("invitations.dismiss")}):C?e.jsxs(e.Fragment,{children:[e.jsx(Mi,{variant:"outline",onClick:N,children:n("invitations.dismiss")}),e.jsx(Mi,{onClick:()=>{o().then(()=>w({kind:"none"})).catch(e=>q(e,{component:"InvitationLanding",action:"signOut"}))},children:n("invitations.signOut")})]}):f?a?null:s?e.jsxs(e.Fragment,{children:[e.jsx(Mi,{variant:"outline",disabled:b,onClick:async()=>{if(f){v(!0),w({kind:"none"});try{await d(f.id),I({kind:"declined"})}catch(e){q(e,{component:"InvitationLanding",action:"decline"}),$e(e)&&e.code===Oe.EMAIL_MISMATCH?w({kind:"wrongAccount",email:e.invitedEmail??f.email}):$e(e)&&e.code===Oe.ALREADY_HANDLED?I("accepted"===e.invitationStatus?{kind:"alreadyAccepted"}:{kind:"revoked"}):w({kind:"declineFailed"})}finally{v(!1)}}},children:n("invitations.decline")}),e.jsx(Mi,{progress:b,onClick:async()=>{if(f){v(!0),w({kind:"none"});try{const{workspace:e}=await l(f.id,{token:h??void 0});I({kind:"accepted",workspace:f.workspaceName}),e&&await u(e)}catch(e){if(q(e,{component:"InvitationLanding",action:"accept"}),$e(e))switch(e.code){case Oe.EMAIL_NOT_VERIFIED:w({kind:"verifyFirst"});break;case Oe.EMAIL_MISMATCH:w({kind:"wrongAccount",email:e.invitedEmail??f.email});break;case Oe.SEAT_LIMIT:w({kind:"workspaceFull"});break;case Oe.INVITES_DISABLED:I({kind:"disabled"});break;case Oe.EXPIRED:I({kind:"expired",inviter:f.inviterName});break;case Oe.ALREADY_HANDLED:case Oe.NOT_FOUND:I("accepted"===e.invitationStatus?{kind:"alreadyAccepted"}:{kind:"revoked"});break;default:w({kind:"raw",message:e.message})}else w({kind:"acceptFailed"})}finally{v(!1)}}},children:n("invitations.accept")})]}):e.jsxs(e.Fragment,{children:[e.jsx(Mi,{variant:"outline",onClick:N,children:n("invitations.dismiss")}),e.jsx(Mi,{onClick:()=>{i(window.location.href).catch(e=>q(e,{component:"InvitationLanding",action:"signIn"}))},children:n("invitations.signInToAccept")})]}):e.jsx(Mi,{variant:"outline",onClick:N,disabled:!A,children:n("invitations.dismiss")})})]})})}function Jo(e){const{user:n}=Li(),{currentWorkspace:r}=Ei(),{settings:s}=Ga(),{appPermissions:a}=so(),i=e??r??null,o=n?.id??null,c=t.useMemo(()=>i?tn(i,o):null,[i,o]),l=t.useMemo(()=>!!i&&en(i,o),[i,o]),d=t.useMemo(()=>cn({userId:o,workspaceRole:c,workspace:i,settings:s,appPermissions:a}),[o,c,i,s,a]),u=t.useCallback(e=>Array.isArray(e)?e.every(e=>d.has(e)):d.has(e),[d]),p=t.useMemo(()=>un(s,a),[s,a]);return{can:u,permissions:d,isOwner:l,role:c,appPermissionDefinitions:p}}function Yo(){const e=gi(),{can:n}=Jo();return{visible:t.useCallback((t,r)=>!1!==t(e)&&(void 0===r||n(r)),[e,n]),ui:e}}function Ho(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 Ko=[["second",60],["minute",60],["hour",24],["day",7],["week",4.34524],["month",12],["year",Number.POSITIVE_INFINITY]];function Qo(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 a=(r-n)/1e3;if(Math.abs(a)<60)return s.format(0,"second");for(const[e,t]of Ko){if(Math.abs(a)<t)return s.format(Math.round(a),e);a/=t}return""}catch{return""}}function Zo(){const e=t.useRef(null);return t.useEffect(()=>()=>{e.current&&clearTimeout(e.current)},[]),t.useCallback((t,n=5e3)=>{e.current&&clearTimeout(e.current),e.current=setTimeout(()=>{e.current=null,t()},n)},[])}function Xo(){const e=Ba();return t.useMemo(()=>new we(e),[e.serverUrl,e.version])}function ec(){const e=Xo(),{t:n}=ss(),[r,s]=t.useState([]),[a,i]=t.useState(!0),[o,c]=t.useState(null),[l,d]=t.useState(null),u=t.useRef(null),p=t.useRef(n);t.useEffect(()=>{p.current=n},[n]);const h=t.useCallback(async()=>{u.current?.abort();const t=new AbortController;u.current=t,i(!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{u.current===t&&(u.current=null,i(!1))}},[e]);t.useEffect(()=>(h(),()=>u.current?.abort()),[h]);const m=t.useCallback(async t=>{d(t),c(null);try{return await e.revoke(t),s(e=>e.filter(e=>e.clientId!==t)),!0}catch(e){return B(e,{component:"useConnectedAgents",action:"revoke"}),c(V(e,"security.connectedAgentsRevokeFailed",p.current)),!1}finally{d(null)}},[e]);return t.useMemo(()=>({agents:r,loading:a,error:o,revoking:l,refresh:h,revoke:m}),[r,a,o,l,h,m])}const tc=P.Root,nc=P.Trigger,rc=P.Portal,sc=k.forwardRef(({className:t,...n},r)=>e.jsx(P.Overlay,{className:T("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}));sc.displayName=P.Overlay.displayName;const ac=k.forwardRef(({className:t,...n},r)=>{const{container:s}=k.useContext(ho);return e.jsxs(rc,{container:s,children:[e.jsx(sc,{}),e.jsx(P.Content,{ref:r,className:T("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})]})});ac.displayName=P.Content.displayName;const ic=({className:t,...n})=>e.jsx("div",{className:T("flex flex-col space-y-2 text-center sm:text-start",t),...n});ic.displayName="AlertDialogHeader";const oc=({className:t,...n})=>e.jsx("div",{className:T("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...n});oc.displayName="AlertDialogFooter";const cc=k.forwardRef(({className:t,...n},r)=>e.jsx(P.Title,{ref:r,className:T("text-lg font-semibold",t),...n}));cc.displayName=P.Title.displayName;const lc=k.forwardRef(({className:t,...n},r)=>e.jsx(P.Description,{ref:r,className:T("text-sm text-muted-foreground",t),...n}));lc.displayName=P.Description.displayName;const dc=k.forwardRef(({className:t,...n},r)=>e.jsx(P.Action,{ref:r,className:T($i(),t),...n}));dc.displayName=P.Action.displayName;const uc=k.forwardRef(({className:t,...n},r)=>e.jsx(P.Cancel,{ref:r,className:T($i({variant:"outline"}),"mt-2 sm:mt-0",t),...n}));function pc({icon:t,title:n,description:r,action:s,className:a}){return e.jsxs("div",{className:T("flex flex-col items-center gap-2 rounded-md border border-dashed p-6 text-center",a),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 hc({title:t,description:n,actions:r,help:s,className:a,titleClassName:i}){if(!t&&!n&&!r)return null;const o=t&&e.jsx("h3",{className:T("text-sm font-medium",i),children:t}),c=n&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n});return e.jsxs("div",{className:T(a),children:[(t||r)&&e.jsxs("div",{className:T("flex items-center gap-2",t?"justify-between":"justify-end"),children:[o&&s?e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[o,s]}):o,r]}),c&&s&&!t?e.jsxs("div",{className:"flex items-start gap-1",children:[c,s]}):c]})}function mc({className:t,...n}){return e.jsx("div",{className:T("animate-pulse rounded-md bg-primary/10",t),...n})}uc.displayName=P.Cancel.displayName;const fc=j.Root,gc=k.forwardRef(({className:t,...n},r)=>e.jsx(j.Item,{ref:r,className:T("border-b last:border-b-0",t),...n}));gc.displayName="AccordionItem";const yc=k.forwardRef(({className:t,children:n,...r},a)=>e.jsx(j.Header,{className:"flex",children:e.jsxs(j.Trigger,{ref:a,className:T("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(s.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})]})}));yc.displayName="AccordionTrigger";const wc=k.forwardRef(({className:t,children:n,...r},s)=>e.jsx(j.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:T("pb-3 pt-0",t),children:n})}));function bc({value:t,displayValue:n,copyLabel:r,copiedLabel:a,variant:i="inline",className:o}){const c=n??t,[l,d]=k.useState(!1),u=k.useRef(null);k.useEffect(()=>()=>{u.current&&clearTimeout(u.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)&&(d(!0),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>d(!1),2e3))},h=t=>e.jsxs(Mi,{type:"button",variant:"ghost",size:"sm",onClick:p,"aria-label":l?a:r,className:"h-7 shrink-0 gap-1.5 px-2",children:[l?e.jsx(s.Check,{className:"h-3.5 w-3.5","aria-hidden":"true"}):e.jsx(s.Copy,{className:"h-3.5 w-3.5","aria-hidden":"true"}),e.jsx("span",{className:T("text-xs",t&&"hidden sm:inline"),children:l?a:r})]});return"inline"===i?e.jsxs("div",{dir:"ltr",className:T("flex items-center gap-2 rounded-md border bg-muted/40 py-1 ps-3 pe-1",o),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:T("overflow-hidden rounded-md border bg-muted/40",o),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 vc({config:t,title:n,description:r,className:a}){const{t:i}=ss(),o=to(),c=t??o;if(!c?.url)return null;const l=c.name?.trim()||"app",d={url:c.url,name:l,key:Xi(l)},u=(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")},u("cursor","Cursor","~/.cursor/mcp.json",'{\n "mcpServers": {\n "{{key}}": {\n "url": "{{url}}"\n }\n }\n}'),u("vscode","VS Code",".vscode/mcp.json",'{\n "servers": {\n "{{key}}": {\n "type": "http",\n "url": "{{url}}"\n }\n }\n}'),u("windsurf","Windsurf","~/.codeium/windsurf/mcp_config.json",'{\n "mcpServers": {\n "{{key}}": {\n "serverUrl": "{{url}}"\n }\n }\n}'),{id:"cline",name:"Cline",instructions:i("security.mcpClientClineInstructions")}],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"),w=!1===c.prompt?null:c.prompt??i("security.mcpPromptTemplate"),b=Zi(w??void 0,d),v=Zi(w??void 0,{...d,url:`${d.url}`,name:`${d.name}`});return e.jsxs("div",{className:T("space-y-5",a),children:[e.jsx(hc,{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(bc,{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(bc,{value:b,displayValue:v,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(fc,{type:"single",collapsible:!0,defaultValue:h[0]?.id,className:"rounded-md border px-3",children:h.map(t=>{const n=Zi(t.instructions,d),r=Zi(t.snippet,d);return e.jsxs(gc,{value:t.id,children:[e.jsx(yc,{children:t.name}),e.jsx(wc,{children:e.jsxs("div",{className:"space-y-2",children:[n&&e.jsx("p",{className:"text-sm text-muted-foreground",children:n}),r&&e.jsx(bc,{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(s.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(s.ExternalLink,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}function xc(){const e=Ba();return t.useMemo(()=>new be(e),[e.serverUrl,e.version])}function kc(){const e=xc(),{t:n}=ss(),[r,s]=t.useState([]),[a,i]=t.useState(!0),[o,c]=t.useState(null),[l,d]=t.useState(null),u=t.useRef(null),p=t.useRef(n);t.useEffect(()=>{p.current=n},[n]);const h=t.useCallback(async()=>{u.current?.abort();const t=new AbortController;u.current=t,i(!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{u.current===t&&(u.current=null,i(!1))}},[e]);t.useEffect(()=>(h(),()=>u.current?.abort()),[h]);const m=t.useCallback(async(t,n)=>{d(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{d(null)}},[e]),f=t.useCallback(async t=>{d(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{d(null)}},[e]),g=t.useCallback(async t=>{d(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{d(null)}},[e]);return t.useMemo(()=>({devices:r,loading:a,error:o,busyId:l,refresh:h,rename:m,signOut:f,forget:g}),[r,a,o,l,h,m,f,g])}function Sc(e){return!!e&&/Mobi|Android|iPhone|iPad|iPod|Windows Phone/i.test(e)}function Cc(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 Ic(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":""),Cc(e)].filter(Boolean).join(" · "):"";var t}wc.displayName="AccordionContent";const Nc=k.forwardRef(({className:t,type:n,...r},s)=>e.jsx("input",{type:n,className:T("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 Ac(){const e=Ba();return t.useMemo(()=>new Ce(e),[e.serverUrl,e.version])}function Ec(){const e=Ac(),{t:n}=ss(),[r,s]=t.useState([]),[a,i]=t.useState(!0),[o,c]=t.useState(null),[l,d]=t.useState(null),u=t.useRef(null),p=t.useRef(n);t.useEffect(()=>{p.current=n},[n]);const h=t.useCallback(async()=>{u.current?.abort();const t=new AbortController;u.current=t,i(!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{u.current===t&&(u.current=null,i(!1))}},[e]);t.useEffect(()=>(h(),()=>u.current?.abort()),[h]);const m=t.useCallback(async t=>{d(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{d(null)}},[e]);return t.useMemo(()=>({sessions:r,loading:a,error:o,revoking:l,refresh:h,revoke:m}),[r,a,o,l,h,m])}Nc.displayName="Input";const jc=_.Root,Pc=_.Trigger,_c=k.forwardRef(({className:t,align:n="center",sideOffset:r=4,...s},a)=>{const{container:i}=k.useContext(ho);return e.jsx(_.Portal,{container:i,children:e.jsx(_.Content,{ref:a,align:n,sideOffset:r,className:T("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})})});_c.displayName=_.Content.displayName;const Tc=o.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Uc=k.forwardRef(({className:t,...n},r)=>e.jsx(C.Root,{ref:r,className:T(Tc(),t),...n}));Uc.displayName=C.Root.displayName;const Rc=u.FormProvider,Oc=k.createContext({}),Fc=({...t})=>e.jsx(Oc.Provider,{value:{name:t.name},children:e.jsx(u.Controller,{...t})}),Wc=()=>{const e=k.useContext(Oc),t=k.useContext(Dc),{getFieldState:n,formState:r}=u.useFormContext(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:a}=t;return{id:a,name:e.name,formItemId:`${a}-form-item`,formDescriptionId:`${a}-form-item-description`,formMessageId:`${a}-form-item-message`,...s}},Dc=k.createContext({}),Lc=k.forwardRef(({className:t,...n},r)=>{const s=k.useId();return e.jsx(Dc.Provider,{value:{id:s},children:e.jsx("div",{ref:r,className:T("space-y-2",t),...n})})});Lc.displayName="FormItem";const $c=k.forwardRef(({className:t,...n},r)=>{const{error:s,formItemId:a}=Wc();return e.jsx(Uc,{ref:r,className:T(s&&"text-destructive",t),htmlFor:a,...n})});$c.displayName="FormLabel";const Mc=k.forwardRef(({...t},n)=>{const{error:r,formItemId:s,formDescriptionId:a,formMessageId:o}=Wc();return e.jsx(i.Slot,{ref:n,id:s,"aria-describedby":r?`${a} ${o}`:`${a}`,"aria-invalid":!!r,...t})});Mc.displayName="FormControl";const qc=k.forwardRef(({className:t,...n},r)=>{const{formDescriptionId:s}=Wc();return e.jsx("p",{ref:r,id:s,className:T("text-sm text-muted-foreground",t),...n})});qc.displayName="FormDescription";const Bc=k.forwardRef(({className:t,children:n,...r},s)=>{const{error:a,formMessageId:i}=Wc(),o=a?String(a?.message):n;return o?e.jsx("p",{ref:s,id:i,className:T("text-sm font-medium text-destructive",t),...r,children:o}):null});Bc.displayName="FormMessage";const Vc=k.forwardRef(({className:t,...n},r)=>e.jsx(N.Root,{className:T("grid gap-2",t),...n,ref:r}));Vc.displayName=N.Root.displayName;const zc=k.forwardRef(({className:t,...n},r)=>e.jsx(N.Item,{ref:r,className:T("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"})})}));zc.displayName=N.Item.displayName;const Gc=k.forwardRef(({className:t,children:n,...r},s)=>e.jsxs(A.Root,{ref:s,className:T("relative overflow-hidden",t),...r,children:[e.jsx(A.Viewport,{className:"h-full w-full rounded-[inherit]",children:n}),e.jsx(Jc,{}),e.jsx(A.Corner,{})]}));Gc.displayName=A.Root.displayName;const Jc=k.forwardRef(({className:t,orientation:n="vertical",...r},s)=>e.jsx(A.ScrollAreaScrollbar,{ref:s,orientation:n,className:T("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(A.ScrollAreaThumb,{className:T("relative rounded-full bg-border","vertical"===n&&"flex-1")})}));function Yc(){const e=Ba();return t.useMemo(()=>new Ue(e),[e.serverUrl,e.version])}Jc.displayName=A.ScrollAreaScrollbar.displayName;const Hc={tooLarge:"uploads.errorTooLarge",invalid:"uploads.errorInvalid",disabled:"uploads.errorDisabled",userLimit:"uploads.errorUserLimit",unavailable:"uploads.errorUnavailable",failed:"uploads.errorFailed"};function Kc(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 Qc=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑💻","👨💻","👩💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨💼","👩💼","👨🏫","👩🏫","👨🔬","👩🔬","👨🎨","👩🎨","👨🔧","👩🔧","👨🚀","👩🚀","👨⚖️","👩⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️🌈","🎟️","🎫"],Zc={step:"details",request:null,profile:null,error:null,retryAfter:0,resent:!1};function Xc(e){if(de(e))return{message:"",unreachable:!0};const{status:t,code:n}=e??{};return{message:e instanceof Error&&e.message?e.message:"",..."number"==typeof t?{status:t}:{},..."string"==typeof n?{code:n}:{}}}function el(e){const t=e?.retryAfter;return"number"==typeof t&&t>0?t:0}async function tl(e,t,n){const r=n??t.request;if(!r)return t;try{const{retryAfter:s}=await e.requestGuestUpgrade(r);return{...t,step:"code",request:r,error:null,retryAfter:s,resent:!n}}catch(e){return{...t,error:Xc(e),retryAfter:el(e),resent:!1}}}function nl(){const[e,n]=t.useState(0),[r,s]=t.useState(()=>Date.now());t.useEffect(()=>{if(e<=Date.now())return;s(Date.now());const t=setInterval(()=>{const n=Date.now();s(n),n>=e&&clearInterval(t)},1e3);return()=>clearInterval(t)},[e]);const a=t.useCallback(e=>{const t=Date.now();s(t),n(t+1e3*e)},[]),i=t.useCallback(()=>n(0),[]);return{waitSeconds:Math.max(0,Math.ceil((e-r)/1e3)),wait:a,clear:i}}function rl(){const{api:e}=Ja(),{t:n}=ss(),r=pr(),s=!0===Di().session?.user.isAnonymous,{waitSeconds:a,wait:i,clear:o}=nl(),[c,l]=t.useState(Zc),[d,u]=t.useState(null),p=t.useRef(c);p.current=c;const h=t.useCallback((e,t)=>{const r=e.error&&!e.error.message?{...e,error:{...e.error,message:n(e.error.unreachable?"errors.unreachable":"settings.common.error")}}:e;return l(r),r.retryAfter>0&&i(r.retryAfter),r.error&&q(Object.assign(new Error(r.error.message),r.error),{component:"useGuestUpgrade",action:t}),!r.error},[i,n]),m=t.useCallback(async t=>{u("send");try{const n=await tl(e,{...p.current,error:null},t);return h(n,"requestGuestUpgrade")}finally{u(null)}},[e,h]),f=t.useCallback(async()=>{u("resend");try{const t=await tl(e,{...p.current,error:null});return h(t,"requestGuestUpgrade")}finally{u(null)}},[e,h]),g=t.useCallback(async t=>{u("confirm");try{const n=await async function(e,t,n){try{const r=await e.confirmGuestUpgrade(n);return{...t,step:"done",profile:r,error:null,retryAfter:0,resent:!1}}catch(e){return{...t,error:Xc(e),resent:!1}}}(e,{...p.current,error:null},t);if("done"===n.step){o();const e=r.getState().session;e&&r.dispatch(er.setSession(function(e,t,n){if(t)try{const n=Fi({...t,isAnonymous:!1},e.user.org,e.user.clientId);return{...e,user:n}}catch{}const r=n?.name?.trim();return{...e,user:{...e.user,isAnonymous:!1,...n?{email:n.email.trim(),emailVerified:!0}:{},...r?{name:r}:{}}}}(e,n.profile,n.request)))}return h(n,"confirmGuestUpgrade")}finally{u(null)}},[e,h,o,r]),y=t.useCallback(()=>{o(),l(Zc)},[o]);return t.useMemo(()=>({isGuest:s,step:c.step,email:c.request?.email.trim()??null,profile:c.profile,pending:d,error:c.error,waitSeconds:a,resent:c.resent,start:m,resend:f,confirm:g,reset:y}),[s,c,d,a,m,f,g,y])}const sl=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,al=({busy:t,waitSeconds:n,onSubmit:r})=>{const{t:s}=ss(),a=h.z.object({email:h.z.string().trim().refine(e=>sl.test(e),{message:s("guest.emailInvalid")}),name:h.z.string().max(200),password:h.z.string().refine(e=>""===e||e.length>=8,{message:s("guest.passwordMinLength")})}),i=u.useForm({resolver:d.zodResolver(a),defaultValues:{email:"",name:"",password:""}});return e.jsx(Rc,{...i,children:e.jsxs("form",{noValidate:!0,onSubmit:i.handleSubmit(e=>r({email:e.email,...e.name.trim()?{name:e.name.trim()}:{},...e.password?{password:e.password}:{}})),className:"space-y-3 rounded-md border p-4",children:[e.jsx(Fc,{disabled:t,control:i.control,name:"email",render:({field:t})=>e.jsxs(Lc,{children:[e.jsx($c,{children:s("guest.emailLabel")}),e.jsx(Mc,{children:e.jsx(Nc,{type:"email",dir:"ltr",autoComplete:"email",autoCapitalize:"off",spellCheck:!1,...t})}),e.jsx(Bc,{})]})}),e.jsx(Fc,{disabled:t,control:i.control,name:"name",render:({field:t})=>e.jsxs(Lc,{children:[e.jsx($c,{children:s("guest.nameLabel")}),e.jsx(Mc,{children:e.jsx(Nc,{autoComplete:"name",maxLength:200,...t})}),e.jsx(Bc,{})]})}),e.jsx(Fc,{disabled:t,control:i.control,name:"password",render:({field:t})=>e.jsxs(Lc,{children:[e.jsx($c,{children:s("guest.passwordLabel")}),e.jsx(Mc,{children:e.jsx(Nc,{type:"password",autoComplete:"new-password",maxLength:256,...t})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s("guest.passwordHint")}),e.jsx(Bc,{})]})}),e.jsx("div",{className:"flex justify-end",children:e.jsx(Mi,{type:"submit",progress:t,disabled:t||n>0,children:n>0?s("guest.resendIn",{seconds:n}):s("guest.send")})})]})})},il=({email:t,confirming:n,resending:r,waitSeconds:s,onSubmit:a,onResend:i,onCancel:o})=>{const{t:c}=ss(),l=n||r,p=h.z.object({code:h.z.string().refine(e=>/^\d{6}$/.test((e=>e.replace(/\s+/g,""))(e)),{message:c("guest.codeInvalid")})}),m=u.useForm({resolver:d.zodResolver(p),defaultValues:{code:""}});return e.jsx(Rc,{...m,children:e.jsxs("form",{onSubmit:m.handleSubmit(e=>a(e.code)),className:"space-y-3 rounded-md border p-4",children:[e.jsx("p",{className:"break-words text-sm",children:c("guest.sentTo",{email:t})}),e.jsx(Fc,{disabled:l,control:m.control,name:"code",render:({field:t})=>e.jsxs(Lc,{children:[e.jsx($c,{children:c("guest.codeLabel")}),e.jsx(Mc,{children:e.jsx(Nc,{dir:"ltr",autoFocus:!0,autoComplete:"one-time-code",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,inputMode:"numeric",maxLength:7,className:"font-mono sm:max-w-xs",...t})}),e.jsx(Bc,{})]})}),e.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(Mi,{type:"button",variant:"outline",progress:r,disabled:l||s>0,onClick:i,children:s>0?c("guest.resendIn",{seconds:s}):c("guest.resend")}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx(Mi,{type:"button",variant:"ghost",disabled:l,onClick:o,children:c("settings.common.cancel")}),e.jsx(Mi,{type:"submit",progress:n,disabled:l,children:c("guest.confirm")})]})]})]})})};const ol=k.forwardRef(({className:t,...n},r)=>e.jsx(I.Root,{ref:r,className:T("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...n}));ol.displayName=I.Root.displayName;const cl=k.forwardRef(({className:t,...n},r)=>e.jsx(I.Image,{ref:r,className:T("aspect-square h-full w-full",t),...n}));cl.displayName=I.Image.displayName;const ll=k.forwardRef(({className:t,...n},r)=>e.jsx(I.Fallback,{ref:r,className:T("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...n}));function dl(e){return e?.workspace}function ul(e){return!1!==dl(e)?.canInviteMembers}ll.displayName=I.Fallback.displayName;const pl="text-foreground/70";const hl=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-Ch8X6WXy.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));const ml=({children:n})=>{const{currentWorkspace:r,switchToWorkspace:s,workspaces:a}=Ei(),[i,o]=t.useState(!1),[c,l]=t.useState(ki.Profile),d=t.useRef(!1);return t.useEffect(()=>{const e=Ci.getState();o(e.open),l(e.section);return Ci.subscribe(e=>{o(e.open),l(e.section)})},[]),t.useEffect(()=>{if(d.current)return;if(!r)return;const e=pt();if(!e)return;const t=function(e){if(e.screen&&Si.has(e.screen))return e.screen;switch(e.action){case ot.Checkout:case ot.Billing:case ot.SelectPlan:return ki.Subscription;case ot.CreditPurchase:return ki.Credits;case ot.OpenConnectGuide:return ki.ConnectedAgents;default:return null}}(e);if(!t)return d.current=!0,void ht();const n=e.ws;if(n&&n!==r._id){const e=a.find(e=>e._id===n);return e?void s(e).catch(e=>{q(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:n}}),d.current=!0,ht()}):(d.current=!0,void ht())}d.current=!0,Ci.openWorkspaceSettings(t,e),ht()},[r,a,s]),e.jsxs(e.Fragment,{children:[n,e.jsx(Go,{}),r&&i&&e.jsx(Xn,{fallback:null,children:e.jsx(t.Suspense,{fallback:null,children:e.jsx(hl,{workspace:r,open:i,onOpenChange:e=>{e||Ci.closeSettings()},section:c,onSectionChange:e=>{Ci.setSection(e)},showTrigger:!1})})})]})},fl=(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).`)};function gl(){const{impersonationBanner:t}=gi();return!1===t?null:e.jsx(qi,{})}const yl=t.memo(({serverUrl:n,version:r,orgId:s,region:a,auth:i,locale:o,defaultPermissions:c,getCheckoutStripeParams:l,loadingComponent:d,ui:u,mcp:p,tracking:h,children:m})=>{fl(n,r,s);const f=t.useMemo(()=>({serverUrl:n,version:r,orgId:s,...void 0!==a&&{region:a}}),[n,r,s,a]),g=t.useMemo(()=>i?.callbacks,[i?.callbacks?.handleAuthentication,i?.callbacks?.onSignOut,i?.callbacks?.getSession,i?.callbacks?.onSessionExpired,i?.callbacks?.handleEvent,i?.callbacks?.onWorkspaceChange]),y=i?.callbacks?.handleEvent;return t.useEffect(()=>(Ye.setCallbacks(y?{handleEvent:y}:null),()=>{Ye.setCallbacks(null)}),[y]),e.jsx(Qr,{locale:o,messageOverrides:u?.messages,children:e.jsx(Mr,{children:e.jsx(ai,{loadingComponent:d,children:e.jsx(uo,{callbacks:g,children:e.jsx(mo,{children:e.jsx(po,{config:f,auth:i,children:e.jsx(fi,{ui:u,children:e.jsx(Br,{getCheckoutStripeParams:l,children:e.jsx(ro,{appPermissions:c,children:e.jsx(Ai,{children:e.jsxs(eo,{mcp:p,children:[e.jsx(gl,{}),e.jsx(Po,{children:e.jsx(ei,{children:e.jsx(io,{children:e.jsx(Hi,{children:e.jsx(yo,{children:h&&i?.clientId?e.jsx(La,{serverUrl:n,orgId:s,clientId:i.clientId,...h,children:e.jsx(ml,{children:e.jsx(Eo,{children:m})})}):e.jsx(ml,{children:m})})})})})})]})})})})})})})})})})})});yl.displayName="SaaSOSProviderInner";const wl=({children:t,...n})=>e.jsx(Xn,{errorTitle:n.ui?.errorBoundary?.title,retryLabel:n.ui?.errorBoundary?.retryLabel,children:e.jsx(yl,{...n,children:t})});wl.displayName="SaaSOSProvider";const bl=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{status:s}=Li();return hn(s).isLoading?n??null:s!==exports.AuthStatus.authenticated?r??null:t},vl=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{status:s}=Li();return hn(s).isLoading?n??null:s!==exports.AuthStatus.unauthenticated?r??null:t};bl.displayName="WhenAuthenticated",vl.displayName="WhenUnauthenticated";function xl(){const{isAuthenticated:e}=Li(),{orgId:n}=Ba(),{settings:r}=Ga(),s=ul(r),{myInvitations:a,acceptInvitation:i,declineInvitation:o}=Ei(),{t:c}=ss(),l=t.useMemo(()=>xi(n??""),[n]),d=t.useSyncExternalStore(l.subscribe,l.getSnapshot,l.getSnapshot),[u,p]=t.useState(null),h=t.useRef(c);t.useEffect(()=>{h.current=c},[c]);const m=t.useCallback(e=>l.load(a,{maxAgeMs:e,onError:e=>(B(e,{component:"useMyInvitations",action:"list"}),V(e,"invitations.loadFailed",h.current))}),[l,a]),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 i(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,i]),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:d.rows,loading:d.loading,error:d.error,busy:u,refresh:f,accept:g,decline:y}),[d,u,f,g,y])}function kl({className:t,title:n,description:r,emptyLabel:a,hideWhenEmpty:i=!1,switchOnAccept:o=!0,onAccepted:c}){const{t:l,formattingLocale:d}=ss(),{formats:u}=gi(),{invitations:p,loading:h,error:m,busy:f,accept:g,decline:y}=xl(),{switchToWorkspace:w}=Ei(),b=void 0===n?l("invitations.title"):n,v=void 0===r?l("invitations.listDescription"):r,x=a??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:T("space-y-4",t),children:[e.jsx(hc,{title:b,description:v}),m&&e.jsx(Mo,{variant:"error",message:m}),h?e.jsxs("div",{className:"space-y-2",children:[e.jsx(mc,{className:"h-16 w-full"}),e.jsx(mc,{className:"h-16 w-full"})]}):0===p.length?e.jsx(pc,{icon:e.jsx(s.MailOpen,{className:"h-5 w-5 text-muted-foreground"}),description:x}):e.jsx("ul",{className:"space-y-2",children:p.map(t=>{const n=Gn(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:zn(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?Ho(s,d,u?.date??{dateStyle:"medium"}):"")})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx(Mi,{variant:"outline",size:"sm",disabled:r,onClick:()=>y(t._id).catch(()=>{}),children:l("invitations.decline")}),e.jsx(Mi,{size:"sm",progress:r,onClick:()=>(async e=>{let t;try{t=await g(e)}catch{return}t&&(c?.(t),o&&await w(t))})(t._id),children:l("invitations.accept")})]})]})},t._id);var s})})]})}):null}const Sl=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{invitations:s,loading:a}=xl();return a?n??null:0===s.length?r??null:t},Cl="https://www.buildbase.app",Il={"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}}},Nl={"built-with":"Built with BuildBase","powered-by":"Powered by BuildBase",mark:"BuildBase"};function Al(e,t){return`${Cl}/badge/v1/${e}.svg?theme=${t}`}function El(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 jl(e,{refCode:t,params:n}={}){const r=new URLSearchParams({utm_source:"badge",utm_medium:e}),s=El(t);s&&r.set("ref",s);for(const[e,t]of Object.entries(n??{}))e&&null!=t&&r.set(e,String(t));return`${Cl}/?${r.toString()}`}const Pl=e=>{const{children:t,fallback:n,roles:r}=e,{user:s}=Li();return r.includes(s?.role??"")?t:n||null},_l=e=>{const{children:t,fallback:n,roles:r}=e,{user:s}=Li(),{currentWorkspace:a}=Ei(),i=a?.users.find(e=>e._id===s?.id);return i&&r.includes(i?.role??"")?t:n||null};Pl.displayName="WhenRoles",_l.displayName="WhenWorkspaceRoles";const Tl=e=>{const{children:t,fallback:n,permission:r}=e,{can:s}=Jo();return s(r)?t:n??null};function Ul(){const e=Ba();return t.useMemo(()=>new ke(e),[e.serverUrl,e.version])}Tl.displayName="WhenPermission";const Rl=async(e,t)=>{const{io:n}=await import("socket.io-client");return n(e,t)};let Ol=null;function Fl(e){e.timer&&clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null;for(const t of e.listeners)try{t()}catch{}},500)}function Wl(e){e.closed=!0,e.timer&&clearTimeout(e.timer),e.socket?.disconnect(),e.socket=null}function Dl(e,t,n,r=Rl){const s=`${e}|${t}`;if(Ol&&Ol.key!==s&&(Wl(Ol),Ol=null),!Ol){const n={key:s,listeners:new Set,socket:null,closed:!1,timer:null};Ol=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",()=>Fl(n)),e.on("connect",()=>Fl(n)))}).catch(()=>{})}const a=Ol;a.listeners.add(n);let i=!1;return()=>{i||(i=!0,a.listeners.delete(n),0===a.listeners.size&&(Wl(a),Ol===a&&(Ol=null)))}}const Ll={items:[],counts:{unread:0,unseen:0},loading:!1,loadingMore:!1,error:null,hasNextPage:!1,page:0,fetchedAt:0},$l=e=>!e.readAt,Ml=e=>!e.readAt&&!e.seenAt;function ql(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 Bl{constructor(){this.snapshot=Ll,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:ql(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:ql(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 a=this.snapshot.counts;if(s.unread===a.unread&&s.unseen===a.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-($l(n)?1:0)),unseen:Math.max(0,r.unseen-(Ml(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=Ll;for(const e of this.listeners)e()}adjustCounts(e,t){const{unread:n,unseen:r}=this.snapshot.counts;return{unread:Math.max(0,n+($l(t)?1:0)-($l(e)?1:0)),unseen:Math.max(0,r+(Ml(t)?1:0)-(Ml(e)?1:0))}}}const Vl=new Map;const zl=()=>"undefined"==typeof document||"hidden"!==document.visibilityState;function Gl(e={}){const{isAuthenticated:n}=Li(),{orgId:r,serverUrl:s}=Ba(),{currentWorkspace:a}=Ei(),i=Ul(),{t:o}=ss(),c="current"===e.workspaceId?a?._id:e.workspaceId,l="current"===e.workspaceId&&!a?._id,d=Math.max(1,Math.min(e.pageSize??20,100)),u=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=Vl.get(n);return r||(r=new Bl,Vl.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)),[]),w=t.useCallback(e=>i.list({workspaceId:c,page:e,limit:d}),[i,c,d]),b=t.useCallback(()=>i.counts(c),[i,c]),v=t.useCallback(e=>m.load(w,b,{maxAgeMs:e,onError:y("list")}),[m,w,b,y]),x=t.useCallback(()=>v(0),[v]);t.useEffect(()=>{n?l||v(15e3).catch(()=>{}):m.reset()},[n,l,m,v]),t.useEffect(()=>{if(!n||l||u<=0)return;const e=()=>{zl()&&m.poll(w,b,y("poll"))},t=m.retainPoll(u,e),r=()=>{zl()&&e()};return"undefined"!=typeof document&&document.addEventListener("visibilitychange",r),()=>{t(),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",r)}},[n,l,u,m,w,b,y]),t.useEffect(()=>{if(!n||l||!p||!s)return;const e=ne();return e?Dl(s,e,()=>{v(0).catch(()=>{})}):void 0},[n,l,p,s,v]);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}),()=>i.markRead(e))},[k,i,m]),C=t.useCallback(e=>k("unread",()=>m.optimistic(e,{readAt:null,readVia:null}),()=>i.markUnread(e)),[k,i,m]),I=t.useCallback(e=>k("archive",()=>m.remove(e),async()=>{await i.archive(e)}),[k,i,m]),N=t.useCallback(()=>k("read-all",()=>m.markAll("readAt"),()=>i.markAllRead(c)),[k,i,m,c]),A=t.useCallback(async()=>{0!==m.getSnapshot().counts.unseen&&await k("seen",()=>m.markAll("seenAt"),()=>i.markSeen(c)).catch(()=>{})},[k,i,m,c]),E=t.useCallback(()=>m.loadMore(w,{onError:y("load-more")}),[m,w,y]),j=t.useMemo(()=>f.items.filter(e=>!e.readAt),[f.items]);return t.useMemo(()=>({notifications:f.items,unread:j,counts:f.counts,loading:f.loading||n&&l,loadingMore:f.loadingMore,hasMore:f.hasNextPage,error:f.error,refresh:x,loadMore:E,markRead:S,markUnread:C,archive:I,markAllRead:N,markSeen:A}),[f,n,l,j,x,E,S,C,I,N,A])}function Jl({className:n,title:r,description:a,showFilter:i=!0,onSelect:o,emptyLabel:c,markSeenOnView:l=!0,compact:d=!1,...u}){const{t:p,formattingLocale:h}=ss(),{notifications:m,unread:f,counts:g,loading:y,loadingMore:w,hasMore:b,error:v,loadMore:x,markRead:k,markUnread:S,archive:C,markAllRead:I,markSeen:N}=Gl(u),[A,E]=t.useState("all");t.useEffect(()=>{l&&!y&&g.unseen>0&&N()},[l,y,g.unseen,N]);const j=void 0===r?p("notifications.inbox.title"):r,P=void 0===a?p("notifications.inbox.description"):a,_="unread"===A?f:m,U=c??p("unread"===A?"notifications.inbox.emptyUnread":"notifications.inbox.empty"),R=e=>{k(e.id).catch(()=>{}),o?o(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:T(d?"space-y-3":"space-y-4",n),children:[e.jsx(hc,{title:j,description:P}),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":A===t,onClick:()=>E(t),className:T("rounded px-2.5 py-1 font-medium transition-colors",A===t?"bg-secondary text-secondary-foreground":"text-muted-foreground hover:text-foreground"),children:[p("all"===t?"notifications.inbox.filterAll":"notifications.inbox.filterUnread"),"unread"===t&&g.unread>0&&e.jsxs("span",{className:"ms-1 tabular-nums",children:["(",g.unread,")"]})]},t))}):e.jsx("span",{}),e.jsx(Mi,{variant:"ghost",size:"sm",disabled:0===g.unread,startIcon:e.jsx(s.Check,{}),onClick:()=>I().catch(()=>{}),children:p("notifications.inbox.markAllRead")})]}),v&&e.jsx(Mo,{variant:"error",message:v}),y?e.jsxs("div",{className:"space-y-2",children:[e.jsx(mc,{className:"h-14 w-full"}),e.jsx(mc,{className:"h-14 w-full"}),e.jsx(mc,{className:"h-14 w-full"})]}):0===_.length?e.jsx(pc,{icon:e.jsx(s.BellOff,{className:"h-5 w-5 text-muted-foreground"}),description:U}):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:T("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:T("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:Qo(t.createdAt,h)})]}),t.body&&e.jsx("p",{className:T("mt-0.5 text-sm text-muted-foreground",d?"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(s.Mail,{className:"h-3 w-3","aria-hidden":"true"}):e.jsx(s.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(Mi,{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(s.MailOpen,{className:"h-4 w-4"}):e.jsx(s.Mail,{className:"h-4 w-4"})}),e.jsx(Mi,{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(s.Archive,{className:"h-4 w-4"})})]})]},t.id)})}),b&&!y&&e.jsx(Mi,{variant:"outline",size:"sm",fullWidth:!0,progress:w,onClick:()=>x().catch(()=>{}),children:p("notifications.inbox.loadMore")})]})})}function Yl(){const e=t.useContext(jo);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 Hl=e=>{const{children:t,slug:n}=e,{currentWorkspace:r}=Ei(),s=r?.features?.[n];return s?t:null},Kl=e=>{const{children:t,slug:n}=e,{currentWorkspace:r}=Ei(),s=r?.features?.[n];return pi(!!r&&!s,`workspace:${n}`,"feature_gate_shown",{feature:n,scope:"workspace"}),s?null:t},Ql=e=>{const{children:t,slug:n}=e,{isFeatureEnabled:r}=Yl();return r(n)?t:null},Zl=e=>{const{children:t,slug:n}=e,{isFeatureEnabled:r,loading:s}=Yl(),a=r(n);return pi(!s&&!a,`user:${n}`,"feature_gate_shown",{feature:n,scope:"user"}),a?null:t};Hl.displayName="WhenWorkspaceFeatureEnabled",Kl.displayName="WhenWorkspaceFeatureDisabled",Ql.displayName="WhenUserFeatureEnabled",Zl.displayName="WhenUserFeatureDisabled";const Xl=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:s,loading:a}=ti();return a?n??null:s?.subscription?t:r??null},ed=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:s,loading:a}=ti();return a?n??null:s?.subscription?r??null:t},td=e=>{const{children:t,plans:n,loadingComponent:r,fallbackComponent:s}=e,{response:a,loading:i}=ti(),o=a?.subscription?a.plan??a.subscription?.plan:void 0,c=n.map(e=>e.trim().toLowerCase()),l=(o?.slug??"").toLowerCase(),d=!!o&&c.includes(l),{currentWorkspace:u}=Ei();return pi(!!u&&!i&&!d&&null!=s,c.join(","),"plan_gate_shown",{required_plans:c.join(","),current_plan:l||"none"}),i?r??null:d?t:s??null},nd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:s,loading:a}=ti();return a?n??null:"trialing"!==s?.subscription?.subscriptionStatus?r??null:t},rd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{response:s,loading:a}=ti();return a?n??null:s?.subscription?.subscriptionStatus===Lt.Trialing?r??null:t},sd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{behavior:s}=gi(),a=e.daysThreshold??s?.trialEndingDays??3,{response:i,loading:o}=ti();if(o)return n??null;const c=i?.subscription;if(!c||"trialing"!==c.subscriptionStatus)return r??null;const l=c.trialEnd||c.stripeCurrentPeriodEnd;if(!l)return r??null;const d=new Date(l);if(isNaN(d.getTime()))return r??null;return Math.max(0,Math.ceil((d.getTime()-Date.now())/864e5))>a?r??null:t};Xl.displayName="WhenSubscription",ed.displayName="WhenNoSubscription",td.displayName="WhenSubscriptionToPlans",nd.displayName="WhenTrialing",rd.displayName="WhenNotTrialing",sd.displayName="WhenTrialEnding";const ad=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:s}=e,{quotas:a,loading:i}=oo(),o=i?void 0:a?.[t];return pi(!!o&&o.available<=0&&null!=s,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),i?r??null:o?o.available<=0?s??null:n:s??null},id=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:s}=e,{quotas:a,loading:i}=oo(),o=i?void 0:a?.[t];return pi(!!o&&o.available<=0,t,"quota_limit_reached",{quota:t,included:o?.included,consumed:o?.consumed}),i?r??null:o?o.available>0?s??null:n:s??null},od=e=>{const{slug:t,children:n,loadingComponent:r,fallbackComponent:s}=e,{quotas:a,loading:i}=oo();if(i)return r??null;const o=a?.[t];return o&&o.hasOverage&&!1!==o.allowOverage?n:s??null},cd=e=>{const{slug:t,threshold:n,children:r,loadingComponent:s,fallbackComponent:a}=e,{quotas:i,loading:o}=oo(),c=o?void 0:i?.[t],l=c?c.included>0?c.consumed/c.included*100:c.consumed>0?100:0:0;return pi(!!c&&l>=n,`${t}@${n}`,"quota_threshold_reached",{quota:t,threshold:n,percent_used:Math.round(l)}),o?s??null:c?l<n?a??null:r:a??null};ad.displayName="WhenQuotaAvailable",id.displayName="WhenQuotaExhausted",od.displayName="WhenQuotaOverage",cd.displayName="WhenQuotaThreshold";const ld=({children:e})=>{const{currentWorkspace:t}=Ei(),n=t?._id,{balance:r,loading:s,error:a,refetch:i}=Ki(),{packages:o,loading:c}=Gi(n),{consumeCredits:l,loading:d,error:u}=Vi(n),{purchaseCredits:p,loading:h,error:m}=zi(n);return e({balance:r,loading:s,packages:o,packagesLoading:c,consume:l,consuming:d,purchase:async e=>{if(!n)throw new Error("No workspace selected");const{successUrl:t,cancelUrl:r}=ut(n),s=await p({creditPackageId:e._id,successUrl:t,cancelUrl:r});s.url&&wt(s.url)},purchasing:h,refetch:i,error:u||m||a})};ld.displayName="CreditActionsProvider";const dd=({children:e})=>{const{balance:t,loading:n,error:r,refetch:s}=Ki();return e({balance:t,loading:n,error:r,refetch:s})};dd.displayName="CreditBalance";const ud=e=>{const{min:t=1,children:n,loadingComponent:r,fallbackComponent:s}=e,{balance:a,loading:i}=Ki();return i?r??null:a?a.available<t?s??null:n:s??null},pd=e=>{const{children:t,loadingComponent:n,fallbackComponent:r}=e,{balance:s,loading:a}=Ki();return a?n??null:s?s.available>0?r??null:t:r??null},hd=e=>{const{threshold:t,children:n,loadingComponent:r,fallbackComponent:s}=e,{balance:a,loading:i}=Ki();return i?r??null:a?a.available>t?s??null:n:s??null};function md(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}ud.displayName="WhenCreditsAvailable",pd.displayName="WhenCreditsExhausted",hd.displayName="WhenCreditsLow";const fd=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 gd({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 yd({logo:t}){const{t:n}=ss();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 wd=k.forwardRef(({className:t,orientation:n="horizontal",decorative:r=!0,...s},a)=>e.jsx(E.Root,{ref:a,decorative:r,orientation:n,className:T("shrink-0 bg-border","horizontal"===n?"h-[1px] w-full":"h-full w-[1px]",t),...s}));wd.displayName=E.Root.displayName;const bd=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-Ch8X6WXy.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));function vd({message:t}){return e.jsxs(e.Fragment,{children:[e.jsx(s.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 xd(n){const{t:r}=ss(),{visible:a}=Yo(),i=a(e=>e.workspaceSwitcher?.memberCount),o=a(e=>e.workspaceSwitcher?.planBadge),{workspace:c,setCurrentWorkspace:l,setOpen:d,workspacesToUse:u,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:T("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":h}),children:[e.jsxs(ol,{className:"h-8 w-8 flex items-center justify-center",children:[e.jsx("div",{children:e.jsx(cl,{src:c.image&&c.image.trim()?c.image:void 0})}),e.jsx(ll,{children:(w=c.name,w.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(s.Users,{className:"h-3 w-3"}),e.jsx("span",{children:r("workspace.membersCount",{count:c.users?.length||0})})]}),o&&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(Mi,{size:"sm",disabled:null!==p||m,progress:m,onClick:()=>{n.switchToWorkspace(c).then(()=>d(!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(bd,{workspace:c,onClose:()=>{if(h){const e=u.findIndex(e=>e._id?.toString()===c._id?.toString());-1!==e&&l(u[e])}}})})]})]});var w}function kd(n){const{t:r,dir:a}=ss(),{switching:i}=Ei(),[o,c]=t.useState(!1),[l,p]=t.useState("emoji"),[m,f]=t.useState("🏢"),[g,y]=t.useState(!1),{createWorkspace:w}=Ei(),b=h.z.object({name:h.z.string().min(2,{message:r("workspace.workspaceNameMinLength")}),image:h.z.string().optional()}),v=u.useForm({resolver:d.zodResolver(b),defaultValues:{name:"",image:""}});return e.jsxs(_o,{open:o,onOpenChange:c,children:[e.jsx(To,{asChild:!0,children:e.jsxs(Mi,{className:"w-full rounded-none",disabled:i,children:[e.jsx(s.Plus,{className:"h-4 w-4 me-2"}),r("workspace.createNew")]})}),e.jsxs(Oo,{dir:a,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e.jsxs(Fo,{children:[e.jsx(Do,{children:r("workspace.createTitle")}),e.jsx(Lo,{children:r("workspace.createDescription")})]}),e.jsx(Rc,{...v,children:e.jsxs("form",{onSubmit:v.handleSubmit(async function(e){let t="";if("emoji"===l)t=Kc(m);else if("url"===l&&e.image)try{new URL(e.image),t=e.image}catch{return void v.setError("image",{message:r("workspace.invalidUrl")})}y(!0);try{await w(e.name,t),c(!1),v.reset(),f("🏢"),p("emoji"),n?.onCreated?.()}catch(t){q(t,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{y(!1)}}),children:[e.jsx(Fc,{control:v.control,name:"name",render:({field:t})=>e.jsxs(Lc,{children:[e.jsx($c,{children:r("workspace.workspaceName")}),e.jsx(Mc,{children:e.jsx(Nc,{placeholder:r("workspace.workspaceNamePlaceholder"),...t})}),e.jsx(Bc,{})]})}),e.jsxs("div",{className:"flex flex-col gap-y-2 my-2",children:[e.jsxs("div",{children:[e.jsx(Uc,{className:"text-sm font-medium",children:r("workspace.workspaceIcon")}),e.jsx(qc,{children:r("workspace.iconDescription")})]}),e.jsxs(Vc,{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(zc,{value:"emoji",id:"emoji"}),e.jsxs(Uc,{htmlFor:"emoji",className:"flex items-center gap-2",children:[e.jsx(s.Smile,{className:"h-4 w-4"}),r("workspace.chooseEmoji")]})]}),e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(zc,{value:"url",id:"url"}),e.jsxs(Uc,{htmlFor:"url",className:"flex items-center gap-2",children:[e.jsx(s.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(Gc,{className:"h-32 w-full rounded-md border",children:e.jsx("div",{className:"p-4 grid grid-cols-8 gap-2",children:Qc.map((t,n)=>e.jsx("button",{type:"button",onClick:()=>(e=>{f(e),v.setValue("image",Kc(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(Fc,{control:v.control,name:"image",render:({field:t})=>e.jsxs(Lc,{children:[e.jsx($c,{children:r("workspace.imageUrl")}),e.jsx(Mc,{children:e.jsx(Nc,{placeholder:r("workspace.imageUrlPlaceholder"),...t})}),e.jsx(qc,{children:r("workspace.imageUrlDescription")}),e.jsx(Bc,{})]})}),v.watch("image")&&v.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:v.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(Mi,{type:"button",variant:"outline",onClick:()=>{c(!1),v.reset(),f("🏢"),p("emoji")},disabled:g,children:r("settings.common.cancel")}),e.jsx(Mi,{type:"submit",disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(s.Loader2,{className:"me-2 h-4 w-4 animate-spin"}),r("workspace.creating")]}):r("workspace.createWorkspace")})]})]})})]})]})}exports.APP_PERMISSION_FALLBACK_GROUP=dn,exports.AlertDialog=tc,exports.AlertDialogAction=dc,exports.AlertDialogCancel=uc,exports.AlertDialogContent=ac,exports.AlertDialogDescription=lc,exports.AlertDialogFooter=oc,exports.AlertDialogHeader=ic,exports.AlertDialogTitle=cc,exports.AlertDialogTrigger=nc,exports.AuthApi=fe,exports.Avatar=ol,exports.AvatarFallback=ll,exports.AvatarImage=cl,exports.BBAction=ot,exports.BBScreen=lt,exports.BBStatus=ct,exports.BB_PARAM=it,exports.BaseApi=me,exports.BetaForm=({onSuccess:n,onError:r,className:s="w-full",fieldClassName:a="flex flex-col gap-1.5 w-full",autoFocus:i=!0,showSuccessMessage:o=!0,hideLogo:c=!1,hideTitles:l=!1})=>{const{t:p}=ss(),[h,m]=t.useState(!1),[f,g]=t.useState(!1),{submitBetaForm:y,isLoading:w,isSubmitting:b,error:v,config:x,success:k,message:S}=(()=>{const{t:e}=ss(),n=Ba(),[r,s]=t.useState(null),[a,i]=t.useState(!0),[o,c]=t.useState(!1),[l,d]=t.useState(null),[u,p]=t.useState(!1),[h,m]=t.useState(null);return t.useEffect(()=>{let t=!1;return(async()=>{i(!0),d(null);try{const e=new ye(n),r=await e.fetchConfig();t||s(r)}catch(n){t||d(n instanceof Error?n.message:e("beta.errorMessage"))}finally{t||i(!1)}})(),()=>{t=!0}},[n]),{isLoading:a,isSubmitting:o,config:r,error:l,success:u,message:h,submitBetaForm:t.useCallback(async t=>{if(!n){const t=e("errors.generic");return d(t),{success:!1,message:t}}try{c(!0),d(null),p(!1),m(null);const e=new ye(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 d(n),p(!1),m(n),{success:!1,message:n}}finally{c(!1)}},[n])}})();t.useEffect(()=>{k&&o&&(m(!0),g(!0)),v&&g(!0)},[k,o,v]);const C=u.useForm({resolver:d.zodResolver(fd),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});t.useEffect(()=>{i&&C.setFocus("name")},[i,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:w?e.jsxs("div",{className:T("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(mc,{className:"h-24 w-24 rounded-lg"}),e.jsx(mc,{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(mc,{className:"h-4 w-16"}),e.jsx(mc,{className:"h-10 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mc,{className:"h-4 w-16"}),e.jsx(mc,{className:"h-10 w-full"})]}),e.jsx(mc,{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(yd,{logo:x?.logo}),x?.name&&e.jsx("div",{children:x?.name})]}),e.jsx(u.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(gd,{screen:x?.screen?.register}),e.jsx(Fc,{control:C.control,name:"name",render:({field:t})=>e.jsxs(Lc,{className:a,children:[e.jsx($c,{children:p("beta.nameLabel")}),e.jsx(Mc,{children:e.jsx(Nc,{...t})}),e.jsx(qc,{}),e.jsx(Bc,{})]})}),e.jsx(Fc,{control:C.control,name:"email",render:({field:t})=>e.jsxs(Lc,{className:a,children:[e.jsx($c,{children:p("beta.emailLabel")}),e.jsx(Mc,{children:e.jsx(Nc,{...t})}),e.jsx(qc,{}),e.jsx(Bc,{})]})}),e.jsx(Mi,{type:"submit",disabled:!I,className:a,children:p(b?"beta.submittingText":"beta.submitText")})]}),f&&v&&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:"❗"}),v]}),e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx(Mi,{type:"button",onClick:()=>{g(!1),C.reset()},className:a,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(gd,{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=Dt,exports.BuildBaseBadge=({variant:t="built-with",theme:n="auto",size:r="md",alt:s,className:a,link:i=!0,refCode:o,params:c})=>{const l=Il[t][r],d=e.jsx("img",{src:Al(t,n),alt:s??Nl[t],width:l.width,height:l.height,loading:"lazy",decoding:"async"});return i?e.jsx("a",{href:jl(t,{refCode:o,params:c}),target:"_blank",rel:"noopener",className:T("inline-block",a),children:d}):e.jsx("span",{className:a,children:d})},exports.Button=Mi,exports.CURRENCY_DISPLAY=Ct,exports.CURRENCY_FLAG=It,exports.ConnectMcpGuide=vc,exports.ConnectedAgents=function({className:n,title:r,description:a,disconnectLabel:i,emptyLabel:o,showConnectGuide:c=!0}){const{t:l,formattingLocale:d}=ss(),{formats:u}=gi(),{agents:p,loading:h,error:m,revoking:f,revoke:g}=ec(),y=to(),w=c&&Boolean(y?.url),[b,v]=t.useState(!1),[x,k]=t.useState(null),[S,C]=t.useState(null),I=Zo(),N=t.useRef(!1);t.useEffect(()=>{if(N.current||!w)return;const e=Ci.getState().params;e?.action===ot.OpenConnectGuide&&(N.current=!0,Ci.clearParams(),v(!0))},[w]);const A=void 0===r?l("security.connectedAgentsTitle"):r,E=void 0===a?l("security.connectedAgentsDescription"):a,j=i??l("security.connectedAgentsDisconnect"),P=o??l("security.connectedAgentsEmpty"),_=l("security.mcpConnectAction"),U=e=>Ho(e,d,u?.date??{dateStyle:"medium"}),R=t=>w?e.jsxs(Mi,{size:"sm",onClick:()=>v(!0),"aria-label":_,className:"shrink-0 gap-1.5",children:[e.jsx(s.Plus,{className:"h-4 w-4","aria-hidden":"true"}),e.jsx("span",{className:t?"hidden sm:inline":void 0,children:_})]}):null;return e.jsxs("div",{className:T("space-y-4",n),children:[e.jsx(hc,{title:A,description:E,actions:!h&&p.length>0?R(!0):void 0}),h&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mc,{className:"h-20 rounded-md"},t))}),m&&!h&&e.jsx("p",{role:"alert",className:"text-destructive text-sm",children:m}),S&&e.jsx(Mo,{variant:"success",message:l("security.connectedAgentsDisconnected",{name:S})}),!h&&!m&&0===p.length&&e.jsx(pc,{icon:e.jsx(s.Bot,{className:"h-5 w-5 text-muted-foreground"}),description:P,action:R(!1)??void 0}),!h&&p.length>0&&e.jsx("ul",{className:"space-y-3",children:p.map(t=>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"),": ",U(t.lastGrantedAt)]})]}),e.jsx(Mi,{variant:"outline",size:"sm",progress:f===t.clientId,disabled:null!==f,onClick:()=>k(t),className:"shrink-0",children:j})]},t.clientId))}),e.jsx(tc,{open:null!==x,onOpenChange:e=>{e||k(null)},children:e.jsxs(ac,{children:[e.jsxs(ic,{children:[e.jsx(cc,{children:l("security.connectedAgentsConfirmTitle",{name:x?.title??""})}),e.jsx(lc,{children:l("security.connectedAgentsConfirmBody")})]}),e.jsxs(oc,{children:[e.jsx(uc,{children:l("security.connectedAgentsCancel")}),e.jsx(dc,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{if(!x)return;const{clientId:e,title:t}=x;k(null),C(null),await g(e)&&(C(t),I(()=>C(null)))},children:j})]})]})}),w&&e.jsx(_o,{open:b,onOpenChange:v,children:e.jsxs(Oo,{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(Fo,{className:"pe-8",children:[e.jsx(Do,{children:l("security.mcpGuideTitle")}),e.jsx(Lo,{children:l("security.mcpGuideDescription")})]}),e.jsx(vc,{title:null,description:null})]})})]})},exports.ConnectedAgentsApi=we,exports.CopyField=bc,exports.CreditActionsProvider=ld,exports.CreditBalance=dd,exports.CreditBalanceContextProvider=Hi,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:a}){const{packages:i,notes:o,loading:c,error:l,refetch:d}=Ji(),{isAuthenticated:u,signIn:p}=Li(),h=t.useCallback(e=>{if(u)Ci.openWorkspaceSettings(ki.Credits,{action:ot.CreditPurchase,packageId:e});else if(a){const t=dt({action:ot.CreditPurchase,screen:"credits",packageId:e},a);p(t)}else p()},[u,p,a]);return c?void 0!==r?e.jsx(e.Fragment,{children:r}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(mc,{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(mc,{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:i,notes:o,refetch:d,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=sn,exports.Devices=function({className:n,title:r,description:a,showRename:i,showSignOut:o,showRemove:c,renameLabel:l,signOutLabel:d,removeLabel:u,emptyLabel:p}){const{t:h,formattingLocale:m}=ss(),{formats:f}=gi(),{visible:g}=Yo(),{devices:y,loading:w,error:b,busyId:v,rename:x,signOut:k,forget:S}=kc(),[C,I]=t.useState(null),[N,A]=t.useState(""),[E,j]=t.useState(null),P=i??g(e=>e.settings?.devices?.rename),_=o??g(e=>e.settings?.devices?.signOut),U=c??g(e=>e.settings?.devices?.forget),R=P||_||U,O=void 0===r?h("security.devicesTitle"):r,F=void 0===a?h("security.devicesDescription"):a,W=l??h("security.deviceRename"),D=d??h("security.deviceSignOut"),L=u??h("security.deviceForget"),$=p??h("security.devicesEmpty"),M=e=>Ho(e,m,f?.date??{dateStyle:"medium"}),q=async e=>{const t=N.trim();t&&await x(e,t),I(null)};return e.jsxs("div",{className:T("space-y-4",n),children:[e.jsx(hc,{title:O,description:F}),w&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mc,{className:"h-24 rounded-md"},t))}),b&&!w&&e.jsx("p",{className:"text-destructive text-sm",children:b}),!w&&!b&&0===y.length&&e.jsx(pc,{icon:e.jsx(s.Monitor,{className:"h-5 w-5 text-muted-foreground"}),description:$}),!w&&y.length>0&&e.jsx("ul",{className:"space-y-3",children:y.map(t=>{const n=C===t.deviceId,r=v===t.deviceId,a=Ic(t.userAgent),i=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(t),o=Sc(t.userAgent)?s.Smartphone:s.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(o,{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(Nc,{value:N,onChange:e=>A(e.target.value),placeholder:h("security.deviceRenamePlaceholder"),className:"h-8 w-48",autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&q(t.deviceId),"Escape"===e.key&&I(null)}}),e.jsx(Mi,{size:"sm",variant:"ghost","aria-label":h("security.deviceSave"),progress:r,onClick:()=>q(t.deviceId),children:e.jsx(s.Check,{className:"h-4 w-4","aria-hidden":"true"})}),e.jsx(Mi,{size:"sm",variant:"ghost","aria-label":h("security.deviceCancel"),onClick:()=>I(null),children:e.jsx(s.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(s.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(s.Bell,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]}),a&&e.jsx("span",{className:"text-muted-foreground text-xs break-words",children:a}),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:M(t.lastActiveAt)}),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:[(P||_)&&e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[P&&e.jsx(Mi,{variant:"ghost",size:"sm",disabled:r,onClick:()=>(e=>{I(e.deviceId),A(e.name)})(t),children:W}),_&&t.activeSessions>0&&e.jsx(Mi,{variant:"outline",size:"sm",progress:r,onClick:()=>k(t.deviceId),children:D})]}),U&&e.jsx(Mi,{variant:"ghost",size:"sm",className:"text-destructive hover:bg-destructive/10 hover:text-destructive",disabled:r,onClick:()=>j(t),children:L})]})]},t.deviceId)})}),e.jsx(tc,{open:null!==E,onOpenChange:e=>{e||j(null)},children:e.jsxs(ac,{children:[e.jsxs(ic,{children:[e.jsx(cc,{children:h("security.deviceForgetConfirmTitle")}),e.jsx(lc,{children:h("security.deviceForgetConfirmBody")})]}),e.jsxs(oc,{children:[e.jsx(uc,{children:h("security.deviceCancel")}),e.jsx(dc,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:async()=>{if(!E)return;const{deviceId:e}=E;j(null),await S(e)},children:L})]})]})})]})},exports.DevicesApi=be,exports.Dialog=_o,exports.DialogContent=Oo,exports.DialogDescription=Lo,exports.DialogTitle=Do,exports.DialogTrigger=To,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EmptyState=pc,exports.EventEmitter=Je,exports.FALLBACK_WORKSPACE_ROLE=an,exports.Form=Rc,exports.FormControl=Mc,exports.FormDescription=qc,exports.FormField=Fc,exports.FormItem=Lc,exports.FormLabel=$c,exports.FormMessage=Bc,exports.FullScreenLoader=ri,exports.GuestUpgrade=function({className:n,title:r,description:s,onUpgraded:a}){const{t:i}=ss(),o=rl(),c=t.useRef(!1);if(t.useEffect(()=>{"done"!==o.step||c.current||(c.current=!0,a?.({profile:o.profile,email:o.profile?.email||o.email||""}))},[o.step,o.profile,o.email,a]),!o.isGuest&&"done"!==o.step)return null;const l=void 0===r?i("guest.title"):r,d=void 0===s?i("guest.description"):s;return e.jsx("div",{className:"saas-os-ui",style:{backgroundColor:"transparent"},children:e.jsxs("div",{className:T("space-y-4",n),children:[(l||d)&&e.jsx(hc,{title:l??void 0,description:d??void 0}),o.error&&e.jsx(Mo,{variant:"error",title:i("settings.common.error"),message:o.error.message}),"code"===o.step&&o.resent&&!o.error&&o.email&&e.jsx(Mo,{variant:"success",message:i("guest.resent",{email:o.email})}),"done"===o.step?e.jsx(Mo,{variant:"success",title:i("settings.common.success"),message:i("guest.done",{email:o.email??""})}):"code"===o.step&&o.email?e.jsx(il,{email:o.email,confirming:"confirm"===o.pending,resending:"resend"===o.pending,waitSeconds:o.waitSeconds,onSubmit:e=>{o.confirm(e)},onResend:()=>{o.resend()},onCancel:o.reset}):e.jsx(al,{busy:"send"===o.pending,waitSeconds:o.waitSeconds,onSubmit:e=>{o.start(e)}})]})})},exports.INVITATION_ERROR_CODE=Oe,exports.ImpersonationBanner=qi,exports.Input=Nc,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.Label=Uc,exports.LoadingState=function({label:t,className:n}){const{t:r}=ss();return e.jsxs("div",{role:"status","aria-live":"polite",className:T("flex items-center gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground",n),children:[e.jsx(s.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:a,maxCount:i=99,...o}){const{t:c}=ss(),{counts:l}=Gl(o),[d,u]=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(jc,{open:d,onOpenChange:u,children:[e.jsx(Pc,{asChild:!0,children:e.jsxs(Mi,{variant:"ghost",size:"icon","aria-label":m,title:m,className:T("relative",n),children:[e.jsx(s.Bell,{className:"h-5 w-5"}),p>0&&e.jsx("span",{"aria-hidden":"true",className:T("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(_c,{align:r,className:"w-[min(24rem,calc(100vw-2rem))] max-h-[min(32rem,calc(100vh-6rem))] overflow-y-auto p-3",children:d&&e.jsx(Jl,{description:null,...a,...o,compact:!0})})]})})},exports.NotificationInbox=Jl,exports.NotificationsApi=ke,exports.PLAN_CURRENCY_CODES=At,exports.PLAN_CURRENCY_OPTIONS=Et,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=kl,exports.Permission=nn,exports.Popover=jc,exports.PopoverContent=_c,exports.PopoverTrigger=Pc,exports.PortalContext=ho,exports.PricingPage=function({slug:n,children:r,loadingFallback:s,errorFallback:a,redirectBaseUrl:i}){const{items:o,plans:c,notes:l,loading:d,error:u,refetch:p}=Ya(n),{isAuthenticated:h,signIn:m}=Li(),{currentWorkspace:f,fetchWorkspaces:g}=Ei(),{emit:y}=hi();pi(!d&&!u&&c.length>0,n,"pricing_viewed",{pricing_slug:n,plan_count:c.length,authenticated:h});const w=t.useCallback((e,t,n)=>i?dt({action:"selectPlan",plan:e,interval:t,currency:n},i):null,[i]),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 Ci.openWorkspaceSettings(ki.Subscription,{action:"selectPlan",plan:e,interval:t,currency:r}),void(f||g());const s=w(e,t,r);m(s??void 0)},[h,m,w,y,n,f,g]);return d?void 0!==s?e.jsx(e.Fragment,{children:s}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(mc,{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(mc,{className:"h-64 rounded-lg"},t))})]}):u?a?e.jsx(e.Fragment,{children:a(u)}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:u}):e.jsx(e.Fragment,{children:r({loading:d,error:u,items:o,plans:c,notes:l,refetch:p,selectPlan:b})})},exports.PushApi=Se,exports.PushNotificationProvider=yo,exports.QuotaUsageContextProvider=io,exports.RadioGroup=Vc,exports.RadioGroupItem=zc,exports.SDKEvent=Ge,exports.SETTINGS_SCREENS=Si,exports.SIDEBAR_SECONDARY_TEXT=pl,exports.SUPPORTED_LOCALES=Gr,exports.SaaSOSProvider=wl,exports.ScrollArea=Gc,exports.SectionHeader=hc,exports.Sessions=function({className:t,title:n,description:r,showSignOut:a,signOutLabel:i,emptyLabel:o}){const{t:c,formattingLocale:l}=ss(),{formats:d}=gi(),{visible:u}=Yo(),{sessions:p,loading:h,error:m,revoking:f,revoke:g}=Ec(),y=a??u(e=>e.settings?.devices?.sessionSignOut),w=void 0===n?c("security.sessionsTitle"):n,b=void 0===r?c("security.sessionsDescription"):r,v=i??c("security.sessionSignOut"),x=o??c("security.sessionsEmpty"),k=e=>Ho(e,l,d?.date??{dateStyle:"medium"});return e.jsxs("div",{className:T("space-y-4",t),children:[e.jsx(hc,{title:w,description:b}),h&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(mc,{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(pc,{icon:e.jsx(s.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=Ic(t.userAgent),r=function(e){return[[e.ipInfo?.city,e.ipInfo?.country].filter(Boolean).join(", "),e.ip].filter(Boolean).join(" · ")}(t),a=t.device?.name||n||c("security.sessionsTitle"),i=Sc(t.userAgent)?s.Smartphone:s.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:a}),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&&a!==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(Mi,{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:v})]},t.id)})})]})},exports.SessionsApi=Ce,exports.SettingsApi=Ie,exports.SettingsScreen=ki,exports.SidebarNavItem=function({icon:t,label:n,active:r=!1,onClick:a,className:i}){return e.jsxs("button",{className:T("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:a,"aria-current":r?"true":void 0,children:[t,e.jsx("span",{className:"min-w-0 truncate",children:n}),e.jsx(s.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:T("px-2 flex flex-col gap-1",r),children:[e.jsx("div",{className:T("text-xs font-bold uppercase tracking-wide px-2 pb-1 shrink-0 whitespace-nowrap",pl),children:t}),n]})},exports.Skeleton=mc,exports.StatusBanner=Mo,exports.SubscriptionContextProvider=ei,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus=Lt,exports.UIConfigProvider=fi,exports.UPLOAD_ACCEPT="image/png,image/jpeg,image/gif,image/webp,image/svg+xml",exports.UPLOAD_MAX_BYTES=Ne,exports.UploadsApi=Ue,exports.UserApi=Re,exports.WALLET_LINK_STATEMENT=Un,exports.WalletFlowError=On,exports.WhenAuthenticated=bl,exports.WhenCreditsAvailable=ud,exports.WhenCreditsExhausted=pd,exports.WhenCreditsLow=hd,exports.WhenNoSubscription=ed,exports.WhenNotTrialing=rd,exports.WhenPendingInvitations=Sl,exports.WhenPermission=Tl,exports.WhenQuotaAvailable=ad,exports.WhenQuotaExhausted=id,exports.WhenQuotaOverage=od,exports.WhenQuotaThreshold=cd,exports.WhenRoles=Pl,exports.WhenSubscription=Xl,exports.WhenSubscriptionToPlans=td,exports.WhenTrialEnding=sd,exports.WhenTrialing=nd,exports.WhenUnauthenticated=vl,exports.WhenUserFeatureDisabled=Zl,exports.WhenUserFeatureEnabled=Ql,exports.WhenWorkspaceFeatureDisabled=Kl,exports.WhenWorkspaceFeatureEnabled=Hl,exports.WhenWorkspaceRoles=_l,exports.WorkspaceApi=Ve,exports.WorkspaceSwitcher=function(n){const{t:r,dir:a}=ss(),{isAuthenticated:i,user:o}=Li(),c=ze(Ba()),{workspaces:l,currentWorkspace:d,loading:u,refreshing:p,switchingToId:h,fetchWorkspaces:m,getFeatures:f,refreshWorkspaces:g,setCurrentWorkspace:y,switchToWorkspace:w}=Ei(),{settings:b,loading:v}=Ga(),{visible:x}=Yo(),[k,S]=t.useState(!1),[C,I]=t.useState(0),[N,A]=t.useState(""),E=u||p;t.useEffect(()=>{i&&c&&(0===l.length?(m(),f()):f())},[i,c]),t.useEffect(()=>{i&&c&&C>0&&g()},[C,i,c]);const j=l,P=j.filter(e=>e._id!==d?._id).filter(e=>e.name.toLowerCase().includes(N.toLowerCase())),_=(b?.workspace?.canCreateWorkspace??!0)&&x(e=>e.workspaceSwitcher?.createButton),T=(b?.workspace?.showSwitcher??!0)&&x(e=>e.workspaceSwitcher?.show),U=b?.workspace?.maxWorkspacesPerUser??0,R=j?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===o?.id?.toString()).length??0,O=!1!==_&&(0===U||R<U);t.useEffect(()=>{!T&&l.length>0&&!d&&w(l[0]).catch(e=>{q(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[T,l,d]);const{emit:F}=hi();return t.useEffect(()=>{k&&T&&F("workspace_switcher_opened",{workspace_count:l.length})},[k]),v&&!b?e.jsx(e.Fragment,{children:n.trigger?.(!0,d)}):!T&&d?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?.(E,d)}),e.jsx(t.Suspense,{fallback:null,children:e.jsx(bd,{workspace:d,open:k,onOpenChange:S,showTrigger:!1})})]}):e.jsxs(_o,{open:k,onOpenChange:S,children:[e.jsx(To,{children:n.trigger?.(E,d)}),e.jsxs(Oo,{dir:a,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e.jsxs(Fo,{dir:a,children:[e.jsxs(Do,{className:"flex items-center gap-2",children:[e.jsx(s.Building2,{className:"h-5 w-5"}),r("workspace.switchTitle")]}),e.jsx(Lo,{children:r("workspace.switchDescription")})]}),!o&&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")})}),o&&e.jsxs("div",{dir:a,className:"flex flex-col gap-4",children:[d&&e.jsx(xd,{workspace:d,isCurrentWorkspace:!0,switchToWorkspace:w,switchingToId:h,setCurrentWorkspace:y,setOpen:S,workspacesToUse:j}),e.jsx(wd,{}),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:P.length})}),e.jsx("div",{children:e.jsx(Mi,{progress:p,disabled:p,variant:"ghost",onClick:function(){i&&c&&I(e=>e+1)},startIcon:e.jsx(s.RefreshCcw,{}),children:r("settings.common.refreshAction",{loading:String(p)})})})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(Nc,{placeholder:r("workspace.searchPlaceholder"),value:N,onChange:e=>A(e.target.value),className:"ps-10"})]}),u?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(s.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===P.length?e.jsx("div",{className:"text-center py-8",children:N?e.jsx(vd,{message:r("workspace.noWorkspacesFound")}):e.jsx(Sl,{fallbackComponent:e.jsx(vd,{message:r("workspace.noWorkspacesAvailable")}),children:e.jsx(kl,{title:null,description:null,className:"text-start"})})}):e.jsx(Gc,{className:"h-64",dir:a,children:e.jsx("div",{dir:a,className:"flex flex-col gap-2 my-2.5",children:P.map(t=>{const n=t._id===d?._id;return e.jsx(xd,{workspace:t,isCurrentWorkspace:n,switchToWorkspace:w,switchingToId:h,setCurrentWorkspace:y,setOpen:S,workspacesToUse:j},t._id)})})})]}),O&&e.jsxs(e.Fragment,{children:[e.jsx(wd,{}),e.jsx(kd,{onCreated:()=>{m()}})]})]})]})]})},exports.actionableInvitations=Vn,exports.appPermissionCatalogue=un,exports.authActions=er,exports.buildWalletMessage=Rn,exports.calculateBillableSeats=zt,exports.calculateSeatOverageCents=Gt,exports.calculateTotalSubscriptionCents=function(e,t,n,r){const s=Mt(e,t,n);return null===s?null:void 0===r?s:s+(Gt(e,t,n,r)??0)},exports.cleanBBParams=ht,exports.clearAuthIntent=St,exports.clearPendingInvite=Zn,exports.cn=T,exports.coerceBadgeRef=El,exports.connectWallet=function(e,t){return"ethereum"===e?Dn(t):Ln(t)},exports.consumeAuthIntent=kt,exports.consumeReverified=function(e=Date.now()){try{const t=sessionStorage.getItem(fn);if(null===t)return!1;sessionStorage.removeItem(fn);const n=Number(t);return Number.isFinite(n)&&e-n>=0&&e-n<6e5}catch{return!1}},exports.createBBUrl=dt,exports.createCheckoutRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:dt({action:ot.Checkout,status:ct.Success,ws:e,screen:lt.Subscription},n),cancelUrl:dt({action:ot.Checkout,status:ct.Cancel,ws:e,screen:lt.Subscription},n)}},exports.createCreditPurchaseRedirectUrls=ut,exports.errorMessageFor=function(e,t,n="settings.common.error"){return de(e)?t("errors.unreachable"):e instanceof Error&&e.message?e.message:t(n)},exports.eventEmitter=Ye,exports.fillMcpTemplate=Zi,exports.formatCents=Ot,exports.formatDate=Ho,exports.formatDateTime=function(e,t="en-US"){return Ho(e,t,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})},exports.formatMinorAmountIntl=Rt,exports.formatOverageRate=function(e,t,n,r,s){if(null==e||e<0)return null;const a={...Ft,...r},i=null!=t&&t>=1?t:1,o=Nt(n),c=Ut(e,n);return 1===i?`${o}${c}/${a.unit}`:`${o}${c}/${i.toLocaleString(s)} ${a.units}`},exports.formatOverageRateWithLabel=function(e,t,n,r,s,a,i){if(null==e||e<0)return null;const o={...Ft,...a},c=null!=t&&t>=1?t:1,l=Nt(r),d=Ut(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${d}/${c.toLocaleString(i)} ${e}`:`${l}${d}/${n}`}return 1===c?`${l}${d}/${o.unit}`:`${l}${d}/${c.toLocaleString(i)} ${o.units}`},exports.formatQuotaIncludedOverage=function(e,t,n,r,s,a,i,o,c){const l={...Ft,...i};if(!1===o)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:i?.hardLimit??"Hard limit";const d=a??(n.endsWith("s")?n:`${n}s`),u=null!=s&&s>=2?`${s.toLocaleString(c)} ${d}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${Ot(t,r)}/${u}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${Ot(t,r)}/${u}`:"—"},exports.formatQuotaWithPrice=function(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,a={...Wt,...n.labels},i=n.currencySymbol??Nt(s??"");if(null==e)return"—";const{included:o,overage:c}=e,l=`${o} ${a.included}`;if(!1===e.allowOverage)return`${l} (${a.hardLimit})`;if(null==c)return l;const d=Tt(s),u=r&&d>0?c/10**d:c,p="number"==typeof u&&Number.isFinite(u)?0===d?u.toLocaleString("en-US"):u.toFixed(d):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${a.then} ${i}${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=Te,exports.getAvailableBillingIntervals=function(e,t){return[Dt.Monthly,Dt.Quarterly,Dt.Yearly].filter(n=>n===Dt.Monthly||e.some(e=>null!=Mt(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=Mt,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=Tt,exports.getCurrencyFlag=function(e){return e&&e.trim()?It[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=Nt,exports.getDisplayCurrency=function(e,t){const n=$t(e,t);return n?n.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=Vt,exports.getPricingVariant=$t,exports.getQuotaDisplayParts=function(e,t,n={}){if(null==e)return null;const{overageInCents:r=!0,currency:s,locale:a="en"}=n,{included:i,overage:o}=e;if(!(!1!==e.allowOverage))return{included:i,hasOverage:!1,allowOverage:!1,price:"",unit:""};if(null==o)return{included:i,hasOverage:!1,allowOverage:!0,price:"",unit:""};const c=Tt(s),l=r&&c>0?o/10**c:o,d=(s??"").trim().toUpperCase();let u;if(d&&"number"==typeof l&&Number.isFinite(l))try{u=new Intl.NumberFormat(a,{style:"currency",currency:d,minimumFractionDigits:c,maximumFractionDigits:c}).format(l)}catch{u=`${n.currencySymbol??Nt(s??"")}${l.toFixed(c)}`}else{u=`${n.currencySymbol??Nt(s??"")}${"number"==typeof l?l.toFixed(c):String(o)}`}return{included:i,hasOverage:!0,allowOverage:!0,price:u,unit:t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(a)} ${t}`:t||""}},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 a=s[r];if(!a)return null;const i=qt(e,t,n,r);return{included:a.included,...void 0!==a.unitSize&&{unitSize:a.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==s.allowOverage}},exports.getQuotaOverageCents=qt,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=Bt,exports.getStripePriceIdForInterval=function(e,t,n){const r=$t(e,t);if(!r?.stripePrices)return null;const s=n===Dt.Monthly?"monthlyPriceId":n===Dt.Yearly?"yearlyPriceId":"quarterlyPriceId",a=n===Dt.Monthly?"monthly":n===Dt.Yearly?"yearly":void 0;return r.stripePrices[s]??(a?r.stripePrices[a]:void 0)??null},exports.getSvgImage=Kc,exports.handleError=q,exports.hasPermission=function(e,t){const n=cn(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)},exports.invalidateCreditBalance=Xe,exports.invalidateQuotaUsage=nt,exports.invalidateSubscription=at,exports.inviterNameOf=Gn,exports.isE164=Pi,exports.isGuestProfile=_i,exports.isImpersonationSignInLocked=function(e){return e instanceof Error&&"impersonation_sign_in_locked"===e.code},exports.isInvitationActionable=Bn,exports.isInvitationError=$e,exports.isInvitationLapsed=function(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!Bn(e,t)},exports.isReadOnlySession=function(e){return e instanceof Error&&"read_only_session"===e.code},exports.isReauthRequired=function(e){return e instanceof Error&&"reauth_required"===e.code},exports.isValidUsername=function(e){return null!==vn(e)},exports.isWalletProvider=function(e){return $n.includes(e)},exports.isWorkspaceOwner=en,exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===Tt(e)},exports.mcpServerKey=Xi,exports.mergeUIConfig=function(e,t){return t?yi(e,t):e},exports.minorAmountToDisplay=Ut,exports.normaliseUsername=vn,exports.parkPendingInvite=Kn,exports.pickDefaultCurrency=function(e,t){for(const n of[...t,"usd"]){const t=n?.trim().toLowerCase();if(t&&e.includes(t))return t}return e[0]??""},exports.pickDefaultRole=function(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(an)?an:e.find(e=>"admin"!==e)??""},exports.preflightUpload=_e,exports.readBBParams=pt,exports.readChangeEmail=Ri,exports.readPendingInvite=Qn,exports.readPhone=Oi,exports.resendCooldownSeconds=function(e,t=new Date){const n=Mn(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0},exports.resolveMaxUsers=Jt,exports.resolvePermissions=cn,exports.resolveRolePermissions=ln,exports.safeRedirect=wt,exports.saveAuthIntent=xt,exports.shouldLoadWorkspaceInvitations=function(e){return e.canView},exports.sortInvitations=qn,exports.toChecksumAddress=jn,exports.toMajorUnits=Ws,exports.uploadFailureOf=je,exports.uploadPolicyOf=Pe,exports.useAllQuotaUsage=Za,exports.useAuthSelector=ur,exports.useAuthStore=pr,exports.useBillingPortal=e=>{const{t:n}=ss(),{api:r}=Ja(),[s,a]=t.useState(!1),[i,o]=t.useState(null);return{openBillingPortal:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!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{a(!1)}},[e,r]),loading:s,error:i}},exports.useCancelSubscription=e=>{const{t:n}=ss(),{api:r}=Ja(),[s,a]=t.useState(!1),[i,o]=t.useState(null);return{cancelSubscription:t.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const t=await r.cancelSubscriptionAtPeriodEnd(e);return at(),t}catch(t){const r=V(t,"errors.cancelSubscription",n);throw o(r),q(t,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),t}finally{a(!1)}},[r,e]),loading:s,error:i}},exports.useConnectedAgents=ec,exports.useConnectedAgentsApi=Xo,exports.useConsumeCredits=Vi,exports.useCreateCheckoutSession=e=>{const{t:n}=ss(),{api:r}=Ja(),{getCheckoutStripeParams:s}=t.useContext(qr),{track:a,consent:i,getProperties:o}=Wa(),c=Da(),[l,d]=t.useState(!1),[u,p]=t.useState(null);return{createCheckoutSession:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");d(!0),p(null);const l=oa();try{const n=s?await s(t):void 0,d=c?ua(l,i.effective,o(),da({...t.stripeOptions?.metadata,...n?.metadata},{...t.stripeOptions?.subscriptionMetadata,...n?.subscriptionMetadata})):{},u=Object.keys(d).length>0||n?{...t,stripeOptions:{...t.stripeOptions,...n,metadata:{...d,...t.stripeOptions?.metadata,...n?.metadata},subscriptionMetadata:{...d,...t.stripeOptions?.subscriptionMetadata,...n?.subscriptionMetadata}}}:t,p=await r.createCheckoutSession(e,u),h="checkout"!==p.type&&p.type?void 0:p,m=h?.currency??t.currency,f=Ws(h?.amountTotal,m);return h&&c&&Ns({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()}),a("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&&(at(),nt()),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{d(!1)}},[r,e,s,a,n,i.effective,c]),loading:l,error:u}},exports.useCreditBalance=Bi,exports.useCreditBalanceContext=Ki,exports.useCreditPackages=Gi,exports.useCreditTransactions=(e,n)=>{const{t:r}=ss(),{api:s}=Ja(),[a,i]=t.useState([]),[o,c]=t.useState(0),[l,d]=t.useState(0),[u,p]=t.useState(1),[h,m]=t.useState(!1),[f,g]=t.useState(!1),[y,w]=t.useState(!1),[b,v]=t.useState(null),{begin:x,settle:k}=os(),S=n?.type,C=n?.page,I=n?.limit,N=t.useCallback(async()=>{if(!e)return x(),i([]),c(0),d(0),p(1),m(!1),g(!1),void w(!1);const t=x();w(!0),v(null);try{const n=await s.getCreditTransactions(e,{type:S,page:C,limit:I});if(t.signal.aborted)return;i(n.docs||[]),c(n.totalDocs||0),d(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);v(s),q(n,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{k(t)&&w(!1)}},[s,e,S,C,I,x,k]);return t.useEffect(()=>{N()},[N]),{transactions:a,totalDocs:o,totalPages:l,page:u,hasNextPage:h,hasPrevPage:f,loading:y,error:b,refetch:N}},exports.useDevices=kc,exports.useDevicesApi=xc,exports.useExpiringCredits=(e,n)=>{const{t:r}=ss(),{api:s}=Ja(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,d]=t.useState(null),{begin:u,settle:p}=os(),h=t.useCallback(async()=>{if(!e)return u(),i(null),void c(!1);const t=u();c(!0),d(null);try{const r=await s.getExpiringCredits(e,n);if(t.signal.aborted)return;i(r)}catch(s){if(t.signal.aborted)return;const a=V(s,"errors.fetchExpiringCredits",r);d(a),q(s,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:n}})}finally{p(t)&&c(!1)}},[s,e,n,u,p]);return t.useEffect(()=>{h()},[h]),{expiringCredits:a?.expiringCredits??0,buckets:a?.buckets??[],days:a?.days??n??7,loading:o,error:l,refetch:h}},exports.useFullScreenLoader=ii,exports.useFunnel=hi,exports.useGateReport=pi,exports.useGuestUpgrade=rl,exports.useInvoice=(e,n)=>{const{t:r}=ss(),{api:s}=Ja(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,d]=t.useState(null),{begin:u,settle:p}=os(),h=t.useCallback(async()=>{if(!e||!n)return u(),i(null),void c(!1);const t=u();c(!0),d(null);try{const r=await s.getInvoice(e,n);if(t.signal.aborted)return;i(r.invoice)}catch(s){if(t.signal.aborted)return;const a=V(s,"errors.fetchInvoice",r);d(a),q(s,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:n}})}finally{p(t)&&c(!1)}},[s,e,n,u,p]);return t.useEffect(()=>{h()},[h]),{invoice:a,loading:o,error:l,refetch:h}},exports.useInvoices=(e,n=10,r)=>{const{t:s}=ss(),{api:a}=Ja(),[i,o]=t.useState([]),[c,l]=t.useState(!1),[d,u]=t.useState(!1),[p,h]=t.useState(null),{begin:m,settle:f}=os(),g=t.useCallback(async()=>{if(!e)return m(),o([]),l(!1),void u(!1);const t=m();u(!0),h(null);try{const s=await a.listInvoices(e,n,r);if(t.signal.aborted)return;o(s.invoices||[]),l(s.has_more||!1)}catch(a){if(t.signal.aborted)return;const i=V(a,"errors.fetchInvoices",s);h(i),q(a,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:n,startingAfter:r}})}finally{f(t)&&u(!1)}},[a,e,n,r,m,f]);return t.useEffect(()=>{g()},[g]),{invoices:i,hasMore:c,loading:d,error:p,refetch:g}},exports.useMcpConnection=to,exports.useMyInvitations=xl,exports.useNotifications=Gl,exports.useNotificationsApi=Ul,exports.usePermissionConfig=so,exports.usePermissions=Jo,exports.usePlanGroup=Ka,exports.usePlanGroupVersions=e=>{const{t:n}=ss(),{api:r}=Ja(),[s,a]=t.useState(null),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:d,settle:u}=os(),p=t.useCallback(async()=>{if(!e)return d(),a(null),void o(!1);const t=d();o(!0),l(null);try{const n=await r.getPlanGroupVersions(e);if(t.signal.aborted)return;a(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{u(t)&&o(!1)}},[r,e,d,u]);return t.useEffect(()=>{p()},[p]),{versions:s,loading:i,error:c,refetch:p}},exports.usePublicCreditPackages=Ji,exports.usePublicPlanGroupVersion=e=>{const{t:n}=ss(),{api:r}=Ja(),[s,a]=t.useState(null),[i,o]=t.useState(!1),[c,l]=t.useState(null),{begin:d,settle:u}=os(),p=t.useCallback(async()=>{if(!e)return d(),a(null),void o(!1);const t=d();o(!0),l(null);try{const n=await r.getPlanGroupVersion(e);if(t.signal.aborted)return;a(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{u(t)&&o(!1)}},[r,e,d,u]);return t.useEffect(()=>{p()},[p]),{planGroupVersion:s,loading:i,error:c,refetch:p}},exports.usePublicPlans=Ya,exports.usePurchaseCredits=zi,exports.usePushNotifications=function(){const e=t.useContext(fo);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e},exports.useQuotaUsageContext=oo,exports.useQuotaUsageStatus=(e,n)=>{const{t:r}=ss(),{api:s}=Ja(),[a,i]=t.useState(null),[o,c]=t.useState(!1),[l,d]=t.useState(null),{begin:u,settle:p}=os(),h=t.useCallback(async()=>{if(!e||!n)return u(),i(null),void c(!1);const t=u();c(!0),d(null);try{const r=await s.getQuotaUsageStatus(e,n);if(t.signal.aborted)return;i(r)}catch(s){if(t.signal.aborted)return;const a=V(s,"errors.fetchQuotaUsage",r);d(a),q(s,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:n}})}finally{p(t)&&c(!1)}},[s,e,n,u,p]);return t.useEffect(()=>{h()},[h]),{status:a,loading:o,error:l,refetch:h}},exports.useRecordUsage=e=>{const{t:n}=ss(),{api:r}=Ja(),[s,a]=t.useState(!1),[i,o]=t.useState(null);return{recordUsage:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const n=await r.recordUsage(e,t);return nt(),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{a(!1)}},[r,e]),loading:s,error:i}},exports.useResendCooldown=nl,exports.useResumeSubscription=e=>{const{t:n}=ss(),{api:r}=Ja(),[s,a]=t.useState(!1),[i,o]=t.useState(null);return{resumeSubscription:t.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");a(!0),o(null);try{const t=await r.resumeSubscription(e);return at(),t}catch(t){const r=V(t,"errors.resumeSubscription",n);throw o(r),q(t,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),t}finally{a(!1)}},[r,e]),loading:s,error:i}},exports.useSaaSAuth=Li,exports.useSaaSOs=Ba,exports.useSaaSSettings=Ga,exports.useSaaSWorkspaces=Ei,exports.useSeatStatus=function(e,n){const{response:r}=ti(),{settings:s}=Ga(),a=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,i=r?.subscription,o=e.billingCurrency||"usd",c=Jt({planVersion:s,currency:o,settingsMaxUsers:a}),{maxUsers:l,hasSeatPricing:d,includedSeats:u}=c,p=d?Math.max(0,t-u):0,h=l>0?Math.max(0,l-t):1/0,m=l>0&&t>=l,f=l>0&&t>=.8*l&&!m,g=d&&s?Vt(s,o,i?.billingInterval??"monthly"):null,y=Yt({memberCount:t,maxUsersConfig:c});return{hasSeatPricing:d,memberCount:t,includedSeats:u,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,a,n?.pendingInvitations])},exports.useSessions=Ec,exports.useSessionsApi=Ac,exports.useSubscription=Ha,exports.useSubscriptionContext=ti,exports.useSubscriptionManagement=(e,n)=>{const r=Ha(e),s=Ka(e,n),a=Qa(e),i=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||a.loading,error:r.error||s.error||a.error,updateSubscription:a.updateSubscription,refetch:i}},exports.useTransientStatus=Zo,exports.useTranslation=ss,exports.useTrialStatus=function(){const{response:e}=ti();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=md(t.trialEnd)??md(t.stripeCurrentPeriodEnd),r=md(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=gi,exports.useUIVisibility=Yo,exports.useUpdateSubscription=Qa,exports.useUpload=function(e){const n=Yc(),{settings:r}=Ga(),{t:s,formattingLocale:a}=ss(),[i,o]=t.useState(!1),[c,l]=t.useState(null),d=t.useRef(null),u=t.useRef(!0),p=t.useMemo(()=>Pe(r),[r]),h=t.useMemo(()=>Te(p.maxFileBytes,a),[p.maxFileBytes,a]);t.useEffect(()=>(u.current=!0,()=>{u.current=!1,d.current?.abort()}),[]);const m=t.useCallback(()=>d.current?.abort(),[]),f=t.useCallback(async t=>{d.current?.abort();const r=_e(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;d.current=s,o(!0),l(null);try{return await n.upload(t,{purpose:e,signal:s.signal})}catch(e){throw!W(e)&&u.current&&l(je(e)),B(e,{component:"useUpload",action:"upload"}),e}finally{d.current===s&&(d.current=null,u.current&&o(!1))}},[n,e,p]),g=c?s(Hc[c],{max:h}):null;return t.useMemo(()=>({upload:f,cancel:m,loading:i,error:g,failure:c,enabled:p.enabled,maxBytes:p.maxFileBytes,maxLabel:h}),[f,m,i,g,c,p,h])},exports.useUploadsApi=Yc,exports.useUsageLogs=(e,n,r)=>{const{t:s}=ss(),{api:a}=Ja(),[i,o]=t.useState([]),[c,l]=t.useState(0),[d,u]=t.useState(0),[p,h]=t.useState(1),[m,f]=t.useState(!1),[g,y]=t.useState(!1),[w,b]=t.useState(!1),[v,x]=t.useState(null),{begin:k,settle:S}=os(),C=r?.from,I=r?.to,N=r?.source,A=r?.page,E=r?.limit,j=t.useCallback(async()=>{if(!e)return k(),o([]),l(0),u(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},...A&&{page:A},...E&&{limit:E}},s=await a.getUsageLogs(e,r);if(t.signal.aborted)return;o(s.docs||[]),l(s.totalDocs||0),u(s.totalPages||0),h(s.page||1),f(s.hasNextPage||!1),y(s.hasPrevPage||!1)}catch(r){if(t.signal.aborted)return;const a=V(r,"errors.fetchUsageLogs",s);x(a),q(r,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:n}})}finally{S(t)&&b(!1)}},[a,e,n,C,I,N,A,E,k,S]);return t.useEffect(()=>{j()},[j]),{logs:i,totalDocs:c,totalPages:d,page:p,hasNextPage:m,hasPrevPage:g,loading:w,error:v,refetch:j}},exports.useUserAttributes=function(){const e=t.useContext(jo);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=Yl,exports.useWorkspaceApiWithOs=Ja,exports.useWorkspaceInvitations=function(e){const{listInvitations:n,resendInvitation:r,revokeInvitation:s}=Ei(),{t:a}=ss(),{begin:i,settle:o}=os(),[c,l]=t.useState([]),[d,u]=t.useState(Boolean(e)),[p,h]=t.useState(null),[m,f]=t.useState(null),g=t.useRef(a);t.useEffect(()=>{g.current=a},[a]);const y=t.useCallback(async()=>{if(!e)return l([]),void u(!1);const t=i();u(!0),h(null);try{const r=await n(e);if(t.signal.aborted)return;l(qn(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)&&u(!1)}},[e,n,i,o]);t.useEffect(()=>{y()},[y]);const w=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=>qn(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]),v=t.useMemo(()=>c.filter(e=>Bn(e)).length,[c]);return t.useMemo(()=>({invitations:c,pendingCount:v,loading:d,error:p,busy:m,refresh:y,resend:w,revoke:b}),[c,v,d,p,m,y,w,b])},exports.validateInvite=Yt,exports.validateRedirectUrl=yt,exports.workspaceCanBeDeleted=function(e){return 1!==dl(e)?.maxWorkspacesPerUser},exports.workspaceEmojis=Qc,exports.workspaceIdOf=function(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace},exports.workspaceInvitesEnabled=ul,exports.workspaceNameOf=zn,exports.workspaceSettingsManager=Ci;
|