@buildbase/sdk 0.0.53 → 0.0.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +11 -5
- package/CHANGELOG.md +46 -0
- package/README.md +87 -52
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +393 -33
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -1
- package/dist/mcp/index.d.ts +562 -8
- package/dist/mcp/index.mjs +1 -1
- package/dist/react/chunks/{SettingsDialog-Dy8W3NA6.cjs → SettingsDialog-B28WJsAr.cjs} +1 -1
- package/dist/react/chunks/{SettingsDialog-BxDYsie6.mjs → SettingsDialog-blhppbNm.mjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-6c5dHoQd.mjs → SubscriptionDialog-BTWVX3cH.mjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-CpVnnXJg.cjs → SubscriptionDialog-QKmwvJU1.cjs} +1 -1
- package/dist/react/chunks/react-6QJCOE-D.cjs +2 -0
- package/dist/react/chunks/react-CC6T7Zky.mjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +60 -12
- package/dist/react/index.mjs +1 -1
- package/package.json +4 -2
- package/dist/react/chunks/react-4SlWxHdh.cjs +0 -2
- package/dist/react/chunks/react-OL1uSkpr.mjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";var e=require("react/jsx-runtime"),t=require("react"),r=require("clsx"),s=require("tailwind-merge"),n=require("intl-messageformat"),a=require("@hookform/resolvers/zod"),o=require("react-hook-form"),i=require("@radix-ui/react-slot"),c=require("class-variance-authority"),l=require("lucide-react"),u=require("@radix-ui/react-label"),d=require("zod"),p=require("@radix-ui/react-avatar"),h=require("@radix-ui/react-dialog"),m=require("@radix-ui/react-icons"),g=require("@radix-ui/react-radio-group"),f=require("@radix-ui/react-scroll-area"),b=require("@radix-ui/react-separator");function w(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var y=w(t),x=w(u),k=w(p),v=w(h),S=w(g),C=w(f),P=w(b);function E(...e){return s.twMerge(r.clsx(e))}let N=!0;function I(e,...t){N&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function R(e,...t){console.error(e,...t)}function j(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}async function A(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 U(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await A(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await A(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class W extends Error{constructor(e,t,r,s){super(e),this.code=t,this.context=r,this.originalError=s,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,W)}}const F=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(N=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(j(e))return;const r=e instanceof Error?e:new W("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),s=r instanceof W?r:new W(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&I(`[SDK Error] ${t.component||"Unknown"}:`,{message:s.message,code:s.code,context:s.context,originalError:s.originalError,stack:s.stack}),this.config.onError)try{this.config.onError(s,t)}catch(e){R("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(s,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function T(e,t={}){F.handleError(e,t)}function _(e,t={}){return!j(e)&&(F.handleError(e,t),!0)}function O(e,t,r){return e instanceof Error?e.message:r(t)}function D(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return T(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function L(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){T(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}function M(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){T(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}const $="saas-session-id",B="code",q="state";function V(e){L($,e)}function z(){M($)}function G(){return function(){if("undefined"==typeof window)return null;try{return D($)}catch(e){return T(e,{component:"auth-utils",action:"getSessionId",metadata:{key:$}}),null}}()}function J(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(B)}catch(e){return T(e,{component:"auth-utils",action:"getTokenFromUrl",metadata:{param:B}}),null}}function K(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.delete(B),e.searchParams.delete(q),window.history.replaceState({},"",e.toString())}catch(e){T(e,{component:"auth-utils",action:"removeTokenFromUrl",metadata:{param:B}})}}const Y=new WeakSet,H=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Q="SDK is not ready (missing serverUrl, version, or orgId)";class Z{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(Q);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(Q)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=G(),t={};return e&&(t["x-session-id"]=e),t}()}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){Y.has(e)||(Y.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((r,s)=>{const n=()=>{clearTimeout(a),s(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return n();const a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}async executeFetchUrl(e,t,r){const s=(t.method??"GET").toUpperCase(),n=r??e,a=this.buildHeaders(t),o={...t,headers:a},i=H.has(s);let c,l;if(this._timeout>0){l=new AbortController;const e=l;c=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const s=new AbortController,n=e=>{s.signal.aborted||s.abort(e.reason)};for(const r of[e,t]){if(r.aborted){n(r);break}r.addEventListener("abort",()=>n(r),{once:!0})}return s.signal}(t.signal,e.signal):e.signal}const u=e=>{if(l?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${n}`);return this.reportError(e,{method:s,path:n}),e}return e},d=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const r=this._fetch.bind(globalThis),n=await r(e,o);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&i&&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 Z.delay(e,o.signal),d(t+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw u(e);if(i&&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 Z.delay(e,o.signal)}catch(e){throw u(e)}return d(t+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:n}),e}};try{return await d(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await U(s,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw new Error(r)}apiPath(e,...t){return e.reduce((e,r,s)=>e+r+(s<t.length?encodeURIComponent(String(t[s])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class X extends Z{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,r=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return r.ok||await this.throwResponseError(r,"Failed to initiate authentication"),r.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class ee extends Z{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 te=class{constructor(e){this.api=new ee(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},r=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),s=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),n=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),a=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:r,language:s,timezone:n,currency:a}})}};class re extends Z{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 se extends Z{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 ne extends Z{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class ae extends Z{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class oe extends Z{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`);return t.ok||await this.throwResponseError(t,"Failed to fetch subscription"),this.unwrapResponse(t,"Failed to fetch subscription")}async getPlanGroup(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group"),this.unwrapResponse(t,"Failed to fetch plan group")}async getPlanGroupByVersion(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch plan group version"),this.unwrapResponse(r,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group/versions`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group versions"),this.unwrapResponse(t,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plans"),this.unwrapResponse(t,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(this.apiPath`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const t=await this.fetchResponse(this.apiPath`plan-group-versions/${e}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async createCheckoutSession(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create checkout session"),this.unwrapResponse(r,"Failed to create checkout session")}async selectFreePlan(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return r.ok||await this.throwResponseError(r,"Failed to select free plan"),r.json()}async updateSubscription(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to update subscription"),this.unwrapResponse(r,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,r){const s=new URLSearchParams;s.append("limit",t.toString()),r&&s.append("starting_after",r);const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoices"),this.unwrapResponse(n,"Failed to fetch invoices")}async getInvoice(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices/${t}`);return r.ok||await this.throwResponseError(r,"Failed to fetch invoice"),this.unwrapResponse(r,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to cancel subscription"),this.unwrapResponse(t,"Failed to cancel subscription")}async resumeSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to resume subscription"),this.unwrapResponse(t,"Failed to resume subscription")}async recordUsage(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record usage"),this.unwrapResponse(r,"Failed to record usage")}async recordUsageBatch(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record batch usage"),this.unwrapResponse(r,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch quota usage status"),this.unwrapResponse(r,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){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(),n=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:""),a=await this.fetchResponse(n);return a.ok||await this.throwResponseError(a,"Failed to fetch usage logs"),this.unwrapResponse(a,"Failed to fetch usage logs")}async sendNotification(e,t,r,s){const n={event:t};return r&&(n.userId=r),s&&(n.data=s),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(n)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});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){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create credit purchase checkout"),this.unwrapResponse(r,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const r=await this.unwrapResponse(t,"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t){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(),n=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:""),a=await this.fetchResponse(n);return a.ok||await this.throwResponseError(a,"Failed to fetch credit transactions"),this.unwrapResponse(a,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){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(),n=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:""),a=await this.fetchResponse(n);return a.ok||await this.throwResponseError(a,"Failed to fetch credit buckets"),this.unwrapResponse(a,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const r=t?`?days=${t}`:"",s=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/expiring`+r);return s.ok||await this.throwResponseError(s,"Failed to fetch expiring credits"),this.unwrapResponse(s,"Failed to fetch expiring credits")}}function ie(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const ce={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted"};class le{constructor(){this.callbacks=null}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){T(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(ce.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(ce.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(ce.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(ce.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit(ce.WorkspaceUserAdded,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit(ce.WorkspaceUserRemoved,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,s){await this.emit(ce.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:r,newRole:s})}async emitWorkspaceCreated(e){await this.emit(ce.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(ce.WorkspaceDeleted,{workspace:e})}}const ue=new le;function de(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const pe=de(),he=pe.subscribe,me=pe.invalidate,ge=de(),fe=ge.subscribe,be=ge.invalidate,we=de(),ye=we.subscribe,xe=we.invalidate,ke="bb",ve={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},Se={Success:"success",Cancel:"cancel",Error:"error"},Ce={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function Pe(e,t){const r=t??("undefined"!=typeof window?window.location.href:"https://localhost");let s;try{s=new URL(r)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(r)}`)}return s.search="",s.searchParams.set(ke,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),s.toString()}function Ee(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Pe({action:ve.CreditPurchase,status:Se.Success,ws:e,screen:Ce.Credits},r),cancelUrl:Pe({action:ve.CreditPurchase,status:Se.Cancel,ws:e,screen:Ce.Credits},r)}}function Ne(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(ke);if(!e)return null;const t=function(e){const t={};if(!e)return t;const r=e.split(",");for(const e of r){const r=e.indexOf(":");if(-1===r)continue;const s=decodeURIComponent(e.slice(0,r)),n=decodeURIComponent(e.slice(r+1));s&&(t[s]=n)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function Ie(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(ke)&&(e.searchParams.delete(ke),window.history.replaceState({},"",e.toString()))}catch{}}function Re(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let r;try{r=new URL(e)}catch{return null}const s="https:"===r.protocol,n="http:"===r.protocol&&("localhost"===r.hostname||"127.0.0.1"===r.hostname||"[::1]"===r.hostname);if(!s&&!n)return null;const{sameOrigin:a,allowedOrigins:o}=t;return a||o?.length?a&&"undefined"!=typeof window&&window.location&&r.origin===window.location.origin||o?.some(e=>e.replace(/\/+$/,"")===r.origin)?e:null:e}function je(e,t="/",r={}){if("undefined"==typeof window||!window.location)return!1;const s=Re(e,r);return window.location.href=s??Re(t)??"/",!0}const Ae="saas-auth-intent";function Ue(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function We(e){Re(e,{sameOrigin:!0})&&function(e,t){try{L(e,JSON.stringify(t))}catch(t){T(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}(Ae,{returnUrl:e,createdAt:Date.now()})}function Fe(){const e=function(e,t){const r=D(e);if(!r)return null;try{const s=JSON.parse(r);return t&&!t(s)?(T(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),M(e),null):s}catch(t){return T(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),M(e),null}}(Ae,Ue);return M(Ae),e?Date.now()-e.createdAt>6e5?null:Re(e.returnUrl,{sameOrigin:!0}):null}const Te={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:"฿"},_e={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function Oe(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Te[t]??t.toUpperCase()}const De=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Le=De.map(e=>({value:e,label:`${e.toUpperCase()} (${Oe(e)})`})),Me=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]);function $e(e){return Me.has((e??"").trim().toLowerCase())}function Be(e,t){return $e(t)?e.toLocaleString("en-US"):(e/100).toFixed(2)}function qe(e,t){return Oe(t)+Be(e,t)}const Ve={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};const ze={included:"included",then:"then"};const Ge={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},Je={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"};function Ke(e,t){const r=e.pricingVariants;if(!r?.length)return null;const s=t.toLowerCase();return r.find(e=>e.currency?.toLowerCase()===s)??null}function Ye(e,t,r){const s=Ke(e,t);if(!s?.basePricing)return null;const n=s.basePricing[r];return null!=n?n:null}function He(e,t,r,s){const n=Ke(e,t),a=n?.quotaOverages?.[r];if(a)return a[s]}function Qe(e,t){const r=Ke(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function Ze(e,t,r){const s=Qe(e,t);return s?.perSeat?s.perSeat[r]??null:null}function Xe(e,t){return Math.max(0,e-(t||0))}function et(e,t,r,s){const n=Qe(e,t);if(!n)return null;return Xe(s,n.includedSeats)*(Ze(e,t,r)??0)}function tt(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:s}=e;if(t){const e=Qe(t,r);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=s&&s>0?{maxUsers:s,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function rt(e){const{memberCount:t,maxUsersConfig:r,hasSubscription:s=!0,requireSubscription:n=!1}=e;if(n&&!s)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:a,source:o}=r;if(a<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=a){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[o]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[o]??"users.memberLimitMessage",blockMessageValues:{maxUsers:a}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const st="saas-workspace-current",nt=e=>{e?L(st,e._id):M(st)},at=()=>D(st),ot=()=>{M(st)},it=(e,t)=>!!e&&t.some(t=>t._id===e);function ct(e,t){if(!t)return!1;const r=(s=e.createdBy)?"string"==typeof s?s:"object"==typeof s&&"_id"in s&&"string"==typeof s._id?s._id:null:null;var s;return null!==r&&r===t}function lt(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}const ut={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"},dt=Object.values(ut),pt={admin:dt.filter(e=>e!==ut.WORKSPACE_DELETE),member:[ut.WORKSPACE_SETTINGS_VIEW,ut.WORKSPACE_MEMBERS_VIEW,ut.WORKSPACE_FEATURES_VIEW,ut.WORKSPACE_BILLING_VIEW,ut.WORKSPACE_USAGE_VIEW],viewer:[ut.WORKSPACE_SETTINGS_VIEW,ut.WORKSPACE_MEMBERS_VIEW]};function ht(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function mt(e){const{userId:t,workspace:r,settings:s,appPermissions:n}=e;if(!r||!t)return new Set;if(ct(r,t)){const e=new Set(dt);if(n)for(const t of ht(n))e.add(t);if(r.permissions)for(const t of ht(r.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of ht(s.workspace.permissions))e.add(t);return e}const a=e.workspaceRole??lt(r,t);if(!a)return new Set;const o=r.permissions,i=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=!!o&&a in o,d=!!i&&a in i,p=a in pt;let h;if(u)h=c(o[a]);else if(d)h=c(i[a]);else if(p)h=pt[a];else{const e=s?.workspace?.defaultRole;h=e&&e in pt?pt[e]:[]}const m=new Set(h),g=u?l(o[a]):[],f=n?.[a]?l(n[a]):[],b=u?g:f;for(const e of b)m.add(e);return function(e,t,r){if(!r?.workspace)return;const{canInviteMembers:s}=r.workspace;(!1===s||"admin-only"===s&&"admin"!==t)&&e.delete(ut.WORKSPACE_MEMBERS_INVITE)}(m,a,s),m}var gt;function ft(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,(gt=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",gt.redirecting="redirecting",gt.authenticated="authenticated",gt.unauthenticated="unauthenticated",gt.authenticating="authenticating";class bt 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(T(e,{component:"ErrorBoundary",action:"componentDidCatch",metadata:{componentStack:t.componentStack,errorBoundary:this.constructor.name}}),this.props.onError)try{this.props.onError(e,t)}catch(e){R("[SDK ErrorBoundary] Error in onError callback:",e)}}componentDidUpdate(e){this.state.hasError&&!1!==this.props.resetOnPropsChange&&e.children!==this.props.children&&this.resetError()}render(){return this.state.hasError&&this.state.error?this.props.fallback?"function"==typeof this.props.fallback?this.props.fallback(this.state.error,this.resetError):this.props.fallback:e.jsxs("div",{style:{padding:"1rem",border:"1px solid hsl(var(--destructive, 0 84.2% 60.2%))",borderRadius:"0.5rem",backgroundColor:"hsl(var(--destructive, 0 84.2% 60.2%) / 0.08)",color:"hsl(var(--destructive, 0 70% 35%))"},children:[e.jsx("h3",{style:{margin:"0 0 0.5rem 0",fontSize:"1rem",fontWeight:600},children:this.props.errorTitle??"Something went wrong"}),e.jsx("p",{style:{margin:"0 0 1rem 0",fontSize:"0.875rem"},children:this.state.error.message||"An unexpected error occurred"}),e.jsx("button",{onClick:this.resetError,style:{padding:"0.5rem 1rem",backgroundColor:"hsl(var(--destructive, 0 84.2% 60.2%))",color:"hsl(var(--destructive-foreground, 210 40% 98%))",border:"none",borderRadius:"0.25rem",cursor:"pointer",fontSize:"0.875rem"},children:this.props.retryLabel??"Try again"})]}):this.props.children}}const wt=()=>({type:"AUTHENTICATION_STARTED"}),yt=()=>({type:"AUTHENTICATION_PROCESSING"}),xt=()=>({type:"AUTHENTICATION_FAILED"}),kt=e=>({type:"SET_SESSION",payload:e}),vt=()=>({type:"REMOVE_SESSION"});function St(e,r,s){const n=t.useRef(r),a=t.useRef(s),o=t.useRef(void 0),i=t.useRef(!1),c=n.current!==r,l=a.current!==s,u=c||l;n.current=r,a.current=s;const d=t.useRef(0);u&&(d.current+=1);const p=d.current;return t.useMemo(()=>{const t=r(e);if(i.current){if(s?s(o.current,t):Object.is(o.current,t))return o.current}return o.current=t,i.current=!0,t},[e,p])}function Ct({name:r,initialState:s,reducer:n,initializer:a}){const o=t.createContext(null),i=t.createContext(null),c=t.createContext(null),l=t.memo(({children:r})=>{const[l,u]=t.useReducer(n,s,a||(e=>e)),d=t.useMemo(()=>({state:l,dispatch:u}),[l,u]);return e.jsx(c.Provider,{value:d,children:e.jsx(o.Provider,{value:l,children:e.jsx(i.Provider,{value:u,children:r})})})});l.displayName=`${r}Provider`;const u=e=>new Error(`use${r}${e} must be used within a ${r}Provider. Make sure SaaSOSProvider is wrapping your application.`),d=()=>{const e=t.useContext(o);if(null===e)throw u("State");return e};return{Provider:l,useContext:()=>{const e=t.useContext(c);if(!e)throw u("Context");return e},useState:d,useDispatch:()=>{const e=t.useContext(i);if(null===e)throw u("Dispatch");return e},useSelector:(e,t)=>St(d(),e||(e=>e),t)}}function Pt(e,t,r){return{...e,[t]:r}}function Et(e,t){return{...e,...t}}const Nt=()=>({session:null,status:exports.AuthStatus.loading}),{Provider:It,useState:Rt,useDispatch:jt}=Ct({name:"Auth",initialState:Nt(),reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return Pt(e,"status",exports.AuthStatus.redirecting);case"AUTHENTICATION_PROCESSING":return Pt(e,"status",exports.AuthStatus.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return Et(e,{session:null,status:exports.AuthStatus.unauthenticated});case"SET_SESSION":return Et(e,{session:t.payload,status:exports.AuthStatus.authenticated});default:return e}},initializer:Nt}),At=It,Ut=Rt,Wt=jt,Ft=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),Tt=e=>({type:"SET_SETTINGS",payload:e}),_t=()=>({serverUrl:"",version:exports.ApiVersion.V1,orgId:"",settings:null}),{Provider:Ot,useState:Dt,useDispatch:Lt}=Ct({name:"OS",initialState:_t(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return Et(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return _t();case"SET_SETTINGS":return Pt(e,"settings",t.payload);default:return e}}}),Mt=Ot,$t=Dt,Bt=Lt,qt=e=>({type:"SET_WORKSPACES",payload:e}),Vt=e=>({type:"ADD_WORKSPACE",payload:e}),zt=e=>({type:"UPDATE_WORKSPACE",payload:e}),Gt=e=>({type:"REMOVE_WORKSPACE",payload:e}),Jt=e=>({type:"SET_ALL_FEATURES",payload:e}),Kt=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),Yt=()=>({type:"RESET_CURRENT_WORKSPACE"}),Ht=e=>({type:"SET_IS_INITIALIZED",payload:e}),Qt=e=>({type:"SET_LOADING",payload:e}),Zt=e=>({type:"SET_ERROR",payload:e}),Xt=e=>({type:"SET_REFRESHING",payload:e}),er=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:tr,useState:rr,useDispatch:sr}=Ct({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 Pt(e,"workspaces",t.payload);case"ADD_WORKSPACE":return Pt(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return Pt(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return Pt(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return Pt(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return Pt(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return Pt(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return Pt(e,"isInitialized",t.payload);case"SET_LOADING":return Pt(e,"loading",t.payload);case"SET_ERROR":return Pt(e,"error",t.payload);case"SET_REFRESHING":return Pt(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return Pt(e,"switchingToId",t.payload);default:return e}}}),nr=tr,ar=rr,or=sr,ir=t.memo(({children:t})=>e.jsx(Mt,{children:e.jsx(At,{children:e.jsx(nr,{children:t})})}));ir.displayName="SDKContextProvider";const cr=t.createContext({});cr.displayName="CheckoutConfigContext";const lr=t.memo(({getCheckoutStripeParams:r,children:s})=>{const n=t.useMemo(()=>({getCheckoutStripeParams:r}),[r]);return e.jsx(cr.Provider,{value:n,children:s})});lr.displayName="CheckoutConfigProvider";const ur={settings:{titles:{profile:"Account",security:"Security",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",general:"Settings",users:"Members",subscription:"Plan & Billing",usage:"Usage",credits:"Credits",features:"Features",notifications:"Notifications",permissions:"Permissions",danger:"Danger Zone"},common:{refresh:"Refresh",refreshing:"Refreshing...",retry:"Retry",retrying:"Retrying...",save:"Save",saving:"Saving...",cancel:"Cancel",delete:"Delete",dismiss:"Dismiss",loading:"Loading...",success:"Success!",error:"Error",refreshAction:"{loading, select, true {Refreshing...} other {Refresh}}",retryAction:"{loading, select, true {Retrying...} other {Retry}}",noPermissionTitle:"Access Restricted",noPermissionDescription:"You don't have permission to access this section. Contact a workspace admin if you need access.",billingManageOnly:"Only users with billing management permissions can perform this action.",openSettings:"Open settings",back:"Back"}},subscription:{managePlan:"Manage your plan and billing",changePlan:"Change Plan",viewPricingPlans:"View Pricing Plans",viewPlans:"View Plans",upgradePlan:"Upgrade Now",subscribe:"Subscribe",currentPlan:"Current Plan",noSubscription:"You don't have an active subscription",choosePlan:"Choose Your Plan",choosePlanDescription:"Compare plans and select the one that fits your needs",forWorkspace:"for {name}",planUpdateAvailable:"Plan update available",updateSuccess:"Subscription updated successfully!",updateFailed:"Update failed",cancelTitle:"Cancel Subscription",cancelConfirm:"Are you sure you want to cancel your subscription?",cancelKeep:"Keep Subscription",cancelButton:"Yes, Cancel Subscription",canceling:"Canceling...",cancelSuccess:"Subscription will be canceled at the end of the billing period.",cancelNotCharged:"You won't be charged again after cancellation",cancelResumeAnytime:"You can resume your subscription anytime before it ends",cancelTrialTitle:"Cancel Trial",cancelTrialConfirm:"Are you sure you want to cancel your trial?",cancelTrialAccess:"Your trial will continue until",cancelTrialNoCharge:"You won't be charged — your trial will simply expire",cancelTrialResume:"You can resume your trial anytime before it ends",cancelTrialKeep:"Keep Trial",cancelTrialButton:"Yes, Cancel Trial",resumeTitle:"Resume Subscription",resumeTrial:"Resume Trial",resumeConfirm:"Are you sure you want to resume your subscription?",resumeKeep:"Keep Canceled",resumeButton:"Yes, Resume Subscription",resuming:"Resuming...",resumeSuccess:"Subscription has been resumed.",managePayment:"Manage Payment",openingPortal:"Opening...",viewAllPlans:"View All Plans",scheduledCancellation:"Subscription scheduled for cancellation",scheduledTrialCancellation:"Trial scheduled for cancellation",paymentPastDue:"Payment past due",paymentPastDueDescription:"Please update your payment method to avoid service interruption.",subscriptionPaused:"Subscription paused",subscriptionPausedDescription:"Your subscription is currently paused. Resume to restore full access.",errorLoading:"Error loading subscription data",errorLoadingDescription:"Please check your connection and try again.",errorProcessing:"Failed to process subscription",errorCanceling:"Failed to cancel subscription",errorResuming:"Failed to resume subscription",invalidWorkspace:"Invalid workspace ID",billingInterval:{monthly:"Monthly",quarterly:"Quarterly",yearly:"Yearly",perMonth:"/month",perQuarter:"/quarter",perYear:"/year"},seats:{title:"Seats",members:"Members",included:"Included",billable:"Billable",perExtraSeat:"Per extra seat",limit:"Limit",includedSeats:"Included seats",maxSeats:"Max seats",freeWithBase:"Free with base price",allIncluded:"All included",extra:"extra",unlimited:"Unlimited"},items:{features:"Features",limits:"Limits",quotas:"Usage Quotas",credits:"AI Credits",creditsPerMonth:"Credits per month",creditsOneTime:"Credits (given once)",creditRenewal:"Credit renewal",creditModeReset:"Fresh every month",creditModeTopup:"Adds up every month",creditModeLifetime:"Given once",creditsPerPeriod:"Credits per month",creditRollover:"Credit renewal"},checkout:{upgrade:"Upgrade",downgrade:"Downgrade",switchTo:"Switch to",select:"Select"},status:{active:"Active",canceling:"Canceling",trial:"Trial",canceled:"Canceled",pastDue:"Past Due",paused:"Paused",deprecated:"Deprecated",unknown:"Unknown"},plan:"Plan",invoicesTab:"Invoices",tabsLabel:"Subscription tabs",endsOn:"(ends {date})",versionLabel:"Version {version}",changePlanButton:"Change Plan",noPlanAssigned:"No plan assigned",free:"Free",perSeatDisplay:"+ {price}/seat{interval}",estTotalDisplay:"Est. total: {total}{interval} ({count, plural, one {# extra seat} other {# extra seats}})",nextBillingDisplay:"Next billing: {date}",membersInWorkspace:"{count, plural, one {# member} other {# members}} in workspace",billingInCurrency:"Billing in {currency}",savingsPercent:"Save {percent, number}%",switchToInterval:"Switch to {interval}",seatPriceDisplay:"+ {price}/seat{interval} ({included} {includedLabel})",trialEnded:"Your trial has ended.",trialEndsIn:"Your trial ends in {days, plural, one {# day} other {# days}}.",onTrial:"You are on a trial.",upgradeToKeepAccess:"Upgrade to keep access.",viewInvoices:"View Invoices",cancelTrial:"Cancel Trial",dunningFinal:"Final warning: Subscription will be suspended",dunningSuspended:"Subscription suspended",dunningRecovery:"Payment recovery in progress",dunningSuspendedDescription:"Your subscription has been suspended due to repeated payment failures. Update your payment method to restore access.",dunningRecoveryDescription:"We were unable to process your payment. Please update your payment method to avoid losing access.",cancelEndDescription:"Your subscription will end on",trialEndDescription:"Your trial will end on",cancelEndFallback:"Your subscription will be canceled at the end of the current billing period. You won't be charged again.",resumeChargeDate:"You will be charged again on",resumeChargeFallback:"the next billing date",resumeContinue:"Your subscription will continue automatically and you'll be billed according to your plan",resumeCancelAnytime:"You can cancel anytime before the next billing date if you change your mind",retainAccess:"You'll retain full access to this plan until",retainAccessFallback:"the end of your current billing period",noPlansAvailable:"No plan groups are available for this workspace. Please contact support if you believe this is an error.",noPlansAvailableHint:"No plan groups are available for this workspace.",startTrialDescription:"Try the full plan with no commitment. You can upgrade or cancel anytime.",noSubscriptionDescription:"Choose a plan to get started with your workspace",startFreeTrial:"Start Free Trial",startTrialDays:"Start {days}-day Free Trial",trialBadge:"{days}-day trial"},users:{emailPlaceholder:"example@example.com",title:"Workspace Members",adminOnly:"Only workspace admin can manage users and roles.",inviteByEmail:"Invite member by email",inviteButton:"Invite",inviting:"Inviting...",inviteSuccess:"User invited successfully",emailRequired:"Email is required",invalidEmail:"Invalid email address format",inviteFailed:"Failed to invite member",seatLimitReached:"Seat limit reached",memberLimitReached:"Member limit reached",role:"Role",you:"You",owner:"Owner",noMembers:"No members found in this workspace.",extraSeatCost:"Each additional member adds {price}/{interval, select, yearly {yr} quarterly {qtr} other {mo}} to your subscription",unknownUser:"Unknown User",seats:"Seats",members:"Members",included:"included",perExtraSeat:"/extra seat",maxMembers:"max members",available:"available",noMemberLimit:"No member limit",seatHeading:"{hasSeatPricing, select, true {Seats} other {Members}}",limitReached:"{reason, select, seat_limit_reached {Seat limit reached} other {Member limit reached}}",memberCount:"{count, plural, one {# member} other {# members}}",subscriptionRequired:"A subscription is required to invite members.",seatLimitMessage:"Your plan allows up to {maxUsers, number} members. Upgrade for more seats.",settingsLimitMessage:"This workspace allows up to {maxUsers, number} members.",memberLimitMessage:"Member limit of {maxUsers, number} reached.",selectRole:"Select a role",inviteAs:"Invite as {role}"},invoices:{title:"Billing History",description:"View and download your invoices",pay:"Pay",view:"View",viewDetails:"View Details",download:"PDF",errorLoading:"Error loading invoices",noInvoices:"No invoices yet. Subscribe to a plan to receive invoices.",noInvoicesWithSub:"No invoices with download option found",paidAmount:"Paid: {amount}",na:"N/A",status:{draft:"Draft",open:"Open",paid:"Paid",uncollectible:"Uncollectible",void:"Void"}},usage:{title:"Usage",description:"Monitor your resource consumption and quotas",totalResources:"Total Resources",overallUsage:"Overall Usage",inOverage:"In Overage",estOverageCost:"Est. Overage Cost",overageDetected:"Overage Detected",overageDescription:"Additional usage will be billed as overage on your next invoice.",overageUnits:"Overage units",rate:"Rate",billableBlocks:"Billable blocks",estimatedCharge:"Estimated charge",noData:"No quota usage data available for this workspace.",noDataHint:"Quotas will appear here once your plan includes metered resources.",used:"used",remaining:"remaining",overLimit:"over limit",percentUsed:"{percent, number}% used",availableRemaining:"{count} remaining",overLimitCount:"{count} over limit",overageWarning:"{count, plural, one {# resource has exceeded the included quota.} other {# resources have exceeded the included quota.}} Additional usage will be billed as overage on your next invoice.",fullyUsed:"Fully used",renewingSoon:"renewing soon",almostFull:"Almost full",overage:"Overage",errorLoading:"Failed to load usage data",perUnit:"/ unit",perUnits:"/ units",rateDisplay:"{rate} {unitSize, plural, =1 {/ unit} other {/ {unitSize, number} units}}",resourcesExceeded:"{count, plural, one {# resource has exceeded the included quota.} other {# resources have exceeded the included quota.}}",estOverageCharges:"Estimated overage charges this period: {amount}",overageRateDisplay:"Overage rate: {rate}",resetDateDisplay:"Usage resets on {date}",daysRemainingDisplay:"{count, plural, one {# day remaining} other {# days remaining}}"},profile:{email:"Email",name:"Name",language:"Language",country:"Country",currency:"Currency",timezone:"Timezone",profileImage:"Profile Image",success:"Profile saved successfully",nameMinLength:"Name must be at least 2 characters.",save:"Save",reset:"Reset"},general:{ownerOnly:"Only the workspace owner can change the workspace settings.",name:"Name",namePlaceholder:"My Awesome Workspace",nameMinLength:"Workspace name must be at least 2 characters.",billingCurrency:"Billing currency",icon:"Icon",iconDescription:"Choose an emoji or upload a custom image for your workspace.",imageUrl:"Image URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"Enter a valid URL for your workspace image. Supports PNG, JPG, and SVG formats.",previewLabel:"Preview:",previewImageAlt:"Workspace preview",success:"Workspace settings saved successfully",chooseEmoji:"Choose Emoji",customImageUrl:"Custom Image URL",updateWorkspace:"Update Workspace"},features:{title:"Workspace Features",ownerOnly:"Only the workspace owner can change the features.",noFeatures:"Workspace has no features to manage.",enabled:"enabled",disabled:"disabled",enabling:"Enabling",disabling:"Disabling",featureSuccess:"successfully",updateSuccess:"{feature} {enabled, select, true {enabled} other {disabled}} successfully",actionStatus:"{action, select, enabling {Enabling} disabling {Disabling} other {}}"},danger:{title:"Delete Workspace",adminOnly:"Only workspace admins can delete workspaces.",deleteWorkspace:"Delete Workspace",deleteConfirm:"Are you absolutely sure?",deleteWarning:"This action cannot be undone. This will permanently delete the workspace and all associated data.",deleting:"Deleting...",deleteDescription:"Once you delete a workspace, there is no going back. This will permanently delete the workspace and all of its data, including members, settings, and features.",deleteConfirmDescription:"This action cannot be undone. This will permanently delete the workspace and all of its data.",failedToDelete:"Failed to delete workspace"},notifications:{title:"Notification Preferences",permissionDenied:"Notification permission denied",notSupported:"Push notifications are not supported in this browser.",manageDescription:"Manage how you receive notifications from this workspace.",blocked:"Notifications Blocked",blockedDescription:"You previously blocked notifications for this site. To enable them, update your browser settings:",pushTitle:"Push Notifications",pushEnabledDescription:"You will receive browser notifications for important updates.",pushDisabledDescription:"Get notified about payment issues, trial expiry, and other important updates.",enabling:"Enabling...",disabling:"Disabling...",enable:"Enable",disable:"Disable",toggleAction:"{loading, select, true {{subscribed, select, true {Disabling...} other {Enabling...}}} other {{subscribed, select, true {Disable} other {Enable}}}}",pushDescription:"{subscribed, select, true {You will receive browser notifications for important updates.} other {Get notified about payment issues, trial expiry, and other important updates.}}",deviceNote:"Notifications are sent to this device. Enable on other devices separately.",prefsSaved:"Notification preferences saved.",loadingPrefs:"Loading preferences...",categories:{workspace:"Workspace",billing:"Billing & Payments"},events:{workspace_invite:"Member Invited",workspace_invite_desc:"When a new member is added to the workspace",workspace_removed:"Member Removed",workspace_removed_desc:"When a member is removed from the workspace",workspace_role_changed:"Role Changed",workspace_role_changed_desc:"When a member's role is updated",subscription_created:"Subscription Created",subscription_created_desc:"When a new subscription is activated",subscription_upgraded:"Plan Upgraded",subscription_upgraded_desc:"When the subscription plan is upgraded",subscription_canceled:"Subscription Canceled",subscription_canceled_desc:"When the subscription is canceled",subscription_suspended:"Access Suspended",subscription_suspended_desc:"When access is suspended due to payment failures",trial_ending:"Trial Ending",trial_ending_desc:"A few days before the trial expires",trial_expired:"Trial Expired",trial_expired_desc:"When the trial period has ended",payment_failed:"Payment Failed",payment_failed_desc:"When a payment could not be processed",payment_action_required:"Payment Action Required",payment_action_required_desc:"When a payment requires additional verification",payment_succeeded:"Payment Received",payment_succeeded_desc:"When a payment is successfully processed"},unblock:{firefox:{step1:"Click the lock icon (or shield icon) in the address bar",step2:'Find "Notifications" in the permissions list',step3:'Change from "Blocked" to "Allow"',step4:"Reload this page"},safari:{step1:"Open Safari → Settings → Websites → Notifications",step2:"Find this website in the list",step3:'Change from "Deny" to "Allow"',step4:"Reload this page"},edge:{step1:"Click the lock icon in the address bar",step2:'Click "Permissions for this site"',step3:'Set "Notifications" to "Allow"',step4:"Reload this page"},chrome:{step1:"Click the lock icon (or tune icon) in the address bar",step2:'Click "Site settings"',step3:'Set "Notifications" to "Allow"',step4:"Reload this page"}}},quota:{includedOnly:"{count, number}/mo",includedWithOverage:"{count, number}/mo, then {price} / {unit}",includedHardLimit:"{count, number}/mo (hard limit)",unitFallback:"unit"},pricing:{title:"Choose Your Plan",description:"Compare plans and select the one that fits your needs",currency:"Currency",billingIn:"Billing in",noPlansCurrency:"No plans available for your billing currency.",noPlansCurrencyHint:"Something went wrong. Please contact support.",noPlans:"No plans available",free:"Free",included:"included",save:"Save",current:"Current",processing:"Processing...",unavailable:"Unavailable",selectCurrency:"Select billing currency",billingInterval:"Billing interval"},beta:{logoAlt:"Logo",nameLabel:"Name",emailLabel:"Email",submitText:"Submit",submittingText:"Submitting...",errorMessage:"An error occurred",tryAgain:"Try Again",privacyConsent:"By submitting this form, you consent to our",privacyPolicy:"Privacy Policy",and:"and",termsOfService:"Terms of Service"},workspace:{switchTitle:"Switch Workspace",switchDescription:"Select a workspace to switch to or create a new one.",notLoggedIn:"Looks like you are not logged in. Please login to continue.",availableWorkspaces:"Available Workspaces ({count, number})",loadingWorkspaces:"Loading workspaces...",searchPlaceholder:"Search workspaces...",noWorkspacesFound:"No workspaces found",noWorkspacesAvailable:"No workspaces available",switchTo:"Switch to",membersCount:"{count, plural, one {# member} other {# members}}",createNew:"Create New Workspace",createTitle:"Create New Workspace",createDescription:"Create a new workspace to get started.",workspaceName:"Workspace Name",workspaceNamePlaceholder:"My Awesome Workspace",workspaceNameMinLength:"Workspace name must be at least 2 characters.",workspaceIcon:"Workspace Icon",iconDescription:"Choose an emoji or upload a custom image for your workspace.",chooseEmoji:"Choose Emoji",customImageUrl:"Custom Image URL",imageUrl:"Image URL",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"Enter a valid URL for your workspace image. Supports PNG, JPG, and SVG formats.",invalidUrl:"Please enter a valid URL",creating:"Creating...",createWorkspace:"Create Workspace"},dropdowns:{search:"Search...",chooseOption:"Choose option",chooseCountry:"Choose country",searchCountry:"Choose country...",chooseLanguage:"Choose language",searchLanguage:"Choose language...",chooseCurrency:"Choose currency",searchCurrency:"Choose currency...",chooseTimezone:"Choose timezone",searchTimezone:"Choose timezone...",noResults:"No results found"},push:{failedToSubscribe:"Failed to subscribe to push notifications",failedToUnsubscribe:"Failed to unsubscribe from push notifications"},permissions:{title:"Permissions",description:"Permissions assigned to each role in this workspace.",ownerOnly:"Only the workspace owner can manage permissions.",save:"Save Permissions",saving:"Saving...",saveSuccess:"Permissions saved successfully"},credits:{title:"Credits",description:"Credits can be used for premium actions like AI generation.",balance:"Credit Balance",available:"Available",totalGranted:"Total Granted",totalConsumed:"Total Consumed",totalExpired:"Total Expired",noCredits:"No credits yet",noCreditsHint:"Credits will appear here when granted by your plan or purchased.",buyCredits:"Buy Credits",buyAmount:"Buy {count} Credits",purchasing:"Redirecting...",packages:"Credit Packages",noPackages:"No credit packages available.",creditsAmount:"{count} credits",validityDays:"Valid for {count} days",validityUnlimited:"No expiry",transactions:"Recent Transactions",noTransactions:"No transactions yet.",loadMore:"Load More",viewAll:"View All",expiringSoon:"Expiring Soon",expiringInDays:"{count} credits expiring within {days} days",noExpiring:"No credits expiring soon.",type:{plan_grant:"Plan Grant",pack_purchased:"Purchased",consumed:"Consumed",expired:"Expired",admin_grant:"Granted",admin_revoke:"Revoked",refund:"Refund"},dialogTitle:"Buy Credit Packages",dialogDescription:"Choose a credit package to purchase.",dialogDescriptionWorkspace:"Purchase credits for {workspace}.",perCredit:"{price} per credit",purchaseSuccess:"Credits purchased successfully! Your balance has been updated.",purchaseCanceled:"Credit purchase was canceled. No charges were made.",purchaseFailed:"Credit purchase failed. Please try again or contact support.",errorLoading:"Failed to load credit data",insufficientCredits:"Not enough credits"},loading:{restoringSession:"Restoring your session...",redirecting:"Redirecting...",signingIn:"Signing you in...",verifyingAccount:"Verifying your account...",almostThere:"Almost there..."},errors:{networkError:"Network error: Please check your internet connection",unauthorized:"Unauthorized - Please check your session",notFound:"Resource not found",generic:"An error occurred",fetchPlans:"Failed to fetch plans",fetchPlanGroup:"Failed to fetch plan group",fetchPlanGroupVersion:"Failed to fetch plan group version",fetchPlanGroupVersions:"Failed to fetch plan group versions",fetchSubscription:"Failed to fetch subscription",createCheckout:"Failed to create checkout session",updateSubscription:"Failed to update subscription",fetchInvoices:"Failed to fetch invoices",fetchInvoice:"Failed to fetch invoice",openBillingPortal:"Failed to open billing portal",cancelSubscription:"Failed to cancel subscription",resumeSubscription:"Failed to resume subscription",recordUsage:"Failed to record usage",fetchQuotaUsage:"Failed to fetch quota usage status",fetchAllQuotaUsage:"Failed to fetch all quota usage",fetchUsageLogs:"Failed to fetch usage logs",fetchCreditBalance:"Failed to fetch credit balance",consumeCredits:"Failed to consume credits",purchaseCredits:"Failed to purchase credits",fetchCreditPackages:"Failed to fetch credit packages",fetchCreditTransactions:"Failed to fetch credit transactions",fetchExpiringCredits:"Failed to fetch expiring credits"},security:{connectedAgentsTitle:"Connected agents",connectedAgentsDescription:"AI agents you've authorized to access your account. Disconnect any you no longer use — it revokes access immediately.",connectedAgentsDisconnect:"Disconnect",connectedAgentsEmpty:"No connected agents.",connectedAgentsAccess:"Access",connectedAgentsGranted:"Granted",inactive:"Inactive",inactiveHint:"Registered on a previous sign-in domain and can no longer be used. You can remove it.",passkeysTitle:"Passkeys",passkeysDescription:"Passkeys let you sign in with your fingerprint, face, or device PIN.",noPasskeys:"No passkeys registered",addHint:'To add a passkey, choose "Add a passkey" the next time you sign in on the device you want to use.',rename:"Rename",remove:"Remove",removeTitle:"Remove passkey",removeDescription:"You will no longer be able to sign in with this passkey.",renamePlaceholder:"Passkey name",lastUsed:"Last used",added:"Added"}},dr={en:async()=>ur,es:async()=>(await Promise.resolve().then(function(){return require("./es-BBPsSZUp.cjs")})).es,fr:async()=>(await Promise.resolve().then(function(){return require("./fr-Cax48X_S.cjs")})).fr,de:async()=>(await Promise.resolve().then(function(){return require("./de-BjdDg60Y.cjs")})).de,ja:async()=>(await Promise.resolve().then(function(){return require("./ja-DvVyj5xX.cjs")})).ja,zh:async()=>(await Promise.resolve().then(function(){return require("./zh-BAcqxkxk.cjs")})).zh,hi:async()=>(await Promise.resolve().then(function(){return require("./hi-BJqvpG6d.cjs")})).hi,ar:async()=>(await Promise.resolve().then(function(){return require("./ar-VGzBv3AZ.cjs")})).ar},pr=["en","es","fr","de","ja","zh","hi","ar"];const hr={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function mr(e,t){const r={...e};for(const s of Object.keys(t)){const n=t[s],a=e[s];"string"==typeof n?r[s]=n:n&&"object"==typeof n&&a&&"object"==typeof a&&(r[s]=mr(a,n))}return r}const gr=t.createContext({messages:ur,locale:"en",formattingLocale:"en"});function fr({locale:e="en",messageOverrides:r,children:s}){const n=function(e){const t=e.toLowerCase().replace("_","-");if(pr.includes(t))return t;const r=t.split("-")[0];return pr.includes(r)?r:"en"}(e),[a,o]=t.useState(ur);t.useEffect(()=>{if("en"===n)return void o(ur);let e=!1;const t=dr[n];return t&&t().then(t=>{e||o(t)}),()=>{e=!0}},[n]);const i=t.useMemo(()=>r?mr(a,r):a,[a,r]),c=function(e){return hr[e]??e}(n),l=t.useMemo(()=>({messages:i,locale:n,formattingLocale:c}),[i,n,c]);return t.createElement(gr.Provider,{value:l},s)}const br=new Map,wr=new Map,yr=new Map;function xr(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const kr={getNumberFormat(e,t){const r=xr(e,t);let s=br.get(r);return s||(s=new Intl.NumberFormat(e,t),br.set(r,s)),s},getDateTimeFormat(e,t){const r=xr(e,t);let s=wr.get(r);return s||(s=new Intl.DateTimeFormat(e,t),wr.set(r,s)),s},getPluralRules(e,t){const r=xr(e,t);let s=yr.get(r);return s||(s=new Intl.PluralRules(e,t),yr.set(r,s)),s}},vr=new Map;function Sr(){const{messages:e,locale:r,formattingLocale:s}=t.useContext(gr),a=t.useMemo(()=>{const t=(e,t)=>{let r=e;for(const e of t.split(".")){if(!r||"object"!=typeof r||!(e in r))return;r=r[e]}return"string"==typeof r?r:void 0};return(r,a)=>{const o=t(e,r)??t(ur,r)??r;if(!a)return o;try{const e=function(e,t){const r=`${t}:${e}`;let s=vr.get(r);return s||(s=new n(e,t,void 0,{formatters:kr}),vr.set(r,s)),s}(o,s),t=e.format(a);return"string"==typeof t?t:String(t)}catch{return o.replace(/\{(\w+)\}/g,(e,t)=>String(a[t]??`{${t}}`))}}},[e,s]),o="ar"===r?"rtl":"ltr",i=t.useMemo(()=>e=>e.toLocaleString(s),[s]),c=t.useMemo(()=>(e,t)=>{const r=(t??"").trim().toUpperCase();if(!r)return(e/100).toLocaleString(s,{minimumFractionDigits:2});try{return new Intl.NumberFormat(s,{style:"currency",currency:r,minimumFractionDigits:2}).format(e/100)}catch{return(e/100).toLocaleString(s,{minimumFractionDigits:2})}},[s]);return{t:a,locale:r,formattingLocale:s,dir:o,fmtNum:i,fmtCents:c,messages:e}}function Cr(){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),[])}}function Pr(){const e=Wt(),r=Bt(),s=or();return t.useMemo(()=>({auth:e,os:r,workspaces:s}),[e,r,s])}function Er(e,r){const s=$t(),n=Ut(),a=ar();return St(t.useMemo(()=>({os:s,auth:n,workspaces:a}),[s,n,a]),e||(e=>e),r)}function Nr(e,r,s){t.useEffect(()=>{const t=new AbortController;return e(t.signal).catch(e=>{j(e)||(s?.onError?s.onError(e):T(e,{component:"useAsyncEffect",action:"effect",metadata:{note:"Unhandled rejection - consider passing onError"}}))}),()=>t.abort()},r)}function Ir(){return Er(e=>e.os)}let Rr=null;function jr(){const e=Pr(),r=Ir(),{serverUrl:s,version:n,orgId:a,settings:o}=r,i=t.useMemo(()=>ie(r)?new ne({serverUrl:s,version:n,orgId:a}):null,[s,n,a]),c=t.useCallback(async t=>i?Rr||(Rr=(async()=>{try{const t=await i.getSettings();return e.os(Tt(t)),t}catch(e){return _(e,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:s,version:n,orgId:a}}),null}finally{Rr=null}})(),Rr):null,[i,e,s,n,a]);return Nr(async()=>{o||ie(r)&&await c()},[s,n,a],{onError:e=>_(e,{component:"useSaaSSettings",action:"fetchSettings",metadata:{serverUrl:s,version:n,orgId:a}})}),t.useMemo(()=>({settings:o,getSettings:c}),[o,c])}function Ar(){const e=Ir(),r=Pr(),s=t.useCallback(()=>{z(),r.auth(vt()),e.auth?.callbacks?.onSessionExpired?.("expired")},[r,e.auth?.callbacks?.onSessionExpired]),n=function(e,r){return t.useMemo(()=>new oe({...e,onUnauthorized:r}),[e.serverUrl,e.version,e.orgId,r])}(e,s);return t.useMemo(()=>({os:e,api:n}),[e,n])}const Ur=e=>{const{t:r}=Sr(),{os:s,api:n}=Ar(),a=ie(s),[o,i]=t.useState(null),[c,l]=t.useState(!1),[u,d]=t.useState(null),{begin:p,settle:h}=Cr(),m=t.useCallback(async()=>{if(!e||!a)return p(),i(null),void l(!1);const t=p();l(!0),d(null);try{const r=await n.getPublicPlans(e);if(t.signal.aborted)return;i(r)}catch(s){if(t.signal.aborted)return;const n=O(s,"errors.fetchPlans",r);d(n),T(s,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{h(t)&&l(!1)}},[n,e,a,p,h]);t.useEffect(()=>{m()},[m]);const g=e&&!a||c;return{items:o?.items??[],plans:o?.plans??[],notes:o?.notes,loading:g,error:u,refetch:m}},Wr=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Cr(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void i(!1);const t=u();i(!0),l(null);try{const r=await s.getCurrentSubscription(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=O(s,"errors.fetchSubscription",r);l(n),T(s,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{d(t)&&i(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{subscription:n,loading:o,error:c,refetch:p}},Fr=(e,r)=>{const{t:s}=Sr(),{api:n}=Ar(),[a,o]=t.useState(null),[i,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Cr(),h=t.useCallback(async()=>{if(!e)return d(),o(null),void c(!1);const t=d();c(!0),u(null);try{const s=r?await n.getPlanGroupByVersion(e,r):await n.getPlanGroup(e);if(t.signal.aborted)return;o(s)}catch(n){if(t.signal.aborted)return;const a=O(n,"errors.fetchPlanGroup",s);u(a),T(n,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:r}})}finally{p(t)&&c(!1)}},[n,e,r,d,p]);return t.useEffect(()=>{h()},[h]),{planGroup:a,loading:i,error:l,refetch:h}},Tr=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(!1),[o,i]=t.useState(null);return{updateSubscription:t.useCallback(async(t,n)=>{if(!e)throw new Error("Workspace ID is required");a(!0),i(null);try{const r={planVersionId:t,...n?.billingInterval&&{billingInterval:n.billingInterval},...n?.successUrl&&{successUrl:n.successUrl},...n?.cancelUrl&&{cancelUrl:n.cancelUrl}},a=await s.updateSubscription(e,r);return xe(),a}catch(s){const a=O(s,"errors.updateSubscription",r);throw i(a),T(s,{component:"useUpdateSubscription",action:"updateSubscription",metadata:{workspaceId:e,planVersionId:t,options:n}}),s}finally{a(!1)}},[s,e]),loading:n,error:o}},_r=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Cr(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void i(!1);const t=u();i(!0),l(null);try{const r=await s.getAllQuotaUsage(e);if(t.signal.aborted)return;a(r.quotas)}catch(s){if(t.signal.aborted)return;const n=O(s,"errors.fetchAllQuotaUsage",r);l(n),T(s,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{d(t)&&i(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{quotas:n,loading:o,error:c,refetch:p}},Or=t.createContext(null);Or.displayName="SubscriptionContext";const Dr=t.memo(function({children:r}){const s=Er(e=>e.workspaces.currentWorkspace),{subscription:n,loading:a,error:o,refetch:i}=Wr(s?._id);t.useEffect(()=>ye(i),[i]);const c=t.useMemo(()=>({response:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return e.jsx(Or.Provider,{value:c,children:r})});function Lr(){const e=t.useContext(Or);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}Dr.displayName="SubscriptionContextProvider";const Mr=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Cr(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void i(!1);const t=u();i(!0),l(null);try{const r=await s.getCreditBalance(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=O(s,"errors.fetchCreditBalance",r);l(n),T(s,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{d(t)&&i(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{balance:n,loading:o,error:c,refetch:p}},$r=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(!1),[o,i]=t.useState(null);return{consumeCredits:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),i(null);try{const r=await s.consumeCredits(e,t);return me(),r}catch(s){const n="INSUFFICIENT_CREDITS"===s.code?`Insufficient credits. Available: ${s.available}, requested: ${s.requested}`:O(s,"errors.consumeCredits",r);throw i(n),T(s,{component:"useConsumeCredits",action:"consumeCredits",metadata:{workspaceId:e,request:t}}),s}finally{a(!1)}},[s,e]),loading:n,error:o}},Br=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(!1),[o,i]=t.useState(null);return{purchaseCredits:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),i(null);try{return await s.purchaseCredits(e,t)}catch(s){const n=O(s,"errors.purchaseCredits",r);throw i(n),T(s,{component:"usePurchaseCredits",action:"purchaseCredits",metadata:{workspaceId:e,request:t}}),s}finally{a(!1)}},[s,e]),loading:n,error:o}},qr=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState([]),[o,i]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Cr(),p=t.useCallback(async()=>{if(!e)return u(),a([]),void i(!1);const t=u();i(!0),l(null);try{const r=await s.getCreditPackages(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=O(s,"errors.fetchCreditPackages",r);l(n),T(s,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{d(t)&&i(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{packages:n,loading:o,error:c,refetch:p}},Vr=()=>{const{t:e}=Sr(),{os:r,api:s}=Ar(),n=ie(r),[a,o]=t.useState([]),[i,c]=t.useState(),[l,u]=t.useState(!1),[d,p]=t.useState(null),{begin:h,settle:m}=Cr(),g=t.useCallback(async()=>{if(!n)return h(),o([]),void u(!1);const t=h();u(!0),p(null);try{const e=await s.getPublicCreditPackages();if(t.signal.aborted)return;o(e.packages||[]),c(e.notes)}catch(r){if(t.signal.aborted)return;const s=O(r,"errors.fetchCreditPackages",e);p(s),T(r,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{m(t)&&u(!1)}},[s,n,h,m]);t.useEffect(()=>{g()},[g]);return{packages:a,notes:i,loading:!n||l,error:d,refetch:g}},zr=t.createContext(null);zr.displayName="CreditBalanceContext";const Gr=t.memo(function({children:r}){const s=Er(e=>e.workspaces.currentWorkspace),{balance:n,loading:a,error:o,refetch:i}=Mr(s?._id);t.useEffect(()=>he(i),[i]);const c=t.useMemo(()=>({balance:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return e.jsx(zr.Provider,{value:c,children:r})});function Jr(){const e=t.useContext(zr);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}Gr.displayName="CreditBalanceContextProvider";const Kr=({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 "})]}),Yr=({children:t,message:r="Loading...",backgroundColor:s})=>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:s??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:r}),t??e.jsx(Kr,{message:r}),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 "})]});Yr.displayName="FullScreenLoader";const Hr=t.createContext(null),Qr=({children:r,loadingComponent:s})=>{const[n,a]=t.useState({visible:!1,message:""}),o=t.useRef(null),i=t.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),c=t.useCallback(()=>{i(),a({visible:!1,message:""})},[i]),l=t.useCallback(e=>{i(),a({visible:!0,message:e}),o.current=setTimeout(()=>{T(new Error("FullScreenLoader timed out — auto-hiding after 60s"),{component:"FullScreenLoaderProvider",action:"timeout"}),a({visible:!1,message:""})},6e4)},[i]);t.useEffect(()=>()=>i(),[i]);const u=t.useMemo(()=>({show:l,hide:c,visible:n.visible,message:n.message}),[l,c,n.visible,n.message]),d="function"==typeof s?s({message:n.message}):s;return e.jsxs(Hr.Provider,{value:u,children:[r,n.visible&&e.jsx(Yr,{message:n.message,children:d})]})};function Zr(){const e=t.useContext(Hr);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}Qr.displayName="FullScreenLoaderProvider";const Xr=t.createContext({appPermissions:void 0});function es({appPermissions:r,children:s}){const n=t.useMemo(()=>({appPermissions:r}),[r]);return e.jsx(Xr.Provider,{value:n,children:s})}function ts(){return t.useContext(Xr)}const rs=t.createContext(null);rs.displayName="QuotaUsageContext";const ss=t.memo(function({children:r}){const s=Er(e=>e.workspaces.currentWorkspace),{quotas:n,loading:a,error:o,refetch:i}=_r(s?._id);t.useEffect(()=>fe(i),[i]);const c=t.useMemo(()=>({quotas:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return e.jsx(rs.Provider,{value:c,children:r})});function ns(){const e=t.useContext(rs);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}ss.displayName="QuotaUsageContextProvider";const as=t.createContext({});function os({ui:r,children:s}){const n=t.useMemo(()=>r??{},[r]);return e.jsx(as.Provider,{value:n,children:s})}function is(){return t.useContext(as)}function cs(e,t){if(!e||!t||"object"!=typeof e||"object"!=typeof t||Array.isArray(e)||Array.isArray(t))return t;const r={...e};for(const[e,s]of Object.entries(t))r[e]=e in r?cs(r[e],s):s;return r}const ls="saas-oauth-state";function us(){M(ls)}const ds={Profile:"profile",Security:"security",ConnectedAgents:"connected-agents",General:"general",Users:"users",Subscription:"subscription",Usage:"usage",Credits:"credits",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"},ps=new Set(Object.values(ds));const hs=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:ds.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||ds.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)})}},ms=()=>{const e=Pr(),{os:r,api:s}=Ar(),{settings:n}=jr(),a=Er(e=>e.workspaces),o=Er(e=>e.auth.session?.user),i=t.useCallback((t,r)=>{if((!(t._id===a.currentWorkspace?._id)||r?.forceEmit)&&t){const r=a.currentWorkspace;nt(t),e.workspaces(Kt(t)),ue.emitWorkspaceChanged(t,r).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceChanged",metadata:{workspaceId:t._id}})})}},[a.currentWorkspace,e]),c=t.useCallback(async(t,s)=>{const n=++h.current;e.workspaces(er(t._id));try{const e=r.auth?.callbacks?.onWorkspaceChange;if(e){const r=lt(t,o?.id);try{await e({workspace:t,user:o??null,role:r})}catch(e){throw T(e,{component:"useSaaSWorkspaces",action:"onWorkspaceChange",metadata:{workspaceId:t._id}}),e}if(n!==h.current)return}i(t,s)}finally{n===h.current&&e.workspaces(er(null))}},[e,r.auth?.callbacks?.onWorkspaceChange,i,o]),l=t.useRef(c);l.current=c,t.useEffect(()=>{if(!a.isInitialized){const t=at();if(e.workspaces(Ht(!0)),t){const e=a.workspaces.find(e=>e._id===t);e&&l.current(e,{forceEmit:!0}).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"initWorkspaceSwitch",metadata:{savedWorkspaceId:t}})})}}},[a.isInitialized,a.workspaces,e]);const u=t.useCallback(()=>{ot(),e.workspaces(Yt())},[e]),d=t.useRef(!1),p=t.useRef(!1),h=t.useRef(0),m=t.useCallback(async()=>{if(!a.loading&&!d.current){d.current=!0,e.workspaces(Qt(!0)),e.workspaces(Zt(null));try{const t=await s.getWorkspaces();if(e.workspaces(qt(t)),t.length>0){const e=at();if(e&&it(e,t)){const r=t.find(t=>t._id===e);if(r)try{await c(r,{forceEmit:!0})}catch{}}else{const e=t[0];try{await c(e,{forceEmit:!0})}catch{}}}}catch(t){e.workspaces(Zt(t instanceof Error?t.message:"Failed to fetch workspaces"))}finally{e.workspaces(Qt(!1)),d.current=!1}}},[s,a.loading,e,c]),g=t.useCallback(async()=>{if(!a.refreshing&&!d.current){d.current=!0,e.workspaces(Xt(!0));try{const t=await s.getWorkspaces();e.workspaces(qt(t))}catch(e){}finally{e.workspaces(Xt(!1)),d.current=!1}}},[s,a.refreshing,e]),f=t.useRef(null);t.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const b=t.useCallback(async(t,r)=>{const n=await s.createWorkspace({name:t,image:r});e.workspaces(Vt(n)),await c(n),ue.emitWorkspaceCreated(n).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceCreated",metadata:{workspaceId:n._id}})}),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{f.current=null,hs.openWorkspaceSettings(ds.Subscription)},300)},[s,e,c]),w=t.useCallback(async(t,r)=>{const n=await s.updateWorkspace(t._id,r);e.workspaces(zt(n)),ue.emitWorkspaceUpdated(n).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceUpdated",metadata:{workspaceId:n._id}})})},[s,e]),y=t.useCallback(async()=>{if(p.current)return a.allFeatures.length>0?a.allFeatures:null;if(a.allFeatures.length>0)return a.allFeatures;p.current=!0;try{const t=await s.getFeatures();return e.workspaces(Jt(t)),t}catch(e){return T(e,{component:"useSaaSWorkspaces",action:"getFeatures"}),null}finally{p.current=!1}},[s,e,a.allFeatures]),x=t.useCallback(async(e,t,r)=>await s.updateFeature(e,t,r),[s]),k=t.useCallback(async e=>s.updateSettings(e),[s]),v=t.useCallback(async(e,t)=>{const r=await s.updateWorkspacePermissions(e,t);return await g(),r},[s,g]);t.useEffect(()=>{if(!a.currentWorkspace?._id||0===a.workspaces.length)return;const t=a.currentWorkspace._id,r=a.workspaces.find(e=>e._id===t);if(r)r!==a.currentWorkspace&&(nt(r),e.workspaces(Kt(r)));else if(a.workspaces.length>0){const e=a.workspaces[0];e._id!==t&&c(e).catch(t=>{T(t,{component:"useSaaSWorkspaces",action:"fallbackWorkspaceSwitch",metadata:{workspaceId:e._id}})})}},[a.workspaces,a.currentWorkspace,e,c]);const S=t.useCallback(async e=>await s.getWorkspaceUsers(e),[s]),C=t.useCallback(async(e,t,r)=>{const o=a.workspaces.find(t=>t._id===e);if(o){const e=tt({settingsMaxUsers:n?.workspace?.maxWorkspaceUsers}),t=rt({memberCount:o.users?.length??0,maxUsersConfig:e});if(!t.canInvite)throw new Error(t.blockMessageKey||"users.memberLimitReached")}const i=await s.addUser(e,{email:t,role:r});return o&&ue.emitWorkspaceUserAdded(i.userId,o,r).catch(t=>{T(t,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserAdded",metadata:{workspaceId:e,userId:i.userId,role:r}})}),g().catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"refreshAfterAddUser"})}),xe(),i},[s,a.workspaces,g,n]),P=t.useCallback(async(e,t)=>{const r=a.workspaces.find(t=>t._id===e);if(r&&ct(r,t))throw new Error("Cannot remove the workspace owner");const n=(await s.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t),o=await s.removeUser(e,t);if(r&&n){const t=n.role;ue.emitWorkspaceUserRemoved(o.userId,r,t).catch(r=>{T(r,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRemoved",metadata:{workspaceId:e,userId:o.userId,role:t}})})}return g().catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"refreshAfterRemoveUser"})}),xe(),o},[s,a.workspaces,g]),E=t.useCallback(async(e,t,r)=>{if(r.role){const r=a.workspaces.find(t=>t._id===e);if(r&&ct(r,t))throw new Error("Cannot change the role of the workspace owner")}let n;if(r.role){const r=(await s.getWorkspaceUsers(e).catch(()=>[])).find(e=>("string"==typeof e.user?e.user:e.user._id)===t);n=r?.role}const o=await s.updateUser(e,t,r);return r.role&&n&&n!==r.role&&ue.emitWorkspaceUserRoleChanged(o.userId,o.workspace,n,r.role).catch(s=>{T(s,{component:"useSaaSWorkspaces",action:"emitWorkspaceUserRoleChanged",metadata:{workspaceId:e,userId:t,previousRole:n,newRole:r.role}})}),o},[s,a.workspaces]),N=t.useCallback(async e=>{const t=await s.getProfile().catch(()=>null),r=await s.updateUserProfile(e);return ue.emitUserUpdated(r,t||void 0).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"emitUserUpdated",metadata:{userId:r._id}})}),r},[s]),I=t.useCallback(async()=>await s.getProfile(),[s]),R=t.useCallback(async e=>await s.getWorkspace(e),[s]),j=t.useCallback(async t=>{if(!o)throw new Error("User must be authenticated to delete a workspace");const r=a.workspaces.find(e=>e._id===t);if(!r)throw new Error("Workspace not found");if(!ct(r,o.id))throw new Error("Only the workspace creator can delete the workspace");const n=await s.deleteWorkspace(t);return e.workspaces(Gt(t)),a.currentWorkspace?._id===t&&(ot(),e.workspaces(Yt())),r&&ue.emitWorkspaceDeleted(r).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceDeleted",metadata:{workspaceId:t}})}),n},[s,a.workspaces,a.currentWorkspace,e,o]);return{workspaces:a.workspaces,loading:a.loading,error:a.error,fetchWorkspaces:m,refreshWorkspaces:g,refreshing:a.refreshing,currentWorkspace:a.currentWorkspace,setCurrentWorkspace:i,switchToWorkspace:c,resetCurrentWorkspace:u,createWorkspace:b,allFeatures:a.allFeatures,getFeatures:y,updateFeature:x,updateWorkspaceSettings:k,updateWorkspacePermissions:v,getWorkspace:R,updateWorkspace:w,getUsers:S,addUser:C,removeUser:P,updateUser:E,getProfile:I,updateUserProfile:N,deleteWorkspace:j,switching:null!==a.switchingToId,switchingToId:a.switchingToId}};function gs(e,t,r){const s=e._id||e.id;if(!s||"string"!=typeof s)throw new Error("User data missing required ID field");if(!e.email||"string"!=typeof e.email)throw new Error("User data missing required email field");return{id:s,name:e.name||"",org:t,email:e.email,emailVerified:!1!==e.emailVerified,clientId:r,role:e.role||"",image:e.image}}function fs(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function bs(){return Er(e=>e.auth)}function ws(){const{t:e}=Sr(),r=Pr(),s=bs(),n=Ir(),{serverUrl:a,orgId:o,auth:i}=n,{resetCurrentWorkspace:c,currentWorkspace:l}=ms(),u=Zr(),d=t.useMemo(()=>new X({serverUrl:a,version:n.version}),[a,n.version]),p=t.useCallback(async t=>{We(t||window.location.href),r.auth(wt()),u.show(e("loading.redirecting"));try{const t=function(){const e=new Uint8Array(32);crypto.getRandomValues(e);const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return L(ls,t),t}(),s=await d.requestAuth({orgId:o,clientId:i?.clientId??"",redirect:{success:i?.redirectUrl||window.location.href,error:i?.redirectUrl||window.location.href},state:t});if(!s.success)throw u.hide(),r.auth(xt()),new Error(s.message||e("errors.generic"));je(s.data.redirectUrl)}catch(e){throw u.hide(),r.auth(xt()),T(e,{component:"useSaaSAuth",action:"signIn"}),e}},[d,o,i,r,u,e]),h=t.useCallback(async()=>{try{i?.callbacks?.onSignOut&&"function"==typeof i.callbacks.onSignOut&&await i.callbacks.onSignOut()}catch(e){T(e,{component:"useSaaSAuth",action:"signOut"})}finally{z(),r.auth(vt()),c()}},[r,c,i?.callbacks?.onSignOut]),m=t.useCallback(e=>{l?hs.openWorkspaceSettings(e):T(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),g=t.useCallback(()=>{l?hs.openWorkspaceSettings(ds.Credits,{action:ve.OpenCreditStore}):T(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),f=t.useCallback(()=>{l?hs.openWorkspaceSettings(ds.Subscription,{action:ve.SelectPlan}):T(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),b=t.useMemo(()=>ft(s.status),[s.status]);return t.useMemo(()=>({user:s.session?.user,session:s.session,status:s.status,...b,signIn:p,signOut:h,openWorkspaceSettings:m,openCreditStore:g,openPlanPicker:f}),[s.session,s.status,b,p,h,m,g,f])}const ys=t.memo(({children:r,callbacks:s})=>{const{t:n}=Sr(),a=Pr(),o=bs(),i=Ir(),c=ft(o.status).isAuthenticated,l=Zr(),u=t.useRef(!1),d=t.useRef(null),p=t.useRef(!1),h=t.useRef(null),m=t.useCallback(async e=>{try{if(s?.handleAuthentication){l.show(n("loading.signingIn"));const{sessionId:t}=await s.handleAuthentication(e);if(!t||"string"!=typeof t||""===t.trim())throw new Error("Invalid sessionId received from authentication callback");const r=i;if(!ie(r))throw new Error("OS configuration is not available");const{serverUrl:o,version:c,orgId:u}=r;l.show(n("loading.verifyingAccount"));const d=new X({serverUrl:o,version:c}),p=await d.getProfile(t),h=fs(gs(p,u,r.auth?.clientId||""),t);l.show(n("loading.almostThere")),V(h.sessionId),a.auth(kt(h)),K();const m=Fe();m&&m!==window.location.href&&je(m),l.hide()}}catch(t){throw l.hide(),Fe(),T(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),a.auth(xt()),t}},[a,s,i,l,n]);return t.useEffect(()=>{if("undefined"==typeof window)return;if(c)return;if(p.current)return;if(h.current)return;if(!ie(i))return;if(J())return;if(!s?.getSession)return p.current=!0,void a.auth(xt());const e=s.getSession,{serverUrl:t,version:r,orgId:o}=i,u=i.auth?.clientId||"";h.current=(async()=>{l.show(n("loading.restoringSession"));let i=null;try{i=await e()}catch(e){T(e,{component:"AuthProviderWrapper",action:"getSession"})}if(!i)return p.current=!0,a.auth(xt()),l.hide(),"undefined"!=typeof window&&We(window.location.href),void s?.onSessionExpired?.("missing");try{l.show(n("loading.verifyingAccount"));const e=new X({serverUrl:t,version:r}),s=await e.getProfile(i),c=fs(gs(s,o,u),i);V(c.sessionId),p.current=!0,a.auth(kt(c)),l.hide();const d=Fe();d&&d!==window.location.href&&je(d)}catch(e){T(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),p.current=!0,a.auth(xt()),l.hide(),"undefined"!=typeof window&&We(window.location.href),s?.onSessionExpired?.("expired")}finally{h.current=null}})()},[c,a,i,s]),t.useEffect(()=>{const e=J();if(!e)return;if(u.current||d.current===e)return;if(!ie(i))return;const t=function(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get(q)}catch(e){return T(e,{component:"auth-utils",action:"getStateFromUrl",metadata:{param:q}}),null}}();if(t&&!function(e){if(!e)return!1;const t=D(ls);if(M(ls),!t)return!1;if(t.length!==e.length)return!1;let r=0;for(let s=0;s<t.length;s++)r|=t.charCodeAt(s)^e.charCodeAt(s);return 0===r}(t))return us(),K(),T(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void a.auth(xt());us(),u.current=!0,d.current=e;let r=!1;return a.auth(yt()),m(e).then(()=>{r||(d.current=null)}).catch(e=>{r||(T(e,{component:"AuthProviderWrapper",action:"handleAuthRedirectEffect",metadata:{hasCode:!0}}),K(),d.current=null)}).finally(()=>{u.current=!1}),()=>{r=!0}},[m,i.serverUrl,i.version,i.orgId]),e.jsx(e.Fragment,{children:r})});ys.displayName="AuthProviderWrapper";const xs=t.memo(({config:r,auth:s,children:n})=>{const a=Pr();Ir();const o=t.useMemo(()=>({clientId:s?.clientId||"",redirectUrl:s?.redirectUrl||"",callbacks:s?.callbacks}),[s?.clientId,s?.redirectUrl,s?.callbacks]);return t.useEffect(()=>{a.os(Ft({...r,auth:o}))},[r,o,a]),e.jsx(e.Fragment,{children:n})});xs.displayName="ContextConfigProvider";const ks=t.createContext({container:null,setContainer:()=>{}}),vs=t.memo(({children:r})=>{const[s,n]=t.useState(null),a=t.useMemo(()=>({container:s,setContainer:n}),[s]);return e.jsxs(ks.Provider,{value:a,children:[r,e.jsx("div",{ref:n,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});vs.displayName="PortalProvider";const Ss=t.createContext(null);function Cs(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}const Ps=t.memo(function({children:r,serviceWorkerPath:s="/push-sw.js",autoSubscribe:n=!1}){const{t:a}=Sr(),o=Ir(),{isAuthenticated:i}=ws(),c=t.useMemo(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=t.useMemo(()=>new se({serverUrl:o.serverUrl,version:o.version,orgId:o.orgId}),[o.serverUrl,o.version,o.orgId]),[u,d]=t.useState({permission:c?Notification.permission:"default",isSubscribed:!1,isSupported:c,loading:!1,error:null});t.useEffect(()=>{if(!i||!c)return;let e=!1;return(async()=>{try{const t=await navigator.serviceWorker.getRegistration(s);if(e)return;if(!t)return void d(e=>({...e,isSubscribed:!1}));const r=await t.pushManager.getSubscription();if(e)return;d(e=>({...e,isSubscribed:!!r,permission:Notification.permission}))}catch{e||d(e=>({...e,isSubscribed:!1}))}})(),()=>{e=!0}},[i,c,s]);const p=t.useCallback(async()=>{if(!c)return!1;const e=await Notification.requestPermission();return d(t=>({...t,permission:e})),"granted"===e},[c]),h=t.useCallback(async()=>{if(c&&i){d(e=>({...e,loading:!0,error:null}));try{if(!await p())return void d(e=>({...e,loading:!1,error:a("notifications.permissionDenied")}));const{publicKey:e}=await l.getVapidPublicKey(),t=await navigator.serviceWorker.register(s);await navigator.serviceWorker.ready;const r=(await t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Cs(e)})).toJSON();await l.subscribe({endpoint:r.endpoint,keys:{p256dh:r.keys.p256dh,auth:r.keys.auth}},navigator.userAgent),d(e=>({...e,isSubscribed:!0,loading:!1}))}catch(e){const t=e instanceof Error?e.message:a("push.failedToSubscribe");d(e=>({...e,loading:!1,error:t})),T(e,{component:"PushNotificationProvider",action:"subscribe"})}}},[c,i,l,s,p]),m=t.useCallback(async()=>{if(c){d(e=>({...e,loading:!0,error:null}));try{const e=await navigator.serviceWorker.getRegistration(s);if(e){const t=await e.pushManager.getSubscription();if(t){const e=t.endpoint;await t.unsubscribe(),await l.unsubscribe(e)}}d(e=>({...e,isSubscribed:!1,loading:!1}))}catch(e){const t=e instanceof Error?e.message:a("push.failedToUnsubscribe");d(e=>({...e,loading:!1,error:t})),T(e,{component:"PushNotificationProvider",action:"unsubscribe"})}}},[c,l,s]),g=t.useMemo(()=>({...u,requestPermission:p,subscribe:h,unsubscribe:m}),[u,p,h,m]);return e.jsx(Ss.Provider,{value:g,children:r})});const Es=t.createContext(void 0),Ns=t.memo(({children:r})=>{const{t:s}=Sr(),n=Ir(),a=function(){const e=Ir();return t.useMemo(()=>new ae(e),[e.serverUrl,e.version])}(),{isAuthenticated:o}=ws(),{serverUrl:i,version:c}=n,[l,u]=t.useState({}),[d,p]=t.useState({}),[h,m]=t.useState(!1),[g,f]=t.useState(!1),[b,w]=t.useState(null),[y,x]=t.useState(null),k=t.useCallback(async e=>{if(i&&c&&o){w(null);try{const t=await a.getAttributes(e);u(t)}catch(e){if(j(e))return;const t=e instanceof Error?e:new Error(s("errors.generic"));w(t),T(e,{component:"UserProvider",action:"fetchAttributes"})}}else u({})},[a,i,c,o,s]),v=t.useCallback(async()=>{if(i&&c&&o){m(!0);try{await k()}finally{m(!1)}}},[i,c,o,k]),S=t.useCallback(async e=>{m(!0),w(null);try{const t=await a.updateAttributes(e);return await k(),t}catch(t){const r=t instanceof Error?t:new Error(s("errors.generic"));throw w(r),T(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{m(!1)}},[a,k,s]),C=t.useCallback(async(e,t)=>{m(!0),w(null);try{const r=await a.updateAttribute(e,t);return await k(),r}catch(r){const n=r instanceof Error?r:new Error(s("errors.generic"));throw w(n),T(r,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),r}finally{m(!1)}},[a,k,s]),P=t.useCallback(async e=>{if(i&&c&&o){x(null);try{const t=await a.getFeatures(e);p(t)}catch(e){if(j(e))return;const t=e instanceof Error?e:new Error(s("errors.generic"));x(t),T(e,{component:"UserProvider",action:"fetchFeatures"})}}else p({})},[a,i,c,o,s]),E=t.useCallback(async()=>{if(i&&c&&o){f(!0);try{await P()}finally{f(!1)}}},[i,c,o,P]);Nr(async e=>{if(!o||!i||!c)return u({}),void p({});m(!0),f(!0),await Promise.all([k(e).finally(()=>m(!1)),P(e).finally(()=>f(!1))])},[o,i,c,k,P],{onError:e=>T(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const N=t.useMemo(()=>({attributes:l,features:d,isLoading:h||g,error:b??y,attributesLoading:h,featuresLoading:g,attributesError:b,featuresError:y,updateAttributes:S,updateAttribute:C,refreshAttributes:v,refreshFeatures:E}),[l,d,h,g,b,y,S,C,v,E]);return e.jsx(Es.Provider,{value:N,children:r})});Ns.displayName="UserProvider";const Is=c.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"}}),Rs=y.forwardRef(({className:t,variant:r,progress:s,size:n,startIcon:a,endIcon:o,asChild:c=!1,...u},d)=>{const p=c?i.Slot:"button",h=function(e){switch(e){case"lg":return 20;case"sm":return 14;default:return 16}}(n);return e.jsxs(p,{disabled:s||u.disabled,className:E(Is({variant:r,size:n,withIcon:null!=s||null!=a||null!=o,className:t})),ref:d,...u,children:[s&&e.jsx(l.Loader2,{size:h,className:"animate-spin"}),a&&y.cloneElement(a,{size:h}),u.children,o&&y.cloneElement(o,{size:h})]})});Rs.displayName="Button";const js=v.Root,As=v.Trigger,Us=v.Portal,Ws=y.forwardRef(({className:t,...r},s)=>e.jsx(v.Overlay,{ref:s,className:E("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),...r}));Ws.displayName=v.Overlay.displayName;const Fs=y.forwardRef(({className:t,children:r,...s},n)=>{const{container:a}=y.useContext(ks);return e.jsxs(Us,{container:a,children:[e.jsx(Ws,{}),e.jsxs(v.Content,{ref:n,className:E("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),...s,children:[r,e.jsxs(v.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(m.Cross2Icon,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Fs.displayName=v.Content.displayName;const Ts=({className:t,...r})=>e.jsx("div",{className:E("flex flex-col space-y-1.5 text-center sm:text-start",t),...r});Ts.displayName="DialogHeader";const _s=y.forwardRef(({className:t,...r},s)=>e.jsx(v.Title,{ref:s,className:E("text-lg font-semibold leading-none tracking-tight",t),...r}));_s.displayName=v.Title.displayName;const Os=y.forwardRef(({className:t,...r},s)=>e.jsx(v.Description,{ref:s,className:E("text-sm text-muted-foreground",t),...r}));function Ds(e){const{user:r}=ws(),{currentWorkspace:s}=ms(),{settings:n}=jr(),{appPermissions:a}=ts(),o=e??s??null,i=r?.id??null,c=t.useMemo(()=>o?lt(o,i):null,[o,i]),l=t.useMemo(()=>!!o&&ct(o,i),[o,i]),u=t.useMemo(()=>mt({userId:i,workspaceRole:c,workspace:o,settings:n,appPermissions:a}),[i,c,o,n,a]);return{can:t.useCallback(e=>Array.isArray(e)?e.every(e=>u.has(e)):u.has(e),[u]),permissions:u,isOwner:l,role:c}}function Ls(){const e=is(),{can:r}=Ds();return{visible:t.useCallback((t,s)=>!1!==t(e)&&(void 0===s||r(s)),[e,r]),ui:e}}function Ms(){const e=Ir();return t.useMemo(()=>new re(e),[e.serverUrl,e.version])}function $s(){const e=Ms(),[r,s]=t.useState([]),[n,a]=t.useState(!0),[o,i]=t.useState(null),[c,l]=t.useState(null),u=t.useRef(null),d=t.useCallback(async()=>{u.current?.abort();const t=new AbortController;u.current=t,a(!0),i(null);try{const r=await e.list(t.signal);t.signal.aborted||s(r)}catch(e){if(t.signal.aborted)return;_(e,{component:"useConnectedAgents",action:"list"}),i(e instanceof Error?e.message:"Failed to load")}finally{u.current===t&&(u.current=null,a(!1))}},[e]);t.useEffect(()=>(d(),()=>u.current?.abort()),[d]);const p=t.useCallback(async t=>{l(t),i(null);try{await e.revoke(t),s(e=>e.filter(e=>e.clientId!==t))}catch(e){_(e,{component:"useConnectedAgents",action:"revoke"}),i(e instanceof Error?e.message:"Failed to disconnect")}finally{l(null)}},[e]);return t.useMemo(()=>({agents:r,loading:n,error:o,revoking:c,refresh:d,revoke:p}),[r,n,o,c,d,p])}function Bs({icon:t,title:r,description:s,action:n,className:a}){return e.jsxs("div",{className:E("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}),r&&e.jsx("p",{className:"text-sm font-medium",children:r}),s&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s}),n]})}function qs({title:t,description:r,actions:s,className:n,titleClassName:a}){return t||r||s?e.jsxs("div",{className:E(n),children:[(t||s)&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t&&e.jsx("h3",{className:E("text-sm font-medium",a),children:t}),s]}),r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r})]}):null}function Vs({className:t,...r}){return e.jsx("div",{className:E("animate-pulse rounded-md bg-primary/10",t),...r})}Os.displayName=v.Description.displayName;const zs={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"}};const Gs=c.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Js=y.forwardRef(({className:t,...r},s)=>e.jsx(x.Root,{ref:s,className:E(Gs(),t),...r}));Js.displayName=x.Root.displayName;const Ks=o.FormProvider,Ys=y.createContext({}),Hs=({...t})=>e.jsx(Ys.Provider,{value:{name:t.name},children:e.jsx(o.Controller,{...t})}),Qs=()=>{const e=y.useContext(Ys),t=y.useContext(Zs),{getFieldState:r,formState:s}=o.useFormContext(),n=r(e.name,s);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`,...n}},Zs=y.createContext({}),Xs=y.forwardRef(({className:t,...r},s)=>{const n=y.useId();return e.jsx(Zs.Provider,{value:{id:n},children:e.jsx("div",{ref:s,className:E("space-y-2",t),...r})})});Xs.displayName="FormItem";const en=y.forwardRef(({className:t,...r},s)=>{const{error:n,formItemId:a}=Qs();return e.jsx(Js,{ref:s,className:E(n&&"text-destructive",t),htmlFor:a,...r})});en.displayName="FormLabel";const tn=y.forwardRef(({...t},r)=>{const{error:s,formItemId:n,formDescriptionId:a,formMessageId:o}=Qs();return e.jsx(i.Slot,{ref:r,id:n,"aria-describedby":s?`${a} ${o}`:`${a}`,"aria-invalid":!!s,...t})});tn.displayName="FormControl";const rn=y.forwardRef(({className:t,...r},s)=>{const{formDescriptionId:n}=Qs();return e.jsx("p",{ref:s,id:n,className:E("text-sm text-muted-foreground",t),...r})});rn.displayName="FormDescription";const sn=y.forwardRef(({className:t,children:r,...s},n)=>{const{error:a,formMessageId:o}=Qs(),i=a?String(a?.message):r;return i?e.jsx("p",{ref:n,id:o,className:E("text-sm font-medium text-destructive",t),...s,children:i}):null});sn.displayName="FormMessage";const nn=y.forwardRef(({className:t,type:r,...s},n)=>e.jsx("input",{type:r,className:E("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:n,...s}));nn.displayName="Input";const an=y.forwardRef(({className:t,...r},s)=>e.jsx(S.Root,{className:E("grid gap-2",t),...r,ref:s}));an.displayName=S.Root.displayName;const on=y.forwardRef(({className:t,...r},s)=>e.jsx(S.Item,{ref:s,className:E("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),...r,children:e.jsx(S.Indicator,{className:"flex items-center justify-center",children:e.jsx(m.CheckIcon,{className:"h-3.5 w-3.5 fill-primary"})})}));on.displayName=S.Item.displayName;const cn=y.forwardRef(({className:t,children:r,...s},n)=>e.jsxs(C.Root,{ref:n,className:E("relative overflow-hidden",t),...s,children:[e.jsx(C.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e.jsx(ln,{}),e.jsx(C.Corner,{})]}));cn.displayName=C.Root.displayName;const ln=y.forwardRef(({className:t,orientation:r="vertical",...s},n)=>e.jsx(C.ScrollAreaScrollbar,{ref:n,orientation:r,className:E("flex touch-none select-none transition-colors","vertical"===r&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===r&&"h-2.5 border-t border-t-transparent p-[1px]",t),...s,children:e.jsx(C.ScrollAreaThumb,{className:E("relative rounded-full bg-border","vertical"===r&&"flex-1")})}));function un(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>`}ln.displayName=C.ScrollAreaScrollbar.displayName;const dn=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑💻","👨💻","👩💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨💼","👩💼","👨🏫","👩🏫","👨🔬","👩🔬","👨🎨","👩🎨","👨🔧","👩🔧","👨🚀","👩🚀","👨⚖️","👩⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️🌈","🎟️","🎫"];const pn=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-B28WJsAr.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));const hn=({children:r})=>{const{currentWorkspace:s,switchToWorkspace:n,workspaces:a}=ms(),[o,i]=t.useState(!1),[c,l]=t.useState(ds.Profile),u=t.useRef(!1);return t.useEffect(()=>{const e=hs.getState();i(e.open),l(e.section);return hs.subscribe(e=>{i(e.open),l(e.section)})},[]),t.useEffect(()=>{if(u.current)return;if(!s)return;const e=Ne();if(!e)return;const t=function(e){if(e.screen&&ps.has(e.screen))return e.screen;switch(e.action){case ve.Checkout:case ve.Billing:case ve.SelectPlan:return ds.Subscription;case ve.CreditPurchase:return ds.Credits;default:return null}}(e);if(!t)return u.current=!0,void Ie();const r=e.ws;if(r&&r!==s._id){const e=a.find(e=>e._id===r);return e?void n(e).catch(e=>{T(e,{component:"WorkspaceSettingsProvider",action:"switchWorkspaceFromUrl",metadata:{targetWs:r}}),u.current=!0,Ie()}):(u.current=!0,void Ie())}u.current=!0,hs.openWorkspaceSettings(t,e),Ie()},[s,a,n]),e.jsxs(e.Fragment,{children:[r,s&&o&&e.jsx(bt,{fallback:null,children:e.jsx(t.Suspense,{fallback:null,children:e.jsx(pn,{workspace:s,open:o,onOpenChange:e=>{e||hs.closeSettings()},section:c,onSectionChange:e=>{hs.setSection(e)},showTrigger:!1})})})]})},mn=(e,t,r)=>{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(!r||"string"!=typeof r)throw new Error("orgId is required and must be a string");if(!/^[0-9a-fA-F]{24}$/.test(r))throw new Error(`Invalid orgId: "${r}". Must be a valid MongoDB ObjectId (24 hexadecimal characters).`)},gn=t.memo(({serverUrl:r,version:s,orgId:n,auth:a,locale:o,defaultPermissions:i,getCheckoutStripeParams:c,loadingComponent:l,ui:u,children:d})=>{mn(r,s,n);const p=t.useMemo(()=>({serverUrl:r,version:s,orgId:n}),[r,s,n]),h=t.useMemo(()=>a?.callbacks,[a?.callbacks?.handleAuthentication,a?.callbacks?.onSignOut,a?.callbacks?.getSession,a?.callbacks?.onSessionExpired,a?.callbacks?.handleEvent,a?.callbacks?.onWorkspaceChange]),m=a?.callbacks?.handleEvent;return t.useEffect(()=>(ue.setCallbacks(m?{handleEvent:m}:null),()=>{ue.setCallbacks(null)}),[m]),e.jsx(fr,{locale:o,messageOverrides:u?.messages,children:e.jsx(ir,{children:e.jsx(Qr,{loadingComponent:l,children:e.jsx(ys,{callbacks:h,children:e.jsx(vs,{children:e.jsx(xs,{config:p,auth:a,children:e.jsx(lr,{getCheckoutStripeParams:c,children:e.jsx(es,{appPermissions:i,children:e.jsx(os,{ui:u,children:e.jsx(Ns,{children:e.jsx(Dr,{children:e.jsx(ss,{children:e.jsx(Gr,{children:e.jsx(Ps,{children:e.jsx(hn,{children:d})})})})})})})})})})})})})})})});gn.displayName="SaaSOSProviderInner";const fn=({children:t,...r})=>e.jsx(bt,{errorTitle:r.ui?.errorBoundary?.title,retryLabel:r.ui?.errorBoundary?.retryLabel,children:e.jsx(gn,{...r,children:t})});fn.displayName="SaaSOSProvider";const bn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{status:n}=ws();return ft(n).isLoading?r??null:n!==exports.AuthStatus.authenticated?s??null:t},wn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{status:n}=ws();return ft(n).isLoading?r??null:n!==exports.AuthStatus.unauthenticated?s??null:t};bn.displayName="WhenAuthenticated",wn.displayName="WhenUnauthenticated";const yn=e=>{const{children:t,fallback:r,roles:s}=e,{user:n}=ws();return s.includes(n?.role??"")?t:r||null},xn=e=>{const{children:t,fallback:r,roles:s}=e,{user:n}=ws(),{currentWorkspace:a}=ms(),o=a?.users.find(e=>e._id===n?.id);return o&&s.includes(o?.role??"")?t:r||null};yn.displayName="WhenRoles",xn.displayName="WhenWorkspaceRoles";const kn=e=>{const{children:t,fallback:r,permission:s}=e,{can:n}=Ds();return n(s)?t:r??null};function vn(){const e=t.useContext(Es);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return{features:e.features,isLoading:e.featuresLoading,error:e.featuresError,refreshFeatures:e.refreshFeatures,isFeatureEnabled:t=>Boolean(e.features[t])}}kn.displayName="WhenPermission";const Sn=e=>{const{children:t,slug:r}=e,{currentWorkspace:s}=ms(),n=s?.features?.[r];return n?t:null},Cn=e=>{const{children:t,slug:r}=e,{currentWorkspace:s}=ms(),n=s?.features?.[r];return n?null:t},Pn=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:s}=vn();return s(r)?t:null},En=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:s}=vn();return s(r)?null:t};Sn.displayName="WhenWorkspaceFeatureEnabled",Cn.displayName="WhenWorkspaceFeatureDisabled",Pn.displayName="WhenUserFeatureEnabled",En.displayName="WhenUserFeatureDisabled";const Nn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Lr();return a?r??null:n?.subscription?t:s??null},In=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Lr();return a?r??null:n?.subscription?s??null:t},Rn=e=>{const{children:t,plans:r,loadingComponent:s,fallbackComponent:n}=e,{response:a,loading:o}=Lr();if(o)return s??null;if(!a?.subscription)return n??null;const i=a.plan??a.subscription?.plan;if(!i)return n??null;const c=r.map(e=>e.trim().toLowerCase()),l=(i.slug??"").toLowerCase();return c.includes(l)?t:n??null},jn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Lr();return a?r??null:"trialing"!==n?.subscription?.subscriptionStatus?s??null:t},An=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Lr();return a?r??null:n?.subscription?.subscriptionStatus===Je.Trialing?s??null:t},Un=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{behavior:n}=is(),a=e.daysThreshold??n?.trialEndingDays??3,{response:o,loading:i}=Lr();if(i)return r??null;const c=o?.subscription;if(!c||"trialing"!==c.subscriptionStatus)return s??null;const l=c.trialEnd||c.stripeCurrentPeriodEnd;if(!l)return s??null;const u=new Date(l);if(isNaN(u.getTime()))return s??null;return Math.max(0,Math.ceil((u.getTime()-Date.now())/864e5))>a?s??null:t};Nn.displayName="WhenSubscription",In.displayName="WhenNoSubscription",Rn.displayName="WhenSubscriptionToPlans",jn.displayName="WhenTrialing",An.displayName="WhenNotTrialing",Un.displayName="WhenTrialEnding";const Wn=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:o}=ns();if(o)return s??null;const i=a?.[t];return i?i.available<=0?n??null:r:n??null},Fn=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:o}=ns();if(o)return s??null;const i=a?.[t];return i?i.available>0?n??null:r:n??null},Tn=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:o}=ns();if(o)return s??null;const i=a?.[t];return i&&i.hasOverage&&!1!==i.allowOverage?r:n??null},_n=e=>{const{slug:t,threshold:r,children:s,loadingComponent:n,fallbackComponent:a}=e,{quotas:o,loading:i}=ns();if(i)return n??null;const c=o?.[t];if(!c)return a??null;return(c.included>0?c.consumed/c.included*100:c.consumed>0?100:0)<r?a??null:s};Wn.displayName="WhenQuotaAvailable",Fn.displayName="WhenQuotaExhausted",Tn.displayName="WhenQuotaOverage",_n.displayName="WhenQuotaThreshold";const On=({children:e})=>{const{currentWorkspace:t}=ms(),r=t?._id,{balance:s,loading:n,error:a,refetch:o}=Jr(),{packages:i,loading:c}=qr(r),{consumeCredits:l,loading:u,error:d}=$r(r),{purchaseCredits:p,loading:h,error:m}=Br(r);return e({balance:s,loading:n,packages:i,packagesLoading:c,consume:l,consuming:u,purchase:async e=>{if(!r)throw new Error("No workspace selected");const{successUrl:t,cancelUrl:s}=Ee(r),n=await p({creditPackageId:e._id,successUrl:t,cancelUrl:s});n.url&&je(n.url)},purchasing:h,refetch:o,error:d||m||a})};On.displayName="CreditActionsProvider";const Dn=({children:e})=>{const{balance:t,loading:r,error:s,refetch:n}=Jr();return e({balance:t,loading:r,error:s,refetch:n})};Dn.displayName="CreditBalance";const Ln=e=>{const{min:t=1,children:r,loadingComponent:s,fallbackComponent:n}=e,{balance:a,loading:o}=Jr();return o?s??null:a?a.available<t?n??null:r:n??null},Mn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{balance:n,loading:a}=Jr();return a?r??null:n?n.available>0?s??null:t:s??null},$n=e=>{const{threshold:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{balance:a,loading:o}=Jr();return o?s??null:a?a.available>t?n??null:r:n??null};function Bn(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}Ln.displayName="WhenCreditsAvailable",Mn.displayName="WhenCreditsExhausted",$n.displayName="WhenCreditsLow";const qn=d.z.object({name:d.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:d.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 Vn({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 zn({logo:t}){const{t:r}=Sr();return"string"==typeof t?e.jsx("img",{src:t,alt:r("beta.logoAlt"),className:"max-h-24"}):e.jsx("img",{src:t.bucket?.url,alt:r("beta.logoAlt"),className:"max-h-24"})}const Gn=y.forwardRef(({className:t,...r},s)=>e.jsx(k.Root,{ref:s,className:E("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...r}));Gn.displayName=k.Root.displayName;const Jn=y.forwardRef(({className:t,...r},s)=>e.jsx(k.Image,{ref:s,className:E("aspect-square h-full w-full",t),...r}));Jn.displayName=k.Image.displayName;const Kn=y.forwardRef(({className:t,...r},s)=>e.jsx(k.Fallback,{ref:s,className:E("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...r}));Kn.displayName=k.Fallback.displayName;const Yn=y.forwardRef(({className:t,orientation:r="horizontal",decorative:s=!0,...n},a)=>e.jsx(P.Root,{ref:a,decorative:s,orientation:r,className:E("shrink-0 bg-border","horizontal"===r?"h-[1px] w-full":"h-full w-[1px]",t),...n}));Yn.displayName=P.Root.displayName;const Hn=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-B28WJsAr.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));function Qn(r){const{t:s}=Sr(),{visible:n}=Ls(),a=n(e=>e.workspaceSwitcher?.memberCount),o=n(e=>e.workspaceSwitcher?.planBadge),{workspace:i,setCurrentWorkspace:c,setOpen:u,workspacesToUse:d,switchingToId:p}=r,h=r.isCurrentWorkspace??!1,m=p===i._id,g=i.subscription??null,f=null!=g&&"object"==typeof g?g.plan??null:null,b=f?.name??"";return e.jsxs("div",{className:E("flex items-center gap-3 rounded-lg border-2 p-3 border-border",{"bg-muted text-muted-foreground":h}),children:[e.jsxs(Gn,{className:"h-8 w-8 flex items-center justify-center",children:[e.jsx("div",{children:e.jsx(Jn,{src:i.image&&i.image.trim()?i.image:void 0})}),e.jsx(Kn,{children:(w=i.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:i.name})}),a&&e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(l.Users,{className:"h-3 w-3"}),e.jsx("span",{children:s("workspace.membersCount",{count:i.users?.length||0})})]}),o&&b&&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:b})})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[h?null:e.jsx(Rs,{size:"sm",disabled:null!==p||m,progress:m,onClick:()=>{r.switchToWorkspace(i).then(()=>u(!1)).catch(e=>{T(e,{component:"WorkspaceItem",action:"switchToWorkspace",metadata:{workspaceId:i._id}})})},children:s("workspace.switchTo")}),e.jsx(t.Suspense,{fallback:null,children:e.jsx(Hn,{workspace:i,onClose:()=>{if(h){const e=d.findIndex(e=>e._id?.toString()===i._id?.toString());-1!==e&&c(d[e])}}})})]})]});var w}function Zn(r){const{t:s,dir:n}=Sr(),{switching:i}=ms(),[c,u]=t.useState(!1),[p,h]=t.useState("emoji"),[m,g]=t.useState("🏢"),[f,b]=t.useState(!1),{createWorkspace:w}=ms(),y=d.z.object({name:d.z.string().min(2,{message:s("workspace.workspaceNameMinLength")}),image:d.z.string().optional()}),x=o.useForm({resolver:a.zodResolver(y),defaultValues:{name:"",image:""}});return e.jsxs(js,{open:c,onOpenChange:u,children:[e.jsx(As,{asChild:!0,children:e.jsxs(Rs,{className:"w-full rounded-none",disabled:i,children:[e.jsx(l.Plus,{className:"h-4 w-4 me-2"}),s("workspace.createNew")]})}),e.jsxs(Fs,{dir:n,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e.jsxs(Ts,{children:[e.jsx(_s,{children:s("workspace.createTitle")}),e.jsx(Os,{children:s("workspace.createDescription")})]}),e.jsx(Ks,{...x,children:e.jsxs("form",{onSubmit:x.handleSubmit(async function(e){let t="";if("emoji"===p)t=un(m);else if("url"===p&&e.image)try{new URL(e.image),t=e.image}catch{return void x.setError("image",{message:s("workspace.invalidUrl")})}b(!0);try{await w(e.name,t),u(!1),x.reset(),g("🏢"),h("emoji"),r?.onCreated?.()}catch(t){T(t,{component:"WorkspaceProvider",action:"createWorkspace",metadata:{name:e.name}})}finally{b(!1)}}),children:[e.jsx(Hs,{control:x.control,name:"name",render:({field:t})=>e.jsxs(Xs,{children:[e.jsx(en,{children:s("workspace.workspaceName")}),e.jsx(tn,{children:e.jsx(nn,{placeholder:s("workspace.workspaceNamePlaceholder"),...t})}),e.jsx(sn,{})]})}),e.jsxs("div",{className:"flex flex-col gap-y-2 my-2",children:[e.jsxs("div",{children:[e.jsx(Js,{className:"text-sm font-medium",children:s("workspace.workspaceIcon")}),e.jsx(rn,{children:s("workspace.iconDescription")})]}),e.jsxs(an,{value:p,onValueChange:e=>h(e),className:"flex flex-col gap-y-2",children:[e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(on,{value:"emoji",id:"emoji"}),e.jsxs(Js,{htmlFor:"emoji",className:"flex items-center gap-2",children:[e.jsx(l.Smile,{className:"h-4 w-4"}),s("workspace.chooseEmoji")]})]}),e.jsxs("div",{className:"flex items-center gap-x-2 my-1",children:[e.jsx(on,{value:"url",id:"url"}),e.jsxs(Js,{htmlFor:"url",className:"flex items-center gap-2",children:[e.jsx(l.Image,{className:"h-4 w-4"}),s("workspace.customImageUrl")]})]})]}),"emoji"===p&&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:s("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(cn,{className:"h-32 w-full rounded-md border",children:e.jsx("div",{className:"p-4 grid grid-cols-8 gap-2",children:dn.map((t,r)=>e.jsx("button",{type:"button",onClick:()=>(e=>{g(e),x.setValue("image",un(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},r))})})]}),"url"===p&&e.jsxs("div",{className:"flex flex-col gap-y-2",children:[e.jsx(Hs,{control:x.control,name:"image",render:({field:t})=>e.jsxs(Xs,{children:[e.jsx(en,{children:s("workspace.imageUrl")}),e.jsx(tn,{children:e.jsx(nn,{placeholder:s("workspace.imageUrlPlaceholder"),...t})}),e.jsx(rn,{children:s("workspace.imageUrlDescription")}),e.jsx(sn,{})]})}),x.watch("image")&&x.watch("image")?.trim()&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:s("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:x.watch("image")||void 0,alt:s("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(Rs,{type:"button",variant:"outline",onClick:()=>{u(!1),x.reset(),g("🏢"),h("emoji")},disabled:f,children:s("settings.common.cancel")}),e.jsx(Rs,{type:"submit",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"me-2 h-4 w-4 animate-spin"}),s("workspace.creating")]}):s("workspace.createWorkspace")})]})]})})]})]})}exports.AuthApi=X,exports.BBAction=ve,exports.BBScreen=Ce,exports.BBStatus=Se,exports.BB_PARAM=ke,exports.BaseApi=Z,exports.BetaForm=({onSuccess:r,onError:s,className:n="w-full",fieldClassName:i="flex flex-col gap-1.5 w-full",autoFocus:c=!0,showSuccessMessage:l=!0,hideLogo:u=!1,hideTitles:d=!1})=>{const{t:p}=Sr(),[h,m]=t.useState(!1),[g,f]=t.useState(!1),{submitBetaForm:b,isLoading:w,isSubmitting:y,error:x,config:k,success:v,message:S}=(()=>{const{t:e}=Sr(),r=Ir(),[s,n]=t.useState(null),[a,o]=t.useState(!0),[i,c]=t.useState(!1),[l,u]=t.useState(null),[d,p]=t.useState(!1),[h,m]=t.useState(null);return t.useEffect(()=>{let t=!1;return(async()=>{o(!0),u(null);try{const e=new te(r),s=await e.fetchConfig();t||n(s)}catch(r){t||u(r instanceof Error?r.message:e("beta.errorMessage"))}finally{t||o(!1)}})(),()=>{t=!0}},[r]),{isLoading:a,isSubmitting:i,config:s,error:l,success:d,message:h,submitBetaForm:t.useCallback(async t=>{if(!r){const t=e("errors.generic");return u(t),{success:!1,message:t}}try{c(!0),u(null),p(!1),m(null);const e=new te(r),s=await e.submitBetaUser({name:t.name||"",email:t.email}),n="success"===s.status;return p(n),m(s.message),{success:n,message:s.message}}catch(t){const r=t instanceof Error?t.message:e("beta.errorMessage");return u(r),p(!1),m(r),{success:!1,message:r}}finally{c(!1)}},[r])}})();t.useEffect(()=>{v&&l&&(m(!0),f(!0)),x&&f(!0)},[v,l,x]);const C=o.useForm({resolver:a.zodResolver(qn),defaultValues:{email:"",name:""},mode:"onChange",reValidateMode:"onChange"});t.useEffect(()=>{c&&C.setFocus("name")},[c,C]);const P=C.formState.isValid&&!y;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:E("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",n),children:[e.jsx(Vs,{className:"h-24 w-24 rounded-lg"}),e.jsx(Vs,{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(Vs,{className:"h-4 w-16"}),e.jsx(Vs,{className:"h-10 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Vs,{className:"h-4 w-16"}),e.jsx(Vs,{className:"h-10 w-full"})]}),e.jsx(Vs,{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:[!u&&e.jsxs("div",{className:"flex flex-col items-center justify-center w-full",children:[k?.logo&&e.jsx(zn,{logo:k?.logo}),k?.name&&e.jsx("div",{children:k?.name})]}),e.jsx(o.FormProvider,{...C,children:e.jsxs("form",{onSubmit:C.handleSubmit(async e=>{try{const t=await b(e);t.success?(r?.(),C.reset(),l&&m(!0),f(!0)):(s?.(t.message),f(!0))}catch(e){s?.(e instanceof Error?e.message:p("beta.errorMessage")),f(!0)}}),className:n,noValidate:!0,"aria-busy":y,children:[!g&&e.jsxs(e.Fragment,{children:[!d&&k?.screen?.register&&e.jsx(Vn,{screen:k?.screen?.register}),e.jsx(Hs,{control:C.control,name:"name",render:({field:t})=>e.jsxs(Xs,{className:i,children:[e.jsx(en,{children:p("beta.nameLabel")}),e.jsx(tn,{children:e.jsx(nn,{...t})}),e.jsx(rn,{}),e.jsx(sn,{})]})}),e.jsx(Hs,{control:C.control,name:"email",render:({field:t})=>e.jsxs(Xs,{className:i,children:[e.jsx(en,{children:p("beta.emailLabel")}),e.jsx(tn,{children:e.jsx(nn,{...t})}),e.jsx(rn,{}),e.jsx(sn,{})]})}),e.jsx(Rs,{type:"submit",disabled:!P,className:i,children:p(y?"beta.submittingText":"beta.submitText")})]}),g&&x&&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:"❗"}),x]}),e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx(Rs,{type:"button",onClick:()=>{f(!1),C.reset()},className:i,children:p("beta.tryAgain")})})]}),g&&h&&S&&e.jsx("div",{className:"flex flex-col items-center justify-center w-full text-success border-success/30 text-center",children:k?.screen?.thankYou&&e.jsx(Vn,{screen:k?.screen?.thankYou})})]})}),!g&&e.jsx("div",{children:e.jsxs("div",{children:[p("beta.privacyConsent")," ",e.jsx("a",{href:k?.privacyPolicy,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:p("beta.privacyPolicy")})," ",p("beta.and")," ",e.jsx("a",{href:k?.termsOfService,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info",children:p("beta.termsOfService")}),"."]})})]})})},exports.BillingIntervals=Ge,exports.Button=Rs,exports.CURRENCY_DISPLAY=Te,exports.CURRENCY_FLAG=_e,exports.ConnectedAgents=function({className:t,title:r,description:s,disconnectLabel:n,emptyLabel:a}){const{t:o,formattingLocale:i}=Sr(),{formats:c}=is(),{agents:u,loading:d,error:p,revoking:h,revoke:m}=$s(),g=void 0===r?o("security.connectedAgentsTitle"):r,f=void 0===s?o("security.connectedAgentsDescription"):s,b=n??o("security.connectedAgentsDisconnect"),w=a??o("security.connectedAgentsEmpty"),y=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat(i,c?.date??{dateStyle:"medium"}).format(t)};return e.jsxs("div",{className:E("space-y-4",t),children:[e.jsx(qs,{title:g,description:f}),d&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(Vs,{className:"h-20 rounded-md"},t))}),p&&!d&&e.jsx("p",{className:"text-destructive text-sm",children:p}),!d&&!p&&0===u.length&&e.jsx(Bs,{icon:e.jsx(l.Bot,{className:"h-5 w-5 text-muted-foreground"}),description:w}),!d&&u.length>0&&e.jsx("ul",{className:"space-y-3",children:u.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 flex-col gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium",children:t.title}),t.scope.length>0&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:[o("security.connectedAgentsAccess"),": ",t.scope.join(", ")]}),t.lastGrantedAt&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:[o("security.connectedAgentsGranted"),": ",y(t.lastGrantedAt)]})]}),e.jsx(Rs,{variant:"outline",size:"sm",progress:h===t.clientId,onClick:()=>m(t.clientId),children:b})]},t.clientId))})]})},exports.ConnectedAgentsApi=re,exports.CreditActionsProvider=On,exports.CreditBalance=Dn,exports.CreditBalanceContextProvider=Gr,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:r,loadingFallback:s,errorFallback:n,redirectBaseUrl:a}){const{packages:o,notes:i,loading:c,error:l,refetch:u}=Vr(),{isAuthenticated:d,signIn:p}=ws(),h=t.useCallback(e=>{if(d)hs.openWorkspaceSettings(ds.Credits,{action:ve.CreditPurchase,packageId:e});else if(a){const t=Pe({action:ve.CreditPurchase,screen:"credits",packageId:e},a);p(t)}else p()},[d,p,a]);return c?void 0!==s?e.jsx(e.Fragment,{children:s}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{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(Vs,{className:"h-48 rounded-lg"},t))})]}):l?n?e.jsx(e.Fragment,{children:n(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:r({loading:c,error:l,packages:o,notes:i,refetch:u,selectPackage:h})})},exports.CreditTransactionType={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"},exports.DEFAULT_ROLE_PERMISSIONS=pt,exports.Dialog=js,exports.DialogContent=Fs,exports.DialogDescription=Os,exports.DialogTitle=_s,exports.DialogTrigger=As,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EmptyState=Bs,exports.EventEmitter=le,exports.Form=Ks,exports.FormControl=tn,exports.FormDescription=rn,exports.FormField=Hs,exports.FormItem=Xs,exports.FormLabel=en,exports.FormMessage=sn,exports.FullScreenLoader=Yr,exports.Input=nn,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.Label=Js,exports.LoadingState=function({label:t,className:r}){const{t:s}=Sr();return e.jsxs("div",{role:"status","aria-live":"polite",className:E("flex items-center gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground",r),children:[e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin flex-shrink-0"}),e.jsx("span",{children:t??s("settings.common.loading")})]})},exports.PLAN_CURRENCY_CODES=De,exports.PLAN_CURRENCY_OPTIONS=Le,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 try {\n const payload = event.data.json();\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n",exports.Permission=ut,exports.PortalContext=ks,exports.PricingPage=function({slug:r,children:s,loadingFallback:n,errorFallback:a,redirectBaseUrl:o}){const{items:i,plans:c,notes:l,loading:u,error:d,refetch:p}=Ur(r),{isAuthenticated:h,signIn:m}=ws(),g=t.useCallback((e,t,r)=>o?Pe({action:"selectPlan",plan:e,interval:t,currency:r},o):null,[o]),f=t.useCallback((e,t,r)=>{if(h)return void hs.openWorkspaceSettings(ds.Subscription,{action:"selectPlan",plan:e,interval:t,currency:r});const s=g(e,t,r);m(s??void 0)},[h,m,g]);return u?void 0!==n?e.jsx(e.Fragment,{children:n}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(Vs,{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(Vs,{className:"h-64 rounded-lg"},t))})]}):d?a?e.jsx(e.Fragment,{children:a(d)}):e.jsx("div",{className:"rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive",children:d}):e.jsx(e.Fragment,{children:s({loading:u,error:d,items:i,plans:c,notes:l,refetch:p,selectPlan:f})})},exports.PushApi=se,exports.PushNotificationProvider=Ps,exports.QuotaUsageContextProvider=ss,exports.RadioGroup=an,exports.RadioGroupItem=on,exports.SDKEvent=ce,exports.SETTINGS_SCREENS=ps,exports.SUPPORTED_LOCALES=pr,exports.SaaSOSProvider=fn,exports.ScrollArea=cn,exports.SectionHeader=qs,exports.SettingsApi=ne,exports.SettingsScreen=ds,exports.SidebarNavItem=function({icon:t,label:r,active:s=!1,onClick:n,className:a}){return e.jsxs("button",{className:E("flex w-full text-start px-2 py-2.5 sm:py-1 rounded text-sm items-center gap-x-2 sm:gap-x-1 whitespace-nowrap shrink-0",s?"bg-primary/10 text-primary font-medium":"hover:bg-muted hover:text-foreground",a),onClick:n,"aria-current":s?"true":void 0,children:[t,e.jsx("span",{className:"min-w-0 truncate",children:r}),e.jsx(l.ChevronRight,{"aria-hidden":"true",className:"h-4 w-4 ms-auto opacity-40 sm:hidden rtl:rotate-180"})]})},exports.SidebarNavSection=function({title:t,children:r,className:s}){return e.jsxs("div",{className:E("px-2 flex flex-col gap-1",s),children:[e.jsx("div",{className:"text-xs font-bold text-muted-foreground uppercase tracking-wide px-2 pb-1 shrink-0 whitespace-nowrap",children:t}),r]})},exports.Skeleton=Vs,exports.StatusBanner=function({variant:t,title:r,message:s,description:n,icon:a,actionLabel:o,onAction:i,actionDisabled:c,className:l}){const u=zs[t];return e.jsxs("div",{role:"error"===t?"alert":"status","aria-live":"error"===t?"assertive":"polite","aria-atomic":"true",className:E("border px-4 py-3 rounded-lg flex items-start justify-between gap-2 sm:gap-4",u.box,l),children:[e.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[a,e.jsxs("div",{className:"min-w-0",children:[r&&e.jsx("p",{className:"text-sm font-medium",children:r}),s&&e.jsx("p",{className:E("text-sm",r&&"mt-1"),children:s}),n&&e.jsx("p",{className:E("text-xs mt-2",u.sub),children:n})]})]}),o&&e.jsx(Rs,{variant:"outline",size:"sm",onClick:i,disabled:c,className:E("flex-shrink-0",u.button),children:o})]})},exports.SubscriptionContextProvider=Dr,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus=Je,exports.UIConfigProvider=os,exports.UserApi=ae,exports.WhenAuthenticated=bn,exports.WhenCreditsAvailable=Ln,exports.WhenCreditsExhausted=Mn,exports.WhenCreditsLow=$n,exports.WhenNoSubscription=In,exports.WhenNotTrialing=An,exports.WhenPermission=kn,exports.WhenQuotaAvailable=Wn,exports.WhenQuotaExhausted=Fn,exports.WhenQuotaOverage=Tn,exports.WhenQuotaThreshold=_n,exports.WhenRoles=yn,exports.WhenSubscription=Nn,exports.WhenSubscriptionToPlans=Rn,exports.WhenTrialEnding=Un,exports.WhenTrialing=jn,exports.WhenUnauthenticated=wn,exports.WhenUserFeatureDisabled=En,exports.WhenUserFeatureEnabled=Pn,exports.WhenWorkspaceFeatureDisabled=Cn,exports.WhenWorkspaceFeatureEnabled=Sn,exports.WhenWorkspaceRoles=xn,exports.WorkspaceApi=oe,exports.WorkspaceSwitcher=function(r){const{t:s,dir:n}=Sr(),{isAuthenticated:a,user:o}=ws(),i=ie(Ir()),{workspaces:c,currentWorkspace:u,loading:d,refreshing:p,switchingToId:h,fetchWorkspaces:m,getFeatures:g,refreshWorkspaces:f,setCurrentWorkspace:b,switchToWorkspace:w}=ms(),{settings:y}=jr(),{visible:x}=Ls(),[k,v]=t.useState(!1),[S,C]=t.useState(0),[P,E]=t.useState(""),N=d||p;t.useEffect(()=>{a&&i&&(0===c.length?(m(),g()):g())},[a,i]),t.useEffect(()=>{a&&i&&S>0&&f()},[S,a,i]);const I=c,R=I.filter(e=>e._id!==u?._id).filter(e=>e.name.toLowerCase().includes(P.toLowerCase())),j=(y?.workspace?.canCreateWorkspace??!0)&&x(e=>e.workspaceSwitcher?.createButton),A=(y?.workspace?.showSwitcher??!0)&&x(e=>e.workspaceSwitcher?.show),U=y?.workspace?.maxWorkspacesPerUser??0,W=I?.filter(e=>("object"==typeof e.createdBy?e.createdBy._id?.toString():e.createdBy?.toString())===o?.id?.toString()).length??0,F=!1!==j&&(0===U||W<U);return t.useEffect(()=>{!A&&c.length>0&&!u&&w(c[0]).catch(e=>{T(e,{component:"WorkspaceProvider",action:"autoSelectWorkspace"})})},[A,c,u]),!A&&u?e.jsxs(e.Fragment,{children:[e.jsx("div",{role:"button",tabIndex:0,"aria-label":s("settings.common.openSettings"),className:"cursor-pointer",onClick:()=>v(!0),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),v(!0))},children:r.trigger?.(N,u)}),e.jsx(t.Suspense,{fallback:null,children:e.jsx(Hn,{workspace:u,open:k,onOpenChange:v,showTrigger:!1})})]}):e.jsxs(js,{open:k,onOpenChange:v,children:[e.jsx(As,{children:r.trigger?.(N,u)}),e.jsxs(Fs,{dir:n,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e.jsxs(Ts,{dir:n,children:[e.jsxs(_s,{className:"flex items-center gap-2",children:[e.jsx(l.Building2,{className:"h-5 w-5"}),s("workspace.switchTitle")]}),e.jsx(Os,{children:s("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:s("workspace.notLoggedIn")})}),o&&e.jsxs("div",{dir:n,className:"flex flex-col gap-4",children:[u&&e.jsx(Qn,{workspace:u,isCurrentWorkspace:!0,switchToWorkspace:w,switchingToId:h,onClose:()=>v(!1),setCurrentWorkspace:b,setOpen:v,workspacesToUse:I}),e.jsx(Yn,{}),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:s("workspace.availableWorkspaces",{count:R.length})}),e.jsx("div",{children:e.jsx(Rs,{progress:p,disabled:p,variant:"ghost",onClick:function(){a&&i&&C(e=>e+1)},startIcon:e.jsx(l.RefreshCcw,{}),children:s("settings.common.refreshAction",{loading:String(p)})})})]}),e.jsxs("div",{className:"relative",children:[e.jsx(l.Search,{className:"absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"}),e.jsx(nn,{placeholder:s("workspace.searchPlaceholder"),value:P,onChange:e=>E(e.target.value),className:"ps-10"})]}),d?e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ms-2 text-sm text-muted-foreground",children:s("workspace.loadingWorkspaces")})]}):0===R.length?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(l.Building2,{className:"mx-auto h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:s(P?"workspace.noWorkspacesFound":"workspace.noWorkspacesAvailable")})]}):e.jsx(cn,{className:"h-64",dir:n,children:e.jsx("div",{dir:n,className:"flex flex-col gap-2 my-2.5",children:R.map(t=>{const r=t._id===u?._id;return e.jsx(Qn,{workspace:t,isCurrentWorkspace:r,switchToWorkspace:w,switchingToId:h,onClose:()=>v(!1),setCurrentWorkspace:b,setOpen:v,workspacesToUse:I},t._id)})})})]}),F&&e.jsxs(e.Fragment,{children:[e.jsx(Yn,{}),e.jsx(Zn,{onCreated:()=>{m()}})]})]})]})]})},exports.buttonVariants=Is,exports.calculateBillableSeats=Xe,exports.calculateSeatOverageCents=et,exports.calculateTotalSubscriptionCents=function(e,t,r,s){const n=Ye(e,t,r);return null===n?null:void 0===s?n:n+(et(e,t,r,s)??0)},exports.cleanBBParams=Ie,exports.clearAuthIntent=function(){M(Ae)},exports.cn=E,exports.consumeAuthIntent=Fe,exports.createBBUrl=Pe,exports.createCheckoutRedirectUrls=function(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Pe({action:ve.Checkout,status:Se.Success,ws:e,screen:Ce.Subscription},r),cancelUrl:Pe({action:ve.Checkout,status:Se.Cancel,ws:e,screen:Ce.Subscription},r)}},exports.createCreditPurchaseRedirectUrls=Ee,exports.eventEmitter=ue,exports.formatCents=qe,exports.formatOverageRate=function(e,t,r,s){if(null==e||e<0)return null;const n={...Ve,...s},a=null!=t&&t>=1?t:1,o=Oe(r),i=Be(e,r);return 1===a?`${o}${i}/${n.unit}`:`${o}${i}/${a.toLocaleString()} ${n.units}`},exports.formatOverageRateWithLabel=function(e,t,r,s,n,a){if(null==e||e<0)return null;const o={...Ve,...a},i=null!=t&&t>=1?t:1,c=Oe(s),l=Be(e,s);if(r){const e=n??(r.endsWith("s")?r:`${r}s`);return i>=2?`${c}${l}/${i.toLocaleString()} ${e}`:`${c}${l}/${r}`}return 1===i?`${c}${l}/${o.unit}`:`${c}${l}/${i.toLocaleString()} ${o.units}`},exports.formatQuotaIncludedOverage=function(e,t,r,s,n,a,o,i){const c={...Ve,...o};if(!1===i)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const l=a??(r.endsWith("s")?r:`${r}s`),u=null!=n&&n>=2?`${n.toLocaleString()} ${l}`:r;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${qe(t,s)}/${u}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${qe(t,s)}/${u}`:"—"},exports.formatQuotaWithPrice=function(e,t,r={}){const{overageInCents:s=!0,currency:n}=r,a=r.labels??ze,o=r.currencySymbol??Oe(n??"");if(null==e)return"—";const{included:i,overage:c}=e,l=`${i} ${a.included}`;if(!1===e.allowOverage)return`${l} (hard limit)`;if(null==c)return l;const u=$e(n),d=s&&!u?c/100:c,p="number"==typeof d&&Number.isFinite(d)?u?d.toLocaleString("en-US"):d.toFixed(2):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${a.then} ${o}${p}${h}`},exports.getAvailableCurrenciesFromPlans=function(e){const t=new Set;for(const r of e)r.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()},exports.getBasePriceCents=Ye,exports.getBillingIntervalAndCurrencyFromPriceId=function(e,t){if(!e)return null;for(const r of t){const t=r.pricingVariants;if(t?.length)for(const r of t){const t=r.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:r.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:r.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:r.currency}}}}return null},exports.getCurrencyFlag=function(e){return e&&e.trim()?_e[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=Oe,exports.getDisplayCurrency=function(e,t){const r=Ke(e,t);return r?r.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=Ze,exports.getPricingVariant=Ke,exports.getQuotaDisplayParts=function(e,t,r={}){if(null==e)return null;const{overageInCents:s=!0,currency:n,locale:a="en"}=r,{included:o,overage:i}=e;if(!(!1!==e.allowOverage))return{included:o,hasOverage:!1,allowOverage:!1,price:"",unit:""};if(null==i)return{included:o,hasOverage:!1,allowOverage:!0,price:"",unit:""};const c=$e(n),l=s&&!c?i/100:i,u=c?0:2,d=(n??"").trim().toUpperCase();let p;if(d&&"number"==typeof l&&Number.isFinite(l))try{p=new Intl.NumberFormat(a,{style:"currency",currency:d,minimumFractionDigits:u}).format(l)}catch{p=`${r.currencySymbol??Oe(n??"")}${l.toFixed(u)}`}else{p=`${r.currencySymbol??Oe(n??"")}${"number"==typeof l?l.toFixed(u):String(i)}`}return{included:o,hasOverage:!0,allowOverage:!0,price:p,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 r=e[t??"monthly"];return r?{included:r.included,...void 0!==r.overage&&{overage:r.overage},...void 0!==r.unitSize&&{unitSize:r.unitSize},allowOverage:!1!==e.allowOverage}:null},exports.getQuotaDisplayWithVariant=function(e,t,r,s){const n=e.quotas?.[r];if(null==n)return null;const a=n[s];if(!a)return null;const o=He(e,t,r,s);return{included:a.included,...void 0!==a.unitSize&&{unitSize:a.unitSize},...void 0!==o&&{overage:o},allowOverage:!1!==n.allowOverage}},exports.getQuotaOverageCents=He,exports.getQuotaUnitLabelFromName=function(e,t="unit"){const r=(e||"").trim().toLowerCase();if(!r)return t;const s=r.split(/\s+/)[0]??r;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(s)?s:s.endsWith("ies")&&s.length>3?s.slice(0,-3)+"y":s.endsWith("ses")||s.endsWith("xes")||s.endsWith("zes")||s.endsWith("ches")||s.endsWith("shes")?s.slice(0,-2):s.endsWith("s")&&!s.endsWith("ss")&&s.length>1?s.slice(0,-1):s||t},exports.getSeatPricing=Qe,exports.getStripePriceIdForInterval=function(e,t,r){const s=Ke(e,t);if(!s?.stripePrices)return null;const n=r===Ge.Monthly?"monthlyPriceId":r===Ge.Yearly?"yearlyPriceId":"quarterlyPriceId",a=r===Ge.Monthly?"monthly":r===Ge.Yearly?"yearly":void 0;return s.stripePrices[n]??(a?s.stripePrices[a]:void 0)??null},exports.getSvgImage=un,exports.handleError=T,exports.hasPermission=function(e,t){const r=mt(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)},exports.invalidateCreditBalance=me,exports.invalidateQuotaUsage=be,exports.invalidateSubscription=xe,exports.isWorkspaceOwner=ct,exports.isZeroDecimalCurrency=$e,exports.mergeUIConfig=function(e,t){return t?cs(e,t):e},exports.minorAmountToDisplay=Be,exports.readBBParams=Ne,exports.resolveMaxUsers=tt,exports.resolvePermissions=mt,exports.safeRedirect=je,exports.saveAuthIntent=We,exports.useAllQuotaUsage=_r,exports.useBillingPortal=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(!1),[o,i]=t.useState(null);return{openBillingPortal:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),i(null);try{const r=t||window.location.href,n=await s.createBillingPortalSession(e,r);return n.url&&window.open(n.url,"_blank","noopener,noreferrer"),n}catch(t){const s=O(t,"errors.openBillingPortal",r);throw i(s),T(t,{component:"useBillingPortal",action:"openBillingPortal",metadata:{workspaceId:e}}),t}finally{a(!1)}},[e,s]),loading:n,error:o}},exports.useCancelSubscription=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(!1),[o,i]=t.useState(null);return{cancelSubscription:t.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");a(!0),i(null);try{const t=await s.cancelSubscriptionAtPeriodEnd(e);return xe(),t}catch(t){const s=O(t,"errors.cancelSubscription",r);throw i(s),T(t,{component:"useCancelSubscription",action:"cancelSubscription",metadata:{workspaceId:e}}),t}finally{a(!1)}},[s,e]),loading:n,error:o}},exports.useConnectedAgents=$s,exports.useConnectedAgentsApi=Ms,exports.useConsumeCredits=$r,exports.useCreateCheckoutSession=e=>{const{t:r}=Sr(),{api:s}=Ar(),{getCheckoutStripeParams:n}=t.useContext(cr),[a,o]=t.useState(!1),[i,c]=t.useState(null);return{createCheckoutSession:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");o(!0),c(null);try{let r=t;if(n){const e=await n(t);e&&(r={...t,stripeOptions:{...t.stripeOptions,...e,metadata:{...t.stripeOptions?.metadata,...e.metadata},subscriptionMetadata:{...t.stripeOptions?.subscriptionMetadata,...e.subscriptionMetadata}}})}const a=await s.createCheckoutSession(e,r);return"trial_started"===a.type&&(xe(),be()),a}catch(s){const n=O(s,"errors.createCheckout",r);throw c(n),T(s,{component:"useCreateCheckoutSession",action:"createCheckoutSession",metadata:{workspaceId:e,request:t}}),s}finally{o(!1)}},[s,e,n]),loading:a,error:i}},exports.useCreditBalance=Mr,exports.useCreditBalanceContext=Jr,exports.useCreditPackages=qr,exports.useCreditTransactions=(e,r)=>{const{t:s}=Sr(),{api:n}=Ar(),[a,o]=t.useState([]),[i,c]=t.useState(0),[l,u]=t.useState(0),[d,p]=t.useState(1),[h,m]=t.useState(!1),[g,f]=t.useState(!1),[b,w]=t.useState(!1),[y,x]=t.useState(null),{begin:k,settle:v}=Cr(),S=r?.type,C=r?.page,P=r?.limit,E=t.useCallback(async()=>{if(!e)return k(),o([]),c(0),u(0),p(1),m(!1),f(!1),void w(!1);const t=k();w(!0),x(null);try{const r=await n.getCreditTransactions(e,{type:S,page:C,limit:P});if(t.signal.aborted)return;o(r.docs||[]),c(r.totalDocs||0),u(r.totalPages||0),p(r.page||1),m(r.hasNextPage||!1),f(r.hasPrevPage||!1)}catch(r){if(t.signal.aborted)return;const n=O(r,"errors.fetchCreditTransactions",s);x(n),T(r,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{v(t)&&w(!1)}},[n,e,S,C,P,k,v]);return t.useEffect(()=>{E()},[E]),{transactions:a,totalDocs:i,totalPages:l,page:d,hasNextPage:h,hasPrevPage:g,loading:b,error:y,refetch:E}},exports.useExpiringCredits=(e,r)=>{const{t:s}=Sr(),{api:n}=Ar(),[a,o]=t.useState(null),[i,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Cr(),h=t.useCallback(async()=>{if(!e)return d(),o(null),void c(!1);const t=d();c(!0),u(null);try{const s=await n.getExpiringCredits(e,r);if(t.signal.aborted)return;o(s)}catch(n){if(t.signal.aborted)return;const a=O(n,"errors.fetchExpiringCredits",s);u(a),T(n,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:r}})}finally{p(t)&&c(!1)}},[n,e,r,d,p]);return t.useEffect(()=>{h()},[h]),{expiringCredits:a?.expiringCredits??0,buckets:a?.buckets??[],days:a?.days??r??7,loading:i,error:l,refetch:h}},exports.useFullScreenLoader=Zr,exports.useInvoice=(e,r)=>{const{t:s}=Sr(),{api:n}=Ar(),[a,o]=t.useState(null),[i,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Cr(),h=t.useCallback(async()=>{if(!e||!r)return d(),o(null),void c(!1);const t=d();c(!0),u(null);try{const s=await n.getInvoice(e,r);if(t.signal.aborted)return;o(s.invoice)}catch(n){if(t.signal.aborted)return;const a=O(n,"errors.fetchInvoice",s);u(a),T(n,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:r}})}finally{p(t)&&c(!1)}},[n,e,r,d,p]);return t.useEffect(()=>{h()},[h]),{invoice:a,loading:i,error:l,refetch:h}},exports.useInvoices=(e,r=10,s)=>{const{t:n}=Sr(),{api:a}=Ar(),[o,i]=t.useState([]),[c,l]=t.useState(!1),[u,d]=t.useState(!1),[p,h]=t.useState(null),{begin:m,settle:g}=Cr(),f=t.useCallback(async()=>{if(!e)return m(),i([]),l(!1),void d(!1);const t=m();d(!0),h(null);try{const n=await a.listInvoices(e,r,s);if(t.signal.aborted)return;i(n.invoices||[]),l(n.has_more||!1)}catch(a){if(t.signal.aborted)return;const o=O(a,"errors.fetchInvoices",n);h(o),T(a,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:r,startingAfter:s}})}finally{g(t)&&d(!1)}},[a,e,r,s,m,g]);return t.useEffect(()=>{f()},[f]),{invoices:o,hasMore:c,loading:u,error:p,refetch:f}},exports.usePermissionConfig=ts,exports.usePermissions=Ds,exports.usePlanGroup=Fr,exports.usePlanGroupVersions=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Cr(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void i(!1);const t=u();i(!0),l(null);try{const r=await s.getPlanGroupVersions(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=O(s,"errors.fetchPlanGroupVersions",r);l(n),T(s,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{d(t)&&i(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{versions:n,loading:o,error:c,refetch:p}},exports.usePublicCreditPackages=Vr,exports.usePublicPlanGroupVersion=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),{begin:u,settle:d}=Cr(),p=t.useCallback(async()=>{if(!e)return u(),a(null),void i(!1);const t=u();i(!0),l(null);try{const r=await s.getPlanGroupVersion(e);if(t.signal.aborted)return;a(r)}catch(s){if(t.signal.aborted)return;const n=O(s,"errors.fetchPlanGroupVersion",r);l(n),T(s,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{d(t)&&i(!1)}},[s,e,u,d]);return t.useEffect(()=>{p()},[p]),{planGroupVersion:n,loading:o,error:c,refetch:p}},exports.usePublicPlans=Ur,exports.usePurchaseCredits=Br,exports.usePushNotifications=function(){const e=t.useContext(Ss);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e},exports.useQuotaUsageContext=ns,exports.useQuotaUsageStatus=(e,r)=>{const{t:s}=Sr(),{api:n}=Ar(),[a,o]=t.useState(null),[i,c]=t.useState(!1),[l,u]=t.useState(null),{begin:d,settle:p}=Cr(),h=t.useCallback(async()=>{if(!e||!r)return d(),o(null),void c(!1);const t=d();c(!0),u(null);try{const s=await n.getQuotaUsageStatus(e,r);if(t.signal.aborted)return;o(s)}catch(n){if(t.signal.aborted)return;const a=O(n,"errors.fetchQuotaUsage",s);u(a),T(n,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:r}})}finally{p(t)&&c(!1)}},[n,e,r,d,p]);return t.useEffect(()=>{h()},[h]),{status:a,loading:i,error:l,refetch:h}},exports.useRecordUsage=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(!1),[o,i]=t.useState(null);return{recordUsage:t.useCallback(async t=>{if(!e)throw new Error("Workspace ID is required");a(!0),i(null);try{const r=await s.recordUsage(e,t);return be(),r}catch(s){const n=O(s,"errors.recordUsage",r);throw i(n),T(s,{component:"useRecordUsage",action:"recordUsage",metadata:{workspaceId:e,request:t}}),s}finally{a(!1)}},[s,e]),loading:n,error:o}},exports.useResumeSubscription=e=>{const{t:r}=Sr(),{api:s}=Ar(),[n,a]=t.useState(!1),[o,i]=t.useState(null);return{resumeSubscription:t.useCallback(async()=>{if(!e)throw new Error("Workspace ID is required");a(!0),i(null);try{const t=await s.resumeSubscription(e);return xe(),t}catch(t){const s=O(t,"errors.resumeSubscription",r);throw i(s),T(t,{component:"useResumeSubscription",action:"resumeSubscription",metadata:{workspaceId:e}}),t}finally{a(!1)}},[s,e]),loading:n,error:o}},exports.useSaaSAuth=ws,exports.useSaaSOs=Ir,exports.useSaaSSettings=jr,exports.useSaaSWorkspaces=ms,exports.useSeatStatus=function(e,r){const{response:s}=Lr();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=s?.planVersion,a=s?.subscription,o=e.billingCurrency||"usd",i=tt({planVersion:n,currency:o,settingsMaxUsers:r?.settingsMaxUsers}),{maxUsers:c,hasSeatPricing:l,includedSeats:u}=i,d=l?Math.max(0,t-u):0,p=c>0?Math.max(0,c-t):1/0,h=c>0&&t>=c,m=c>0&&t>=.8*c&&!h,g=l&&n?Ze(n,o,a?.billingInterval??"monthly"):null,f=rt({memberCount:t,maxUsersConfig:i});return{hasSeatPricing:l,memberCount:t,includedSeats:u,maxUsers:c,maxSeats:c,limitSource:i.source,billableSeats:d,availableSeats:p,isAtMax:h,isNearMax:m,perSeatPriceCents:g,currency:o,canInvite:f.canInvite,inviteBlockReason:f.blockReason,inviteBlockMessageKey:f.blockMessageKey,inviteBlockMessageValues:f.blockMessageValues}},[s,e,r?.settingsMaxUsers])},exports.useSubscription=Wr,exports.useSubscriptionContext=Lr,exports.useSubscriptionManagement=(e,r)=>{const s=Wr(e),n=Fr(e,r),a=Tr(e),o=t.useCallback(async()=>{await Promise.all([s.refetch(),n.refetch()])},[s.refetch,n.refetch]);return{subscription:s.subscription,planGroup:n.planGroup,loading:s.loading||n.loading||a.loading,error:s.error||n.error||a.error,updateSubscription:a.updateSubscription,refetch:o}},exports.useTranslation=Sr,exports.useTrialStatus=function(){const{response:e}=Lr();return t.useMemo(()=>{const t=e?.subscription;if(!t||"trialing"!==t.subscriptionStatus)return{isTrialing:!1,daysRemaining:0,trialEndsAt:null,trialStartedAt:null,isTrialEnding:!1};const r=Bn(t.trialEnd)??Bn(t.stripeCurrentPeriodEnd),s=Bn(t.trialStart),n=r?Math.max(0,Math.ceil((r.getTime()-Date.now())/864e5)):0;return{isTrialing:!0,daysRemaining:n,trialEndsAt:r,trialStartedAt:s,isTrialEnding:n<=3}},[e])},exports.useUIConfig=is,exports.useUIVisibility=Ls,exports.useUpdateSubscription=Tr,exports.useUsageLogs=(e,r,s)=>{const{t:n}=Sr(),{api:a}=Ar(),[o,i]=t.useState([]),[c,l]=t.useState(0),[u,d]=t.useState(0),[p,h]=t.useState(1),[m,g]=t.useState(!1),[f,b]=t.useState(!1),[w,y]=t.useState(!1),[x,k]=t.useState(null),{begin:v,settle:S}=Cr(),C=s?.from,P=s?.to,E=s?.source,N=s?.page,I=s?.limit,R=t.useCallback(async()=>{if(!e)return v(),i([]),l(0),d(0),h(1),g(!1),b(!1),void y(!1);const t=v();y(!0),k(null);try{const s={...r&&{quotaSlug:r},...C&&{from:C},...P&&{to:P},...E&&{source:E},...N&&{page:N},...I&&{limit:I}},n=await a.getUsageLogs(e,s);if(t.signal.aborted)return;i(n.docs||[]),l(n.totalDocs||0),d(n.totalPages||0),h(n.page||1),g(n.hasNextPage||!1),b(n.hasPrevPage||!1)}catch(s){if(t.signal.aborted)return;const a=O(s,"errors.fetchUsageLogs",n);k(a),T(s,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:r}})}finally{S(t)&&y(!1)}},[a,e,r,C,P,E,N,I,v,S]);return t.useEffect(()=>{R()},[R]),{logs:o,totalDocs:c,totalPages:u,page:p,hasNextPage:m,hasPrevPage:f,loading:w,error:x,refetch:R}},exports.useUserAttributes=function(){const e=t.useContext(Es);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return e},exports.useUserFeatures=vn,exports.useWorkspaceApiWithOs=Ar,exports.validateInvite=rt,exports.validateRedirectUrl=Re,exports.workspaceEmojis=dn,exports.workspaceSettingsManager=hs;
|