@buildbase/sdk 0.0.51 → 0.0.53
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 +18 -8
- package/CHANGELOG.md +56 -0
- package/README.md +247 -32
- package/dist/css/styles.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +865 -53
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -0
- package/dist/mcp/index.d.ts +1402 -0
- package/dist/mcp/index.mjs +1 -0
- package/dist/react/chunks/{SettingsDialog-uVKFxlal.mjs → SettingsDialog-BxDYsie6.mjs} +1 -1
- package/dist/react/chunks/{SettingsDialog-DitAiAqr.cjs → SettingsDialog-Dy8W3NA6.cjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-P0GlXEyn.mjs → SubscriptionDialog-6c5dHoQd.mjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-Cg-qYVKr.cjs → SubscriptionDialog-CpVnnXJg.cjs} +1 -1
- package/dist/react/chunks/ar-1Z1MOGAP.mjs +2 -0
- package/dist/react/chunks/ar-VGzBv3AZ.cjs +2 -0
- package/dist/react/chunks/de-BjdDg60Y.cjs +2 -0
- package/dist/react/chunks/de-CXUItplO.mjs +2 -0
- package/dist/react/chunks/es-BBPsSZUp.cjs +2 -0
- package/dist/react/chunks/es-BTbzVutz.mjs +2 -0
- package/dist/react/chunks/fr-Cax48X_S.cjs +2 -0
- package/dist/react/chunks/fr-DPMeOQu3.mjs +2 -0
- package/dist/react/chunks/hi-BJqvpG6d.cjs +2 -0
- package/dist/react/chunks/hi-JfJx-LV7.mjs +2 -0
- package/dist/react/chunks/ja-CDGtLzTk.mjs +2 -0
- package/dist/react/chunks/ja-DvVyj5xX.cjs +2 -0
- package/dist/react/chunks/react-4SlWxHdh.cjs +2 -0
- package/dist/react/chunks/react-OL1uSkpr.mjs +2 -0
- package/dist/react/chunks/zh-BAcqxkxk.cjs +2 -0
- package/dist/react/chunks/zh-BNZ2Ooe8.mjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +39 -32
- package/dist/react/index.mjs +1 -1
- package/package.json +17 -4
- package/dist/react/chunks/ar-SrPOJXdL.mjs +0 -2
- package/dist/react/chunks/ar-a3aRbPCs.cjs +0 -2
- package/dist/react/chunks/de-DE3_z7r0.cjs +0 -2
- package/dist/react/chunks/de-xnPl61SS.mjs +0 -2
- package/dist/react/chunks/es-C_xcyGtp.cjs +0 -2
- package/dist/react/chunks/es-CyuBtosP.mjs +0 -2
- package/dist/react/chunks/fr-BMu7Bk4k.cjs +0 -2
- package/dist/react/chunks/fr-CxuDLZ27.mjs +0 -2
- package/dist/react/chunks/hi-CQ215yc9.cjs +0 -2
- package/dist/react/chunks/hi-CpuvyorS.mjs +0 -2
- package/dist/react/chunks/ja-DIJ_xCIi.mjs +0 -2
- package/dist/react/chunks/ja-DK6Buuws.cjs +0 -2
- package/dist/react/chunks/react-C2ikFWBG.cjs +0 -2
- package/dist/react/chunks/react-CCukNQ4q.mjs +0 -2
- package/dist/react/chunks/zh-CYQwZiBL.mjs +0 -2
- package/dist/react/chunks/zh-Dt-apS2s.cjs +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"),w=require("@radix-ui/react-separator");function b(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=b(t),x=b(u),k=b(p),v=b(h),S=b(g),C=b(f),P=b(w);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="SDK is not ready (missing serverUrl, version, or orgId)";class Q{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(H);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(H)}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)}async executeFetchUrl(e,t,r){const s=(t.method??"GET").toUpperCase(),n=r??e,a=this.buildHeaders(t),o={...t,headers:a};let i,c;if(this._timeout>0){c=new AbortController;const e=c;i=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 l=async r=>{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 t=this._fetch.bind(globalThis),n=await t(e,o);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&r<this._maxRetries){const e=Math.min(1e3*Math.pow(2,r),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${r+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),l(r+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(c?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${n}`);throw this.reportError(e,{method:s,path:n}),e}throw e}if(r<this._maxRetries){const e=Math.min(1e3*Math.pow(2,r),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${r+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),l(r+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:n}),e}};try{return await l(0)}finally{void 0!==i&&clearTimeout(i)}}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 Z extends Q{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 X extends Q{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 ee=class{constructor(e){this.api=new X(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 te extends Q{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 re extends Q{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 se extends Q{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class ne extends Q{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 ae extends Q{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 oe(e){return Boolean(e?.serverUrl&&e?.version&&e?.orgId)}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const ie={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 ce{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(ie.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(ie.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(ie.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(ie.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit(ie.WorkspaceUserAdded,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit(ie.WorkspaceUserRemoved,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,s){await this.emit(ie.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:r,newRole:s})}async emitWorkspaceCreated(e){await this.emit(ie.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(ie.WorkspaceDeleted,{workspace:e})}}const le=new ce;function ue(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const de=ue(),pe=de.subscribe,he=de.invalidate,me=ue(),ge=me.subscribe,fe=me.invalidate,we=ue(),be=we.subscribe,ye=we.invalidate,xe="bb",ke={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},ve={Success:"success",Cancel:"cancel",Error:"error"},Se={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function Ce(e,t){let r;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");r=new URL(e),r.search=""}catch{r=new URL("https://localhost")}return r.searchParams.set(xe,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function Pe(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Ce({action:ke.CreditPurchase,status:ve.Success,ws:e,screen:Se.Credits},r),cancelUrl:Ce({action:ke.CreditPurchase,status:ve.Cancel,ws:e,screen:Se.Credits},r)}}function Ee(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(xe);if(!e)return null;const t=function(e){const t={};if(!e)return t;const 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 Ne(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(xe)&&(e.searchParams.delete(xe),window.history.replaceState({},"",e.toString()))}catch{}}function Ie(e){if(!e||"string"!=typeof e)return null;try{const t=new URL(e);return"https:"===t.protocol?e:"http:"!==t.protocol||"localhost"!==t.hostname&&"127.0.0.1"!==t.hostname&&"::1"!==t.hostname?null:e}catch{return null}}function Re(e,t="/"){if("undefined"==typeof window||!window.location)return!1;const r=Ie(e);return window.location.href=r??t,!0}const je="saas-auth-intent";function Ae(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function Ue(e){Ie(e)&&function(e,t){try{L(e,JSON.stringify(t))}catch(t){T(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}(je,{returnUrl:e,createdAt:Date.now()})}function We(){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}}(je,Ae);return M(je),e?Date.now()-e.createdAt>6e5?null:Ie(e.returnUrl):null}const Fe={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:"฿"},Te={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function _e(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Fe[t]??t.toUpperCase()}const Oe=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],De=Oe.map(e=>({value:e,label:`${e.toUpperCase()} (${_e(e)})`}));function Le(e,t){return _e(t)+(e/100).toFixed(2)}const Me={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};const $e={included:"included",then:"then"};const Be={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},qe={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"};function Ve(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 ze(e,t,r){const s=Ve(e,t);if(!s?.basePricing)return null;const n=s.basePricing[r];return null!=n?n:null}function Ge(e,t,r,s){const n=Ve(e,t),a=n?.quotaOverages?.[r];if(a)return a[s]}function Je(e,t){const r=Ve(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function Ke(e,t,r){const s=Je(e,t);return s?.perSeat?s.perSeat[r]??null:null}function Ye(e,t){return Math.max(0,e-(t||0))}function He(e,t,r,s){const n=Je(e,t);if(!n)return null;return Ye(s,n.includedSeats)*(Ke(e,t,r)??0)}function Qe(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:s}=e;if(t){const e=Je(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 Ze(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 Xe="saas-workspace-current",et=e=>{e?L(Xe,e._id):M(Xe)},tt=()=>D(Xe),rt=()=>{M(Xe)},st=(e,t)=>!!e&&t.some(t=>t._id===e);function nt(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 at(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 ot={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"},it=Object.values(ot),ct={admin:it.filter(e=>e!==ot.WORKSPACE_DELETE),member:[ot.WORKSPACE_SETTINGS_VIEW,ot.WORKSPACE_MEMBERS_VIEW,ot.WORKSPACE_FEATURES_VIEW,ot.WORKSPACE_BILLING_VIEW,ot.WORKSPACE_USAGE_VIEW],viewer:[ot.WORKSPACE_SETTINGS_VIEW,ot.WORKSPACE_MEMBERS_VIEW]};function lt(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 ut(e){const{userId:t,workspace:r,settings:s,appPermissions:n}=e;if(!r||!t)return new Set;if(nt(r,t)){const e=new Set(it);if(n)for(const t of lt(n))e.add(t);if(r.permissions)for(const t of lt(r.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of lt(s.workspace.permissions))e.add(t);return e}const a=e.workspaceRole??at(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 ct;let h;if(u)h=c(o[a]);else if(d)h=c(i[a]);else if(p)h=ct[a];else{const e=s?.workspace?.defaultRole;h=e&&e in ct?ct[e]:[]}const m=new Set(h),g=u?l(o[a]):[],f=n?.[a]?l(n[a]):[],w=u?g:f;for(const e of w)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(ot.WORKSPACE_MEMBERS_INVITE)}(m,a,s),m}var dt;function pt(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,(dt=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",dt.redirecting="redirecting",dt.authenticated="authenticated",dt.unauthenticated="unauthenticated",dt.authenticating="authenticating";class ht 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 mt=()=>({type:"AUTHENTICATION_STARTED"}),gt=()=>({type:"AUTHENTICATION_PROCESSING"}),ft=()=>({type:"AUTHENTICATION_FAILED"}),wt=e=>({type:"SET_SESSION",payload:e}),bt=()=>({type:"REMOVE_SESSION"});function yt(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 xt({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)=>yt(d(),e||(e=>e),t)}}function kt(e,t,r){return{...e,[t]:r}}function vt(e,t){return{...e,...t}}const St=()=>({session:null,status:exports.AuthStatus.loading}),{Provider:Ct,useState:Pt,useDispatch:Et}=xt({name:"Auth",initialState:St(),reducer:(e,t)=>{switch(t.type){case"AUTHENTICATION_STARTED":return kt(e,"status",exports.AuthStatus.redirecting);case"AUTHENTICATION_PROCESSING":return kt(e,"status",exports.AuthStatus.authenticating);case"AUTHENTICATION_FAILED":case"REMOVE_SESSION":return vt(e,{session:null,status:exports.AuthStatus.unauthenticated});case"SET_SESSION":return vt(e,{session:t.payload,status:exports.AuthStatus.authenticated});default:return e}},initializer:St}),Nt=Ct,It=Pt,Rt=Et,jt=e=>({type:"SET_SAAS_OS_CONFIG",payload:e}),At=e=>({type:"SET_SETTINGS",payload:e}),Ut=()=>({serverUrl:"",version:exports.ApiVersion.V1,orgId:"",settings:null}),{Provider:Wt,useState:Ft,useDispatch:Tt}=xt({name:"OS",initialState:Ut(),reducer:(e,t)=>{switch(t.type){case"SET_SAAS_OS_CONFIG":return vt(e,t.payload);case"REMOVE_SAAS_OS_CONFIG":return Ut();case"SET_SETTINGS":return kt(e,"settings",t.payload);default:return e}}}),_t=Wt,Ot=Ft,Dt=Tt,Lt=e=>({type:"SET_WORKSPACES",payload:e}),Mt=e=>({type:"ADD_WORKSPACE",payload:e}),$t=e=>({type:"UPDATE_WORKSPACE",payload:e}),Bt=e=>({type:"REMOVE_WORKSPACE",payload:e}),qt=e=>({type:"SET_ALL_FEATURES",payload:e}),Vt=e=>({type:"SET_CURRENT_WORKSPACE",payload:e}),zt=()=>({type:"RESET_CURRENT_WORKSPACE"}),Gt=e=>({type:"SET_IS_INITIALIZED",payload:e}),Jt=e=>({type:"SET_LOADING",payload:e}),Kt=e=>({type:"SET_ERROR",payload:e}),Yt=e=>({type:"SET_REFRESHING",payload:e}),Ht=e=>({type:"SET_SWITCHING_TO_ID",payload:e}),{Provider:Qt,useState:Zt,useDispatch:Xt}=xt({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 kt(e,"workspaces",t.payload);case"ADD_WORKSPACE":return kt(e,"workspaces",[...e.workspaces,t.payload]);case"UPDATE_WORKSPACE":return kt(e,"workspaces",e.workspaces.map(e=>e._id===t.payload._id?t.payload:e));case"REMOVE_WORKSPACE":return kt(e,"workspaces",e.workspaces.filter(e=>e._id!==t.payload));case"SET_ALL_FEATURES":return kt(e,"allFeatures",t.payload);case"SET_CURRENT_WORKSPACE":return kt(e,"currentWorkspace",t.payload);case"RESET_CURRENT_WORKSPACE":return kt(e,"currentWorkspace",null);case"SET_IS_INITIALIZED":return kt(e,"isInitialized",t.payload);case"SET_LOADING":return kt(e,"loading",t.payload);case"SET_ERROR":return kt(e,"error",t.payload);case"SET_REFRESHING":return kt(e,"refreshing",t.payload);case"SET_SWITCHING_TO_ID":return kt(e,"switchingToId",t.payload);default:return e}}}),er=Qt,tr=Zt,rr=Xt,sr=t.memo(({children:t})=>e.jsx(_t,{children:e.jsx(Nt,{children:e.jsx(er,{children:t})})}));sr.displayName="SDKContextProvider";const nr=t.createContext({});nr.displayName="CheckoutConfigContext";const ar=t.memo(({getCheckoutStripeParams:r,children:s})=>{const n=t.useMemo(()=>({getCheckoutStripeParams:r}),[r]);return e.jsx(nr.Provider,{value:n,children:s})});ar.displayName="CheckoutConfigProvider";const or={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"}},ir={en:async()=>or,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},cr=["en","es","fr","de","ja","zh","hi","ar"];const lr={hi:"hi-u-nu-deva",ar:"ar-u-nu-arab"};function ur(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]=ur(a,n))}return r}const dr=t.createContext({messages:or,locale:"en",formattingLocale:"en"});function pr({locale:e="en",messageOverrides:r,children:s}){const n=function(e){const t=e.toLowerCase().replace("_","-");if(cr.includes(t))return t;const r=t.split("-")[0];return cr.includes(r)?r:"en"}(e),[a,o]=t.useState(or);t.useEffect(()=>{if("en"===n)return void o(or);let e=!1;const t=ir[n];return t&&t().then(t=>{e||o(t)}),()=>{e=!0}},[n]);const i=t.useMemo(()=>r?ur(a,r):a,[a,r]),c=function(e){return lr[e]??e}(n),l=t.useMemo(()=>({messages:i,locale:n,formattingLocale:c}),[i,n,c]);return t.createElement(dr.Provider,{value:l},s)}const hr=new Map,mr=new Map,gr=new Map;function fr(e,t){return t?`${e}:${JSON.stringify(t)}`:e}const wr={getNumberFormat(e,t){const r=fr(e,t);let s=hr.get(r);return s||(s=new Intl.NumberFormat(e,t),hr.set(r,s)),s},getDateTimeFormat(e,t){const r=fr(e,t);let s=mr.get(r);return s||(s=new Intl.DateTimeFormat(e,t),mr.set(r,s)),s},getPluralRules(e,t){const r=fr(e,t);let s=gr.get(r);return s||(s=new Intl.PluralRules(e,t),gr.set(r,s)),s}},br=new Map;function yr(){const{messages:e,locale:r,formattingLocale:s}=t.useContext(dr),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(or,r)??r;if(!a)return o;try{const e=function(e,t){const r=`${t}:${e}`;let s=br.get(r);return s||(s=new n(e,t,void 0,{formatters:wr}),br.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 xr(){const e=Rt(),r=Dt(),s=rr();return t.useMemo(()=>({auth:e,os:r,workspaces:s}),[e,r,s])}function kr(e,r){const s=Ot(),n=It(),a=tr();return yt(t.useMemo(()=>({os:s,auth:n,workspaces:a}),[s,n,a]),e||(e=>e),r)}function vr(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 Sr(){return kr(e=>e.os)}let Cr=null;function Pr(){const e=xr(),r=Sr(),{serverUrl:s,version:n,orgId:a,settings:o}=r,i=t.useMemo(()=>oe(r)?new se({serverUrl:s,version:n,orgId:a}):null,[s,n,a]),c=t.useCallback(async t=>i?Cr||(Cr=(async()=>{try{const r=await i.getSettings(t);return e.os(At(r)),r}catch(e){return _(e,{component:"useSaaSSettings",action:"getSettings",metadata:{serverUrl:s,version:n,orgId:a}}),null}finally{Cr=null}})(),Cr):null,[i,e,s,n,a]);return vr(async e=>{o||oe(r)&&await c(e)},[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 Er(){const e=Sr(),r=xr(),s=t.useCallback(()=>{z(),r.auth(bt()),e.auth?.callbacks?.onSessionExpired?.("expired")},[r,e.auth?.callbacks?.onSessionExpired]),n=function(e,r){return t.useMemo(()=>new ae({...e,onUnauthorized:r}),[e.serverUrl,e.version,e.orgId,r])}(e,s);return t.useMemo(()=>({os:e,api:n}),[e,n])}const Nr=e=>{const{t:r}=yr(),{os:s,api:n}=Er(),a=oe(s),[o,i]=t.useState(null),[c,l]=t.useState(!1),[u,d]=t.useState(null),p=t.useCallback(async()=>{if(e&&a){l(!0),d(null);try{const t=await n.getPublicPlans(e);i(t)}catch(t){const s=O(t,"errors.fetchPlans",r);d(s),T(t,{component:"usePublicPlans",action:"fetchPlans",metadata:{slug:e}})}finally{l(!1)}}else i(null)},[n,e,a]);t.useEffect(()=>{p()},[p]);const h=e&&!a||c;return{items:o?.items??[],plans:o?.plans??[],notes:o?.notes,loading:h,error:u,refetch:p}},Ir=e=>{const{t:r}=yr(),{api:s}=Er(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),u=t.useCallback(async()=>{if(e){i(!0),l(null);try{const t=await s.getCurrentSubscription(e);a(t)}catch(t){const s=O(t,"errors.fetchSubscription",r);l(s),T(t,{component:"useSubscription",action:"fetchSubscription",metadata:{workspaceId:e}})}finally{i(!1)}}else a(null)},[s,e]);return t.useEffect(()=>{u()},[u]),{subscription:n,loading:o,error:c,refetch:u}},Rr=(e,r)=>{const{t:s}=yr(),{api:n}=Er(),[a,o]=t.useState(null),[i,c]=t.useState(!1),[l,u]=t.useState(null),d=t.useCallback(async()=>{if(e){c(!0),u(null);try{const t=r?await n.getPlanGroupByVersion(e,r):await n.getPlanGroup(e);o(t)}catch(t){const n=O(t,"errors.fetchPlanGroup",s);u(n),T(t,{component:"usePlanGroup",action:"fetchPlanGroup",metadata:{workspaceId:e,groupVersionId:r}})}finally{c(!1)}}else o(null)},[n,e,r]);return t.useEffect(()=>{d()},[d]),{planGroup:a,loading:i,error:l,refetch:d}},jr=e=>{const{t:r}=yr(),{api:s}=Er(),[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 ye(),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}},Ar=e=>{const{t:r}=yr(),{api:s}=Er(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),u=t.useCallback(async()=>{if(e){i(!0),l(null);try{const t=await s.getAllQuotaUsage(e);a(t.quotas)}catch(t){const s=O(t,"errors.fetchAllQuotaUsage",r);l(s),T(t,{component:"useAllQuotaUsage",action:"fetchAllUsage",metadata:{workspaceId:e}})}finally{i(!1)}}else a(null)},[s,e]);return t.useEffect(()=>{u()},[u]),{quotas:n,loading:o,error:c,refetch:u}},Ur=t.createContext(null);Ur.displayName="SubscriptionContext";const Wr=t.memo(function({children:r}){const s=kr(e=>e.workspaces.currentWorkspace),{subscription:n,loading:a,error:o,refetch:i}=Ir(s?._id);t.useEffect(()=>be(i),[i]);const c=t.useMemo(()=>({response:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return e.jsx(Ur.Provider,{value:c,children:r})});function Fr(){const e=t.useContext(Ur);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}Wr.displayName="SubscriptionContextProvider";const Tr=e=>{const{t:r}=yr(),{api:s}=Er(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),u=t.useCallback(async()=>{if(e){i(!0),l(null);try{const t=await s.getCreditBalance(e);a(t)}catch(t){const s=O(t,"errors.fetchCreditBalance",r);l(s),T(t,{component:"useCreditBalance",action:"fetchBalance",metadata:{workspaceId:e}})}finally{i(!1)}}else a(null)},[s,e]);return t.useEffect(()=>{u()},[u]),{balance:n,loading:o,error:c,refetch:u}},_r=e=>{const{t:r}=yr(),{api:s}=Er(),[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 he(),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}},Or=e=>{const{t:r}=yr(),{api:s}=Er(),[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}},Dr=e=>{const{t:r}=yr(),{api:s}=Er(),[n,a]=t.useState([]),[o,i]=t.useState(!1),[c,l]=t.useState(null),u=t.useCallback(async()=>{if(e){i(!0),l(null);try{const t=await s.getCreditPackages(e);a(t)}catch(t){const s=O(t,"errors.fetchCreditPackages",r);l(s),T(t,{component:"useCreditPackages",action:"fetchPackages",metadata:{workspaceId:e}})}finally{i(!1)}}else a([])},[s,e]);return t.useEffect(()=>{u()},[u]),{packages:n,loading:o,error:c,refetch:u}},Lr=()=>{const{t:e}=yr(),{os:r,api:s}=Er(),n=oe(r),[a,o]=t.useState([]),[i,c]=t.useState(),[l,u]=t.useState(!1),[d,p]=t.useState(null),h=t.useCallback(async()=>{if(n){u(!0),p(null);try{const e=await s.getPublicCreditPackages();o(e.packages||[]),c(e.notes)}catch(t){const r=O(t,"errors.fetchCreditPackages",e);p(r),T(t,{component:"usePublicCreditPackages",action:"fetchPackages"})}finally{u(!1)}}else o([])},[s,n]);t.useEffect(()=>{h()},[h]);return{packages:a,notes:i,loading:!n||l,error:d,refetch:h}},Mr=t.createContext(null);Mr.displayName="CreditBalanceContext";const $r=t.memo(function({children:r}){const s=kr(e=>e.workspaces.currentWorkspace),{balance:n,loading:a,error:o,refetch:i}=Tr(s?._id);t.useEffect(()=>pe(i),[i]);const c=t.useMemo(()=>({balance:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return e.jsx(Mr.Provider,{value:c,children:r})});function Br(){const e=t.useContext(Mr);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}$r.displayName="CreditBalanceContextProvider";const qr=({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 "})]}),Vr=({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(qr,{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 "})]});Vr.displayName="FullScreenLoader";const zr=t.createContext(null),Gr=({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(zr.Provider,{value:u,children:[r,n.visible&&e.jsx(Vr,{message:n.message,children:d})]})};function Jr(){const e=t.useContext(zr);if(!e)throw new Error("useFullScreenLoader must be used within FullScreenLoaderProvider");return e}Gr.displayName="FullScreenLoaderProvider";const Kr=t.createContext({appPermissions:void 0});function Yr({appPermissions:r,children:s}){const n=t.useMemo(()=>({appPermissions:r}),[r]);return e.jsx(Kr.Provider,{value:n,children:s})}function Hr(){return t.useContext(Kr)}const Qr=t.createContext(null);Qr.displayName="QuotaUsageContext";const Zr=t.memo(function({children:r}){const s=kr(e=>e.workspaces.currentWorkspace),{quotas:n,loading:a,error:o,refetch:i}=Ar(s?._id);t.useEffect(()=>ge(i),[i]);const c=t.useMemo(()=>({quotas:n,loading:a,error:o,refetch:i}),[n,a,o,i]);return e.jsx(Qr.Provider,{value:c,children:r})});function Xr(){const e=t.useContext(Qr);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}Zr.displayName="QuotaUsageContextProvider";const es=t.createContext({});function ts({ui:r,children:s}){const n=t.useMemo(()=>r??{},[r]);return e.jsx(es.Provider,{value:n,children:s})}function rs(){return t.useContext(es)}function ss(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?ss(r[e],s):s;return r}const ns="saas-oauth-state";function as(){M(ns)}const os={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"},is=new Set(Object.values(os));const cs=new class{constructor(){this.listeners=new Set,this.currentState={open:!1,section:os.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||os.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(){this.currentState={...this.currentState,params:void 0}}notifyListeners(){this.listeners.forEach(e=>{e(this.currentState)})}},ls=()=>{const e=xr(),{os:r,api:s}=Er(),{settings:n}=Pr(),a=kr(e=>e.workspaces),o=kr(e=>e.auth.session?.user),i=t.useCallback((t,r)=>{if((!(t._id===a.currentWorkspace?._id)||r?.forceEmit)&&t){const r=a.currentWorkspace;et(t),e.workspaces(Vt(t)),le.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(Ht(t._id));try{const e=r.auth?.callbacks?.onWorkspaceChange;if(e){const r=at(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(Ht(null))}},[e,r.auth?.callbacks?.onWorkspaceChange,i,o]),l=t.useRef(c);l.current=c,t.useEffect(()=>{if(!a.isInitialized){const t=tt();if(e.workspaces(Gt(!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(()=>{rt(),e.workspaces(zt())},[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(Jt(!0)),e.workspaces(Kt(null));try{const t=await s.getWorkspaces();if(e.workspaces(Lt(t)),t.length>0){const e=tt();if(e&&st(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(Kt(t instanceof Error?t.message:"Failed to fetch workspaces"))}finally{e.workspaces(Jt(!1)),d.current=!1}}},[s,a.loading,e,c]),g=t.useCallback(async()=>{if(!a.refreshing&&!d.current){d.current=!0,e.workspaces(Yt(!0));try{const t=await s.getWorkspaces();e.workspaces(Lt(t))}catch(e){}finally{e.workspaces(Yt(!1)),d.current=!1}}},[s,a.refreshing,e]),f=t.useCallback(async(t,r)=>{const n=await s.createWorkspace({name:t,image:r});e.workspaces(Mt(n)),await c(n),le.emitWorkspaceCreated(n).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceCreated",metadata:{workspaceId:n._id}})}),setTimeout(()=>{cs.openWorkspaceSettings(os.Subscription)},300)},[s,e,c]),w=t.useCallback(async(t,r)=>{const n=await s.updateWorkspace(t._id,r);e.workspaces($t(n)),le.emitWorkspaceUpdated(n).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"emitWorkspaceUpdated",metadata:{workspaceId:n._id}})})},[s,e]),b=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(qt(t)),t}catch(e){return T(e,{component:"useSaaSWorkspaces",action:"getFeatures"}),null}finally{p.current=!1}},[s,e,a.allFeatures]),y=t.useCallback(async(e,t,r)=>await s.updateFeature(e,t,r),[s]),x=t.useCallback(async e=>s.updateSettings(e),[s]),k=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&&(et(r),e.workspaces(Vt(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 v=t.useCallback(async e=>await s.getWorkspaceUsers(e),[s]),S=t.useCallback(async(e,t,r)=>{const o=a.workspaces.find(t=>t._id===e);if(o){const e=Qe({settingsMaxUsers:n?.workspace?.maxWorkspaceUsers}),t=Ze({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&&le.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"})}),ye(),i},[s,a.workspaces,g,n]),C=t.useCallback(async(e,t)=>{const r=a.workspaces.find(t=>t._id===e);if(r&&nt(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;le.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"})}),ye(),o},[s,a.workspaces,g]),P=t.useCallback(async(e,t,r)=>{if(r.role){const r=a.workspaces.find(t=>t._id===e);if(r&&nt(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&&le.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]),E=t.useCallback(async e=>{const t=await s.getProfile().catch(()=>null),r=await s.updateUserProfile(e);return le.emitUserUpdated(r,t||void 0).catch(e=>{T(e,{component:"useSaaSWorkspaces",action:"emitUserUpdated",metadata:{userId:r._id}})}),r},[s]),N=t.useCallback(async()=>await s.getProfile(),[s]),I=t.useCallback(async e=>await s.getWorkspace(e),[s]),R=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(!nt(r,o.id))throw new Error("Only the workspace creator can delete the workspace");const n=await s.deleteWorkspace(t);return e.workspaces(Bt(t)),a.currentWorkspace?._id===t&&(rt(),e.workspaces(zt())),r&&le.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:f,allFeatures:a.allFeatures,getFeatures:b,updateFeature:y,updateWorkspaceSettings:x,updateWorkspacePermissions:k,getWorkspace:I,updateWorkspace:w,getUsers:v,addUser:S,removeUser:C,updateUser:P,getProfile:N,updateUserProfile:E,deleteWorkspace:R,switching:null!==a.switchingToId,switchingToId:a.switchingToId}};function us(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 ds(e,t){return{user:e,sessionId:t,expires:new Date(Date.now()+864e5).toISOString()}}function ps(){return kr(e=>e.auth)}function hs(){const{t:e}=yr(),r=xr(),s=ps(),n=Sr(),{serverUrl:a,orgId:o,auth:i}=n,{resetCurrentWorkspace:c,currentWorkspace:l}=ls(),u=Jr(),d=t.useMemo(()=>new Z({serverUrl:a,version:n.version}),[a,n.version]),p=t.useCallback(async t=>{Ue(t||window.location.href),r.auth(mt()),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(ns,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(ft()),new Error(s.message||e("errors.generic"));Re(s.data.redirectUrl)}catch(e){throw u.hide(),r.auth(ft()),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(bt()),c()}},[r,c,i?.callbacks?.onSignOut]),m=t.useCallback(e=>{l?cs.openWorkspaceSettings(e):T(new Error("Cannot open settings: No current workspace"),{component:"useSaaSAuth",action:"openWorkspaceSettings"})},[l]),g=t.useCallback(()=>{l?cs.openWorkspaceSettings(os.Credits,{action:ke.OpenCreditStore}):T(new Error("Cannot open credit store: No current workspace"),{component:"useSaaSAuth",action:"openCreditStore"})},[l]),f=t.useCallback(()=>{l?cs.openWorkspaceSettings(os.Subscription,{action:ke.SelectPlan}):T(new Error("Cannot open plan picker: No current workspace"),{component:"useSaaSAuth",action:"openPlanPicker"})},[l]),w=t.useMemo(()=>pt(s.status),[s.status]);return t.useMemo(()=>({user:s.session?.user,session:s.session,status:s.status,...w,signIn:p,signOut:h,openWorkspaceSettings:m,openCreditStore:g,openPlanPicker:f}),[s.session,s.status,w,p,h,m,g,f])}const ms=t.memo(({children:r,callbacks:s})=>{const{t:n}=yr(),a=xr(),o=ps(),i=Sr(),c=pt(o.status).isAuthenticated,l=Jr(),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(!oe(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 Z({serverUrl:o,version:c}),p=await d.getProfile(t),h=ds(us(p,u,r.auth?.clientId||""),t);l.show(n("loading.almostThere")),V(h.sessionId),a.auth(wt(h)),K();const m=We();m&&m!==window.location.href&&Re(m),l.hide()}}catch(t){throw l.hide(),We(),T(t,{component:"AuthProviderWrapper",action:"handleAuthRedirect",metadata:{hasCode:!!e}}),a.auth(ft()),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(!oe(i))return;if(J())return;if(!s?.getSession)return p.current=!0,void a.auth(ft());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(ft()),l.hide(),"undefined"!=typeof window&&Ue(window.location.href),void s?.onSessionExpired?.("missing");try{l.show(n("loading.verifyingAccount"));const e=new Z({serverUrl:t,version:r}),s=await e.getProfile(i),c=ds(us(s,o,u),i);V(c.sessionId),p.current=!0,a.auth(wt(c)),l.hide();const d=We();d&&d!==window.location.href&&Re(d)}catch(e){T(e,{component:"AuthProviderWrapper",action:"fetchUserProfile"}),p.current=!0,a.auth(ft()),l.hide(),"undefined"!=typeof window&&Ue(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(!oe(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(ns);if(M(ns),!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 as(),K(),T(new Error("OAuth state mismatch — possible CSRF attack"),{component:"AuthProviderWrapper",action:"validateOAuthState"}),void a.auth(ft());as(),u.current=!0,d.current=e;let r=!1;return a.auth(gt()),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})});ms.displayName="AuthProviderWrapper";const gs=t.memo(({config:r,auth:s,children:n})=>{const a=xr();Sr();const o=t.useMemo(()=>({clientId:s?.clientId||"",redirectUrl:s?.redirectUrl||"",callbacks:s?.callbacks}),[s?.clientId,s?.redirectUrl,s?.callbacks]);return t.useEffect(()=>{a.os(jt({...r,auth:o}))},[r,o,a]),e.jsx(e.Fragment,{children:n})});gs.displayName="ContextConfigProvider";const fs=t.createContext({container:null,setContainer:()=>{}}),ws=t.memo(({children:r})=>{const[s,n]=t.useState(null),a=t.useMemo(()=>({container:s,setContainer:n}),[s]);return e.jsxs(fs.Provider,{value:a,children:[r,e.jsx("div",{ref:n,id:"saas-os-portal",className:"saas-os-ui",style:{width:"100%",height:"100%"}})]})});ws.displayName="PortalProvider";const bs=t.createContext(null);function ys(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 xs=t.memo(function({children:r,serviceWorkerPath:s="/push-sw.js",autoSubscribe:n=!1}){const{t:a}=yr(),o=Sr(),{isAuthenticated:i}=hs(),c=t.useMemo(()=>"undefined"!=typeof window&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window,[]),l=t.useMemo(()=>new re({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:ys(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(bs.Provider,{value:g,children:r})});const ks=t.createContext(void 0),vs=t.memo(({children:r})=>{const{t:s}=yr(),n=Sr(),a=function(){const e=Sr();return t.useMemo(()=>new ne(e),[e.serverUrl,e.version])}(),{isAuthenticated:o}=hs(),{serverUrl:i,version:c}=n,[l,u]=t.useState({}),[d,p]=t.useState({}),[h,m]=t.useState(!1),[g,f]=t.useState(null),w=t.useCallback(async e=>{if(i&&c&&o)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"));f(t),T(e,{component:"UserProvider",action:"fetchAttributes"})}else u({})},[a,i,c,o]),b=t.useCallback(async()=>{if(i&&c&&o){m(!0),f(null);try{await w()}finally{m(!1)}}},[i,c,o,w]),y=t.useCallback(async e=>{m(!0),f(null);try{const t=await a.updateAttributes(e);return await w(),t}catch(t){const r=t instanceof Error?t:new Error(s("errors.generic"));throw f(r),T(t,{component:"UserProvider",action:"updateAttributes",metadata:{updates:e}}),t}finally{m(!1)}},[a,w]),x=t.useCallback(async(e,t)=>{m(!0),f(null);try{const r=await a.updateAttribute(e,t);return await w(),r}catch(r){const n=r instanceof Error?r:new Error(s("errors.generic"));throw f(n),T(r,{component:"UserProvider",action:"updateAttribute",metadata:{attributeKey:e,value:t}}),r}finally{m(!1)}},[a,w]),k=t.useCallback(async e=>{if(i&&c&&o)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"));f(t),T(e,{component:"UserProvider",action:"fetchFeatures"})}else p({})},[a,i,c,o]),v=t.useCallback(async()=>{if(i&&c&&o){m(!0),f(null);try{await k()}finally{m(!1)}}},[i,c,o,k]);vr(async e=>{if(!o||!i||!c)return u({}),void p({});m(!0),f(null);try{await Promise.all([w(e),k(e)])}finally{m(!1)}},[o,i,c,w,k],{onError:e=>T(e,{component:"UserProvider",action:"initialFetch",metadata:{step:"fetchAttributesAndFeatures"}})});const S=t.useMemo(()=>({attributes:l,features:d,isLoading:h,error:g,updateAttributes:y,updateAttribute:x,refreshAttributes:b,refreshFeatures:v}),[l,d,h,g,y,x,b,v]);return e.jsx(ks.Provider,{value:S,children:r})});vs.displayName="UserProvider";const Ss=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"}}),Cs=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(Ss({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})]})});Cs.displayName="Button";const Ps=v.Root,Es=v.Trigger,Ns=v.Portal,Is=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}));Is.displayName=v.Overlay.displayName;const Rs=y.forwardRef(({className:t,children:r,...s},n)=>{const{container:a}=y.useContext(fs);return e.jsxs(Ns,{container:a,children:[e.jsx(Is,{}),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"})]})]})]})});Rs.displayName=v.Content.displayName;const js=({className:t,...r})=>e.jsx("div",{className:E("flex flex-col space-y-1.5 text-center sm:text-start",t),...r});js.displayName="DialogHeader";const As=y.forwardRef(({className:t,...r},s)=>e.jsx(v.Title,{ref:s,className:E("text-lg font-semibold leading-none tracking-tight",t),...r}));As.displayName=v.Title.displayName;const Us=y.forwardRef(({className:t,...r},s)=>e.jsx(v.Description,{ref:s,className:E("text-sm text-muted-foreground",t),...r}));function Ws(e){const{user:r}=hs(),{currentWorkspace:s}=ls(),{settings:n}=Pr(),{appPermissions:a}=Hr(),o=e??s??null,i=r?.id??null,c=t.useMemo(()=>o?at(o,i):null,[o,i]),l=t.useMemo(()=>!!o&&nt(o,i),[o,i]),u=t.useMemo(()=>ut({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 Fs(){const e=rs(),{can:r}=Ws();return{visible:t.useCallback((t,s)=>!1!==t(e)&&(void 0===s||r(s)),[e,r]),ui:e}}function Ts(){const e=Sr();return t.useMemo(()=>new te(e),[e.serverUrl,e.version])}function _s(){const e=Ts(),[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 Os({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 Ds({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 Ls({className:t,...r}){return e.jsx("div",{className:E("animate-pulse rounded-md bg-primary/10",t),...r})}Us.displayName=v.Description.displayName;const Ms={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 $s=c.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Bs=y.forwardRef(({className:t,...r},s)=>e.jsx(x.Root,{ref:s,className:E($s(),t),...r}));Bs.displayName=x.Root.displayName;const qs=o.FormProvider,Vs=y.createContext({}),zs=({...t})=>e.jsx(Vs.Provider,{value:{name:t.name},children:e.jsx(o.Controller,{...t})}),Gs=()=>{const e=y.useContext(Vs),t=y.useContext(Js),{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}},Js=y.createContext({}),Ks=y.forwardRef(({className:t,...r},s)=>{const n=y.useId();return e.jsx(Js.Provider,{value:{id:n},children:e.jsx("div",{ref:s,className:E("space-y-2",t),...r})})});Ks.displayName="FormItem";const Ys=y.forwardRef(({className:t,...r},s)=>{const{error:n,formItemId:a}=Gs();return e.jsx(Bs,{ref:s,className:E(n&&"text-destructive",t),htmlFor:a,...r})});Ys.displayName="FormLabel";const Hs=y.forwardRef(({...t},r)=>{const{error:s,formItemId:n,formDescriptionId:a,formMessageId:o}=Gs();return e.jsx(i.Slot,{ref:r,id:n,"aria-describedby":s?`${a} ${o}`:`${a}`,"aria-invalid":!!s,...t})});Hs.displayName="FormControl";const Qs=y.forwardRef(({className:t,...r},s)=>{const{formDescriptionId:n}=Gs();return e.jsx("p",{ref:s,id:n,className:E("text-sm text-muted-foreground",t),...r})});Qs.displayName="FormDescription";const Zs=y.forwardRef(({className:t,children:r,...s},n)=>{const{error:a,formMessageId:o}=Gs(),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});Zs.displayName="FormMessage";const Xs=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}));Xs.displayName="Input";const en=y.forwardRef(({className:t,...r},s)=>e.jsx(S.Root,{className:E("grid gap-2",t),...r,ref:s}));en.displayName=S.Root.displayName;const tn=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"})})}));tn.displayName=S.Item.displayName;const rn=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(sn,{}),e.jsx(C.Corner,{})]}));rn.displayName=C.Root.displayName;const sn=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 nn(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>`}sn.displayName=C.ScrollAreaScrollbar.displayName;const an=["🏢","🏬","🏣","🏤","🏦","🏛️","🏠","🏡","🏭","🏗️","🏪","🏨","🏫","🏥","💼","📊","📈","📉","📋","📁","📂","🗂️","🗃️","🗄️","📅","🗓️","📝","🖋️","✏️","🖊️","🖌️","🖍️","📇","📌","📍","📎","🖇️","💻","🖥️","🖨️","🖱️","⌨️","📱","📲","📡","🌐","🔗","🔒","🔓","⚙️","🔧","🛠️","🧑💻","👨💻","👩💻","🕹️","💾","📟","🖥️","🖲️","🚀","💡","🎨","🖼️","🧪","🔬","🧬","🎯","⚡","🎲","🎮","🧩","📷","🎥","✉️","📨","📩","📧","📞","☎️","📠","🗣️","💬","🗨️","📢","📣","🔔","🛎️","💰","💸","💳","🏦","📈","📉","⚖️","🧾","🪙","🏛️","⚗️","🧪","🔭","🔬","🩺","🧬","🩻","🏥","🌱","🌍","🌏","🌎","🌡️","👨💼","👩💼","👨🏫","👩🏫","👨🔬","👩🔬","👨🎨","👩🎨","👨🔧","👩🔧","👨🚀","👩🚀","👨⚖️","👩⚖️","🏅","🎖️","🥇","🥈","🥉","🏆","🎗️","🔑","🗝️","🧭","🛡️","🚩","🏳️🌈","🎟️","🎫"];const on=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-Dy8W3NA6.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));const cn=({children:r})=>{const{currentWorkspace:s,switchToWorkspace:n,workspaces:a}=ls(),[o,i]=t.useState(!1),[c,l]=t.useState(os.Profile),u=t.useRef(!1);return t.useEffect(()=>{const e=cs.getState();i(e.open),l(e.section);return cs.subscribe(e=>{i(e.open),l(e.section)})},[]),t.useEffect(()=>{if(u.current)return;if(!s)return;const e=Ee();if(!e)return;const t=function(e){if(e.screen&&is.has(e.screen))return e.screen;switch(e.action){case ke.Checkout:case ke.Billing:case ke.SelectPlan:return os.Subscription;case ke.CreditPurchase:return os.Credits;default:return null}}(e);if(!t)return u.current=!0,void Ne();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,Ne()}):(u.current=!0,void Ne())}u.current=!0,cs.openWorkspaceSettings(t,e),Ne()},[s,a,n]),e.jsxs(e.Fragment,{children:[r,s&&o&&e.jsx(ht,{fallback:null,children:e.jsx(t.Suspense,{fallback:null,children:e.jsx(on,{workspace:s,open:o,onOpenChange:e=>{e||cs.closeSettings()},section:c,onSectionChange:e=>{cs.setSection(e)},showTrigger:!1})})})]})},ln=(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).`)},un=t.memo(({serverUrl:r,version:s,orgId:n,auth:a,locale:o,defaultPermissions:i,getCheckoutStripeParams:c,loadingComponent:l,ui:u,children:d})=>{ln(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(()=>(le.setCallbacks(m?{handleEvent:m}:null),()=>{le.setCallbacks(null)}),[m]),e.jsx(pr,{locale:o,messageOverrides:u?.messages,children:e.jsx(sr,{children:e.jsx(Gr,{loadingComponent:l,children:e.jsx(ms,{callbacks:h,children:e.jsx(ws,{children:e.jsx(gs,{config:p,auth:a,children:e.jsx(ar,{getCheckoutStripeParams:c,children:e.jsx(Yr,{appPermissions:i,children:e.jsx(ts,{ui:u,children:e.jsx(vs,{children:e.jsx(Wr,{children:e.jsx(Zr,{children:e.jsx($r,{children:e.jsx(xs,{children:e.jsx(cn,{children:d})})})})})})})})})})})})})})})});un.displayName="SaaSOSProviderInner";const dn=({children:t,...r})=>e.jsx(ht,{errorTitle:r.ui?.errorBoundary?.title,retryLabel:r.ui?.errorBoundary?.retryLabel,children:e.jsx(un,{...r,children:t})});dn.displayName="SaaSOSProvider";const pn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{status:n}=hs();return pt(n).isLoading?r??null:n!==exports.AuthStatus.authenticated?s??null:t},hn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{status:n}=hs();return pt(n).isLoading?r??null:n!==exports.AuthStatus.unauthenticated?s??null:t};pn.displayName="WhenAuthenticated",hn.displayName="WhenUnauthenticated";const mn=e=>{const{children:t,fallback:r,roles:s}=e,{user:n}=hs();return s.includes(n?.role??"")?t:r||null},gn=e=>{const{children:t,fallback:r,roles:s}=e,{user:n}=hs(),{currentWorkspace:a}=ls(),o=a?.users.find(e=>e._id===n?.id);return o&&s.includes(o?.role??"")?t:r||null};mn.displayName="WhenRoles",gn.displayName="WhenWorkspaceRoles";const fn=e=>{const{children:t,fallback:r,permission:s}=e,{can:n}=Ws();return n(s)?t:r??null};function wn(){const e=t.useContext(ks);if(void 0===e)throw new Error("useUserFeatures must be used within a UserProvider");return{features:e.features,isLoading:e.isLoading,error:e.error,refreshFeatures:e.refreshFeatures,isFeatureEnabled:t=>Boolean(e.features[t])}}fn.displayName="WhenPermission";const bn=e=>{const{children:t,slug:r}=e,{currentWorkspace:s}=ls(),n=s?.features?.[r];return n?t:null},yn=e=>{const{children:t,slug:r}=e,{currentWorkspace:s}=ls(),n=s?.features?.[r];return n?null:t},xn=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:s}=wn();return s(r)?t:null},kn=e=>{const{children:t,slug:r}=e,{isFeatureEnabled:s}=wn();return s(r)?null:t};bn.displayName="WhenWorkspaceFeatureEnabled",yn.displayName="WhenWorkspaceFeatureDisabled",xn.displayName="WhenUserFeatureEnabled",kn.displayName="WhenUserFeatureDisabled";const vn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Fr();return a?r??null:n?.subscription?t:s??null},Sn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Fr();return a?r??null:n?.subscription?s??null:t},Cn=e=>{const{children:t,plans:r,loadingComponent:s,fallbackComponent:n}=e,{response:a,loading:o}=Fr();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},Pn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Fr();return a?r??null:"trialing"!==n?.subscription?.subscriptionStatus?s??null:t},En=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{response:n,loading:a}=Fr();return a?r??null:n?.subscription?.subscriptionStatus===qe.Trialing?s??null:t},Nn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{behavior:n}=rs(),a=e.daysThreshold??n?.trialEndingDays??3,{response:o,loading:i}=Fr();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};vn.displayName="WhenSubscription",Sn.displayName="WhenNoSubscription",Cn.displayName="WhenSubscriptionToPlans",Pn.displayName="WhenTrialing",En.displayName="WhenNotTrialing",Nn.displayName="WhenTrialEnding";const In=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:o}=Xr();if(o)return s??null;const i=a?.[t];return i?i.available<=0?n??null:r:n??null},Rn=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:o}=Xr();if(o)return s??null;const i=a?.[t];return i?i.available>0?n??null:r:n??null},jn=e=>{const{slug:t,children:r,loadingComponent:s,fallbackComponent:n}=e,{quotas:a,loading:o}=Xr();if(o)return s??null;const i=a?.[t];return i&&i.hasOverage&&!1!==i.allowOverage?r:n??null},An=e=>{const{slug:t,threshold:r,children:s,loadingComponent:n,fallbackComponent:a}=e,{quotas:o,loading:i}=Xr();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};In.displayName="WhenQuotaAvailable",Rn.displayName="WhenQuotaExhausted",jn.displayName="WhenQuotaOverage",An.displayName="WhenQuotaThreshold";const Un=({children:e})=>{const{currentWorkspace:t}=ls(),r=t?._id,{balance:s,loading:n,error:a,refetch:o}=Br(),{packages:i,loading:c}=Dr(r),{consumeCredits:l,loading:u,error:d}=_r(r),{purchaseCredits:p,loading:h,error:m}=Or(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}=Pe(r),n=await p({creditPackageId:e._id,successUrl:t,cancelUrl:s});n.url&&Re(n.url)},purchasing:h,refetch:o,error:d||m||a})};Un.displayName="CreditActionsProvider";const Wn=({children:e})=>{const{balance:t,loading:r,error:s,refetch:n}=Br();return e({balance:t,loading:r,error:s,refetch:n})};Wn.displayName="CreditBalance";const Fn=e=>{const{min:t=1,children:r,loadingComponent:s,fallbackComponent:n}=e,{balance:a,loading:o}=Br();return o?s??null:a?a.available<t?n??null:r:n??null},Tn=e=>{const{children:t,loadingComponent:r,fallbackComponent:s}=e,{balance:n,loading:a}=Br();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}=Br();return o?s??null:a?a.available>t?n??null:r:n??null};function On(e){if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t}Fn.displayName="WhenCreditsAvailable",Tn.displayName="WhenCreditsExhausted",_n.displayName="WhenCreditsLow";const Dn=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 Ln({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 Mn({logo:t}){const{t:r}=yr();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 $n=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}));$n.displayName=k.Root.displayName;const Bn=y.forwardRef(({className:t,...r},s)=>e.jsx(k.Image,{ref:s,className:E("aspect-square h-full w-full",t),...r}));Bn.displayName=k.Image.displayName;const qn=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}));qn.displayName=k.Fallback.displayName;const Vn=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}));Vn.displayName=P.Root.displayName;const zn=t.lazy(()=>Promise.resolve().then(function(){return require("./SettingsDialog-Dy8W3NA6.cjs")}).then(function(e){return e.SettingsDialog}).then(e=>({default:e.default})));function Gn(r){const{t:s}=yr(),{visible:n}=Fs(),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,w=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($n,{className:"h-8 w-8 flex items-center justify-center",children:[e.jsx("div",{children:e.jsx(Bn,{src:i.image&&i.image.trim()?i.image:void 0})}),e.jsx(qn,{children:(b=i.name,b.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&&w&&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:w})})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[h?null:e.jsx(Cs,{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(zn,{workspace:i,onClose:()=>{if(h){const e=d.findIndex(e=>e._id?.toString()===i._id?.toString());-1!==e&&c(d[e])}}})})]})]});var b}function Jn(r){const{t:s,dir:n}=yr(),{switching:i}=ls(),[c,u]=t.useState(!1),[p,h]=t.useState("emoji"),[m,g]=t.useState("🏢"),[f,w]=t.useState(!1),{createWorkspace:b}=ls(),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(Ps,{open:c,onOpenChange:u,children:[e.jsx(Es,{asChild:!0,children:e.jsxs(Cs,{className:"w-full rounded-none",disabled:i,children:[e.jsx(l.Plus,{className:"h-4 w-4 me-2"}),s("workspace.createNew")]})}),e.jsxs(Rs,{dir:n,className:"max-w-xl min-w-full sm:min-w-[600px]",children:[e.jsxs(js,{children:[e.jsx(As,{children:s("workspace.createTitle")}),e.jsx(Us,{children:s("workspace.createDescription")})]}),e.jsx(qs,{...x,children:e.jsxs("form",{onSubmit:x.handleSubmit(async function(e){let t="";if("emoji"===p)t=nn(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")})}w(!0);try{await b(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{w(!1)}}),children:[e.jsx(zs,{control:x.control,name:"name",render:({field:t})=>e.jsxs(Ks,{children:[e.jsx(Ys,{children:s("workspace.workspaceName")}),e.jsx(Hs,{children:e.jsx(Xs,{placeholder:s("workspace.workspaceNamePlaceholder"),...t})}),e.jsx(Zs,{})]})}),e.jsxs("div",{className:"flex flex-col gap-y-2 my-2",children:[e.jsxs("div",{children:[e.jsx(Bs,{className:"text-sm font-medium",children:s("workspace.workspaceIcon")}),e.jsx(Qs,{children:s("workspace.iconDescription")})]}),e.jsxs(en,{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(tn,{value:"emoji",id:"emoji"}),e.jsxs(Bs,{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(tn,{value:"url",id:"url"}),e.jsxs(Bs,{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(rn,{className:"h-32 w-full rounded-md border",children:e.jsx("div",{className:"p-4 grid grid-cols-8 gap-2",children:an.map((t,r)=>e.jsx("button",{type:"button",onClick:()=>(e=>{g(e),x.setValue("image",nn(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(zs,{control:x.control,name:"image",render:({field:t})=>e.jsxs(Ks,{children:[e.jsx(Ys,{children:s("workspace.imageUrl")}),e.jsx(Hs,{children:e.jsx(Xs,{placeholder:s("workspace.imageUrlPlaceholder"),...t})}),e.jsx(Qs,{children:s("workspace.imageUrlDescription")}),e.jsx(Zs,{})]})}),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(Cs,{type:"button",variant:"outline",onClick:()=>{u(!1),x.reset(),g("🏢"),h("emoji")},disabled:f,children:s("settings.common.cancel")}),e.jsx(Cs,{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=Z,exports.BBAction=ke,exports.BBScreen=Se,exports.BBStatus=ve,exports.BB_PARAM=xe,exports.BaseApi=Q,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}=yr(),[h,m]=t.useState(!1),[g,f]=t.useState(!1),{submitBetaForm:w,isLoading:b,isSubmitting:y,error:x,config:k,success:v,message:S}=(()=>{const{t:e}=yr(),r=Sr(),[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 ee(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 ee(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(Dn),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:b?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(Ls,{className:"h-24 w-24 rounded-lg"}),e.jsx(Ls,{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(Ls,{className:"h-4 w-16"}),e.jsx(Ls,{className:"h-10 w-full"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ls,{className:"h-4 w-16"}),e.jsx(Ls,{className:"h-10 w-full"})]}),e.jsx(Ls,{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(Mn,{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 w(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(Ln,{screen:k?.screen?.register}),e.jsx(zs,{control:C.control,name:"name",render:({field:t})=>e.jsxs(Ks,{className:i,children:[e.jsx(Ys,{children:p("beta.nameLabel")}),e.jsx(Hs,{children:e.jsx(Xs,{...t})}),e.jsx(Qs,{}),e.jsx(Zs,{})]})}),e.jsx(zs,{control:C.control,name:"email",render:({field:t})=>e.jsxs(Ks,{className:i,children:[e.jsx(Ys,{children:p("beta.emailLabel")}),e.jsx(Hs,{children:e.jsx(Xs,{...t})}),e.jsx(Qs,{}),e.jsx(Zs,{})]})}),e.jsx(Cs,{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(Cs,{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(Ln,{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=Be,exports.Button=Cs,exports.CURRENCY_DISPLAY=Fe,exports.CURRENCY_FLAG=Te,exports.ConnectedAgents=function({className:t,title:r,description:s,disconnectLabel:n,emptyLabel:a}){const{t:o,formattingLocale:i}=yr(),{formats:c}=rs(),{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,w=n??o("security.connectedAgentsDisconnect"),b=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(Ds,{title:g,description:f}),d&&e.jsx("div",{className:"space-y-3",children:[0,1].map(t=>e.jsx(Ls,{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(Os,{icon:e.jsx(l.Bot,{className:"h-5 w-5 text-muted-foreground"}),description:b}),!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(Cs,{variant:"outline",size:"sm",progress:h===t.clientId,onClick:()=>m(t.clientId),children:w})]},t.clientId))})]})},exports.ConnectedAgentsApi=te,exports.CreditActionsProvider=Un,exports.CreditBalance=Wn,exports.CreditBalanceContextProvider=$r,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}=Lr(),{isAuthenticated:d,signIn:p}=hs(),h=t.useCallback(e=>{if(d)cs.openWorkspaceSettings(os.Credits,{action:ke.CreditPurchase,packageId:e});else if(a){const t=Ce({action:ke.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(Ls,{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(Ls,{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=ct,exports.Dialog=Ps,exports.DialogContent=Rs,exports.DialogDescription=Us,exports.DialogTitle=As,exports.DialogTrigger=Es,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EmptyState=Os,exports.EventEmitter=ce,exports.Form=qs,exports.FormControl=Hs,exports.FormDescription=Qs,exports.FormField=zs,exports.FormItem=Ks,exports.FormLabel=Ys,exports.FormMessage=Zs,exports.FullScreenLoader=Vr,exports.Input=Xs,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.Label=Bs,exports.LoadingState=function({label:t,className:r}){const{t:s}=yr();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=Oe,exports.PLAN_CURRENCY_OPTIONS=De,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=ot,exports.PortalContext=fs,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}=Nr(r),{isAuthenticated:h,signIn:m}=hs(),g=t.useCallback((e,t,r)=>o?Ce({action:"selectPlan",plan:e,interval:t,currency:r},o):null,[o]),f=t.useCallback((e,t,r)=>{if(h)return void cs.openWorkspaceSettings(os.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(Ls,{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(Ls,{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=re,exports.PushNotificationProvider=xs,exports.QuotaUsageContextProvider=Zr,exports.RadioGroup=en,exports.RadioGroupItem=tn,exports.SDKEvent=ie,exports.SETTINGS_SCREENS=is,exports.SUPPORTED_LOCALES=cr,exports.SaaSOSProvider=dn,exports.ScrollArea=rn,exports.SectionHeader=Ds,exports.SettingsApi=se,exports.SettingsScreen=os,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=Ls,exports.StatusBanner=function({variant:t,title:r,message:s,description:n,icon:a,actionLabel:o,onAction:i,actionDisabled:c,className:l}){const u=Ms[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(Cs,{variant:"outline",size:"sm",onClick:i,disabled:c,className:E("flex-shrink-0",u.button),children:o})]})},exports.SubscriptionContextProvider=Wr,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus=qe,exports.UIConfigProvider=ts,exports.UserApi=ne,exports.WhenAuthenticated=pn,exports.WhenCreditsAvailable=Fn,exports.WhenCreditsExhausted=Tn,exports.WhenCreditsLow=_n,exports.WhenNoSubscription=Sn,exports.WhenNotTrialing=En,exports.WhenPermission=fn,exports.WhenQuotaAvailable=In,exports.WhenQuotaExhausted=Rn,exports.WhenQuotaOverage=jn,exports.WhenQuotaThreshold=An,exports.WhenRoles=mn,exports.WhenSubscription=vn,exports.WhenSubscriptionToPlans=Cn,exports.WhenTrialEnding=Nn,exports.WhenTrialing=Pn,exports.WhenUnauthenticated=hn,exports.WhenUserFeatureDisabled=kn,exports.WhenUserFeatureEnabled=xn,exports.WhenWorkspaceFeatureDisabled=yn,exports.WhenWorkspaceFeatureEnabled=bn,exports.WhenWorkspaceRoles=gn,exports.WorkspaceApi=ae,exports.WorkspaceSwitcher=function(r){const{t:s,dir:n}=yr(),{isAuthenticated:a,user:o}=hs(),i=oe(Sr()),{workspaces:c,currentWorkspace:u,loading:d,refreshing:p,switchingToId:h,fetchWorkspaces:m,getFeatures:g,refreshWorkspaces:f,setCurrentWorkspace:w,switchToWorkspace:b}=ls(),{settings:y}=Pr(),{visible:x}=Fs(),[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&&b(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(zn,{workspace:u,open:k,onOpenChange:v,showTrigger:!1})})]}):e.jsxs(Ps,{open:k,onOpenChange:v,children:[e.jsx(Es,{children:r.trigger?.(N,u)}),e.jsxs(Rs,{dir:n,className:"max-w-2xl min-w-full md:min-w-[800px]",children:[e.jsxs(js,{dir:n,children:[e.jsxs(As,{className:"flex items-center gap-2",children:[e.jsx(l.Building2,{className:"h-5 w-5"}),s("workspace.switchTitle")]}),e.jsx(Us,{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(Gn,{workspace:u,isCurrentWorkspace:!0,switchToWorkspace:b,switchingToId:h,onClose:()=>v(!1),setCurrentWorkspace:w,setOpen:v,workspacesToUse:I}),e.jsx(Vn,{}),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(Cs,{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(Xs,{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(rn,{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(Gn,{workspace:t,isCurrentWorkspace:r,switchToWorkspace:b,switchingToId:h,onClose:()=>v(!1),setCurrentWorkspace:w,setOpen:v,workspacesToUse:I},t._id)})})})]}),F&&e.jsxs(e.Fragment,{children:[e.jsx(Vn,{}),e.jsx(Jn,{onCreated:()=>{m()}})]})]})]})]})},exports.buttonVariants=Ss,exports.calculateBillableSeats=Ye,exports.calculateSeatOverageCents=He,exports.calculateTotalSubscriptionCents=function(e,t,r,s){const n=ze(e,t,r);return null===n?null:void 0===s?n:n+(He(e,t,r,s)??0)},exports.cleanBBParams=Ne,exports.clearAuthIntent=function(){M(je)},exports.cn=E,exports.consumeAuthIntent=We,exports.createBBUrl=Ce,exports.createCheckoutRedirectUrls=function(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:Ce({action:ke.Checkout,status:ve.Success,ws:e,screen:Se.Subscription},r),cancelUrl:Ce({action:ke.Checkout,status:ve.Cancel,ws:e,screen:Se.Subscription},r)}},exports.createCreditPurchaseRedirectUrls=Pe,exports.eventEmitter=le,exports.formatCents=Le,exports.formatOverageRate=function(e,t,r,s){if(null==e||e<0)return null;const n={...Me,...s},a=null!=t&&t>=1?t:1,o=_e(r),i=(e/100).toFixed(2);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={...Me,...a},i=null!=t&&t>=1?t:1,c=_e(s),l=(e/100).toFixed(2);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={...Me,...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} ${Le(t,s)}/${u}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${Le(t,s)}/${u}`:"—"},exports.formatQuotaWithPrice=function(e,t,r={}){const{overageInCents:s=!0,currency:n}=r,a=r.labels??$e,o=r.currencySymbol??_e(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=s?c/100:c,d="number"==typeof u&&Number.isFinite(u)?u.toFixed(2):String(c),p=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${a.then} ${o}${d}${p}`},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=ze,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()?Te[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=_e,exports.getDisplayCurrency=function(e,t){const r=Ve(e,t);return r?r.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=Ke,exports.getPricingVariant=Ve,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=s?i/100:i,l=(n??"").trim().toUpperCase();let u;if(l&&"number"==typeof c&&Number.isFinite(c))try{u=new Intl.NumberFormat(a,{style:"currency",currency:l,minimumFractionDigits:2}).format(c)}catch{u=`${r.currencySymbol??_e(n??"")}${c.toFixed(2)}`}else{u=`${r.currencySymbol??_e(n??"")}${"number"==typeof c?c.toFixed(2):String(i)}`}return{included:o,hasOverage:!0,allowOverage:!0,price:u,unit:t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?`${e.unitSize.toLocaleString(a)} ${t}`:t||""}},exports.getQuotaDisplayValue=function(e,t){if(null==e)return null;const 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=Ge(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=Ge,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=Je,exports.getStripePriceIdForInterval=function(e,t,r){const s=Ve(e,t);if(!s?.stripePrices)return null;const n=r===Be.Monthly?"monthlyPriceId":r===Be.Yearly?"yearlyPriceId":"quarterlyPriceId",a=r===Be.Monthly?"monthly":r===Be.Yearly?"yearly":void 0;return s.stripePrices[n]??(a?s.stripePrices[a]:void 0)??null},exports.getSvgImage=nn,exports.handleError=T,exports.hasPermission=function(e,t){const r=ut(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)},exports.invalidateCreditBalance=he,exports.invalidateQuotaUsage=fe,exports.invalidateSubscription=ye,exports.isWorkspaceOwner=nt,exports.mergeUIConfig=function(e,t){return t?ss(e,t):e},exports.readBBParams=Ee,exports.resolveMaxUsers=Qe,exports.resolvePermissions=ut,exports.safeRedirect=Re,exports.saveAuthIntent=Ue,exports.useAllQuotaUsage=Ar,exports.useBillingPortal=e=>{const{t:r}=yr(),{api:s}=Er(),[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}=yr(),{api:s}=Er(),[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 ye(),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=Ts,exports.useConsumeCredits=_r,exports.useCreateCheckoutSession=e=>{const{t:r}=yr(),{api:s}=Er(),{getCheckoutStripeParams:n}=t.useContext(nr),[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&&(ye(),fe()),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=Tr,exports.useCreditBalanceContext=Br,exports.useCreditPackages=Dr,exports.useCreditTransactions=(e,r)=>{const{t:s}=yr(),{api:n}=Er(),[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),[w,b]=t.useState(!1),[y,x]=t.useState(null),k=r?.type,v=r?.page,S=r?.limit,C=t.useCallback(async()=>{if(!e)return o([]),c(0),u(0),p(1),m(!1),void f(!1);b(!0),x(null);try{const t=await n.getCreditTransactions(e,{type:k,page:v,limit:S});o(t.docs||[]),c(t.totalDocs||0),u(t.totalPages||0),p(t.page||1),m(t.hasNextPage||!1),f(t.hasPrevPage||!1)}catch(t){const r=O(t,"errors.fetchCreditTransactions",s);x(r),T(t,{component:"useCreditTransactions",action:"fetchTransactions",metadata:{workspaceId:e}})}finally{b(!1)}},[n,e,k,v,S]);return t.useEffect(()=>{C()},[C]),{transactions:a,totalDocs:i,totalPages:l,page:d,hasNextPage:h,hasPrevPage:g,loading:w,error:y,refetch:C}},exports.useExpiringCredits=(e,r)=>{const{t:s}=yr(),{api:n}=Er(),[a,o]=t.useState(null),[i,c]=t.useState(!1),[l,u]=t.useState(null),d=t.useCallback(async()=>{if(e){c(!0),u(null);try{const t=await n.getExpiringCredits(e,r);o(t)}catch(t){const n=O(t,"errors.fetchExpiringCredits",s);u(n),T(t,{component:"useExpiringCredits",action:"fetchExpiring",metadata:{workspaceId:e,days:r}})}finally{c(!1)}}else o(null)},[n,e,r]);return t.useEffect(()=>{d()},[d]),{expiringCredits:a?.expiringCredits??0,buckets:a?.buckets??[],days:a?.days??r??7,loading:i,error:l,refetch:d}},exports.useFullScreenLoader=Jr,exports.useInvoice=(e,r)=>{const{t:s}=yr(),{api:n}=Er(),[a,o]=t.useState(null),[i,c]=t.useState(!1),[l,u]=t.useState(null),d=t.useCallback(async()=>{if(e&&r){c(!0),u(null);try{const t=await n.getInvoice(e,r);o(t.invoice)}catch(t){const n=O(t,"errors.fetchInvoice",s);u(n),T(t,{component:"useInvoice",action:"fetchInvoice",metadata:{workspaceId:e,invoiceId:r}})}finally{c(!1)}}else o(null)},[n,e,r]);return t.useEffect(()=>{d()},[d]),{invoice:a,loading:i,error:l,refetch:d}},exports.useInvoices=(e,r=10,s)=>{const{t:n}=yr(),{api:a}=Er(),[o,i]=t.useState([]),[c,l]=t.useState(!1),[u,d]=t.useState(!1),[p,h]=t.useState(null),m=t.useCallback(async()=>{if(!e)return i([]),void l(!1);d(!0),h(null);try{const t=await a.listInvoices(e,r,s);i(t.invoices||[]),l(t.has_more||!1)}catch(t){const a=O(t,"errors.fetchInvoices",n);h(a),T(t,{component:"useInvoices",action:"fetchInvoices",metadata:{workspaceId:e,limit:r,startingAfter:s}})}finally{d(!1)}},[a,e,r,s]);return t.useEffect(()=>{m()},[m]),{invoices:o,hasMore:c,loading:u,error:p,refetch:m}},exports.usePermissionConfig=Hr,exports.usePermissions=Ws,exports.usePlanGroup=Rr,exports.usePlanGroupVersions=e=>{const{t:r}=yr(),{api:s}=Er(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),u=t.useCallback(async()=>{if(e){i(!0),l(null);try{const t=await s.getPlanGroupVersions(e);a(t)}catch(t){const s=O(t,"errors.fetchPlanGroupVersions",r);l(s),T(t,{component:"usePlanGroupVersions",action:"fetchVersions",metadata:{workspaceId:e}})}finally{i(!1)}}else a(null)},[s,e]);return t.useEffect(()=>{u()},[u]),{versions:n,loading:o,error:c,refetch:u}},exports.usePublicCreditPackages=Lr,exports.usePublicPlanGroupVersion=e=>{const{t:r}=yr(),{api:s}=Er(),[n,a]=t.useState(null),[o,i]=t.useState(!1),[c,l]=t.useState(null),u=t.useCallback(async()=>{if(e){i(!0),l(null);try{const t=await s.getPlanGroupVersion(e);a(t)}catch(t){const s=O(t,"errors.fetchPlanGroupVersion",r);l(s),T(t,{component:"usePublicPlanGroupVersion",action:"fetchVersion",metadata:{groupVersionId:e}})}finally{i(!1)}}else a(null)},[s,e]);return t.useEffect(()=>{u()},[u]),{planGroupVersion:n,loading:o,error:c,refetch:u}},exports.usePublicPlans=Nr,exports.usePurchaseCredits=Or,exports.usePushNotifications=function(){const e=t.useContext(bs);if(!e)throw new Error("usePushNotifications must be used within PushNotificationProvider");return e},exports.useQuotaUsageContext=Xr,exports.useQuotaUsageStatus=(e,r)=>{const{t:s}=yr(),{api:n}=Er(),[a,o]=t.useState(null),[i,c]=t.useState(!1),[l,u]=t.useState(null),d=t.useCallback(async()=>{if(e&&r){c(!0),u(null);try{const t=await n.getQuotaUsageStatus(e,r);o(t)}catch(t){const n=O(t,"errors.fetchQuotaUsage",s);u(n),T(t,{component:"useQuotaUsageStatus",action:"fetchStatus",metadata:{workspaceId:e,quotaSlug:r}})}finally{c(!1)}}else o(null)},[n,e,r]);return t.useEffect(()=>{d()},[d]),{status:a,loading:i,error:l,refetch:d}},exports.useRecordUsage=e=>{const{t:r}=yr(),{api:s}=Er(),[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 fe(),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}=yr(),{api:s}=Er(),[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 ye(),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=hs,exports.useSaaSOs=Sr,exports.useSaaSSettings=Pr,exports.useSaaSWorkspaces=ls,exports.useSeatStatus=function(e,r){const{response:s}=Fr();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=Qe({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?Ke(n,o,a?.billingInterval??"monthly"):null,f=Ze({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=Ir,exports.useSubscriptionContext=Fr,exports.useSubscriptionManagement=(e,r)=>{const s=Ir(e),n=Rr(e,r),a=jr(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=yr,exports.useTrialStatus=function(){const{response:e}=Fr();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=On(t.trialEnd)??On(t.stripeCurrentPeriodEnd),s=On(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=rs,exports.useUIVisibility=Fs,exports.useUpdateSubscription=jr,exports.useUsageLogs=(e,r,s)=>{const{t:n}=yr(),{api:a}=Er(),[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,w]=t.useState(!1),[b,y]=t.useState(!1),[x,k]=t.useState(null),v=s?.from,S=s?.to,C=s?.source,P=s?.page,E=s?.limit,N=t.useCallback(async()=>{if(!e)return i([]),l(0),d(0),h(1),g(!1),void w(!1);y(!0),k(null);try{const t={...r&&{quotaSlug:r},...v&&{from:v},...S&&{to:S},...C&&{source:C},...P&&{page:P},...E&&{limit:E}},s=await a.getUsageLogs(e,t);i(s.docs||[]),l(s.totalDocs||0),d(s.totalPages||0),h(s.page||1),g(s.hasNextPage||!1),w(s.hasPrevPage||!1)}catch(t){const s=O(t,"errors.fetchUsageLogs",n);k(s),T(t,{component:"useUsageLogs",action:"fetchLogs",metadata:{workspaceId:e,quotaSlug:r}})}finally{y(!1)}},[a,e,r,v,S,C,P,E]);return t.useEffect(()=>{N()},[N]),{logs:o,totalDocs:c,totalPages:u,page:p,hasNextPage:m,hasPrevPage:f,loading:b,error:x,refetch:N}},exports.useUserAttributes=function(){const e=t.useContext(ks);if(void 0===e)throw new Error("useUserAttributes must be used within a UserProvider");return e},exports.useUserFeatures=wn,exports.useWorkspaceApiWithOs=Er,exports.validateInvite=Ze,exports.validateRedirectUrl=Ie,exports.workspaceEmojis=an,exports.workspaceSettingsManager=cs;
|