@buildbase/sdk 0.0.48 → 0.0.50

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/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- let e=!0;function t(t,...s){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...s)}async function s(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 r(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await s(e);r=t.message||t.error||r}catch{r=function(e,t){const s={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}: ${s})`)}(e,t).message}throw new Error(r)}try{return await s(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class n extends Error{constructor(e,t,s,r){super(e),this.code=t,this.context=s,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,n)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,s={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new n("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",s),o=r instanceof n?r:new n(r.message,"SDK_ERROR",s,r);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${s.component||"Unknown"}:`,{message:o.message,code:o.code,context:o.context,originalError:o.originalError,stack:o.stack}),this.config.onError)try{this.config.onError(o,s)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(o,s)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...s)=>e(...s).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...s)=>{try{return e(...s)}catch(e){throw this.handleError(e,t),e}}}};function i(e,t={}){o.handleError(e,t)}function a(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return i(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){i(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function u(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){i(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){i(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const l="saas-session-id";function d(){return function(){if("undefined"==typeof window)return null;try{return a(l)}catch(e){return i(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}const p="SDK is not ready (missing serverUrl, version, or orgId)";class h{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(p);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(p)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=d(),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}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}async executeFetchUrl(e,t,s){const r=(t.method??"GET").toUpperCase(),n=s??e,o=this.buildHeaders(t),i={...t,headers:o};let a;if(this._timeout>0){const e=new AbortController;a=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?AbortSignal.any([t.signal,e.signal]):e.signal}const c=async t=>{try{const s=this._fetch.bind(globalThis),n=await s(e,i);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),c(t+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(void 0!==a){const e=new Error(`Request timeout after ${this._timeout}ms: ${r} ${n}`);throw this._onError?.(e,{method:r,path:n}),e}throw e}if(t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),c(t+1)}throw e instanceof Error&&this._onError?.(e,{method:r,path:n}),e}};try{return await c(0)}finally{void 0!==a&&clearTimeout(a)}}async fetchJson(e,t={},s="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await r(n,s)}catch(s){throw s instanceof Error&&this._onError?.(s,{method:(t.method??"GET").toUpperCase(),path:e}),s}}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 s=t;try{s=(await e.json()).message||s}catch{s=`${t} (${e.status}: ${e.statusText})`}throw new Error(s)}async unwrapResponse(e,t){const s=await e.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||t);return s.data||s}return s}}class f extends h{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,s=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return s.ok||await this.throwResponseError(s,"Failed to initiate authentication"),s.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class g extends h{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")}}class w{constructor(e){this.api=new g(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},s=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),n=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),o=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:s,language:r,timezone:n,currency:o}})}}class y extends h{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 m extends h{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class k extends h{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 s=await this.unwrapResponse(t,"Failed to fetch user attributes");return s&&"object"==typeof s&&!Array.isArray(s)?s:{}}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(`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 s=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof s&&null!==s?s:{}}}class b extends h{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(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,s){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(s)},"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(`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,s){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:s}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(`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(`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(`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(`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 s=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${encodeURIComponent(t)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch plan group version"),this.unwrapResponse(s,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(`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.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.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(`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 s=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to create checkout session"),this.unwrapResponse(s,"Failed to create checkout session")}async selectFreePlan(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return s.ok||await this.throwResponseError(s,"Failed to select free plan"),s.json()}async updateSubscription(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to update subscription"),this.unwrapResponse(s,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,s){const r=new URLSearchParams;r.append("limit",t.toString()),s&&r.append("starting_after",s);const n=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${r.toString()}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoices"),this.unwrapResponse(n,"Failed to fetch invoices")}async getInvoice(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${t}`);return s.ok||await this.throwResponseError(s,"Failed to fetch invoice"),this.unwrapResponse(s,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(`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(`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 s=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to record usage"),this.unwrapResponse(s,"Failed to record usage")}async recordUsageBatch(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to record batch usage"),this.unwrapResponse(s,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const s=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(t)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch quota usage status"),this.unwrapResponse(s,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(`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 s=new URLSearchParams;t?.quotaSlug&&s.append("quotaSlug",t.quotaSlug),t?.from&&s.append("from",t.from),t?.to&&s.append("to",t.to),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=`workspaces/${e}/subscription/usage/logs${r?`?${r}`:""}`,o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch usage logs"),this.unwrapResponse(o,"Failed to fetch usage logs")}async sendNotification(e,t,s,r){const n={event:t};return s&&(n.userId=s),r&&(n.data=r),this.fetchJson(`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(n)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(`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(`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 s=await this.fetchResponse(`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){if(402===s.status){const e=await s.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(s,"Failed to consume credits")}return this.unwrapResponse(s,"Failed to consume credits")}async purchaseCredits(e,t){const s=await this.fetchResponse(`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to create credit purchase checkout"),this.unwrapResponse(s,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const s=await this.unwrapResponse(t,"Failed to fetch credit packages");return s.docs??s}async getCreditTransactions(e,t){const s=new URLSearchParams;t?.type&&s.append("type",t.type),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=`workspaces/${e}/credits/transactions${r?`?${r}`:""}`,o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch credit transactions"),this.unwrapResponse(o,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const s=new URLSearchParams;t?.status&&s.append("status",t.status),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=`workspaces/${e}/credits/buckets${r?`?${r}`:""}`,o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch credit buckets"),this.unwrapResponse(o,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const s=t?`?days=${t}`:"",r=await this.fetchResponse(`workspaces/${e}/credits/expiring${s}`);return r.ok||await this.throwResponseError(r,"Failed to fetch expiring credits"),this.unwrapResponse(r,"Failed to fetch expiring credits")}}var S;!function(e){e.V1="v1"}(S||(S={}));const E={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 R{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){i(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(E.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(E.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(E.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(E.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,s){await this.emit(E.WorkspaceUserAdded,{userId:e,workspace:t,role:s})}async emitWorkspaceUserRemoved(e,t,s){await this.emit(E.WorkspaceUserRemoved,{userId:e,workspace:t,role:s})}async emitWorkspaceUserRoleChanged(e,t,s,r){await this.emit(E.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:s,newRole:r})}async emitWorkspaceCreated(e){await this.emit(E.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(E.WorkspaceDeleted,{workspace:e})}}const v=new R;function P(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const $=P().invalidate,U=P().invalidate,I=P().invalidate,C="bb",F={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},O={Success:"success",Cancel:"cancel",Error:"error"},_={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function W(e,t){let s;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");s=new URL(e),s.search=""}catch{s=new URL("https://localhost")}return s.searchParams.set(C,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),s.toString()}function A(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:W({action:F.Checkout,status:O.Success,ws:e,screen:_.Subscription},s),cancelUrl:W({action:F.Checkout,status:O.Cancel,ws:e,screen:_.Subscription},s)}}function N(e,t){const s=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:W({action:F.CreditPurchase,status:O.Success,ws:e,screen:_.Credits},s),cancelUrl:W({action:F.CreditPurchase,status:O.Cancel,ws:e,screen:_.Credits},s)}}function T(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(C);if(!e)return null;const t=function(e){const t={};if(!e)return t;const s=e.split(",");for(const e of s){const s=e.indexOf(":");if(-1===s)continue;const r=decodeURIComponent(e.slice(0,s)),n=decodeURIComponent(e.slice(s+1));r&&(t[r]=n)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function J(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(C)&&(e.searchParams.delete(C),window.history.replaceState({},"",e.toString()))}catch{}}function x(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 L(e,t="/"){const s=x(e);window.location.href=s||t}const B="saas-auth-intent";function q(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function M(e){x(e)&&u(B,{returnUrl:e,createdAt:Date.now()})}function V(){const e=function(e,t){const s=a(e);if(!s)return null;try{const r=JSON.parse(s);return t&&!t(r)?(i(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):r}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(B,q);return c(B),e?Date.now()-e.createdAt>6e5?null:x(e.returnUrl):null}function K(){c(B)}const D={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:"฿"},G={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function j(e){return e&&e.trim()?G[e.trim().toLowerCase()]??"":""}function H(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return D[t]??t.toUpperCase()}const z=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Q=z.map(e=>({value:e,label:`${e.toUpperCase()} (${H(e)})`}));function Y(e,t){return H(t)+(e/100).toFixed(2)}const Z={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};function X(e,t,s,r){if(null==e||e<0)return null;const n={...Z,...r},o=null!=t&&t>=1?t:1,i=H(s),a=(e/100).toFixed(2);return 1===o?`${i}${a}/${n.unit}`:`${i}${a}/${o.toLocaleString()} ${n.units}`}function ee(e,t,s,r,n,o){if(null==e||e<0)return null;const i={...Z,...o},a=null!=t&&t>=1?t:1,c=H(r),u=(e/100).toFixed(2);if(s){const e=n??(s.endsWith("s")?s:`${s}s`);return a>=2?`${c}${u}/${a.toLocaleString()} ${e}`:`${c}${u}/${s}`}return 1===a?`${c}${u}/${i.unit}`:`${c}${u}/${a.toLocaleString()} ${i.units}`}function te(e,t="unit"){const s=(e||"").trim().toLowerCase();if(!s)return t;const r=s.split(/\s+/)[0]??s;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t}function se(e,t,s,r,n,o,i,a){const c={...Z,...i};if(!1===a)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=o??(s.endsWith("s")?s:`${s}s`),l=null!=n&&n>=2?`${n.toLocaleString()} ${u}`:s;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${Y(t,r)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${Y(t,r)}/${l}`:"—"}function re(e,t){if(null==e)return null;const s=e[t??"monthly"];return s?{included:s.included,...void 0!==s.overage&&{overage:s.overage},...void 0!==s.unitSize&&{unitSize:s.unitSize},allowOverage:!1!==e.allowOverage}:null}const ne={included:"included",then:"then"};function oe(e,t,s={}){const{overageInCents:r=!0,currency:n}=s,o=s.labels??ne,i=s.currencySymbol??H(n??"");if(null==e)return"—";const{included:a,overage:c}=e,u=`${a} ${o.included}`;if(!1===e.allowOverage)return`${u} (hard limit)`;if(null==c)return u;const l=r?c/100:c,d="number"==typeof l&&Number.isFinite(l)?l.toFixed(2):String(c),p=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${o.then} ${i}${d}${p}`}const ie={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},ae={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},ce={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},ue={Feature:"feature",Limit:"limit",Quota:"quota"},le={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},de={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},pe={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},he={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function fe(e,t){const s=e.pricingVariants;if(!s?.length)return null;const r=t.toLowerCase();return s.find(e=>e.currency?.toLowerCase()===r)??null}function ge(e,t,s){const r=fe(e,t);if(!r?.basePricing)return null;const n=r.basePricing[s];return null!=n?n:null}function we(e,t,s){const r=fe(e,t);if(!r?.stripePrices)return null;const n=s===ie.Monthly?"monthlyPriceId":s===ie.Yearly?"yearlyPriceId":"quarterlyPriceId",o=s===ie.Monthly?"monthly":s===ie.Yearly?"yearly":void 0;return r.stripePrices[n]??(o?r.stripePrices[o]:void 0)??null}function ye(e,t,s,r){const n=fe(e,t),o=n?.quotaOverages?.[s];if(o)return o[r]}function me(e,t){const s=fe(e,t);return s?s.currency:e.plan?.currency??""}function ke(e){const t=new Set;for(const s of e)s.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function be(e,t,s,r){const n=e.quotas?.[s];if(null==n)return null;const o=n[r];if(!o)return null;const i=ye(e,t,s,r);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==n.allowOverage}}function Se(e,t){if(!e)return null;for(const s of t){const t=s.pricingVariants;if(t?.length)for(const s of t){const t=s.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:s.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:s.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:s.currency}}}}return null}function Ee(e,t){const s=fe(e,t);return s?.seatPricing?.enabled?s.seatPricing:null}function Re(e,t,s){const r=Ee(e,t);return r?.perSeat?r.perSeat[s]??null:null}function ve(e,t){return Math.max(0,e-(t||0))}function Pe(e,t,s,r){const n=Ee(e,t);if(!n)return null;return ve(r,n.includedSeats)*(Re(e,t,s)??0)}function $e(e,t,s,r){const n=ge(e,t,s);if(null===n)return null;if(void 0===r)return n;return n+(Pe(e,t,s,r)??0)}function Ue(e){const{planVersion:t,currency:s="usd",settingsMaxUsers:r}=e;if(t){const e=Ee(t,s);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function Ie(e){const{memberCount:t,maxUsersConfig:s,hasSubscription:r=!0,requireSubscription:n=!1}=e;if(n&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:o,source:i}=s;if(o<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=o){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:o}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const Ce={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"},Fe=Object.values(Ce),Oe={admin:Fe.filter(e=>e!==Ce.WORKSPACE_DELETE),member:[Ce.WORKSPACE_SETTINGS_VIEW,Ce.WORKSPACE_MEMBERS_VIEW,Ce.WORKSPACE_FEATURES_VIEW,Ce.WORKSPACE_BILLING_VIEW,Ce.WORKSPACE_USAGE_VIEW],viewer:[Ce.WORKSPACE_SETTINGS_VIEW,Ce.WORKSPACE_MEMBERS_VIEW]};function _e(e){const t=new Set;for(const s of Object.values(e))for(const e of s)t.add(e);return Array.from(t)}function We(e){const{userId:t,workspace:s,settings:r,appPermissions:n}=e;if(!s||!t)return new Set;if(function(e,t){if(!t)return!1;const s=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==s&&s===t}(s,t)){const e=new Set(Fe);if(n)for(const t of _e(n))e.add(t);if(s.permissions)for(const t of _e(s.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of _e(r.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const s=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return s&&"object"==typeof s&&"role"in s&&"string"==typeof s.role?s.role:null}(s,t);if(!o)return new Set;const i=s.permissions,a=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=i?.[o]?c(i[o]):[],d=a?.[o]?c(a[o]):[],p=Oe[o]??[];let h;if(l.length>0)h=l;else if(d.length>0)h=d;else if(p.length>0)h=p;else{h=Oe[r?.workspace?.defaultRole??"member"]??Oe.member??[]}const f=new Set(h),g=i?.[o]?u(i[o]):[],w=n?.[o]?u(n[o]):[],y=g.length>0?g:w;for(const e of y)f.add(e);return function(e,t,s){if(!s?.workspace)return;const{canInviteMembers:r}=s.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(Ce.WORKSPACE_MEMBERS_INVITE)}(f,o,r),f}function Ae(e,t){const s=We(t);return Array.isArray(e)?e.every(e=>s.has(e)):s.has(e)}const Ne="\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";var Te;function Je(e){const{body:t,signature:s,timestamp:r,secret:n,maxAgeSeconds:o=300}=e;if(!(s&&r&&n&&t))return!1;const i="sha256=";if(!s.startsWith(i))return!1;const a=s.slice(7);if(o>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>o)return!1}try{const e=require("crypto"),s=e.createHmac("sha256",n).update(`${r}.${t}`).digest("hex"),o=Buffer.from(a,"hex"),i=Buffer.from(s,"hex");return o.length===i.length&&e.timingSafeEqual(o,i)}catch{return!1}}function xe(e){if(!Je(e))return null;try{return JSON.parse(e.body)}catch{return null}}function Le(e){const{serverUrl:t,orgId:s,version:r="v1",getSessionId:n,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!s)throw new Error("BuildBase: orgId is required");const d={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},p=e=>{const n={serverUrl:t,version:r,orgId:s,sessionId:e,...d};return{workspace:new b(n),user:new k(n),settings:new m(n),push:new y(n)}},h=new b({serverUrl:t,version:r,orgId:s,...d}),f=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,s)=>(await e()).workspace.updateWorkspace(t,s),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,s,r)=>(await e()).workspace.addUser(t,{email:s,role:r}),remove:async(t,s)=>(await e()).workspace.removeUser(t,s),updateRole:async(t,s,r)=>(await e()).workspace.updateUser(t,s,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,s)=>(await e()).workspace.createCheckoutSession(t,s),update:async(t,s)=>(await e()).workspace.updateSubscription(t,s),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,s)=>(await e()).workspace.createBillingPortalSession(t,s)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,s,r)=>(await e()).workspace.listInvoices(t,s,r),get:async(t,s)=>(await e()).workspace.getInvoice(t,s)},usage:{record:async(t,s)=>(await e()).workspace.recordUsage(t,s),recordBatch:async(t,s)=>(await e()).workspace.recordUsageBatch(t,s),getQuota:async(t,s)=>(await e()).workspace.getQuotaUsageStatus(t,s),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,s)=>(await e()).workspace.getUsageLogs(t,s)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,s,r)=>(await e()).workspace.updateFeature(t,s,r)},notification:{send:async(t,s,r,n)=>(await e()).workspace.sendNotification(t,s,r,n)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,s)=>(await e()).workspace.consumeCredits(t,s),purchase:async(t,s)=>(await e()).workspace.purchaseCredits(t,s),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,s)=>(await e()).workspace.getCreditTransactions(t,s),getBuckets:async(t,s)=>(await e()).workspace.getCreditBuckets(t,s),getExpiring:async(t,s)=>(await e()).workspace.getExpiringCredits(t,s),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,s,r)=>{const n=await e(),[o,i,a]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return Ae(r,{userId:s,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,s)=>{const r=await e(),[n,o,i]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return We({userId:s,workspaceRole:a?.role??null,workspace:n,settings:o})}}}),g=f(async()=>p(await(async()=>{if(!n)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await n();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!n)return null;const e=await n();return e?{sessionId:e}:null},withSession:e=>{const t=p(e);return f(async()=>t)},client:{forSession:p},...g}}!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Te||(Te={}));export{S as ApiVersion,f as AuthApi,Te as AuthStatus,F as BBAction,_ as BBScreen,O as BBStatus,C as BB_PARAM,h as BaseApi,w as BetaForm,ie as BillingIntervals,Le as BuildBase,D as CURRENCY_DISPLAY,G as CURRENCY_FLAG,de as CreditBucketSource,pe as CreditBucketStatus,he as CreditTransactionType,Oe as DEFAULT_ROLE_PERMISSIONS,le as DunningState,R as EventEmitter,ce as InvoiceStatuses,z as PLAN_CURRENCY_CODES,Q as PLAN_CURRENCY_OPTIONS,Ne as PUSH_SERVICE_WORKER_SCRIPT,Ce as Permission,y as PushApi,E as SDKEvent,m as SettingsApi,ue as SubscriptionItemType,ae as SubscriptionStatus,k as UserApi,b as WorkspaceApi,ve as calculateBillableSeats,Pe as calculateSeatOverageCents,$e as calculateTotalSubscriptionCents,J as cleanBBParams,K as clearAuthIntent,V as consumeAuthIntent,W as createBBUrl,A as createCheckoutRedirectUrls,N as createCreditPurchaseRedirectUrls,Le as default,v as eventEmitter,Y as formatCents,X as formatOverageRate,ee as formatOverageRateWithLabel,se as formatQuotaIncludedOverage,oe as formatQuotaWithPrice,ke as getAvailableCurrenciesFromPlans,ge as getBasePriceCents,Se as getBillingIntervalAndCurrencyFromPriceId,j as getCurrencyFlag,H as getCurrencySymbol,me as getDisplayCurrency,Re as getPerSeatPriceCents,fe as getPricingVariant,re as getQuotaDisplayValue,be as getQuotaDisplayWithVariant,ye as getQuotaOverageCents,te as getQuotaUnitLabelFromName,Ee as getSeatPricing,we as getStripePriceIdForInterval,Ae as hasPermission,$ as invalidateCreditBalance,U as invalidateQuotaUsage,I as invalidateSubscription,xe as parseWebhookEvent,T as readBBParams,Ue as resolveMaxUsers,We as resolvePermissions,L as safeRedirect,M as saveAuthIntent,Ie as validateInvite,x as validateRedirectUrl,Je as verifyWebhookSignature};
1
+ let e=!0;function t(t,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}async function n(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 r(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await n(e);r=t.message||t.error||r}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw new Error(r)}try{return await n(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class s extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,s)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,n={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new s("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",n),o=r instanceof s?r:new s(r.message,"SDK_ERROR",n,r);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${n.component||"Unknown"}:`,{message:o.message,code:o.code,context:o.context,originalError:o.originalError,stack:o.stack}),this.config.onError)try{this.config.onError(o,n)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(o,n)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function i(e,t={}){o.handleError(e,t)}function a(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return i(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){i(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function u(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){i(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){i(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const l="saas-session-id";function d(){return function(){if("undefined"==typeof window)return null;try{return a(l)}catch(e){return i(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}const p=new WeakSet,h="SDK is not ready (missing serverUrl, version, or orgId)";class f{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=d(),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){p.has(e)||(p.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}async executeFetchUrl(e,t,n){const r=(t.method??"GET").toUpperCase(),s=n??e,o=this.buildHeaders(t),i={...t,headers:o};let a;if(this._timeout>0){const e=new AbortController;a=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,s=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){s(n);break}n.addEventListener("abort",()=>s(n),{once:!0})}return r.signal}(t.signal,e.signal):e.signal}const c=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),s=await n(e,i);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),c(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(void 0!==a){const e=new Error(`Request timeout after ${this._timeout}ms: ${r} ${s}`);throw this.reportError(e,{method:r,path:s}),e}throw e}if(t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),c(t+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:s}),e}};try{return await c(0)}finally{void 0!==a&&clearTimeout(a)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await r(s,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw new Error(n)}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return n.data||n}return n}}class g extends f{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return n.ok||await this.throwResponseError(n,"Failed to initiate authentication"),n.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class w extends f{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")}}class y{constructor(e){this.api=new w(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),s=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),o=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:s,currency:o}})}}class m extends f{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 k extends f{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class b extends f{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}class S extends f{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(`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,n){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n)},"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(`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,n){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(`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(`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(`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(`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 n=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${encodeURIComponent(t)}`);return n.ok||await this.throwResponseError(n,"Failed to fetch plan group version"),this.unwrapResponse(n,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(`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.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.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(`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 n=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to create checkout session"),this.unwrapResponse(n,"Failed to create checkout session")}async selectFreePlan(e,t){const n=await this.fetchResponse(`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return n.ok||await this.throwResponseError(n,"Failed to select free plan"),n.json()}async updateSubscription(e,t){const n=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to update subscription"),this.unwrapResponse(n,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,n){const r=new URLSearchParams;r.append("limit",t.toString()),n&&r.append("starting_after",n);const s=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${r.toString()}`);return s.ok||await this.throwResponseError(s,"Failed to fetch invoices"),this.unwrapResponse(s,"Failed to fetch invoices")}async getInvoice(e,t){const n=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${t}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoice"),this.unwrapResponse(n,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(`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(`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 n=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to record usage"),this.unwrapResponse(n,"Failed to record usage")}async recordUsageBatch(e,t){const n=await this.fetchResponse(`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to record batch usage"),this.unwrapResponse(n,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const n=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(t)}`);return n.ok||await this.throwResponseError(n,"Failed to fetch quota usage status"),this.unwrapResponse(n,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(`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 n=new URLSearchParams;t?.quotaSlug&&n.append("quotaSlug",t.quotaSlug),t?.from&&n.append("from",t.from),t?.to&&n.append("to",t.to),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const r=n.toString(),s=`workspaces/${e}/subscription/usage/logs${r?`?${r}`:""}`,o=await this.fetchResponse(s);return o.ok||await this.throwResponseError(o,"Failed to fetch usage logs"),this.unwrapResponse(o,"Failed to fetch usage logs")}async sendNotification(e,t,n,r){const s={event:t};return n&&(s.userId=n),r&&(s.data=r),this.fetchJson(`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(s)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(`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(`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 n=await this.fetchResponse(`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!n.ok){if(402===n.status){const e=await n.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(n,"Failed to consume credits")}return this.unwrapResponse(n,"Failed to consume credits")}async purchaseCredits(e,t){const n=await this.fetchResponse(`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to create credit purchase checkout"),this.unwrapResponse(n,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const n=await this.unwrapResponse(t,"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t){const n=new URLSearchParams;t?.type&&n.append("type",t.type),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const r=n.toString(),s=`workspaces/${e}/credits/transactions${r?`?${r}`:""}`,o=await this.fetchResponse(s);return o.ok||await this.throwResponseError(o,"Failed to fetch credit transactions"),this.unwrapResponse(o,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const n=new URLSearchParams;t?.status&&n.append("status",t.status),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const r=n.toString(),s=`workspaces/${e}/credits/buckets${r?`?${r}`:""}`,o=await this.fetchResponse(s);return o.ok||await this.throwResponseError(o,"Failed to fetch credit buckets"),this.unwrapResponse(o,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const n=t?`?days=${t}`:"",r=await this.fetchResponse(`workspaces/${e}/credits/expiring${n}`);return r.ok||await this.throwResponseError(r,"Failed to fetch expiring credits"),this.unwrapResponse(r,"Failed to fetch expiring credits")}}var v;!function(e){e.V1="v1"}(v||(v={}));const E={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 R{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){i(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(E.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(E.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(E.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(E.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(E.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(E.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(E.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(E.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(E.WorkspaceDeleted,{workspace:e})}}const $=new R;function P(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const U=P().invalidate,C=P().invalidate,I=P().invalidate,_="bb",F={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},A={Success:"success",Cancel:"cancel",Error:"error"},W={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function O(e,t){let n;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");n=new URL(e),n.search=""}catch{n=new URL("https://localhost")}return n.searchParams.set(_,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),n.toString()}function T(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:O({action:F.Checkout,status:A.Success,ws:e,screen:W.Subscription},n),cancelUrl:O({action:F.Checkout,status:A.Cancel,ws:e,screen:W.Subscription},n)}}function x(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:O({action:F.CreditPurchase,status:A.Success,ws:e,screen:W.Credits},n),cancelUrl:O({action:F.CreditPurchase,status:A.Cancel,ws:e,screen:W.Credits},n)}}function N(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(_);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),s=decodeURIComponent(e.slice(n+1));r&&(t[r]=s)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function J(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(_)&&(e.searchParams.delete(_),window.history.replaceState({},"",e.toString()))}catch{}}function L(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 B(e,t="/"){if("undefined"==typeof window||!window.location)return!1;const n=L(e);return window.location.href=n??t,!0}const M="saas-auth-intent";function D(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function z(e){L(e)&&u(M,{returnUrl:e,createdAt:Date.now()})}function q(){const e=function(e,t){const n=a(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(i(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):r}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(M,D);return c(M),e?Date.now()-e.createdAt>6e5?null:L(e.returnUrl):null}function K(){c(M)}const j={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:"฿"},V={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function G(e){return e&&e.trim()?V[e.trim().toLowerCase()]??"":""}function H(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return j[t]??t.toUpperCase()}const Q=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Y=Q.map(e=>({value:e,label:`${e.toUpperCase()} (${H(e)})`}));function Z(e,t){return H(t)+(e/100).toFixed(2)}const X={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};function ee(e,t,n,r){if(null==e||e<0)return null;const s={...X,...r},o=null!=t&&t>=1?t:1,i=H(n),a=(e/100).toFixed(2);return 1===o?`${i}${a}/${s.unit}`:`${i}${a}/${o.toLocaleString()} ${s.units}`}function te(e,t,n,r,s,o){if(null==e||e<0)return null;const i={...X,...o},a=null!=t&&t>=1?t:1,c=H(r),u=(e/100).toFixed(2);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return a>=2?`${c}${u}/${a.toLocaleString()} ${e}`:`${c}${u}/${n}`}return 1===a?`${c}${u}/${i.unit}`:`${c}${u}/${a.toLocaleString()} ${i.units}`}function ne(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t}function re(e,t,n,r,s,o,i,a){const c={...X,...i};if(!1===a)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=o??(n.endsWith("s")?n:`${n}s`),l=null!=s&&s>=2?`${s.toLocaleString()} ${u}`:n;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${Z(t,r)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${Z(t,r)}/${l}`:"—"}function se(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null}const oe={included:"included",then:"then"};function ie(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,o=n.labels??oe,i=n.currencySymbol??H(s??"");if(null==e)return"—";const{included:a,overage:c}=e,u=`${a} ${o.included}`;if(!1===e.allowOverage)return`${u} (hard limit)`;if(null==c)return u;const l=r?c/100:c,d="number"==typeof l&&Number.isFinite(l)?l.toFixed(2):String(c),p=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${o.then} ${i}${d}${p}`}const ae={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},ce={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},ue={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},le={Feature:"feature",Limit:"limit",Quota:"quota"},de={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},pe={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},he={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},fe={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function ge(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function we(e,t,n){const r=ge(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function ye(e,t,n){const r=ge(e,t);if(!r?.stripePrices)return null;const s=n===ae.Monthly?"monthlyPriceId":n===ae.Yearly?"yearlyPriceId":"quarterlyPriceId",o=n===ae.Monthly?"monthly":n===ae.Yearly?"yearly":void 0;return r.stripePrices[s]??(o?r.stripePrices[o]:void 0)??null}function me(e,t,n,r){const s=ge(e,t),o=s?.quotaOverages?.[n];if(o)return o[r]}function ke(e,t){const n=ge(e,t);return n?n.currency:e.plan?.currency??""}function be(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function Se(e,t,n,r){const s=e.quotas?.[n];if(null==s)return null;const o=s[r];if(!o)return null;const i=me(e,t,n,r);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==s.allowOverage}}function ve(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null}function Ee(e,t){const n=ge(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Re(e,t,n){const r=Ee(e,t);return r?.perSeat?r.perSeat[n]??null:null}function $e(e,t){return Math.max(0,e-(t||0))}function Pe(e,t,n,r){const s=Ee(e,t);if(!s)return null;return $e(r,s.includedSeats)*(Re(e,t,n)??0)}function Ue(e,t,n,r){const s=we(e,t,n);if(null===s)return null;if(void 0===r)return s;return s+(Pe(e,t,n,r)??0)}function Ce(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=Ee(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function Ie(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:o,source:i}=n;if(o<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=o){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:o}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const _e={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"},Fe=Object.values(_e),Ae={admin:Fe.filter(e=>e!==_e.WORKSPACE_DELETE),member:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW,_e.WORKSPACE_FEATURES_VIEW,_e.WORKSPACE_BILLING_VIEW,_e.WORKSPACE_USAGE_VIEW],viewer:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW]};function We(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function Oe(e){const{userId:t,workspace:n,settings:r,appPermissions:s}=e;if(!n||!t)return new Set;if(function(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}(n,t)){const e=new Set(Fe);if(s)for(const t of We(s))e.add(t);if(n.permissions)for(const t of We(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of We(r.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);if(!o)return new Set;const i=n.permissions,a=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=i?.[o]?c(i[o]):[],d=a?.[o]?c(a[o]):[],p=Ae[o]??[];let h;if(l.length>0)h=l;else if(d.length>0)h=d;else if(p.length>0)h=p;else{h=Ae[r?.workspace?.defaultRole??"member"]??Ae.member??[]}const f=new Set(h),g=i?.[o]?u(i[o]):[],w=s?.[o]?u(s[o]):[],y=g.length>0?g:w;for(const e of y)f.add(e);return function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(_e.WORKSPACE_MEMBERS_INVITE)}(f,o,r),f}function Te(e,t){const n=Oe(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const xe="\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";var Ne;!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Ne||(Ne={}));const Je=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Le=(e,t)=>e>>>t|e<<32-t;function Be(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,o=1359893119,i=2600822924,a=528734635,c=1541459225;const u=e.length,l=u+1,d=l+(56-l%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[u]=128;const h=8*u,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const w=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;w[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=Le(w[e-15],7)^Le(w[e-15],18)^w[e-15]>>>3,n=Le(w[e-2],17)^Le(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+n>>>0}let u=t,l=n,d=r,h=s,f=o,g=i,y=a,m=c;for(let e=0;e<64;e++){const t=m+(Le(f,6)^Le(f,11)^Le(f,25))+(f&g^~f&y)+Je[e]+w[e]>>>0,n=u&l^u&d^l&d;m=y,y=g,g=f,f=h+t>>>0,h=d,d=l,l=u,u=t+((Le(u,2)^Le(u,13)^Le(u,22))+n>>>0)>>>0}t=t+u>>>0,n=n+l>>>0,r=r+d>>>0,s=s+h>>>0,o=o+f>>>0,i=i+g>>>0,a=a+y>>>0,c=c+m>>>0}const y=new Uint8Array(32),m=[t,n,r,s,o,i,a,c];for(let e=0;e<8;e++)y[4*e]=m[e]>>>24&255,y[4*e+1]=m[e]>>>16&255,y[4*e+2]=m[e]>>>8&255,y[4*e+3]=255&m[e];return y}function Me(e){return(new TextEncoder).encode(e)}function De(e,t){let n=e;n.length>64&&(n=Be(n));const r=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,s[e]=92^t}const o=Be(qe(r,t));return Be(qe(s,o))}function ze(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}function qe(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Ke(e){const{body:t,signature:n,timestamp:r,secret:s,maxAgeSeconds:o=300}=e;if(!(n&&r&&s&&t))return!1;const i="sha256=";if(!n.startsWith(i))return!1;const a=n.slice(7);if(o>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>o)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(a);if(!c)return!1;const u=De(Me(s),Me(`${r}.${t}`));return c.length===u.length&&ze(c,u)}function je(e){if(!Ke(e))return null;try{return JSON.parse(e.body)}catch{return null}}const Ve=300,Ge="/.well-known/oauth-protected-resource",He="/.well-known/agent-skills",Qe="/.well-known/api-catalog",Ye="/.well-known/mcp/server-card.json",Ze="application/json",Xe="text/markdown; charset=utf-8",et="text/plain; charset=utf-8";function tt(e){return e.replace(/\/+$/,"")}function nt(e){return`public, max-age=${e}, s-maxage=${e}`}function rt(e){return"sha256:"+function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(Be(Me(e)))}const st=new Map;async function ot(e){const t=e.cacheTtlSeconds??Ve,n=`${tt(e.serverUrl)}::${e.orgId}`,r=st.get(n);if(r&&r.expiresAt>Date.now())return r.value;const s=e.fetch??fetch,o=`${tt(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const e=await s(o,{headers:{Accept:Ze}});if(e.ok){const t=await e.json();t&&"object"==typeof t&&(i=t)}}catch{}return st.set(n,{value:i,expiresAt:Date.now()+1e3*t}),i}function it(){st.clear()}function at(e,t){const n=tt(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:Ge};t.authorizationServer?.metadataUrl&&(r.oauth_authorization_server=t.authorizationServer.metadataUrl),(t.authorizationServer||e.authMd)&&(r.auth="/auth.md"),e.skills?.length&&(r.agent_skills=`${He}/index.json`),e.apiCatalog?.length&&(r.api_catalog=Qe),e.mcpServerCard&&(r.mcp_server_card=Ye);return yt({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:n,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:n},capabilities:r,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function ct(e,t,n){const r=n.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||Ge,o=r.find(e=>function(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return Ge+n}(e.resource)===s);return o?yt(o.metadata,t):s===Ge&&1===r.length?yt(r[0].metadata,t):null}function ut(e){const t=e.skills??[];if(!t.length)return null;const n=tt(e.siteUrl);return yt({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${n}${lt(e)}`,digest:rt(e.content)}))},e)}function lt(e){return e.path??`${He}/${e.name}/SKILL.md`}function dt(e,t){const n=(t.skills??[]).find(t=>lt(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:nt(t.cacheTtlSeconds??Ve)}:null}function pt(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:et,body:t.join("\n")+"\n",cacheControl:nt(e.cacheTtlSeconds??Ve)}}function ht(e,t){return t.llmsTxt?{status:200,contentType:et,body:t.llmsTxt,cacheControl:nt(e.cacheTtlSeconds??Ve)}:null}function ft(e){const t=e.apiCatalog??[];if(!t.length)return null;const n=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:"application/linkset+json",body:JSON.stringify({linkset:n},null,2),cacheControl:nt(e.cacheTtlSeconds??Ve)}}function gt(e){const t=e.mcpServerCard;return t?yt({schema_version:"2024-11-05",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",endpoint:t.endpoint},capabilities:t.capabilities??{tools:{}},...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function wt(e,t){const n=nt(e.cacheTtlSeconds??Ve);if(e.authMd)return{status:200,contentType:Xe,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const s=(t.protectedResources??[]).map(e=>`- \`${e.resource}\``).join("\n"),o=Array.from(new Set((t.protectedResources??[]).flatMap(e=>e.metadata?.scopes_supported??[]))),i=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${r.issuer}\`\n- Metadata (RFC 8414): ${r.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, and supported grant types / PKCE methods.\n\n## Protected resources (RFC 9728)\n${s||"- See `/.well-known/oauth-protected-resource`"}\n\nEach resource publishes its metadata at \`/.well-known/oauth-protected-resource\`, listing the authorization server(s) that can issue tokens for it.\n${o.length?`\n## Scopes\n${o.map(e=>`- \`${e}\``).join("\n")}\n`:""}\n## How an agent authenticates\n1. Discover this document and \`/.well-known/oauth-protected-resource\`.\n2. Fetch the authorization-server metadata for the endpoints.\n3. Run the authorization-code flow with PKCE (S256), requesting the scopes above and the target \`resource\`.\n4. Exchange the code for an access token and call the API with \`Authorization: Bearer <token>\`.\n\nDocumentation: ${e.site.documentationUrl??e.siteUrl}\n`;return{status:200,contentType:Xe,body:i,cacheControl:n}}function yt(e,t){return{status:200,contentType:Ze,body:JSON.stringify(e,null,2),cacheControl:nt(t.cacheTtlSeconds??Ve)}}async function mt(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return at(t,await ot(t))}if("/.well-known/security.txt"===n)return pt(t);if(n===`${He}/index.json`)return ut(t);if(n.startsWith(`${He}/`)&&n.endsWith("SKILL.md"))return dt(n,t);if("/.well-known/oauth-authorization-server"===n){const e=await ot(t),n=e.authorizationServer?.metadataUrl;return n?yt({...e.authorizationServer?.issuer?{issuer:e.authorizationServer.issuer}:{},oauth_authorization_server_metadata:n},t):null}if(n===Qe)return ft(t);if(n===Ye)return gt(t);if(n.startsWith(Ge)){return ct(n,t,await ot(t))}return null}function kt(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)}class bt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function St(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+n),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}function vt(e){return JSON.parse((new TextDecoder).decode(St(e)))}function Et(e,t,n=60){if(!e||!t)throw new bt("invalid_token","Missing token or client secret");const r=e.split(".");if(3!==r.length)throw new bt("invalid_token","Malformed JWT");const[s,o,i]=r,a=De(Me(t),Me(`${s}.${o}`));let c,u,l;try{c=St(i)}catch{throw new bt("invalid_signature","Unreadable JWT signature")}if(!ze(a,c))throw new bt("invalid_signature","JWT signature verification failed");try{u=vt(s),l=vt(o)}catch{throw new bt("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new bt("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const d=Math.floor(Date.now()/1e3);if("number"==typeof l.exp&&d>l.exp+n)throw new bt("token_expired","JWT has expired");if("number"==typeof l.nbf&&d+n<l.nbf)throw new bt("token_not_yet_valid","JWT is not yet valid");return l}function Rt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function $t(e){const t=Rt(e.authorization);if(!t)throw new bt("invalid_token","Missing Bearer token");return Et(t,e.clientSecret,e.clockToleranceSec)}function Pt(e){const t=Rt(e.authorization);if(!t)throw new bt("invalid_token","Missing Bearer token");return Et(t,e.clientSecret,e.clockToleranceSec)}function Ut(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function Ct(e){return{success:!1,token:"",message:e}}async function It(e){let t;try{t=$t(e)}catch(e){return{status:401,body:Ct(e instanceof bt?e.code:"invalid_token")}}return{status:200,body:Ut(await e.mintToken(t))}}async function _t(e){let t;try{t=Pt(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof bt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}}function Ft(e){const t=[`Bearer resource_metadata="${e.resourceMetadataUrl}"`];return e.error&&t.push(`error="${e.error}"`),e.errorDescription&&t.push(`error_description="${e.errorDescription}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}function At(e){const{serverUrl:t,orgId:n,version:r="v1",getSessionId:s,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const d={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},p=e=>{const s={serverUrl:t,version:r,orgId:n,sessionId:e,...d};return{workspace:new S(s),user:new b(s),settings:new k(s),push:new m(s)}},h=new S({serverUrl:t,version:r,orgId:n,...d}),f=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,r)=>(await e()).workspace.addUser(t,{email:n,role:r}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,r)=>(await e()).workspace.updateUser(t,n,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,n)=>(await e()).workspace.createCheckoutSession(t,n),update:async(t,n)=>(await e()).workspace.updateSubscription(t,n),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,n)=>(await e()).workspace.createBillingPortalSession(t,n)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,n,r)=>(await e()).workspace.listInvoices(t,n,r),get:async(t,n)=>(await e()).workspace.getInvoice(t,n)},usage:{record:async(t,n)=>(await e()).workspace.recordUsage(t,n),recordBatch:async(t,n)=>(await e()).workspace.recordUsageBatch(t,n),getQuota:async(t,n)=>(await e()).workspace.getQuotaUsageStatus(t,n),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,n)=>(await e()).workspace.getUsageLogs(t,n)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,n,r)=>(await e()).workspace.updateFeature(t,n,r)},notification:{send:async(t,n,r,s)=>(await e()).workspace.sendNotification(t,n,r,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,n)=>(await e()).workspace.consumeCredits(t,n),purchase:async(t,n)=>(await e()).workspace.purchaseCredits(t,n),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,n)=>(await e()).workspace.getCreditTransactions(t,n),getBuckets:async(t,n)=>(await e()).workspace.getCreditBuckets(t,n),getExpiring:async(t,n)=>(await e()).workspace.getExpiringCredits(t,n),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,n,r)=>{const s=await e(),[o,i,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return Te(r,{userId:n,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,n)=>{const r=await e(),[s,o,i]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return Oe({userId:n,workspaceRole:a?.role??null,workspace:s,settings:o})}}}),g=f(async()=>p(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=p(e);return f(async()=>t)},client:{forSession:p},...g}}export{v as ApiVersion,bt as AppBridgeError,g as AuthApi,Ne as AuthStatus,F as BBAction,W as BBScreen,A as BBStatus,_ as BB_PARAM,f as BaseApi,y as BetaForm,ae as BillingIntervals,At as BuildBase,j as CURRENCY_DISPLAY,V as CURRENCY_FLAG,pe as CreditBucketSource,he as CreditBucketStatus,fe as CreditTransactionType,Ae as DEFAULT_ROLE_PERMISSIONS,de as DunningState,R as EventEmitter,ue as InvoiceStatuses,Q as PLAN_CURRENCY_CODES,Y as PLAN_CURRENCY_OPTIONS,xe as PUSH_SERVICE_WORKER_SCRIPT,_e as Permission,m as PushApi,E as SDKEvent,k as SettingsApi,le as SubscriptionItemType,ce as SubscriptionStatus,b as UserApi,S as WorkspaceApi,Ct as appTokenFailure,Ut as appTokenSuccess,Ft as bearerChallenge,at as buildAgentCard,ut as buildAgentSkillsIndex,ft as buildApiCatalog,wt as buildAuthMd,ht as buildLlmsTxt,gt as buildMcpServerCard,ct as buildProtectedResourceMetadata,pt as buildSecurityTxt,dt as buildSkillMd,$e as calculateBillableSeats,Pe as calculateSeatOverageCents,Ue as calculateTotalSubscriptionCents,J as cleanBBParams,it as clearAgentReadinessCache,K as clearAuthIntent,q as consumeAuthIntent,O as createBBUrl,T as createCheckoutRedirectUrls,x as createCreditPurchaseRedirectUrls,At as default,$ as eventEmitter,Rt as extractBearerToken,ot as fetchAgentReadiness,Z as formatCents,ee as formatOverageRate,te as formatOverageRateWithLabel,re as formatQuotaIncludedOverage,ie as formatQuotaWithPrice,be as getAvailableCurrenciesFromPlans,we as getBasePriceCents,ve as getBillingIntervalAndCurrencyFromPriceId,G as getCurrencyFlag,H as getCurrencySymbol,ke as getDisplayCurrency,Re as getPerSeatPriceCents,ge as getPricingVariant,se as getQuotaDisplayValue,Se as getQuotaDisplayWithVariant,me as getQuotaOverageCents,ne as getQuotaUnitLabelFromName,Ee as getSeatPricing,ye as getStripePriceIdForInterval,_t as handleAppRevokeRequest,It as handleAppTokenRequest,Te as hasPermission,U as invalidateCreditBalance,C as invalidateQuotaUsage,I as invalidateSubscription,je as parseWebhookEvent,kt as provideWebMcpTools,N as readBBParams,Ce as resolveMaxUsers,Oe as resolvePermissions,mt as resolveWellKnown,B as safeRedirect,z as saveAuthIntent,rt as sha256Digest,Ie as validateInvite,L as validateRedirectUrl,Pt as verifyAppRevokeRequest,$t as verifyAppTokenRequest,Et as verifyClientJwt,Ke as verifyWebhookSignature};
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ "use strict";var e=require("react/jsx-runtime"),t=require("react"),s=require("./react-CTX0_nOV.cjs");require("clsx"),require("tailwind-merge"),require("intl-messageformat"),require("lucide-react"),require("@radix-ui/react-slot"),require("class-variance-authority"),require("@radix-ui/react-dialog"),require("@radix-ui/react-icons"),require("@radix-ui/react-alert-dialog"),require("@radix-ui/react-switch"),require("react-hook-form"),require("zod/v4/core"),require("zod"),require("@radix-ui/react-label"),require("@radix-ui/react-radio-group"),require("@radix-ui/react-scroll-area"),require("cmdk"),require("@radix-ui/react-popover"),require("@radix-ui/react-select"),require("@radix-ui/react-avatar"),require("@radix-ui/react-separator");const r={[s.BillingIntervals.Monthly]:"subscription.billingInterval.perMonth",[s.BillingIntervals.Quarterly]:"subscription.billingInterval.perQuarter",[s.BillingIntervals.Yearly]:"subscription.billingInterval.perYear"},a=(e,t,r)=>{if(!e||0===e)return null;let a;switch(r){case s.BillingIntervals.Yearly:a=t/12;break;case s.BillingIntervals.Quarterly:a=t/3;break;default:return null}const i=(e-a)/e*100;return i>0?Math.round(i):null};exports.default=({open:i,onOpenChange:l,planVersions:n,currentPlanVersionId:c,currentStripePriceId:d,billingCurrency:o,currentMemberCount:m,trialUsedAt:x,workspaceName:p,initialInterval:u,initialCurrency:b,onSelectPlan:h,loading:g=!1})=>{const[y,j]=t.useState(!1),{t:f,formattingLocale:v,dir:N,fmtNum:w,fmtCents:_}=s.useTranslation(),{settings:k}=s.useSaaSSettings(),I=k?.workspace?.mode===s.WorkspaceModes.Personal,S=(e,t)=>null==e||0===e?"":_(e,t),P=e=>f(r[e]??r[s.BillingIntervals.Monthly]),[C,B]=t.useState(null),q=t.useRef(!1),M=t.useMemo(()=>s.getBillingIntervalAndCurrencyFromPriceId(d,n),[d,n]),L=M?.interval??null,D=M?.currency??null,T=t.useMemo(()=>s.getAvailableCurrenciesFromPlans(n),[n]),z=t.useMemo(()=>{const e=o?.trim().toLowerCase();return e?T.includes(e)?[e]:[]:T},[o,T]),[F,G]=t.useState(u||L||s.BillingIntervals.Monthly),[K,V]=t.useState(()=>b&&z.includes(b)?b:D&&z.includes(D)?D:z.length>0?z[0]:""),O=o?.trim()||K;t.useEffect(()=>{if(i){G(u||L||s.BillingIntervals.Monthly);const e=b||D;e&&z.includes(e)?V(e):z.length>0&&!z.includes(K)&&V(z[0])}},[i,u,b,L,D,z]);const Q=t.useMemo(()=>[...n],[n]),W=(e=>{const t=new Map;return e.forEach(e=>{e.subscriptionItems?.forEach(e=>{t.has(e._id)||t.set(e._id,e)})}),Array.from(t.values())})(Q),Y=W.filter(e=>e.type===s.SubscriptionItemType.Feature),A=W.filter(e=>e.type===s.SubscriptionItemType.Limit),$=W.filter(e=>e.type===s.SubscriptionItemType.Quota),R=async e=>{if(!(e===c&&L===F||g||y||q.current)){q.current=!0,j(!0),B(e);try{await h(e,F,O),l(!1)}catch(e){}finally{q.current=!1,j(!1),B(null)}}},E=e=>s.getBasePriceCents(e,O,F),H=e=>!!e.pricingVariants?.some(e=>e.currency?.toLowerCase()===O.toLowerCase()),U=g||y,J=e=>{switch(e){case s.BillingIntervals.Monthly:return f("subscription.billingInterval.monthly");case s.BillingIntervals.Quarterly:return f("subscription.billingInterval.quarterly");case s.BillingIntervals.Yearly:return f("subscription.billingInterval.yearly");default:return f("subscription.billingInterval.monthly")}},X=e=>{const t=e._id===c,s=L===F;if(t&&s)return{labelKey:"subscription.currentPlan",variant:"outline",disabled:!0};if(t&&!s)return e.plan?.isFreemium?{labelKey:"subscription.currentPlan",variant:"outline",disabled:!0}:{labelKey:"_dynamic",dynamicLabel:f("subscription.switchToInterval",{interval:J(F)}),variant:"default",disabled:!1};const r=e.trial?.enabled&&e.trial.durationDays>0&&!x&&!d;if(!c)return r?{labelKey:"_dynamic",dynamicLabel:f("subscription.startTrialDays",{days:e.trial.durationDays}),variant:"default",disabled:!1}:{labelKey:"subscription.subscribe",variant:"default",disabled:!1};const a=Q.findIndex(e=>e._id===c),i=Q.findIndex(t=>t._id===e._id);return-1===a||-1===i?r?{labelKey:"_dynamic",dynamicLabel:f("subscription.startTrialDays",{days:e.trial.durationDays}),variant:"default",disabled:!1}:{labelKey:"subscription.checkout.select",variant:"default",disabled:!1}:i<a?{labelKey:"subscription.checkout.downgrade",variant:"outline",disabled:!1}:i>a?r?{labelKey:"_dynamic",dynamicLabel:f("subscription.startTrialDays",{days:e.trial.durationDays}),variant:"default",disabled:!1}:{labelKey:"subscription.checkout.upgrade",variant:"default",disabled:!1}:{labelKey:"subscription.checkout.select",variant:"default",disabled:!1}},Z=(e,t,r=s.BillingIntervals.Monthly)=>{if(t.type===s.SubscriptionItemType.Feature)return e.features?.[t.slug]??!1;if(t.type===s.SubscriptionItemType.Limit)return e.limits?.[t.slug]??null;if(t.type===s.SubscriptionItemType.Quota){const a=s.getQuotaDisplayWithVariant(e,O,t.slug,r);return a||s.getQuotaDisplayValue(e.quotas?.[t.slug],r)}return null},ee=(e,t,r)=>{if(t.type===s.SubscriptionItemType.Feature)return!0===e?"✓":"—";if(t.type===s.SubscriptionItemType.Limit)return null!=e&&"number"==typeof e?w(e):"—";if(t.type===s.SubscriptionItemType.Quota){const a="object"==typeof e&&null!==e&&"included"in e?e:null,i=s.getQuotaDisplayParts(a,t.name.toLowerCase(),{currency:r,locale:v});return i?i.allowOverage?i.hasOverage?f("quota.includedWithOverage",{count:i.included,price:i.price,unit:i.unit}):f("quota.includedOnly",{count:i.included}):f("quota.includedHardLimit",{count:i.included}):"—"}return"—"};return e.jsx(s.Dialog,{open:i,onOpenChange:l,children:e.jsxs(s.DialogContent,{dir:N,className:"inset-0 w-screen h-screen max-w-none rounded-none translate-x-0 translate-y-0 p-0 flex flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 px-4 py-4 sm:px-6 sm:py-6 border-b space-y-3 sm:space-y-4",children:[e.jsxs("div",{children:[e.jsx(s.DialogTitle,{className:"text-xl sm:text-2xl font-bold",children:f("pricing.title")}),e.jsxs(s.DialogDescription,{className:"mt-1 text-sm",children:[f("subscription.choosePlanDescription"),p&&e.jsx("span",{className:"ml-1 font-medium text-foreground",children:f("subscription.forWorkspace",{name:p})})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[!o?.trim()&&z.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-slate-600",children:f("pricing.currency")}),e.jsx("select",{"aria-label":f("pricing.selectCurrency"),value:K,onChange:e=>V(e.target.value),className:"rounded-md border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-900 shadow-sm focus:outline-none focus:ring-2 focus:ring-primary",children:z.map(t=>{const r=s.getCurrencyFlag(t);return e.jsx("option",{value:t,children:r?`${r} ${t.toUpperCase()}`:t.toUpperCase()},t)})})]}),o?.trim()&&e.jsx("span",{className:"text-xs text-slate-500",children:f("subscription.billingInCurrency",{currency:o.toUpperCase()})})]}),e.jsx("div",{className:"flex items-center gap-0.5 sm:gap-1 p-1 bg-slate-100 rounded-lg w-full sm:w-auto",role:"group","aria-label":f("pricing.billingInterval"),children:[s.BillingIntervals.Monthly,s.BillingIntervals.Quarterly,s.BillingIntervals.Yearly].map(t=>{const r=L===t;return e.jsx("button",{onClick:()=>G(t),"aria-pressed":F===t,className:"flex-1 sm:flex-initial px-3 sm:px-4 py-2 text-sm font-medium rounded-md transition-all relative "+(F===t?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"),children:e.jsxs("span",{className:"flex items-center justify-center gap-1 sm:gap-1.5",children:[t===s.BillingIntervals.Monthly&&f("subscription.billingInterval.monthly"),t===s.BillingIntervals.Quarterly&&f("subscription.billingInterval.quarterly"),t===s.BillingIntervals.Yearly&&f("subscription.billingInterval.yearly"),t===s.BillingIntervals.Yearly&&e.jsx("span",{className:"text-[10px] sm:text-xs px-1 sm:px-1.5 py-0.5 bg-emerald-100 text-emerald-700 rounded-full font-semibold",children:f("pricing.save")}),r&&c&&e.jsx("span",{className:"hidden sm:inline text-xs px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded-full font-semibold",children:f("pricing.current")})]})},t)})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:o?.trim()&&0===z.length?e.jsxs("div",{className:"text-center py-12 px-4",children:[e.jsx("p",{className:"text-slate-600 font-medium",children:f("pricing.noPlansCurrency")}),e.jsx("p",{className:"text-slate-500 text-sm mt-2",children:f("pricing.noPlansCurrencyHint")})]}):0===Q.length?e.jsx("div",{className:"text-center py-12 text-gray-500",children:e.jsx("p",{children:f("pricing.noPlans")})}):e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden bg-white",children:[e.jsx("div",{className:"md:hidden overflow-auto h-full",style:{maxHeight:"calc(100vh - 13rem)"},children:e.jsx("div",{className:"p-4 space-y-4",children:Q.map(t=>{const r=t._id===c,i=X(t),l=U&&t._id===C,n=E(t),o=H(t),p=t.pricingVariants?.length&&t.pricingVariants.some(e=>e.currency?.toLowerCase()===O.toLowerCase())?O:t.plan?.currency??O??"",u=s.getBasePriceCents(t,O,s.BillingIntervals.Monthly)??0,b=F!==s.BillingIntervals.Monthly&&null!==n?a(u,n,F):null,h=s.getSeatPricing(t,O),g=h?s.getPerSeatPriceCents(t,O,F):null;return e.jsxs("div",{className:"rounded-xl border-2 p-4 "+(r?"border-blue-500 bg-blue-50/30":"border-slate-200 bg-white"),children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-bold text-slate-900",children:t.plan.name}),t.trial?.enabled&&t.trial.durationDays>0&&!r&&!x&&!d&&e.jsx("span",{className:"shrink-0 rounded-md bg-emerald-100 text-emerald-700 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider",children:f("subscription.trialBadge",{days:t.trial.durationDays})})]}),t.plan.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:t.plan.description})]}),r&&e.jsx("span",{className:"shrink-0 rounded-md bg-blue-600 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-white",children:f("pricing.current")})]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex items-baseline gap-1 whitespace-nowrap",children:[e.jsx("span",{className:"text-2xl font-bold text-slate-900",children:o&&null!==n||o?S(n,p)||f("pricing.free"):"—"}),null!==n&&n>0&&o&&e.jsx("span",{className:"text-sm text-slate-500",children:P(F)})]}),null!==b&&b>0&&o&&e.jsx("span",{className:"text-xs text-emerald-600 font-medium",children:f("subscription.savingsPercent",{percent:b})}),h?.enabled&&g&&g>0&&!I&&e.jsx("div",{className:"text-xs text-slate-500 mt-1",children:f("subscription.seatPriceDisplay",{price:_(g,p),interval:P(F),included:w(h.includedSeats),includedLabel:f("pricing.included")})})]}),Y.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5",children:f("subscription.items.features")}),e.jsx("div",{className:"space-y-1",children:Y.map(r=>{const a=Z(t,r,F),i=r.type===s.SubscriptionItemType.Feature&&!0===a;return e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[r.type===s.SubscriptionItemType.Feature?i?e.jsx("span",{className:"text-emerald-500 text-xs",children:"✓"}):e.jsx("span",{className:"text-slate-300 text-xs",children:"✕"}):null,e.jsx("span",{className:i?"text-slate-700":"text-slate-400",children:r.name})]},r._id)})})]}),A.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5",children:f("subscription.items.limits")}),e.jsx("div",{className:"space-y-1",children:A.map(s=>{const r=Z(t,s,F);return e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-slate-600",children:s.name}),e.jsx("span",{className:"font-medium text-slate-700",children:"number"==typeof r?w(r):"—"})]},s._id)})})]}),h?.enabled&&!I&&e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"text-xs font-semibold text-emerald-600 uppercase tracking-wider mb-1.5",children:f("subscription.seats.title")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600",children:f("subscription.seats.included")}),e.jsx("span",{className:"font-medium",children:w(h.includedSeats||0)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600",children:f("subscription.seats.maxSeats")}),e.jsx("span",{className:"font-medium",children:(h?.maxSeats??0)>0?w(h.maxSeats):f("subscription.seats.unlimited")})]}),null!=m&&m>0&&(()=>{const t=Math.max(0,m-(h.includedSeats||0));return e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600",children:f("subscription.seats.billable")}),e.jsx("span",{className:"font-medium "+(0===t?"text-emerald-600":"text-amber-600"),children:0===t?f("subscription.seats.allIncluded"):`${w(t)} ${f("subscription.seats.extra")}`})]})})()]})]}),t.creditGrant?.enabled&&"object"==typeof t.creditGrant.creditPackage&&null!==t.creditGrant.creditPackage&&e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"text-xs font-semibold text-purple-600 uppercase tracking-wider mb-1.5",children:f("subscription.items.credits")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600",children:t.creditGrant.renewOnPeriod?f("subscription.items.creditsPerMonth"):f("subscription.items.creditsOneTime")}),e.jsx("span",{className:"font-semibold text-purple-700",children:w(t.creditGrant.creditPackage.creditAmount)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-600",children:f("subscription.items.creditRenewal")}),e.jsx("span",{className:"font-medium text-slate-700",children:t.creditGrant.renewOnPeriod?"reset"===t.creditGrant.mode?f("subscription.items.creditModeReset"):f("subscription.items.creditModeTopup"):f("subscription.items.creditModeLifetime")})]})]})]}),e.jsx(s.Button,{className:"w-full mt-2",variant:i.variant,disabled:i.disabled||U||!o,progress:l,onClick:()=>R(t._id),children:l?f("pricing.processing"):o?i.dynamicLabel??f(i.labelKey):f("pricing.unavailable")})]},t._id)})})}),e.jsx("div",{className:"hidden md:block overflow-auto h-full",style:{maxHeight:"calc(100vh - 12rem)"},children:e.jsxs("table",{className:"w-full border-separate border-spacing-0",style:{minWidth:260+220*Q.length+"px",borderCollapse:"separate"},children:[e.jsxs("colgroup",{children:[e.jsx("col",{style:{width:260,minWidth:260}}),Q.map(t=>e.jsx("col",{style:{width:220,minWidth:220}},t._id))]}),e.jsx("thead",{children:e.jsxs("tr",{className:"align-top",children:[e.jsx("th",{className:"sticky top-0 start-0 z-30 p-0 bg-white text-start"}),Q.map(t=>{const r=t._id===c,i=X(t),l=U&&t._id===C,n=E(t),o=s.getBasePriceCents(t,O,s.BillingIntervals.Monthly)??0,m=F!==s.BillingIntervals.Monthly&&null!==n?a(o,n,F):null,p=H(t),u=t.pricingVariants?.length&&t.pricingVariants.some(e=>e.currency?.toLowerCase()===O.toLowerCase())?O:t.plan?.currency??O??"";return e.jsx("th",{className:"sticky top-0 z-20 border-b border-slate-200 p-3 shadow-[0_2px_4px_-2px_rgba(0,0,0,0.06)] "+(t._id===c?"bg-blue-50/80":"bg-white"),children:e.jsxs("div",{className:"flex h-full flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("h3",{className:"text-base font-bold text-slate-900 truncate",children:t.plan.name}),t.trial?.enabled&&t.trial.durationDays>0&&!r&&!x&&!d&&e.jsx("span",{className:"shrink-0 rounded-md bg-emerald-100 text-emerald-700 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider",children:f("subscription.trialBadge",{days:t.trial.durationDays})})]}),r&&e.jsx("span",{className:"shrink-0 rounded-md bg-blue-600 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-white",children:f("pricing.current")})]}),e.jsxs("div",{className:"flex flex-col items-start min-h-[3rem]",children:[e.jsxs("div",{className:"flex items-baseline gap-1 flex-wrap",children:[e.jsx("span",{className:"text-2xl font-bold text-slate-900",children:p&&null!==n||p?S(n,u)||f("pricing.free"):"—"}),null!==n&&n>0&&p&&e.jsx("span",{className:"text-sm text-slate-500",children:P(F)}),null!==m&&m>0&&p&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-emerald-100 text-emerald-700 rounded-full font-semibold whitespace-nowrap",children:f("subscription.savingsPercent",{percent:m})})]}),(()=>{if(I)return null;const r=s.getSeatPricing(t,O);if(!r)return null;const a=s.getPerSeatPriceCents(t,O,F);return!a||a<=0?null:e.jsx("div",{className:"text-[11px] text-slate-500 mt-1.5 border-t border-slate-100 pt-1 leading-tight",children:e.jsx("div",{children:f("subscription.seatPriceDisplay",{price:_(a,u),interval:P(F),included:w(r.includedSeats),includedLabel:f("pricing.included")})})})})()]}),t.plan.description&&e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed text-start",children:t.plan.description}),e.jsx(s.Button,{className:"mt-auto w-full",variant:i.variant,disabled:i.disabled||U||!p,progress:l,onClick:()=>R(t._id),children:l?f("pricing.processing"):p?i.dynamicLabel??f(i.labelKey):f("pricing.unavailable")})]})},t._id)})]})}),e.jsxs("tbody",{children:[Y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-slate-200 bg-slate-100 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-slate-600 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:f("subscription.items.features")}),e.jsx("td",{colSpan:Q.length,className:"border-t border-slate-200 bg-slate-100"})]}),Y.map(t=>e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsxs("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e.jsx("div",{className:"font-medium text-sm text-slate-900",children:t.name}),t.description&&e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:t.description})]}),Q.map(r=>{const a=Z(r,t,F),i=r.pricingVariants?.length?O:r.plan?.currency??O??"",l=ee(a,t,i),n=t.type===s.SubscriptionItemType.Feature&&!0===a;return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(r._id===c?"bg-blue-50/50":"bg-white"),children:e.jsx("span",{className:"text-sm font-medium "+(n?"text-emerald-600":"—"===l?"text-slate-400":"text-slate-700"),children:l})},r._id)})]},t._id))]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-slate-200 bg-slate-100 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-slate-600 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:f("subscription.items.limits")}),e.jsx("td",{colSpan:Q.length,className:"border-t border-slate-200 bg-slate-100"})]}),A.map(t=>e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsxs("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e.jsx("div",{className:"font-medium text-sm text-slate-900",children:t.name}),t.description&&e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:t.description})]}),Q.map(s=>{const r=Z(s,t,F),a=s.pricingVariants?.length?O:s.plan?.currency??O??"",i=ee(r,t,a);return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(s._id===c?"bg-blue-50/50":"bg-white"),children:e.jsx("span",{className:"text-sm font-medium "+("—"===i?"text-slate-400":"text-slate-700"),children:i})},s._id)})]},t._id))]}),$.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-slate-200 bg-slate-100 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-slate-600 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:f("subscription.items.quotas")}),e.jsx("td",{colSpan:Q.length,className:"border-t border-slate-200 bg-slate-100"})]}),$.map(t=>e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsxs("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e.jsx("div",{className:"font-medium text-sm text-slate-900",children:t.name}),t.description&&e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:t.description})]}),Q.map(s=>{const r=Z(s,t,F),a=s.pricingVariants?.length?O:s.plan?.currency??O??"",i=ee(r,t,a);return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(s._id===c?"bg-blue-50/50":"bg-white"),children:e.jsx("span",{className:"text-sm font-medium "+("—"===i?"text-slate-400":"text-slate-700"),children:i})},s._id)})]},t._id))]}),!I&&Q.some(e=>{const t=s.getSeatPricing(e,O);return t?.enabled})&&e.jsxs(e.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-emerald-200 bg-emerald-50 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-emerald-700 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:f("subscription.seats.title")}),e.jsx("td",{colSpan:Q.length,className:"border-t border-emerald-200 bg-emerald-50"})]}),e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsxs("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e.jsx("div",{className:"font-medium text-sm text-slate-900",children:f("subscription.seats.includedSeats")}),e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:f("subscription.seats.freeWithBase")})]}),Q.map(t=>{const r=s.getSeatPricing(t,O);return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===c?"bg-blue-50/50":"bg-white"),children:e.jsx("span",{className:"text-sm font-medium text-slate-700",children:r?.enabled?w(r.includedSeats||0):"—"})},t._id)})]}),e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:e.jsx("div",{className:"font-medium text-sm text-slate-900",children:f("subscription.seats.maxSeats")})}),Q.map(t=>{const r=s.getSeatPricing(t,O);return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===c?"bg-blue-50/50":"bg-white"),children:e.jsx("span",{className:"text-sm font-medium text-slate-700",children:r?.enabled?(r?.maxSeats??0)>0?w(r.maxSeats):f("subscription.seats.unlimited"):"—"})},t._id)})]}),e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:e.jsx("div",{className:"font-medium text-sm text-slate-900",children:f("subscription.seats.perExtraSeat")})}),Q.map(t=>{const r=s.getPerSeatPriceCents(t,O,F),a=t.pricingVariants?.length?O:t.plan?.currency??O??"";return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===c?"bg-blue-50/50":"bg-white"),children:e.jsx("span",{className:"text-sm font-medium text-slate-700",children:r&&r>0?`${_(r,a)}${P(F)}`:"—"})},t._id)})]}),null!=m&&m>0&&e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsxs("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e.jsx("div",{className:"font-medium text-sm text-slate-900",children:f("subscription.seats.billable")}),e.jsx("div",{className:"text-xs text-slate-500 mt-0.5",children:f("subscription.membersInWorkspace",{count:m})})]}),Q.map(t=>{const r=s.getSeatPricing(t,O);if(!r?.enabled)return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===c?"bg-blue-50/50":"bg-white"),children:e.jsx("span",{className:"text-sm text-slate-400",children:"—"})},t._id);const a=r.includedSeats||0,i=Math.max(0,m-a);return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===c?"bg-blue-50/50":"bg-white"),children:0===i?e.jsx("span",{className:"text-sm font-medium text-emerald-600",children:f("subscription.seats.allIncluded")}):e.jsxs("span",{className:"text-sm font-medium text-amber-600",children:[w(i)," ",f("subscription.seats.extra")]})},t._id)})]})]}),Q.some(e=>e.creditGrant?.enabled&&"object"==typeof e.creditGrant.creditPackage&&null!==e.creditGrant.creditPackage)&&e.jsxs(e.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-purple-200 bg-purple-50 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-purple-700 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:f("subscription.items.credits")}),e.jsx("td",{colSpan:Q.length,className:"border-t border-purple-200 bg-purple-50"})]}),e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:e.jsx("div",{className:"font-medium text-sm text-slate-900",children:Q.every(e=>!e.creditGrant?.enabled||!e.creditGrant.renewOnPeriod)?f("subscription.items.creditsOneTime"):f("subscription.items.creditsPerMonth")})}),Q.map(t=>{const s=t.creditGrant,r=s?.enabled&&"object"==typeof s.creditPackage&&null!==s.creditPackage?s.creditPackage:null;return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===c?"bg-blue-50/50":"bg-white"),children:r?e.jsx("span",{className:"text-sm font-semibold text-purple-700",children:w(r.creditAmount)}):e.jsx("span",{className:"text-sm text-slate-400",children:"—"})},t._id)})]}),e.jsxs("tr",{className:"group hover:bg-slate-50/50",children:[e.jsx("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:e.jsx("div",{className:"font-medium text-sm text-slate-900",children:f("subscription.items.creditRenewal")})}),Q.map(t=>{const s=t.creditGrant;return e.jsx("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===c?"bg-blue-50/50":"bg-white"),children:s?.enabled?e.jsx("span",{className:"text-sm font-medium text-slate-700",children:s.renewOnPeriod?"reset"===s.mode?f("subscription.items.creditModeReset"):f("subscription.items.creditModeTopup"):f("subscription.items.creditModeLifetime")}):e.jsx("span",{className:"text-sm text-slate-400",children:"—"})},t._id)})]})]})]})]})})]})})]})})};
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import r,{useState as s,useMemo as i,useEffect as l}from"react";import{u as n,a as c,W as d,g as o,b as m,B as p,S as u,D as b,c as x,d as h,e as g,f as y,h as f,i as N,j as v,k as w,l as _,m as k,n as P}from"./react-DzQupoqH.mjs";import"clsx";import"tailwind-merge";import"intl-messageformat";import"lucide-react";import"@radix-ui/react-slot";import"class-variance-authority";import"@radix-ui/react-dialog";import"@radix-ui/react-icons";import"@radix-ui/react-alert-dialog";import"@radix-ui/react-switch";import"react-hook-form";import"zod/v4/core";import"zod";import"@radix-ui/react-label";import"@radix-ui/react-radio-group";import"@radix-ui/react-scroll-area";import"cmdk";import"@radix-ui/react-popover";import"@radix-ui/react-select";import"@radix-ui/react-avatar";import"@radix-ui/react-separator";const C={[p.Monthly]:"subscription.billingInterval.perMonth",[p.Quarterly]:"subscription.billingInterval.perQuarter",[p.Yearly]:"subscription.billingInterval.perYear"},M=(e,t,a)=>{if(!e||0===e)return null;let r;switch(a){case p.Yearly:r=t/12;break;case p.Quarterly:r=t/3;break;default:return null}const s=(e-r)/e*100;return s>0?Math.round(s):null},L=({open:L,onOpenChange:I,planVersions:S,currentPlanVersionId:z,currentStripePriceId:j,billingCurrency:D,currentMemberCount:G,trialUsedAt:K,workspaceName:O,initialInterval:V,initialCurrency:Q,onSelectPlan:T,loading:W=!1})=>{const[q,F]=s(!1),{t:Y,formattingLocale:$,dir:R,fmtNum:A,fmtCents:B}=n(),{settings:H}=c(),U=H?.workspace?.mode===d.Personal,E=(e,t)=>null==e||0===e?"":B(e,t),J=e=>Y(C[e]??C[p.Monthly]),[X,Z]=s(null),ee=r.useRef(!1),te=i(()=>o(j,S),[j,S]),ae=te?.interval??null,re=te?.currency??null,se=i(()=>m(S),[S]),ie=i(()=>{const e=D?.trim().toLowerCase();return e?se.includes(e)?[e]:[]:se},[D,se]),[le,ne]=s(V||ae||p.Monthly),[ce,de]=s(()=>Q&&ie.includes(Q)?Q:re&&ie.includes(re)?re:ie.length>0?ie[0]:""),oe=D?.trim()||ce;l(()=>{if(L){ne(V||ae||p.Monthly);const e=Q||re;e&&ie.includes(e)?de(e):ie.length>0&&!ie.includes(ce)&&de(ie[0])}},[L,V,Q,ae,re,ie]);const me=i(()=>[...S],[S]),pe=(e=>{const t=new Map;return e.forEach(e=>{e.subscriptionItems?.forEach(e=>{t.has(e._id)||t.set(e._id,e)})}),Array.from(t.values())})(me),ue=pe.filter(e=>e.type===u.Feature),be=pe.filter(e=>e.type===u.Limit),xe=pe.filter(e=>e.type===u.Quota),he=async e=>{if(!(e===z&&ae===le||W||q||ee.current)){ee.current=!0,F(!0),Z(e);try{await T(e,le,oe),I(!1)}catch(e){}finally{ee.current=!1,F(!1),Z(null)}}},ge=e=>f(e,oe,le),ye=e=>!!e.pricingVariants?.some(e=>e.currency?.toLowerCase()===oe.toLowerCase()),fe=W||q,Ne=e=>{switch(e){case p.Monthly:return Y("subscription.billingInterval.monthly");case p.Quarterly:return Y("subscription.billingInterval.quarterly");case p.Yearly:return Y("subscription.billingInterval.yearly");default:return Y("subscription.billingInterval.monthly")}},ve=e=>{const t=e._id===z,a=ae===le;if(t&&a)return{labelKey:"subscription.currentPlan",variant:"outline",disabled:!0};if(t&&!a)return e.plan?.isFreemium?{labelKey:"subscription.currentPlan",variant:"outline",disabled:!0}:{labelKey:"_dynamic",dynamicLabel:Y("subscription.switchToInterval",{interval:Ne(le)}),variant:"default",disabled:!1};const r=e.trial?.enabled&&e.trial.durationDays>0&&!K&&!j;if(!z)return r?{labelKey:"_dynamic",dynamicLabel:Y("subscription.startTrialDays",{days:e.trial.durationDays}),variant:"default",disabled:!1}:{labelKey:"subscription.subscribe",variant:"default",disabled:!1};const s=me.findIndex(e=>e._id===z),i=me.findIndex(t=>t._id===e._id);return-1===s||-1===i?r?{labelKey:"_dynamic",dynamicLabel:Y("subscription.startTrialDays",{days:e.trial.durationDays}),variant:"default",disabled:!1}:{labelKey:"subscription.checkout.select",variant:"default",disabled:!1}:i<s?{labelKey:"subscription.checkout.downgrade",variant:"outline",disabled:!1}:i>s?r?{labelKey:"_dynamic",dynamicLabel:Y("subscription.startTrialDays",{days:e.trial.durationDays}),variant:"default",disabled:!1}:{labelKey:"subscription.checkout.upgrade",variant:"default",disabled:!1}:{labelKey:"subscription.checkout.select",variant:"default",disabled:!1}},we=(e,t,a=p.Monthly)=>{if(t.type===u.Feature)return e.features?.[t.slug]??!1;if(t.type===u.Limit)return e.limits?.[t.slug]??null;if(t.type===u.Quota){const r=_(e,oe,t.slug,a);return r||k(e.quotas?.[t.slug],a)}return null},_e=(e,t,a)=>{if(t.type===u.Feature)return!0===e?"✓":"—";if(t.type===u.Limit)return null!=e&&"number"==typeof e?A(e):"—";if(t.type===u.Quota){const r=P("object"==typeof e&&null!==e&&"included"in e?e:null,t.name.toLowerCase(),{currency:a,locale:$});return r?r.allowOverage?r.hasOverage?Y("quota.includedWithOverage",{count:r.included,price:r.price,unit:r.unit}):Y("quota.includedOnly",{count:r.included}):Y("quota.includedHardLimit",{count:r.included}):"—"}return"—"};return e(b,{open:L,onOpenChange:I,children:t(x,{dir:R,className:"inset-0 w-screen h-screen max-w-none rounded-none translate-x-0 translate-y-0 p-0 flex flex-col",children:[t("div",{className:"flex-shrink-0 px-4 py-4 sm:px-6 sm:py-6 border-b space-y-3 sm:space-y-4",children:[t("div",{children:[e(h,{className:"text-xl sm:text-2xl font-bold",children:Y("pricing.title")}),t(g,{className:"mt-1 text-sm",children:[Y("subscription.choosePlanDescription"),O&&e("span",{className:"ml-1 font-medium text-foreground",children:Y("subscription.forWorkspace",{name:O})})]})]}),t("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-4",children:[t("div",{className:"flex items-center gap-2",children:[!D?.trim()&&ie.length>1&&t(a,{children:[e("span",{className:"text-sm text-slate-600",children:Y("pricing.currency")}),e("select",{"aria-label":Y("pricing.selectCurrency"),value:ce,onChange:e=>de(e.target.value),className:"rounded-md border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-900 shadow-sm focus:outline-none focus:ring-2 focus:ring-primary",children:ie.map(t=>{const a=y(t);return e("option",{value:t,children:a?`${a} ${t.toUpperCase()}`:t.toUpperCase()},t)})})]}),D?.trim()&&e("span",{className:"text-xs text-slate-500",children:Y("subscription.billingInCurrency",{currency:D.toUpperCase()})})]}),e("div",{className:"flex items-center gap-0.5 sm:gap-1 p-1 bg-slate-100 rounded-lg w-full sm:w-auto",role:"group","aria-label":Y("pricing.billingInterval"),children:[p.Monthly,p.Quarterly,p.Yearly].map(a=>{const r=ae===a;return e("button",{onClick:()=>ne(a),"aria-pressed":le===a,className:"flex-1 sm:flex-initial px-3 sm:px-4 py-2 text-sm font-medium rounded-md transition-all relative "+(le===a?"bg-white text-slate-900 shadow-sm":"text-slate-600 hover:text-slate-900"),children:t("span",{className:"flex items-center justify-center gap-1 sm:gap-1.5",children:[a===p.Monthly&&Y("subscription.billingInterval.monthly"),a===p.Quarterly&&Y("subscription.billingInterval.quarterly"),a===p.Yearly&&Y("subscription.billingInterval.yearly"),a===p.Yearly&&e("span",{className:"text-[10px] sm:text-xs px-1 sm:px-1.5 py-0.5 bg-emerald-100 text-emerald-700 rounded-full font-semibold",children:Y("pricing.save")}),r&&z&&e("span",{className:"hidden sm:inline text-xs px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded-full font-semibold",children:Y("pricing.current")})]})},a)})})]})]}),e("div",{className:"flex-1 min-h-0 flex flex-col",children:D?.trim()&&0===ie.length?t("div",{className:"text-center py-12 px-4",children:[e("p",{className:"text-slate-600 font-medium",children:Y("pricing.noPlansCurrency")}),e("p",{className:"text-slate-500 text-sm mt-2",children:Y("pricing.noPlansCurrencyHint")})]}):0===me.length?e("div",{className:"text-center py-12 text-gray-500",children:e("p",{children:Y("pricing.noPlans")})}):t("div",{className:"flex-1 min-h-0 overflow-hidden bg-white",children:[e("div",{className:"md:hidden overflow-auto h-full",style:{maxHeight:"calc(100vh - 13rem)"},children:e("div",{className:"p-4 space-y-4",children:me.map(a=>{const r=a._id===z,s=ve(a),i=fe&&a._id===X,l=ge(a),n=ye(a),c=a.pricingVariants?.length&&a.pricingVariants.some(e=>e.currency?.toLowerCase()===oe.toLowerCase())?oe:a.plan?.currency??oe??"",d=f(a,oe,p.Monthly)??0,o=le!==p.Monthly&&null!==l?M(d,l,le):null,m=N(a,oe),b=m?v(a,oe,le):null;return t("div",{className:"rounded-xl border-2 p-4 "+(r?"border-blue-500 bg-blue-50/30":"border-slate-200 bg-white"),children:[t("div",{className:"flex items-start justify-between mb-3",children:[t("div",{children:[t("div",{className:"flex items-center gap-2",children:[e("h3",{className:"text-lg font-bold text-slate-900",children:a.plan.name}),a.trial?.enabled&&a.trial.durationDays>0&&!r&&!K&&!j&&e("span",{className:"shrink-0 rounded-md bg-emerald-100 text-emerald-700 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider",children:Y("subscription.trialBadge",{days:a.trial.durationDays})})]}),a.plan.description&&e("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:a.plan.description})]}),r&&e("span",{className:"shrink-0 rounded-md bg-blue-600 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-white",children:Y("pricing.current")})]}),t("div",{className:"mb-4",children:[t("div",{className:"flex items-baseline gap-1 whitespace-nowrap",children:[e("span",{className:"text-2xl font-bold text-slate-900",children:n&&null!==l||n?E(l,c)||Y("pricing.free"):"—"}),null!==l&&l>0&&n&&e("span",{className:"text-sm text-slate-500",children:J(le)})]}),null!==o&&o>0&&n&&e("span",{className:"text-xs text-emerald-600 font-medium",children:Y("subscription.savingsPercent",{percent:o})}),m?.enabled&&b&&b>0&&!U&&e("div",{className:"text-xs text-slate-500 mt-1",children:Y("subscription.seatPriceDisplay",{price:B(b,c),interval:J(le),included:A(m.includedSeats),includedLabel:Y("pricing.included")})})]}),ue.length>0&&t("div",{className:"mb-3",children:[e("div",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5",children:Y("subscription.items.features")}),e("div",{className:"space-y-1",children:ue.map(r=>{const s=we(a,r,le),i=r.type===u.Feature&&!0===s;return t("div",{className:"flex items-center gap-2 text-sm",children:[r.type===u.Feature?e("span",i?{className:"text-emerald-500 text-xs",children:"✓"}:{className:"text-slate-300 text-xs",children:"✕"}):null,e("span",{className:i?"text-slate-700":"text-slate-400",children:r.name})]},r._id)})})]}),be.length>0&&t("div",{className:"mb-3",children:[e("div",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5",children:Y("subscription.items.limits")}),e("div",{className:"space-y-1",children:be.map(r=>{const s=we(a,r,le);return t("div",{className:"flex items-center justify-between text-sm",children:[e("span",{className:"text-slate-600",children:r.name}),e("span",{className:"font-medium text-slate-700",children:"number"==typeof s?A(s):"—"})]},r._id)})})]}),m?.enabled&&!U&&t("div",{className:"mb-3",children:[e("div",{className:"text-xs font-semibold text-emerald-600 uppercase tracking-wider mb-1.5",children:Y("subscription.seats.title")}),t("div",{className:"space-y-1 text-sm",children:[t("div",{className:"flex justify-between",children:[e("span",{className:"text-slate-600",children:Y("subscription.seats.included")}),e("span",{className:"font-medium",children:A(m.includedSeats||0)})]}),t("div",{className:"flex justify-between",children:[e("span",{className:"text-slate-600",children:Y("subscription.seats.maxSeats")}),e("span",{className:"font-medium",children:(m?.maxSeats??0)>0?A(m.maxSeats):Y("subscription.seats.unlimited")})]}),null!=G&&G>0&&(()=>{const a=Math.max(0,G-(m.includedSeats||0));return t("div",{className:"flex justify-between",children:[e("span",{className:"text-slate-600",children:Y("subscription.seats.billable")}),e("span",{className:"font-medium "+(0===a?"text-emerald-600":"text-amber-600"),children:0===a?Y("subscription.seats.allIncluded"):`${A(a)} ${Y("subscription.seats.extra")}`})]})})()]})]}),a.creditGrant?.enabled&&"object"==typeof a.creditGrant.creditPackage&&null!==a.creditGrant.creditPackage&&t("div",{className:"mb-3",children:[e("div",{className:"text-xs font-semibold text-purple-600 uppercase tracking-wider mb-1.5",children:Y("subscription.items.credits")}),t("div",{className:"space-y-1 text-sm",children:[t("div",{className:"flex justify-between",children:[e("span",{className:"text-slate-600",children:a.creditGrant.renewOnPeriod?Y("subscription.items.creditsPerMonth"):Y("subscription.items.creditsOneTime")}),e("span",{className:"font-semibold text-purple-700",children:A(a.creditGrant.creditPackage.creditAmount)})]}),t("div",{className:"flex justify-between",children:[e("span",{className:"text-slate-600",children:Y("subscription.items.creditRenewal")}),e("span",{className:"font-medium text-slate-700",children:a.creditGrant.renewOnPeriod?"reset"===a.creditGrant.mode?Y("subscription.items.creditModeReset"):Y("subscription.items.creditModeTopup"):Y("subscription.items.creditModeLifetime")})]})]})]}),e(w,{className:"w-full mt-2",variant:s.variant,disabled:s.disabled||fe||!n,progress:i,onClick:()=>he(a._id),children:i?Y("pricing.processing"):n?s.dynamicLabel??Y(s.labelKey):Y("pricing.unavailable")})]},a._id)})})}),e("div",{className:"hidden md:block overflow-auto h-full",style:{maxHeight:"calc(100vh - 12rem)"},children:t("table",{className:"w-full border-separate border-spacing-0",style:{minWidth:260+220*me.length+"px",borderCollapse:"separate"},children:[t("colgroup",{children:[e("col",{style:{width:260,minWidth:260}}),me.map(t=>e("col",{style:{width:220,minWidth:220}},t._id))]}),e("thead",{children:t("tr",{className:"align-top",children:[e("th",{className:"sticky top-0 start-0 z-30 p-0 bg-white text-start"}),me.map(a=>{const r=a._id===z,s=ve(a),i=fe&&a._id===X,l=ge(a),n=f(a,oe,p.Monthly)??0,c=le!==p.Monthly&&null!==l?M(n,l,le):null,d=ye(a),o=a.pricingVariants?.length&&a.pricingVariants.some(e=>e.currency?.toLowerCase()===oe.toLowerCase())?oe:a.plan?.currency??oe??"";return e("th",{className:"sticky top-0 z-20 border-b border-slate-200 p-3 shadow-[0_2px_4px_-2px_rgba(0,0,0,0.06)] "+(a._id===z?"bg-blue-50/80":"bg-white"),children:t("div",{className:"flex h-full flex-col gap-2",children:[t("div",{className:"flex items-center justify-between gap-2",children:[t("div",{className:"flex items-center gap-2 min-w-0",children:[e("h3",{className:"text-base font-bold text-slate-900 truncate",children:a.plan.name}),a.trial?.enabled&&a.trial.durationDays>0&&!r&&!K&&!j&&e("span",{className:"shrink-0 rounded-md bg-emerald-100 text-emerald-700 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider",children:Y("subscription.trialBadge",{days:a.trial.durationDays})})]}),r&&e("span",{className:"shrink-0 rounded-md bg-blue-600 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-white",children:Y("pricing.current")})]}),t("div",{className:"flex flex-col items-start min-h-[3rem]",children:[t("div",{className:"flex items-baseline gap-1 flex-wrap",children:[e("span",{className:"text-2xl font-bold text-slate-900",children:d&&null!==l||d?E(l,o)||Y("pricing.free"):"—"}),null!==l&&l>0&&d&&e("span",{className:"text-sm text-slate-500",children:J(le)}),null!==c&&c>0&&d&&e("span",{className:"text-[10px] px-1.5 py-0.5 bg-emerald-100 text-emerald-700 rounded-full font-semibold whitespace-nowrap",children:Y("subscription.savingsPercent",{percent:c})})]}),(()=>{if(U)return null;const t=N(a,oe);if(!t)return null;const r=v(a,oe,le);return!r||r<=0?null:e("div",{className:"text-[11px] text-slate-500 mt-1.5 border-t border-slate-100 pt-1 leading-tight",children:e("div",{children:Y("subscription.seatPriceDisplay",{price:B(r,o),interval:J(le),included:A(t.includedSeats),includedLabel:Y("pricing.included")})})})})()]}),a.plan.description&&e("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed text-start",children:a.plan.description}),e(w,{className:"mt-auto w-full",variant:s.variant,disabled:s.disabled||fe||!d,progress:i,onClick:()=>he(a._id),children:i?Y("pricing.processing"):d?s.dynamicLabel??Y(s.labelKey):Y("pricing.unavailable")})]})},a._id)})]})}),t("tbody",{children:[ue.length>0&&t(a,{children:[t("tr",{children:[e("td",{className:"sticky start-0 z-10 border-t border-slate-200 bg-slate-100 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-slate-600 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:Y("subscription.items.features")}),e("td",{colSpan:me.length,className:"border-t border-slate-200 bg-slate-100"})]}),ue.map(a=>t("tr",{className:"group hover:bg-slate-50/50",children:[t("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e("div",{className:"font-medium text-sm text-slate-900",children:a.name}),a.description&&e("div",{className:"text-xs text-slate-500 mt-0.5",children:a.description})]}),me.map(t=>{const r=we(t,a,le),s=t.pricingVariants?.length?oe:t.plan?.currency??oe??"",i=_e(r,a,s),l=a.type===u.Feature&&!0===r;return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===z?"bg-blue-50/50":"bg-white"),children:e("span",{className:"text-sm font-medium "+(l?"text-emerald-600":"—"===i?"text-slate-400":"text-slate-700"),children:i})},t._id)})]},a._id))]}),be.length>0&&t(a,{children:[t("tr",{children:[e("td",{className:"sticky start-0 z-10 border-t border-slate-200 bg-slate-100 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-slate-600 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:Y("subscription.items.limits")}),e("td",{colSpan:me.length,className:"border-t border-slate-200 bg-slate-100"})]}),be.map(a=>t("tr",{className:"group hover:bg-slate-50/50",children:[t("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e("div",{className:"font-medium text-sm text-slate-900",children:a.name}),a.description&&e("div",{className:"text-xs text-slate-500 mt-0.5",children:a.description})]}),me.map(t=>{const r=we(t,a,le),s=t.pricingVariants?.length?oe:t.plan?.currency??oe??"",i=_e(r,a,s);return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===z?"bg-blue-50/50":"bg-white"),children:e("span",{className:"text-sm font-medium "+("—"===i?"text-slate-400":"text-slate-700"),children:i})},t._id)})]},a._id))]}),xe.length>0&&t(a,{children:[t("tr",{children:[e("td",{className:"sticky start-0 z-10 border-t border-slate-200 bg-slate-100 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-slate-600 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:Y("subscription.items.quotas")}),e("td",{colSpan:me.length,className:"border-t border-slate-200 bg-slate-100"})]}),xe.map(a=>t("tr",{className:"group hover:bg-slate-50/50",children:[t("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e("div",{className:"font-medium text-sm text-slate-900",children:a.name}),a.description&&e("div",{className:"text-xs text-slate-500 mt-0.5",children:a.description})]}),me.map(t=>{const r=we(t,a,le),s=t.pricingVariants?.length?oe:t.plan?.currency??oe??"",i=_e(r,a,s);return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===z?"bg-blue-50/50":"bg-white"),children:e("span",{className:"text-sm font-medium "+("—"===i?"text-slate-400":"text-slate-700"),children:i})},t._id)})]},a._id))]}),!U&&me.some(e=>{const t=N(e,oe);return t?.enabled})&&t(a,{children:[t("tr",{children:[e("td",{className:"sticky start-0 z-10 border-t border-emerald-200 bg-emerald-50 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-emerald-700 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:Y("subscription.seats.title")}),e("td",{colSpan:me.length,className:"border-t border-emerald-200 bg-emerald-50"})]}),t("tr",{className:"group hover:bg-slate-50/50",children:[t("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e("div",{className:"font-medium text-sm text-slate-900",children:Y("subscription.seats.includedSeats")}),e("div",{className:"text-xs text-slate-500 mt-0.5",children:Y("subscription.seats.freeWithBase")})]}),me.map(t=>{const a=N(t,oe);return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===z?"bg-blue-50/50":"bg-white"),children:e("span",{className:"text-sm font-medium text-slate-700",children:a?.enabled?A(a.includedSeats||0):"—"})},t._id)})]}),t("tr",{className:"group hover:bg-slate-50/50",children:[e("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:e("div",{className:"font-medium text-sm text-slate-900",children:Y("subscription.seats.maxSeats")})}),me.map(t=>{const a=N(t,oe);return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===z?"bg-blue-50/50":"bg-white"),children:e("span",{className:"text-sm font-medium text-slate-700",children:a?.enabled?(a?.maxSeats??0)>0?A(a.maxSeats):Y("subscription.seats.unlimited"):"—"})},t._id)})]}),t("tr",{className:"group hover:bg-slate-50/50",children:[e("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:e("div",{className:"font-medium text-sm text-slate-900",children:Y("subscription.seats.perExtraSeat")})}),me.map(t=>{const a=v(t,oe,le),r=t.pricingVariants?.length?oe:t.plan?.currency??oe??"";return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===z?"bg-blue-50/50":"bg-white"),children:e("span",{className:"text-sm font-medium text-slate-700",children:a&&a>0?`${B(a,r)}${J(le)}`:"—"})},t._id)})]}),null!=G&&G>0&&t("tr",{className:"group hover:bg-slate-50/50",children:[t("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:[e("div",{className:"font-medium text-sm text-slate-900",children:Y("subscription.seats.billable")}),e("div",{className:"text-xs text-slate-500 mt-0.5",children:Y("subscription.membersInWorkspace",{count:G})})]}),me.map(a=>{const r=N(a,oe);if(!r?.enabled)return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(a._id===z?"bg-blue-50/50":"bg-white"),children:e("span",{className:"text-sm text-slate-400",children:"—"})},a._id);const s=r.includedSeats||0,i=Math.max(0,G-s);return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(a._id===z?"bg-blue-50/50":"bg-white"),children:0===i?e("span",{className:"text-sm font-medium text-emerald-600",children:Y("subscription.seats.allIncluded")}):t("span",{className:"text-sm font-medium text-amber-600",children:[A(i)," ",Y("subscription.seats.extra")]})},a._id)})]})]}),me.some(e=>e.creditGrant?.enabled&&"object"==typeof e.creditGrant.creditPackage&&null!==e.creditGrant.creditPackage)&&t(a,{children:[t("tr",{children:[e("td",{className:"sticky start-0 z-10 border-t border-purple-200 bg-purple-50 px-4 py-2.5 font-semibold text-xs uppercase tracking-wider text-purple-700 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)]",children:Y("subscription.items.credits")}),e("td",{colSpan:me.length,className:"border-t border-purple-200 bg-purple-50"})]}),t("tr",{className:"group hover:bg-slate-50/50",children:[e("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:e("div",{className:"font-medium text-sm text-slate-900",children:me.every(e=>!e.creditGrant?.enabled||!e.creditGrant.renewOnPeriod)?Y("subscription.items.creditsOneTime"):Y("subscription.items.creditsPerMonth")})}),me.map(t=>{const a=t.creditGrant,r=a?.enabled&&"object"==typeof a.creditPackage&&null!==a.creditPackage?a.creditPackage:null;return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===z?"bg-blue-50/50":"bg-white"),children:e("span",r?{className:"text-sm font-semibold text-purple-700",children:A(r.creditAmount)}:{className:"text-sm text-slate-400",children:"—"})},t._id)})]}),t("tr",{className:"group hover:bg-slate-50/50",children:[e("td",{className:"sticky start-0 z-10 border-t border-slate-100 bg-white p-4 shadow-[2px_0_4px_-2px_rgba(0,0,0,0.06)] group-hover:bg-slate-50/80",children:e("div",{className:"font-medium text-sm text-slate-900",children:Y("subscription.items.creditRenewal")})}),me.map(t=>{const a=t.creditGrant;return e("td",{className:"border-t border-slate-100 p-4 text-center align-middle "+(t._id===z?"bg-blue-50/50":"bg-white"),children:e("span",a?.enabled?{className:"text-sm font-medium text-slate-700",children:a.renewOnPeriod?"reset"===a.mode?Y("subscription.items.creditModeReset"):Y("subscription.items.creditModeTopup"):Y("subscription.items.creditModeLifetime")}:{className:"text-sm text-slate-400",children:"—"})},t._id)})]})]})]})]})})]})})]})})};export{L as default};
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ "use strict";exports.ar={settings:{titles:{profile:"الحساب",security:"الأمان",general:"إعدادات مساحة العمل",users:"أعضاء مساحة العمل",subscription:"الخطة والفوترة",usage:"الاستخدام",credits:"الرصيد",features:"ميزات مساحة العمل",notifications:"الإشعارات",permissions:"الصلاحيات",danger:"منطقة الخطر"},sidebar:{account:"الحساب",workspace:"مساحة العمل",profile:"الحساب",security:"الأمان",general:"الإعدادات",users:"الأعضاء",subscription:"الخطة والفوترة",usage:"الاستخدام",credits:"الرصيد",features:"الميزات",notifications:"الإشعارات",permissions:"الصلاحيات",danger:"منطقة الخطر"},common:{refresh:"تحديث",refreshing:"جارٍ التحديث...",retry:"إعادة المحاولة",retrying:"جارٍ إعادة المحاولة...",save:"حفظ",saving:"جارٍ الحفظ...",cancel:"إلغاء",delete:"حذف",dismiss:"تجاهل",loading:"جارٍ التحميل...",success:"تم بنجاح!",error:"خطأ",refreshAction:"{loading, select, true {جارٍ التحديث...} other {تحديث}}",retryAction:"{loading, select, true {جارٍ إعادة المحاولة...} other {إعادة المحاولة}}",noPermissionTitle:"الوصول مقيد",noPermissionDescription:"ليس لديك إذن للوصول إلى هذا القسم. تواصل مع مسؤول مساحة العمل إذا كنت بحاجة إلى الوصول.",billingManageOnly:"فقط المستخدمون الذين لديهم أذونات إدارة الفواتير يمكنهم تنفيذ هذا الإجراء."}},subscription:{managePlan:"إدارة خطتك وفوترتك",changePlan:"تغيير الخطة",viewPricingPlans:"عرض خطط الأسعار",viewPlans:"عرض الخطط",upgradePlan:"ترقية الآن",subscribe:"اشتراك",currentPlan:"الخطة الحالية",noSubscription:"ليس لديك اشتراك نشط",choosePlan:"اختر خطتك",choosePlanDescription:"قارن بين الخطط واختر ما يناسب احتياجاتك",forWorkspace:"لـ {name}",planUpdateAvailable:"تحديث الخطة متوفر",updateSuccess:"تم تحديث الاشتراك بنجاح!",updateFailed:"فشل التحديث",cancelTitle:"إلغاء الاشتراك",cancelConfirm:"هل أنت متأكد من رغبتك في إلغاء اشتراكك؟",cancelKeep:"الاحتفاظ بالاشتراك",cancelButton:"نعم، إلغاء الاشتراك",cancelTrialTitle:"إلغاء التجربة",cancelTrialConfirm:"هل أنت متأكد من رغبتك في إلغاء فترتك التجريبية؟",cancelTrialAccess:"ستستمر فترتك التجريبية حتى",cancelTrialNoCharge:"لن يتم تحصيل أي رسوم منك — ستنتهي فترتك التجريبية ببساطة",cancelTrialResume:"يمكنك استئناف فترتك التجريبية في أي وقت قبل انتهائها",cancelTrialKeep:"الاحتفاظ بالتجربة",cancelTrialButton:"نعم، إلغاء التجربة",canceling:"جارٍ الإلغاء...",cancelSuccess:"سيتم إلغاء الاشتراك في نهاية فترة الفوترة.",cancelNotCharged:"لن يتم تحصيل رسوم منك مرة أخرى بعد الإلغاء",cancelResumeAnytime:"يمكنك استئناف اشتراكك في أي وقت قبل انتهائه",resumeTitle:"استئناف الاشتراك",resumeTrial:"استئناف التجربة",resumeConfirm:"هل أنت متأكد من رغبتك في استئناف اشتراكك؟",resumeKeep:"إبقاء الإلغاء",resumeButton:"نعم، استئناف الاشتراك",resuming:"جارٍ الاستئناف...",resumeSuccess:"تم استئناف الاشتراك.",managePayment:"إدارة الدفع",openingPortal:"جارٍ الفتح...",viewAllPlans:"عرض جميع الخطط",scheduledCancellation:"تم جدولة إلغاء الاشتراك",scheduledTrialCancellation:"تم جدولة إلغاء التجربة",paymentPastDue:"الدفع متأخر",paymentPastDueDescription:"يرجى تحديث طريقة الدفع لتجنب انقطاع الخدمة.",subscriptionPaused:"الاشتراك موقوف",subscriptionPausedDescription:"اشتراكك موقوف حالياً. استأنف لاستعادة الوصول الكامل.",errorLoading:"خطأ في تحميل بيانات الاشتراك",errorLoadingDescription:"يرجى التحقق من اتصالك والمحاولة مرة أخرى.",errorProcessing:"فشل في معالجة الاشتراك",errorCanceling:"فشل في إلغاء الاشتراك",errorResuming:"فشل في استئناف الاشتراك",invalidWorkspace:"معرّف مساحة العمل غير صالح",billingInterval:{monthly:"شهري",quarterly:"ربع سنوي",yearly:"سنوي",perMonth:"/شهر",perQuarter:"/ربع سنة",perYear:"/سنة"},seats:{title:"المقاعد",members:"الأعضاء",included:"مشمول",billable:"قابل للفوترة",perExtraSeat:"لكل مقعد إضافي",limit:"الحد",includedSeats:"المقاعد المشمولة",maxSeats:"الحد الأقصى للمقاعد",freeWithBase:"مجاني مع السعر الأساسي",allIncluded:"الكل مشمول",extra:"إضافي",unlimited:"غير محدود"},items:{features:"الميزات",limits:"الحدود",quotas:"حصص الاستخدام",credits:"AI Credits",creditsPerMonth:"Credits per month",creditsOneTime:"Credits (given once)",creditRenewal:"Credit renewal",creditModeLifetime:"Given once",creditsPerPeriod:"Credits per month",creditRollover:"Credit renewal",creditModeReset:"Fresh every month",creditModeTopup:"Adds up every month"},checkout:{upgrade:"ترقية",downgrade:"تخفيض",switchTo:"التبديل إلى",select:"اختيار"},status:{active:"نشط",canceling:"جارٍ الإلغاء",trial:"تجريبي",canceled:"ملغى",pastDue:"متأخر",paused:"موقوف",deprecated:"قديم",unknown:"غير معروف"},plan:"الخطة",invoicesTab:"الفواتير",changePlanButton:"تغيير الخطة",noPlanAssigned:"لم يتم تعيين خطة",free:"مجاني",perSeatDisplay:"+ {price}/مقعد{interval}",estTotalDisplay:"الإجمالي التقديري: {total}{interval} ({count, plural, zero {بدون مقاعد إضافية} one {مقعد إضافي واحد} two {مقعدان إضافيان} few {# مقاعد إضافية} many {# مقعداً إضافياً} other {# مقعد إضافي}})",nextBillingDisplay:"الفوترة التالية: {date}",membersInWorkspace:"{count, plural, zero {لا أعضاء} one {عضو واحد} two {عضوان} few {# أعضاء} many {# عضواً} other {# عضو}} في مساحة العمل",billingInCurrency:"الفوترة بـ {currency}",savingsPercent:"وفّر {percent, number}%",switchToInterval:"التبديل إلى {interval}",seatPriceDisplay:"+ {price}/مقعد{interval} ({included} {includedLabel})",trialEnded:"انتهت فترتك التجريبية.",trialEndsIn:"تنتهي فترتك التجريبية خلال {days, plural, zero {اليوم} one {يوم واحد} two {يومين} few {# أيام} many {# يوماً} other {# يوم}}.",onTrial:"أنت في فترة تجريبية.",upgradeToKeepAccess:"قم بالترقية للحفاظ على الوصول.",viewInvoices:"عرض الفواتير",cancelTrial:"إلغاء التجربة",dunningFinal:"تحذير أخير: سيتم تعليق الاشتراك",dunningSuspended:"الاشتراك معلق",dunningRecovery:"جارٍ استرداد الدفع",dunningSuspendedDescription:"تم تعليق اشتراكك بسبب فشل الدفع المتكرر. حدّث طريقة الدفع لاستعادة الوصول.",dunningRecoveryDescription:"لم نتمكن من معالجة دفعتك. يرجى تحديث طريقة الدفع لتجنب فقدان الوصول.",cancelEndDescription:"سينتهي اشتراكك في",trialEndDescription:"ستنتهي فترتك التجريبية في",cancelEndFallback:"سيتم إلغاء اشتراكك في نهاية فترة الفوترة الحالية. لن يتم تحصيل رسوم منك مرة أخرى.",resumeChargeDate:"سيتم تحصيل الرسوم منك مرة أخرى في",resumeChargeFallback:"تاريخ الفوترة التالي",resumeContinue:"سيستمر اشتراكك تلقائياً وسيتم فوترتك وفقاً لخطتك",resumeCancelAnytime:"يمكنك الإلغاء في أي وقت قبل تاريخ الفوترة التالي إذا غيرت رأيك",retainAccess:"ستحتفظ بالوصول الكامل إلى هذه الخطة حتى",retainAccessFallback:"نهاية فترة الفوترة الحالية",noPlansAvailable:"لا توجد مجموعات خطط متاحة لمساحة العمل هذه. يرجى الاتصال بالدعم إذا كنت تعتقد أن هذا خطأ.",noPlansAvailableHint:"لا توجد مجموعات خطط متاحة لمساحة العمل هذه.",startTrialDescription:"جرب الخطة الكاملة بدون التزام. يمكنك الترقية أو الإلغاء في أي وقت.",noSubscriptionDescription:"اختر خطة للبدء مع مساحة العمل الخاصة بك",startFreeTrial:"ابدأ التجربة المجانية",startTrialDays:"ابدأ تجربة مجانية لمدة {days} يوم",trialBadge:"تجربة {days} يوم"},users:{title:"أعضاء مساحة العمل",adminOnly:"فقط مدير مساحة العمل يمكنه إدارة المستخدمين والأدوار.",inviteByEmail:"دعوة عضو عبر البريد الإلكتروني",inviteButton:"دعوة",inviting:"جارٍ الدعوة...",inviteSuccess:"تمت دعوة المستخدم بنجاح",emailRequired:"البريد الإلكتروني مطلوب",invalidEmail:"صيغة البريد الإلكتروني غير صالحة",inviteFailed:"فشل في دعوة العضو",seatLimitReached:"تم الوصول لحد المقاعد",memberLimitReached:"تم الوصول لحد الأعضاء",role:"الدور",you:"أنت",owner:"المالك",noMembers:"لم يتم العثور على أعضاء في مساحة العمل هذه.",extraSeatCost:"كل عضو إضافي يضيف {price}/{interval, select, yearly {سنة} quarterly {ربع سنة} other {شهر}} لاشتراكك",unknownUser:"مستخدم غير معروف",seats:"المقاعد",members:"الأعضاء",included:"مشمول",perExtraSeat:"/مقعد إضافي",maxMembers:"الحد الأقصى للأعضاء",available:"متاح",noMemberLimit:"لا حد للأعضاء",seatHeading:"{hasSeatPricing, select, true {المقاعد} other {الأعضاء}}",limitReached:"{reason, select, seat_limit_reached {تم الوصول لحد المقاعد} other {تم الوصول لحد الأعضاء}}",memberCount:"{count, plural, zero {لا أعضاء} one {عضو واحد} two {عضوان} few {# أعضاء} many {# عضواً} other {# عضو}}",subscriptionRequired:"الاشتراك مطلوب لدعوة الأعضاء.",seatLimitMessage:"خطتك تسمح بحد أقصى {maxUsers, number} {maxUsers, plural, zero {أعضاء} one {عضو} two {عضوين} few {أعضاء} many {عضواً} other {عضو}}. قم بالترقية للحصول على مقاعد إضافية.",settingsLimitMessage:"مساحة العمل هذه تسمح بحد أقصى {maxUsers, number} {maxUsers, plural, zero {أعضاء} one {عضو} two {عضوين} few {أعضاء} many {عضواً} other {عضو}}.",memberLimitMessage:"تم الوصول لحد الأعضاء: {maxUsers, number}.",selectRole:"اختر دوراً",inviteAs:"دعوة كـ {role}"},invoices:{title:"سجل الفوترة",description:"عرض وتحميل فواتيرك",pay:"دفع",view:"عرض",viewDetails:"عرض التفاصيل",download:"PDF",errorLoading:"خطأ في تحميل الفواتير",noInvoices:"لا توجد فواتير بعد. اشترك في خطة لاستلام الفواتير.",noInvoicesWithSub:"لم يتم العثور على فواتير مع خيار التحميل",paidAmount:"المدفوع: {amount}",na:"غ/م",status:{draft:"مسودة",open:"مفتوح",paid:"مدفوع",uncollectible:"غير قابل للتحصيل",void:"ملغى"}},usage:{title:"الاستخدام",description:"راقب استهلاك مواردك وحصصك",totalResources:"إجمالي الموارد",overallUsage:"الاستخدام الإجمالي",inOverage:"تجاوز الحد",estOverageCost:"التكلفة التقديرية للتجاوز",overageDetected:"تم اكتشاف تجاوز",overageDescription:"سيتم فوترة الاستخدام الإضافي كتجاوز في فاتورتك التالية.",overageUnits:"وحدات التجاوز",rate:"المعدل",billableBlocks:"الكتل القابلة للفوترة",estimatedCharge:"الرسوم التقديرية",noData:"لا تتوفر بيانات استخدام الحصص لمساحة العمل هذه.",noDataHint:"ستظهر الحصص هنا عندما تتضمن خطتك موارد مقاسة.",used:"مستخدم",remaining:"متبقٍ",overLimit:"فوق الحد",percentUsed:"{percent, number}% مستخدم",availableRemaining:"{count} متبقٍ",overLimitCount:"{count} فوق الحد",overageWarning:"{count, plural, zero {لم تتجاوز أي موارد الحصة المشمولة.} one {مورد واحد تجاوز الحصة المشمولة.} two {مورداً تجاوزا الحصة المشمولة.} few {# موارد تجاوزت الحصة المشمولة.} many {# مورداً تجاوز الحصة المشمولة.} other {# مورد تجاوز الحصة المشمولة.}} سيتم فوترة الاستخدام الإضافي كتجاوز في فاتورتك التالية.",fullyUsed:"مستخدم بالكامل",renewingSoon:"يتجدد قريباً",almostFull:"ممتلئ تقريباً",overage:"تجاوز",errorLoading:"فشل في تحميل بيانات الاستخدام",perUnit:"/ وحدة",perUnits:"/ وحدات",rateDisplay:"{rate} {unitSize, plural, =1 {/ وحدة} other {/ {unitSize, number} وحدة}}",resourcesExceeded:"{count, plural, zero {لم تتجاوز أي موارد الحصة المشمولة.} one {مورد واحد تجاوز الحصة المشمولة.} two {مورداً تجاوزا الحصة المشمولة.} few {# موارد تجاوزت الحصة المشمولة.} many {# مورداً تجاوز الحصة المشمولة.} other {# مورد تجاوز الحصة المشمولة.}}",estOverageCharges:"الرسوم التقديرية للتجاوز في هذه الفترة: {amount}",overageRateDisplay:"معدل التجاوز: {rate}",resetDateDisplay:"يتم إعادة تعيين الاستخدام في {date}",daysRemainingDisplay:"{count, plural, zero {اليوم} one {يوم واحد متبقٍ} two {يومان متبقيان} few {# أيام متبقية} many {# يوماً متبقياً} other {# يوم متبقٍ}}"},profile:{email:"البريد الإلكتروني",name:"الاسم",language:"اللغة",country:"البلد",currency:"العملة",timezone:"المنطقة الزمنية",profileImage:"صورة الملف الشخصي",success:"تم حفظ الملف الشخصي بنجاح",nameMinLength:"يجب أن يتكون الاسم من حرفين على الأقل.",save:"حفظ",reset:"إعادة تعيين"},general:{ownerOnly:"فقط مالك مساحة العمل يمكنه تغيير إعدادات مساحة العمل.",name:"الاسم",namePlaceholder:"مساحة العمل الرائعة",nameMinLength:"يجب أن يتكون اسم مساحة العمل من حرفين على الأقل.",billingCurrency:"عملة الفوترة",icon:"الأيقونة",iconDescription:"اختر رمزاً تعبيرياً أو حمّل صورة مخصصة لمساحة العمل.",imageUrl:"رابط الصورة",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"أدخل رابطاً صالحاً لصورة مساحة العمل. الصيغ المدعومة: PNG و JPG و SVG.",previewLabel:"معاينة:",success:"تم حفظ إعدادات مساحة العمل بنجاح",chooseEmoji:"اختر رمزاً تعبيرياً",customImageUrl:"رابط صورة مخصص",updateWorkspace:"تحديث مساحة العمل"},features:{title:"ميزات مساحة العمل",ownerOnly:"فقط مالك مساحة العمل يمكنه تغيير الميزات.",noFeatures:"لا توجد ميزات لإدارتها.",enabled:"مفعّل",disabled:"معطّل",enabling:"جارٍ التفعيل",disabling:"جارٍ التعطيل",featureSuccess:"بنجاح",updateSuccess:"تم {enabled, select, true {تفعيل} other {تعطيل}} {feature} بنجاح",actionStatus:"{action, select, enabling {جارٍ التفعيل} disabling {جارٍ التعطيل} other {}}"},danger:{title:"حذف مساحة العمل",adminOnly:"فقط مديرو مساحة العمل يمكنهم حذف مساحات العمل.",deleteWorkspace:"حذف مساحة العمل",deleteConfirm:"هل أنت متأكد تماماً؟",deleteWarning:"لا يمكن التراجع عن هذا الإجراء. سيتم حذف مساحة العمل وجميع البيانات المرتبطة نهائياً.",deleting:"جارٍ الحذف...",deleteDescription:"بمجرد حذف مساحة العمل لا يمكن العودة. سيتم حذف مساحة العمل وجميع بياناتها نهائياً، بما في ذلك الأعضاء والإعدادات والميزات.",deleteConfirmDescription:"لا يمكن التراجع عن هذا الإجراء. سيتم حذف مساحة العمل وجميع بياناتها نهائياً.",failedToDelete:"فشل في حذف مساحة العمل"},notifications:{title:"تفضيلات الإشعارات",permissionDenied:"تم رفض إذن الإشعارات",notSupported:"الإشعارات الفورية غير مدعومة في هذا المتصفح.",manageDescription:"أدِر كيفية تلقي الإشعارات من مساحة العمل هذه.",blocked:"الإشعارات محظورة",blockedDescription:"لقد حظرت الإشعارات لهذا الموقع سابقاً. لتفعيلها، حدّث إعدادات متصفحك:",pushTitle:"الإشعارات الفورية",pushEnabledDescription:"ستتلقى إشعارات المتصفح للتحديثات المهمة.",pushDisabledDescription:"احصل على إشعارات حول مشاكل الدفع وانتهاء التجربة والتحديثات المهمة الأخرى.",enabling:"جارٍ التفعيل...",disabling:"جارٍ التعطيل...",enable:"تفعيل",disable:"تعطيل",toggleAction:"{loading, select, true {{subscribed, select, true {جارٍ التعطيل...} other {جارٍ التفعيل...}}} other {{subscribed, select, true {تعطيل} other {تفعيل}}}}",pushDescription:"{subscribed, select, true {ستتلقى إشعارات المتصفح للتحديثات المهمة.} other {احصل على إشعارات حول مشاكل الدفع وانتهاء التجربة والتحديثات المهمة الأخرى.}}",deviceNote:"يتم إرسال الإشعارات إلى هذا الجهاز. فعّلها على الأجهزة الأخرى بشكل منفصل.",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:"انقر على أيقونة القفل (أو الدرع) في شريط العنوان",step2:'ابحث عن "Notifications" في قائمة الأذونات',step3:'غيّر من "Blocked" إلى "Allow"',step4:"أعد تحميل هذه الصفحة"},safari:{step1:"افتح Safari ← الإعدادات ← مواقع الويب ← الإشعارات",step2:"ابحث عن هذا الموقع في القائمة",step3:'غيّر من "Deny" إلى "Allow"',step4:"أعد تحميل هذه الصفحة"},edge:{step1:"انقر على أيقونة القفل في شريط العنوان",step2:'انقر على "Permissions for this site"',step3:'اضبط "Notifications" على "Allow"',step4:"أعد تحميل هذه الصفحة"},chrome:{step1:"انقر على أيقونة القفل (أو الضبط) في شريط العنوان",step2:'انقر على "Site settings"',step3:'اضبط "Notifications" على "Allow"',step4:"أعد تحميل هذه الصفحة"}}},quota:{includedOnly:"{count, number} مشمول",includedWithOverage:"{count, number} مشمول، ثم {price} / {unit}",includedHardLimit:"{count, number} مشمول (حد أقصى)",unitFallback:"وحدة"},pricing:{title:"اختر خطتك",description:"قارن بين الخطط واختر ما يناسب احتياجاتك",currency:"العملة",billingIn:"الفوترة بـ",noPlansCurrency:"لا توجد خطط متاحة لعملة الفوترة الخاصة بك.",noPlansCurrencyHint:"حدث خطأ ما. يرجى الاتصال بالدعم.",noPlans:"لا توجد خطط متاحة",free:"مجاني",included:"مشمول",save:"وفّر",current:"الحالي",processing:"جارٍ المعالجة...",unavailable:"غير متاح",selectCurrency:"اختر عملة الفوترة",billingInterval:"فترة الفوترة"},beta:{nameLabel:"الاسم",emailLabel:"البريد الإلكتروني",submitText:"إرسال",submittingText:"جارٍ الإرسال...",errorMessage:"حدث خطأ",tryAgain:"حاول مرة أخرى",privacyConsent:"بإرسال هذا النموذج، فإنك توافق على",privacyPolicy:"سياسة الخصوصية",and:"و",termsOfService:"شروط الخدمة"},workspace:{switchTitle:"تبديل مساحة العمل",switchDescription:"اختر مساحة عمل للتبديل إليها أو أنشئ واحدة جديدة.",notLoggedIn:"يبدو أنك لم تسجل الدخول. يرجى تسجيل الدخول للمتابعة.",availableWorkspaces:"مساحات العمل المتاحة ({count, number})",loadingWorkspaces:"جارٍ تحميل مساحات العمل...",searchPlaceholder:"بحث في مساحات العمل...",noWorkspacesFound:"لم يتم العثور على مساحات عمل",noWorkspacesAvailable:"لا تتوفر مساحات عمل",switchTo:"التبديل إلى",membersCount:"{count, plural, zero {لا أعضاء} one {عضو واحد} two {عضوان} few {# أعضاء} many {# عضواً} other {# عضو}}",createNew:"إنشاء مساحة عمل جديدة",createTitle:"إنشاء مساحة عمل جديدة",createDescription:"أنشئ مساحة عمل جديدة للبدء.",workspaceName:"اسم مساحة العمل",workspaceNamePlaceholder:"مساحة العمل الرائعة",workspaceNameMinLength:"يجب أن يتكون اسم مساحة العمل من حرفين على الأقل.",workspaceIcon:"أيقونة مساحة العمل",iconDescription:"اختر رمزاً تعبيرياً أو حمّل صورة مخصصة لمساحة العمل.",chooseEmoji:"اختر رمزاً تعبيرياً",customImageUrl:"رابط صورة مخصص",imageUrl:"رابط الصورة",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"أدخل رابطاً صالحاً لصورة مساحة العمل. الصيغ المدعومة: PNG و JPG و SVG.",invalidUrl:"يرجى إدخال رابط صالح",creating:"جارٍ الإنشاء...",createWorkspace:"إنشاء مساحة العمل"},dropdowns:{search:"بحث...",chooseOption:"اختر خياراً",chooseCountry:"اختر البلد",searchCountry:"اختر البلد...",chooseLanguage:"اختر اللغة",searchLanguage:"اختر اللغة...",chooseCurrency:"اختر العملة",searchCurrency:"اختر العملة...",chooseTimezone:"اختر المنطقة الزمنية",searchTimezone:"اختر المنطقة الزمنية..."},push:{failedToSubscribe:"فشل في الاشتراك في الإشعارات الفورية",failedToUnsubscribe:"فشل في إلغاء الاشتراك من الإشعارات الفورية"},permissions:{title:"الصلاحيات",description:"قم بتكوين ما يمكن لكل دور القيام به في مساحة العمل هذه.",ownerOnly:"يمكن لمالك مساحة العمل فقط إدارة الصلاحيات.",save:"حفظ الصلاحيات",saving:"جارٍ الحفظ...",saveSuccess:"تم حفظ الصلاحيات بنجاح"},credits:{title:"الرصيد",description:"يمكن استخدام الرصيد للإجراءات المميزة مثل التوليد بالذكاء الاصطناعي.",balance:"رصيد الائتمان",available:"متاح",totalGranted:"إجمالي الممنوح",totalConsumed:"إجمالي المستهلك",totalExpired:"إجمالي المنتهي",noCredits:"لا يوجد رصيد بعد",noCreditsHint:"سيظهر الرصيد هنا عند منحه من خطتك أو شرائه.",buyCredits:"شراء رصيد",buyAmount:"Buy {count} Credits",purchasing:"جارٍ إعادة التوجيه...",packages:"حزم الرصيد",noPackages:"لا تتوفر حزم رصيد.",creditsAmount:"{count} رصيد",validityDays:"صالح لمدة {count} يوم",validityUnlimited:"بدون انتهاء صلاحية",transactions:"المعاملات الأخيرة",noTransactions:"لا توجد معاملات بعد.",loadMore:"Load More",viewAll:"عرض الكل",expiringSoon:"ينتهي قريباً",expiringInDays:"{count} رصيد ينتهي خلال {days} يوم",noExpiring:"لا يوجد رصيد ينتهي قريباً.",type:{plan_grant:"منحة الخطة",pack_purchased:"تم الشراء",consumed:"مستهلك",expired:"منتهي",admin_grant:"ممنوح",admin_revoke:"مسحوب",refund:"استرداد"},dialogTitle:"Buy Credit Packages",dialogDescription:"Choose a credit package to purchase.",dialogDescriptionWorkspace:"Purchase credits for {workspace}.",perCredit:"{price} per credit",purchaseSuccess:"تم شراء الرصيد بنجاح! تم تحديث رصيدك.",purchaseCanceled:"تم إلغاء شراء الرصيد. لم يتم تحصيل أي رسوم.",purchaseFailed:"فشل شراء الرصيد. يرجى المحاولة مرة أخرى أو التواصل مع الدعم.",errorLoading:"فشل في تحميل بيانات الرصيد",insufficientCredits:"رصيد غير كافٍ"},loading:{restoringSession:"جارٍ استعادة الجلسة...",redirecting:"جارٍ إعادة التوجيه...",signingIn:"جارٍ تسجيل الدخول...",verifyingAccount:"جارٍ التحقق من حسابك...",almostThere:"أوشكنا على الانتهاء..."},errors:{networkError:"خطأ في الشبكة: يرجى التحقق من اتصالك بالإنترنت",unauthorized:"غير مصرح - يرجى التحقق من جلستك",notFound:"المورد غير موجود",generic:"حدث خطأ",fetchPlans:"فشل في جلب الخطط",fetchPlanGroup:"فشل في جلب مجموعة الخطط",fetchPlanGroupVersion:"فشل في جلب إصدار مجموعة الخطط",fetchPlanGroupVersions:"فشل في جلب إصدارات مجموعة الخطط",fetchSubscription:"فشل في جلب الاشتراك",createCheckout:"فشل في إنشاء جلسة الدفع",updateSubscription:"فشل في تحديث الاشتراك",fetchInvoices:"فشل في جلب الفواتير",fetchInvoice:"فشل في جلب الفاتورة",openBillingPortal:"فشل في فتح بوابة الفوترة",cancelSubscription:"فشل في إلغاء الاشتراك",resumeSubscription:"فشل في استئناف الاشتراك",recordUsage:"فشل في تسجيل الاستخدام",fetchQuotaUsage:"فشل في جلب حالة استخدام الحصص",fetchAllQuotaUsage:"فشل في جلب جميع استخدامات الحصص",fetchUsageLogs:"فشل في جلب سجلات الاستخدام",fetchCreditBalance:"فشل في جلب رصيد الائتمان",consumeCredits:"فشل في استهلاك الرصيد",purchaseCredits:"فشل في شراء الرصيد",fetchCreditPackages:"فشل في جلب حزم الرصيد",fetchCreditTransactions:"فشل في جلب معاملات الرصيد",fetchExpiringCredits:"فشل في جلب الرصيد المنتهي قريباً"},security:{inactive:"غير نشط",inactiveHint:"سُجّل على نطاق تسجيل دخول سابق ولم يعد قابلاً للاستخدام. يمكنك إزالته.",passkeysTitle:"مفاتيح المرور",passkeysDescription:"تتيح مفاتيح المرور تسجيل الدخول ببصمة الإصبع أو الوجه أو رمز PIN للجهاز.",noPasskeys:"لا توجد مفاتيح مرور مسجلة",addHint:'لإضافة مفتاح مرور، اختر "إضافة مفتاح مرور" عند تسجيل الدخول التالي على الجهاز الذي تريد استخدامه.',rename:"إعادة تسمية",remove:"إزالة",removeTitle:"إزالة مفتاح المرور",removeDescription:"لن تتمكن من تسجيل الدخول بمفتاح المرور هذا بعد الآن.",renamePlaceholder:"اسم مفتاح المرور",lastUsed:"آخر استخدام",added:"أُضيف"}};
@@ -0,0 +1,2 @@
1
+ "use client";
2
+ const e={settings:{titles:{profile:"الحساب",security:"الأمان",general:"إعدادات مساحة العمل",users:"أعضاء مساحة العمل",subscription:"الخطة والفوترة",usage:"الاستخدام",credits:"الرصيد",features:"ميزات مساحة العمل",notifications:"الإشعارات",permissions:"الصلاحيات",danger:"منطقة الخطر"},sidebar:{account:"الحساب",workspace:"مساحة العمل",profile:"الحساب",security:"الأمان",general:"الإعدادات",users:"الأعضاء",subscription:"الخطة والفوترة",usage:"الاستخدام",credits:"الرصيد",features:"الميزات",notifications:"الإشعارات",permissions:"الصلاحيات",danger:"منطقة الخطر"},common:{refresh:"تحديث",refreshing:"جارٍ التحديث...",retry:"إعادة المحاولة",retrying:"جارٍ إعادة المحاولة...",save:"حفظ",saving:"جارٍ الحفظ...",cancel:"إلغاء",delete:"حذف",dismiss:"تجاهل",loading:"جارٍ التحميل...",success:"تم بنجاح!",error:"خطأ",refreshAction:"{loading, select, true {جارٍ التحديث...} other {تحديث}}",retryAction:"{loading, select, true {جارٍ إعادة المحاولة...} other {إعادة المحاولة}}",noPermissionTitle:"الوصول مقيد",noPermissionDescription:"ليس لديك إذن للوصول إلى هذا القسم. تواصل مع مسؤول مساحة العمل إذا كنت بحاجة إلى الوصول.",billingManageOnly:"فقط المستخدمون الذين لديهم أذونات إدارة الفواتير يمكنهم تنفيذ هذا الإجراء."}},subscription:{managePlan:"إدارة خطتك وفوترتك",changePlan:"تغيير الخطة",viewPricingPlans:"عرض خطط الأسعار",viewPlans:"عرض الخطط",upgradePlan:"ترقية الآن",subscribe:"اشتراك",currentPlan:"الخطة الحالية",noSubscription:"ليس لديك اشتراك نشط",choosePlan:"اختر خطتك",choosePlanDescription:"قارن بين الخطط واختر ما يناسب احتياجاتك",forWorkspace:"لـ {name}",planUpdateAvailable:"تحديث الخطة متوفر",updateSuccess:"تم تحديث الاشتراك بنجاح!",updateFailed:"فشل التحديث",cancelTitle:"إلغاء الاشتراك",cancelConfirm:"هل أنت متأكد من رغبتك في إلغاء اشتراكك؟",cancelKeep:"الاحتفاظ بالاشتراك",cancelButton:"نعم، إلغاء الاشتراك",cancelTrialTitle:"إلغاء التجربة",cancelTrialConfirm:"هل أنت متأكد من رغبتك في إلغاء فترتك التجريبية؟",cancelTrialAccess:"ستستمر فترتك التجريبية حتى",cancelTrialNoCharge:"لن يتم تحصيل أي رسوم منك — ستنتهي فترتك التجريبية ببساطة",cancelTrialResume:"يمكنك استئناف فترتك التجريبية في أي وقت قبل انتهائها",cancelTrialKeep:"الاحتفاظ بالتجربة",cancelTrialButton:"نعم، إلغاء التجربة",canceling:"جارٍ الإلغاء...",cancelSuccess:"سيتم إلغاء الاشتراك في نهاية فترة الفوترة.",cancelNotCharged:"لن يتم تحصيل رسوم منك مرة أخرى بعد الإلغاء",cancelResumeAnytime:"يمكنك استئناف اشتراكك في أي وقت قبل انتهائه",resumeTitle:"استئناف الاشتراك",resumeTrial:"استئناف التجربة",resumeConfirm:"هل أنت متأكد من رغبتك في استئناف اشتراكك؟",resumeKeep:"إبقاء الإلغاء",resumeButton:"نعم، استئناف الاشتراك",resuming:"جارٍ الاستئناف...",resumeSuccess:"تم استئناف الاشتراك.",managePayment:"إدارة الدفع",openingPortal:"جارٍ الفتح...",viewAllPlans:"عرض جميع الخطط",scheduledCancellation:"تم جدولة إلغاء الاشتراك",scheduledTrialCancellation:"تم جدولة إلغاء التجربة",paymentPastDue:"الدفع متأخر",paymentPastDueDescription:"يرجى تحديث طريقة الدفع لتجنب انقطاع الخدمة.",subscriptionPaused:"الاشتراك موقوف",subscriptionPausedDescription:"اشتراكك موقوف حالياً. استأنف لاستعادة الوصول الكامل.",errorLoading:"خطأ في تحميل بيانات الاشتراك",errorLoadingDescription:"يرجى التحقق من اتصالك والمحاولة مرة أخرى.",errorProcessing:"فشل في معالجة الاشتراك",errorCanceling:"فشل في إلغاء الاشتراك",errorResuming:"فشل في استئناف الاشتراك",invalidWorkspace:"معرّف مساحة العمل غير صالح",billingInterval:{monthly:"شهري",quarterly:"ربع سنوي",yearly:"سنوي",perMonth:"/شهر",perQuarter:"/ربع سنة",perYear:"/سنة"},seats:{title:"المقاعد",members:"الأعضاء",included:"مشمول",billable:"قابل للفوترة",perExtraSeat:"لكل مقعد إضافي",limit:"الحد",includedSeats:"المقاعد المشمولة",maxSeats:"الحد الأقصى للمقاعد",freeWithBase:"مجاني مع السعر الأساسي",allIncluded:"الكل مشمول",extra:"إضافي",unlimited:"غير محدود"},items:{features:"الميزات",limits:"الحدود",quotas:"حصص الاستخدام",credits:"AI Credits",creditsPerMonth:"Credits per month",creditsOneTime:"Credits (given once)",creditRenewal:"Credit renewal",creditModeLifetime:"Given once",creditsPerPeriod:"Credits per month",creditRollover:"Credit renewal",creditModeReset:"Fresh every month",creditModeTopup:"Adds up every month"},checkout:{upgrade:"ترقية",downgrade:"تخفيض",switchTo:"التبديل إلى",select:"اختيار"},status:{active:"نشط",canceling:"جارٍ الإلغاء",trial:"تجريبي",canceled:"ملغى",pastDue:"متأخر",paused:"موقوف",deprecated:"قديم",unknown:"غير معروف"},plan:"الخطة",invoicesTab:"الفواتير",changePlanButton:"تغيير الخطة",noPlanAssigned:"لم يتم تعيين خطة",free:"مجاني",perSeatDisplay:"+ {price}/مقعد{interval}",estTotalDisplay:"الإجمالي التقديري: {total}{interval} ({count, plural, zero {بدون مقاعد إضافية} one {مقعد إضافي واحد} two {مقعدان إضافيان} few {# مقاعد إضافية} many {# مقعداً إضافياً} other {# مقعد إضافي}})",nextBillingDisplay:"الفوترة التالية: {date}",membersInWorkspace:"{count, plural, zero {لا أعضاء} one {عضو واحد} two {عضوان} few {# أعضاء} many {# عضواً} other {# عضو}} في مساحة العمل",billingInCurrency:"الفوترة بـ {currency}",savingsPercent:"وفّر {percent, number}%",switchToInterval:"التبديل إلى {interval}",seatPriceDisplay:"+ {price}/مقعد{interval} ({included} {includedLabel})",trialEnded:"انتهت فترتك التجريبية.",trialEndsIn:"تنتهي فترتك التجريبية خلال {days, plural, zero {اليوم} one {يوم واحد} two {يومين} few {# أيام} many {# يوماً} other {# يوم}}.",onTrial:"أنت في فترة تجريبية.",upgradeToKeepAccess:"قم بالترقية للحفاظ على الوصول.",viewInvoices:"عرض الفواتير",cancelTrial:"إلغاء التجربة",dunningFinal:"تحذير أخير: سيتم تعليق الاشتراك",dunningSuspended:"الاشتراك معلق",dunningRecovery:"جارٍ استرداد الدفع",dunningSuspendedDescription:"تم تعليق اشتراكك بسبب فشل الدفع المتكرر. حدّث طريقة الدفع لاستعادة الوصول.",dunningRecoveryDescription:"لم نتمكن من معالجة دفعتك. يرجى تحديث طريقة الدفع لتجنب فقدان الوصول.",cancelEndDescription:"سينتهي اشتراكك في",trialEndDescription:"ستنتهي فترتك التجريبية في",cancelEndFallback:"سيتم إلغاء اشتراكك في نهاية فترة الفوترة الحالية. لن يتم تحصيل رسوم منك مرة أخرى.",resumeChargeDate:"سيتم تحصيل الرسوم منك مرة أخرى في",resumeChargeFallback:"تاريخ الفوترة التالي",resumeContinue:"سيستمر اشتراكك تلقائياً وسيتم فوترتك وفقاً لخطتك",resumeCancelAnytime:"يمكنك الإلغاء في أي وقت قبل تاريخ الفوترة التالي إذا غيرت رأيك",retainAccess:"ستحتفظ بالوصول الكامل إلى هذه الخطة حتى",retainAccessFallback:"نهاية فترة الفوترة الحالية",noPlansAvailable:"لا توجد مجموعات خطط متاحة لمساحة العمل هذه. يرجى الاتصال بالدعم إذا كنت تعتقد أن هذا خطأ.",noPlansAvailableHint:"لا توجد مجموعات خطط متاحة لمساحة العمل هذه.",startTrialDescription:"جرب الخطة الكاملة بدون التزام. يمكنك الترقية أو الإلغاء في أي وقت.",noSubscriptionDescription:"اختر خطة للبدء مع مساحة العمل الخاصة بك",startFreeTrial:"ابدأ التجربة المجانية",startTrialDays:"ابدأ تجربة مجانية لمدة {days} يوم",trialBadge:"تجربة {days} يوم"},users:{title:"أعضاء مساحة العمل",adminOnly:"فقط مدير مساحة العمل يمكنه إدارة المستخدمين والأدوار.",inviteByEmail:"دعوة عضو عبر البريد الإلكتروني",inviteButton:"دعوة",inviting:"جارٍ الدعوة...",inviteSuccess:"تمت دعوة المستخدم بنجاح",emailRequired:"البريد الإلكتروني مطلوب",invalidEmail:"صيغة البريد الإلكتروني غير صالحة",inviteFailed:"فشل في دعوة العضو",seatLimitReached:"تم الوصول لحد المقاعد",memberLimitReached:"تم الوصول لحد الأعضاء",role:"الدور",you:"أنت",owner:"المالك",noMembers:"لم يتم العثور على أعضاء في مساحة العمل هذه.",extraSeatCost:"كل عضو إضافي يضيف {price}/{interval, select, yearly {سنة} quarterly {ربع سنة} other {شهر}} لاشتراكك",unknownUser:"مستخدم غير معروف",seats:"المقاعد",members:"الأعضاء",included:"مشمول",perExtraSeat:"/مقعد إضافي",maxMembers:"الحد الأقصى للأعضاء",available:"متاح",noMemberLimit:"لا حد للأعضاء",seatHeading:"{hasSeatPricing, select, true {المقاعد} other {الأعضاء}}",limitReached:"{reason, select, seat_limit_reached {تم الوصول لحد المقاعد} other {تم الوصول لحد الأعضاء}}",memberCount:"{count, plural, zero {لا أعضاء} one {عضو واحد} two {عضوان} few {# أعضاء} many {# عضواً} other {# عضو}}",subscriptionRequired:"الاشتراك مطلوب لدعوة الأعضاء.",seatLimitMessage:"خطتك تسمح بحد أقصى {maxUsers, number} {maxUsers, plural, zero {أعضاء} one {عضو} two {عضوين} few {أعضاء} many {عضواً} other {عضو}}. قم بالترقية للحصول على مقاعد إضافية.",settingsLimitMessage:"مساحة العمل هذه تسمح بحد أقصى {maxUsers, number} {maxUsers, plural, zero {أعضاء} one {عضو} two {عضوين} few {أعضاء} many {عضواً} other {عضو}}.",memberLimitMessage:"تم الوصول لحد الأعضاء: {maxUsers, number}.",selectRole:"اختر دوراً",inviteAs:"دعوة كـ {role}"},invoices:{title:"سجل الفوترة",description:"عرض وتحميل فواتيرك",pay:"دفع",view:"عرض",viewDetails:"عرض التفاصيل",download:"PDF",errorLoading:"خطأ في تحميل الفواتير",noInvoices:"لا توجد فواتير بعد. اشترك في خطة لاستلام الفواتير.",noInvoicesWithSub:"لم يتم العثور على فواتير مع خيار التحميل",paidAmount:"المدفوع: {amount}",na:"غ/م",status:{draft:"مسودة",open:"مفتوح",paid:"مدفوع",uncollectible:"غير قابل للتحصيل",void:"ملغى"}},usage:{title:"الاستخدام",description:"راقب استهلاك مواردك وحصصك",totalResources:"إجمالي الموارد",overallUsage:"الاستخدام الإجمالي",inOverage:"تجاوز الحد",estOverageCost:"التكلفة التقديرية للتجاوز",overageDetected:"تم اكتشاف تجاوز",overageDescription:"سيتم فوترة الاستخدام الإضافي كتجاوز في فاتورتك التالية.",overageUnits:"وحدات التجاوز",rate:"المعدل",billableBlocks:"الكتل القابلة للفوترة",estimatedCharge:"الرسوم التقديرية",noData:"لا تتوفر بيانات استخدام الحصص لمساحة العمل هذه.",noDataHint:"ستظهر الحصص هنا عندما تتضمن خطتك موارد مقاسة.",used:"مستخدم",remaining:"متبقٍ",overLimit:"فوق الحد",percentUsed:"{percent, number}% مستخدم",availableRemaining:"{count} متبقٍ",overLimitCount:"{count} فوق الحد",overageWarning:"{count, plural, zero {لم تتجاوز أي موارد الحصة المشمولة.} one {مورد واحد تجاوز الحصة المشمولة.} two {مورداً تجاوزا الحصة المشمولة.} few {# موارد تجاوزت الحصة المشمولة.} many {# مورداً تجاوز الحصة المشمولة.} other {# مورد تجاوز الحصة المشمولة.}} سيتم فوترة الاستخدام الإضافي كتجاوز في فاتورتك التالية.",fullyUsed:"مستخدم بالكامل",renewingSoon:"يتجدد قريباً",almostFull:"ممتلئ تقريباً",overage:"تجاوز",errorLoading:"فشل في تحميل بيانات الاستخدام",perUnit:"/ وحدة",perUnits:"/ وحدات",rateDisplay:"{rate} {unitSize, plural, =1 {/ وحدة} other {/ {unitSize, number} وحدة}}",resourcesExceeded:"{count, plural, zero {لم تتجاوز أي موارد الحصة المشمولة.} one {مورد واحد تجاوز الحصة المشمولة.} two {مورداً تجاوزا الحصة المشمولة.} few {# موارد تجاوزت الحصة المشمولة.} many {# مورداً تجاوز الحصة المشمولة.} other {# مورد تجاوز الحصة المشمولة.}}",estOverageCharges:"الرسوم التقديرية للتجاوز في هذه الفترة: {amount}",overageRateDisplay:"معدل التجاوز: {rate}",resetDateDisplay:"يتم إعادة تعيين الاستخدام في {date}",daysRemainingDisplay:"{count, plural, zero {اليوم} one {يوم واحد متبقٍ} two {يومان متبقيان} few {# أيام متبقية} many {# يوماً متبقياً} other {# يوم متبقٍ}}"},profile:{email:"البريد الإلكتروني",name:"الاسم",language:"اللغة",country:"البلد",currency:"العملة",timezone:"المنطقة الزمنية",profileImage:"صورة الملف الشخصي",success:"تم حفظ الملف الشخصي بنجاح",nameMinLength:"يجب أن يتكون الاسم من حرفين على الأقل.",save:"حفظ",reset:"إعادة تعيين"},general:{ownerOnly:"فقط مالك مساحة العمل يمكنه تغيير إعدادات مساحة العمل.",name:"الاسم",namePlaceholder:"مساحة العمل الرائعة",nameMinLength:"يجب أن يتكون اسم مساحة العمل من حرفين على الأقل.",billingCurrency:"عملة الفوترة",icon:"الأيقونة",iconDescription:"اختر رمزاً تعبيرياً أو حمّل صورة مخصصة لمساحة العمل.",imageUrl:"رابط الصورة",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"أدخل رابطاً صالحاً لصورة مساحة العمل. الصيغ المدعومة: PNG و JPG و SVG.",previewLabel:"معاينة:",success:"تم حفظ إعدادات مساحة العمل بنجاح",chooseEmoji:"اختر رمزاً تعبيرياً",customImageUrl:"رابط صورة مخصص",updateWorkspace:"تحديث مساحة العمل"},features:{title:"ميزات مساحة العمل",ownerOnly:"فقط مالك مساحة العمل يمكنه تغيير الميزات.",noFeatures:"لا توجد ميزات لإدارتها.",enabled:"مفعّل",disabled:"معطّل",enabling:"جارٍ التفعيل",disabling:"جارٍ التعطيل",featureSuccess:"بنجاح",updateSuccess:"تم {enabled, select, true {تفعيل} other {تعطيل}} {feature} بنجاح",actionStatus:"{action, select, enabling {جارٍ التفعيل} disabling {جارٍ التعطيل} other {}}"},danger:{title:"حذف مساحة العمل",adminOnly:"فقط مديرو مساحة العمل يمكنهم حذف مساحات العمل.",deleteWorkspace:"حذف مساحة العمل",deleteConfirm:"هل أنت متأكد تماماً؟",deleteWarning:"لا يمكن التراجع عن هذا الإجراء. سيتم حذف مساحة العمل وجميع البيانات المرتبطة نهائياً.",deleting:"جارٍ الحذف...",deleteDescription:"بمجرد حذف مساحة العمل لا يمكن العودة. سيتم حذف مساحة العمل وجميع بياناتها نهائياً، بما في ذلك الأعضاء والإعدادات والميزات.",deleteConfirmDescription:"لا يمكن التراجع عن هذا الإجراء. سيتم حذف مساحة العمل وجميع بياناتها نهائياً.",failedToDelete:"فشل في حذف مساحة العمل"},notifications:{title:"تفضيلات الإشعارات",permissionDenied:"تم رفض إذن الإشعارات",notSupported:"الإشعارات الفورية غير مدعومة في هذا المتصفح.",manageDescription:"أدِر كيفية تلقي الإشعارات من مساحة العمل هذه.",blocked:"الإشعارات محظورة",blockedDescription:"لقد حظرت الإشعارات لهذا الموقع سابقاً. لتفعيلها، حدّث إعدادات متصفحك:",pushTitle:"الإشعارات الفورية",pushEnabledDescription:"ستتلقى إشعارات المتصفح للتحديثات المهمة.",pushDisabledDescription:"احصل على إشعارات حول مشاكل الدفع وانتهاء التجربة والتحديثات المهمة الأخرى.",enabling:"جارٍ التفعيل...",disabling:"جارٍ التعطيل...",enable:"تفعيل",disable:"تعطيل",toggleAction:"{loading, select, true {{subscribed, select, true {جارٍ التعطيل...} other {جارٍ التفعيل...}}} other {{subscribed, select, true {تعطيل} other {تفعيل}}}}",pushDescription:"{subscribed, select, true {ستتلقى إشعارات المتصفح للتحديثات المهمة.} other {احصل على إشعارات حول مشاكل الدفع وانتهاء التجربة والتحديثات المهمة الأخرى.}}",deviceNote:"يتم إرسال الإشعارات إلى هذا الجهاز. فعّلها على الأجهزة الأخرى بشكل منفصل.",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:"انقر على أيقونة القفل (أو الدرع) في شريط العنوان",step2:'ابحث عن "Notifications" في قائمة الأذونات',step3:'غيّر من "Blocked" إلى "Allow"',step4:"أعد تحميل هذه الصفحة"},safari:{step1:"افتح Safari ← الإعدادات ← مواقع الويب ← الإشعارات",step2:"ابحث عن هذا الموقع في القائمة",step3:'غيّر من "Deny" إلى "Allow"',step4:"أعد تحميل هذه الصفحة"},edge:{step1:"انقر على أيقونة القفل في شريط العنوان",step2:'انقر على "Permissions for this site"',step3:'اضبط "Notifications" على "Allow"',step4:"أعد تحميل هذه الصفحة"},chrome:{step1:"انقر على أيقونة القفل (أو الضبط) في شريط العنوان",step2:'انقر على "Site settings"',step3:'اضبط "Notifications" على "Allow"',step4:"أعد تحميل هذه الصفحة"}}},quota:{includedOnly:"{count, number} مشمول",includedWithOverage:"{count, number} مشمول، ثم {price} / {unit}",includedHardLimit:"{count, number} مشمول (حد أقصى)",unitFallback:"وحدة"},pricing:{title:"اختر خطتك",description:"قارن بين الخطط واختر ما يناسب احتياجاتك",currency:"العملة",billingIn:"الفوترة بـ",noPlansCurrency:"لا توجد خطط متاحة لعملة الفوترة الخاصة بك.",noPlansCurrencyHint:"حدث خطأ ما. يرجى الاتصال بالدعم.",noPlans:"لا توجد خطط متاحة",free:"مجاني",included:"مشمول",save:"وفّر",current:"الحالي",processing:"جارٍ المعالجة...",unavailable:"غير متاح",selectCurrency:"اختر عملة الفوترة",billingInterval:"فترة الفوترة"},beta:{nameLabel:"الاسم",emailLabel:"البريد الإلكتروني",submitText:"إرسال",submittingText:"جارٍ الإرسال...",errorMessage:"حدث خطأ",tryAgain:"حاول مرة أخرى",privacyConsent:"بإرسال هذا النموذج، فإنك توافق على",privacyPolicy:"سياسة الخصوصية",and:"و",termsOfService:"شروط الخدمة"},workspace:{switchTitle:"تبديل مساحة العمل",switchDescription:"اختر مساحة عمل للتبديل إليها أو أنشئ واحدة جديدة.",notLoggedIn:"يبدو أنك لم تسجل الدخول. يرجى تسجيل الدخول للمتابعة.",availableWorkspaces:"مساحات العمل المتاحة ({count, number})",loadingWorkspaces:"جارٍ تحميل مساحات العمل...",searchPlaceholder:"بحث في مساحات العمل...",noWorkspacesFound:"لم يتم العثور على مساحات عمل",noWorkspacesAvailable:"لا تتوفر مساحات عمل",switchTo:"التبديل إلى",membersCount:"{count, plural, zero {لا أعضاء} one {عضو واحد} two {عضوان} few {# أعضاء} many {# عضواً} other {# عضو}}",createNew:"إنشاء مساحة عمل جديدة",createTitle:"إنشاء مساحة عمل جديدة",createDescription:"أنشئ مساحة عمل جديدة للبدء.",workspaceName:"اسم مساحة العمل",workspaceNamePlaceholder:"مساحة العمل الرائعة",workspaceNameMinLength:"يجب أن يتكون اسم مساحة العمل من حرفين على الأقل.",workspaceIcon:"أيقونة مساحة العمل",iconDescription:"اختر رمزاً تعبيرياً أو حمّل صورة مخصصة لمساحة العمل.",chooseEmoji:"اختر رمزاً تعبيرياً",customImageUrl:"رابط صورة مخصص",imageUrl:"رابط الصورة",imageUrlPlaceholder:"https://example.com/image.png",imageUrlDescription:"أدخل رابطاً صالحاً لصورة مساحة العمل. الصيغ المدعومة: PNG و JPG و SVG.",invalidUrl:"يرجى إدخال رابط صالح",creating:"جارٍ الإنشاء...",createWorkspace:"إنشاء مساحة العمل"},dropdowns:{search:"بحث...",chooseOption:"اختر خياراً",chooseCountry:"اختر البلد",searchCountry:"اختر البلد...",chooseLanguage:"اختر اللغة",searchLanguage:"اختر اللغة...",chooseCurrency:"اختر العملة",searchCurrency:"اختر العملة...",chooseTimezone:"اختر المنطقة الزمنية",searchTimezone:"اختر المنطقة الزمنية..."},push:{failedToSubscribe:"فشل في الاشتراك في الإشعارات الفورية",failedToUnsubscribe:"فشل في إلغاء الاشتراك من الإشعارات الفورية"},permissions:{title:"الصلاحيات",description:"قم بتكوين ما يمكن لكل دور القيام به في مساحة العمل هذه.",ownerOnly:"يمكن لمالك مساحة العمل فقط إدارة الصلاحيات.",save:"حفظ الصلاحيات",saving:"جارٍ الحفظ...",saveSuccess:"تم حفظ الصلاحيات بنجاح"},credits:{title:"الرصيد",description:"يمكن استخدام الرصيد للإجراءات المميزة مثل التوليد بالذكاء الاصطناعي.",balance:"رصيد الائتمان",available:"متاح",totalGranted:"إجمالي الممنوح",totalConsumed:"إجمالي المستهلك",totalExpired:"إجمالي المنتهي",noCredits:"لا يوجد رصيد بعد",noCreditsHint:"سيظهر الرصيد هنا عند منحه من خطتك أو شرائه.",buyCredits:"شراء رصيد",buyAmount:"Buy {count} Credits",purchasing:"جارٍ إعادة التوجيه...",packages:"حزم الرصيد",noPackages:"لا تتوفر حزم رصيد.",creditsAmount:"{count} رصيد",validityDays:"صالح لمدة {count} يوم",validityUnlimited:"بدون انتهاء صلاحية",transactions:"المعاملات الأخيرة",noTransactions:"لا توجد معاملات بعد.",loadMore:"Load More",viewAll:"عرض الكل",expiringSoon:"ينتهي قريباً",expiringInDays:"{count} رصيد ينتهي خلال {days} يوم",noExpiring:"لا يوجد رصيد ينتهي قريباً.",type:{plan_grant:"منحة الخطة",pack_purchased:"تم الشراء",consumed:"مستهلك",expired:"منتهي",admin_grant:"ممنوح",admin_revoke:"مسحوب",refund:"استرداد"},dialogTitle:"Buy Credit Packages",dialogDescription:"Choose a credit package to purchase.",dialogDescriptionWorkspace:"Purchase credits for {workspace}.",perCredit:"{price} per credit",purchaseSuccess:"تم شراء الرصيد بنجاح! تم تحديث رصيدك.",purchaseCanceled:"تم إلغاء شراء الرصيد. لم يتم تحصيل أي رسوم.",purchaseFailed:"فشل شراء الرصيد. يرجى المحاولة مرة أخرى أو التواصل مع الدعم.",errorLoading:"فشل في تحميل بيانات الرصيد",insufficientCredits:"رصيد غير كافٍ"},loading:{restoringSession:"جارٍ استعادة الجلسة...",redirecting:"جارٍ إعادة التوجيه...",signingIn:"جارٍ تسجيل الدخول...",verifyingAccount:"جارٍ التحقق من حسابك...",almostThere:"أوشكنا على الانتهاء..."},errors:{networkError:"خطأ في الشبكة: يرجى التحقق من اتصالك بالإنترنت",unauthorized:"غير مصرح - يرجى التحقق من جلستك",notFound:"المورد غير موجود",generic:"حدث خطأ",fetchPlans:"فشل في جلب الخطط",fetchPlanGroup:"فشل في جلب مجموعة الخطط",fetchPlanGroupVersion:"فشل في جلب إصدار مجموعة الخطط",fetchPlanGroupVersions:"فشل في جلب إصدارات مجموعة الخطط",fetchSubscription:"فشل في جلب الاشتراك",createCheckout:"فشل في إنشاء جلسة الدفع",updateSubscription:"فشل في تحديث الاشتراك",fetchInvoices:"فشل في جلب الفواتير",fetchInvoice:"فشل في جلب الفاتورة",openBillingPortal:"فشل في فتح بوابة الفوترة",cancelSubscription:"فشل في إلغاء الاشتراك",resumeSubscription:"فشل في استئناف الاشتراك",recordUsage:"فشل في تسجيل الاستخدام",fetchQuotaUsage:"فشل في جلب حالة استخدام الحصص",fetchAllQuotaUsage:"فشل في جلب جميع استخدامات الحصص",fetchUsageLogs:"فشل في جلب سجلات الاستخدام",fetchCreditBalance:"فشل في جلب رصيد الائتمان",consumeCredits:"فشل في استهلاك الرصيد",purchaseCredits:"فشل في شراء الرصيد",fetchCreditPackages:"فشل في جلب حزم الرصيد",fetchCreditTransactions:"فشل في جلب معاملات الرصيد",fetchExpiringCredits:"فشل في جلب الرصيد المنتهي قريباً"},security:{inactive:"غير نشط",inactiveHint:"سُجّل على نطاق تسجيل دخول سابق ولم يعد قابلاً للاستخدام. يمكنك إزالته.",passkeysTitle:"مفاتيح المرور",passkeysDescription:"تتيح مفاتيح المرور تسجيل الدخول ببصمة الإصبع أو الوجه أو رمز PIN للجهاز.",noPasskeys:"لا توجد مفاتيح مرور مسجلة",addHint:'لإضافة مفتاح مرور، اختر "إضافة مفتاح مرور" عند تسجيل الدخول التالي على الجهاز الذي تريد استخدامه.',rename:"إعادة تسمية",remove:"إزالة",removeTitle:"إزالة مفتاح المرور",removeDescription:"لن تتمكن من تسجيل الدخول بمفتاح المرور هذا بعد الآن.",renamePlaceholder:"اسم مفتاح المرور",lastUsed:"آخر استخدام",added:"أُضيف"}};export{e as ar};