@buildbase/sdk 0.0.50 → 0.0.51

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.
Files changed (49) hide show
  1. package/AGENTS.md +29 -11
  2. package/CHANGELOG.md +53 -0
  3. package/README.md +102 -18
  4. package/dist/css/styles.css +1 -1
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.ts +9 -0
  7. package/dist/index.mjs +1 -1
  8. package/dist/react/chunks/SettingsDialog-DitAiAqr.cjs +2 -0
  9. package/dist/react/chunks/SettingsDialog-uVKFxlal.mjs +2 -0
  10. package/dist/react/chunks/SubscriptionDialog-Cg-qYVKr.cjs +2 -0
  11. package/dist/react/chunks/SubscriptionDialog-P0GlXEyn.mjs +2 -0
  12. package/dist/react/chunks/ar-SrPOJXdL.mjs +2 -0
  13. package/dist/react/chunks/ar-a3aRbPCs.cjs +2 -0
  14. package/dist/react/chunks/de-DE3_z7r0.cjs +2 -0
  15. package/dist/react/chunks/de-xnPl61SS.mjs +2 -0
  16. package/dist/react/chunks/es-C_xcyGtp.cjs +2 -0
  17. package/dist/react/chunks/es-CyuBtosP.mjs +2 -0
  18. package/dist/react/chunks/fr-BMu7Bk4k.cjs +2 -0
  19. package/dist/react/chunks/fr-CxuDLZ27.mjs +2 -0
  20. package/dist/react/chunks/hi-CQ215yc9.cjs +2 -0
  21. package/dist/react/chunks/hi-CpuvyorS.mjs +2 -0
  22. package/dist/react/chunks/ja-DIJ_xCIi.mjs +2 -0
  23. package/dist/react/chunks/ja-DK6Buuws.cjs +2 -0
  24. package/dist/react/chunks/react-C2ikFWBG.cjs +2 -0
  25. package/dist/react/chunks/react-CCukNQ4q.mjs +2 -0
  26. package/dist/react/chunks/zh-CYQwZiBL.mjs +2 -0
  27. package/dist/react/chunks/zh-Dt-apS2s.cjs +2 -0
  28. package/dist/react/index.cjs +1 -1
  29. package/dist/react/index.d.ts +446 -62
  30. package/dist/react/index.mjs +1 -1
  31. package/package.json +7 -3
  32. package/dist/react/chunks/SubscriptionDialog-A6oETKbb.cjs +0 -2
  33. package/dist/react/chunks/SubscriptionDialog-nuMunBn4.mjs +0 -2
  34. package/dist/react/chunks/ar-BRvKHRYS.cjs +0 -2
  35. package/dist/react/chunks/ar-IhPhJAZA.mjs +0 -2
  36. package/dist/react/chunks/de-D3q0vQBG.cjs +0 -2
  37. package/dist/react/chunks/de-bvh5IFSx.mjs +0 -2
  38. package/dist/react/chunks/es-B9kiwJmF.cjs +0 -2
  39. package/dist/react/chunks/es-TyUz4_E1.mjs +0 -2
  40. package/dist/react/chunks/fr-C500Ytao.cjs +0 -2
  41. package/dist/react/chunks/fr-CKm-bSvG.mjs +0 -2
  42. package/dist/react/chunks/hi-CfFhH2uQ.cjs +0 -2
  43. package/dist/react/chunks/hi-Ck9cPpd-.mjs +0 -2
  44. package/dist/react/chunks/ja-AM4H1tXw.mjs +0 -2
  45. package/dist/react/chunks/ja-DfROrx_j.cjs +0 -2
  46. package/dist/react/chunks/react-CTX0_nOV.cjs +0 -2
  47. package/dist/react/chunks/react-DzQupoqH.mjs +0 -2
  48. package/dist/react/chunks/zh-CLmBh-it.cjs +0 -2
  49. package/dist/react/chunks/zh-DCVPxie-.mjs +0 -2
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});let e=!0;function t(t,...r){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...r)}async function r(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 s(e,t="Request failed"){if(!e.ok){let s=t;try{const t=await r(e);s=t.message||t.error||s}catch{s=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(s)}try{return await r(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,r,s){super(e),this.code=t,this.context=r,this.originalError=s,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,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,r={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const s=e instanceof Error?e:new n("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",r),o=s instanceof n?s:new n(s.message,"SDK_ERROR",r,s);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${r.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,r)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(o,r)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function 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,r){const s=(t.method??"GET").toUpperCase(),n=r??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 r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const s=new AbortController,n=e=>{s.signal.aborted||s.abort(e.reason)};for(const r of[e,t]){if(r.aborted){n(r);break}r.addEventListener("abort",()=>n(r),{once:!0})}return s.signal}(t.signal,e.signal):e.signal}const 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 r=this._fetch.bind(globalThis),n=await r(e,i);if(this._debug&&console.log(`[BuildBase] ${s} ${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: ${s} ${n}`);throw this.reportError(e,{method:s,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.reportError(e,{method:s,path:n}),e}};try{return await c(0)}finally{void 0!==a&&clearTimeout(a)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await s(n,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw new Error(r)}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return r.data||r}return r}}class g 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 w 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 y extends f{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class m 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 r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class k 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,r){return this.fetchJson(`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,r){return this.fetchJson(`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}})},"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 r=await this.fetchResponse(`workspaces/${e}/subscription/plan-group?groupVersionId=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch plan group version"),this.unwrapResponse(r,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(`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 r=await this.fetchResponse(`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create checkout session"),this.unwrapResponse(r,"Failed to create checkout session")}async selectFreePlan(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return r.ok||await this.throwResponseError(r,"Failed to select free plan"),r.json()}async updateSubscription(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to update subscription"),this.unwrapResponse(r,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,r){const s=new URLSearchParams;s.append("limit",t.toString()),r&&s.append("starting_after",r);const n=await this.fetchResponse(`workspaces/${e}/subscription/invoices?${s.toString()}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoices"),this.unwrapResponse(n,"Failed to fetch invoices")}async getInvoice(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/invoices/${t}`);return r.ok||await this.throwResponseError(r,"Failed to fetch invoice"),this.unwrapResponse(r,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(`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 r=await this.fetchResponse(`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record usage"),this.unwrapResponse(r,"Failed to record usage")}async recordUsageBatch(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record batch usage"),this.unwrapResponse(r,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const r=await this.fetchResponse(`workspaces/${e}/subscription/usage/status?quotaSlug=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch quota usage status"),this.unwrapResponse(r,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=`workspaces/${e}/subscription/usage/logs${s?`?${s}`:""}`,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,r,s){const n={event:t};return r&&(n.userId=r),s&&(n.data=s),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 r=await this.fetchResponse(`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t){const r=await this.fetchResponse(`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create credit purchase checkout"),this.unwrapResponse(r,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const r=await this.unwrapResponse(t,"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=`workspaces/${e}/credits/transactions${s?`?${s}`:""}`,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 r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=`workspaces/${e}/credits/buckets${s?`?${s}`:""}`,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 r=t?`?days=${t}`:"",s=await this.fetchResponse(`workspaces/${e}/credits/expiring${r}`);return s.ok||await this.throwResponseError(s,"Failed to fetch expiring credits"),this.unwrapResponse(s,"Failed to fetch expiring credits")}}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const b={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 S{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(b.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(b.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(b.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(b.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit(b.WorkspaceUserAdded,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit(b.WorkspaceUserRemoved,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,s){await this.emit(b.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:r,newRole:s})}async emitWorkspaceCreated(e){await this.emit(b.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(b.WorkspaceDeleted,{workspace:e})}}const v=new S;function E(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const R=E().invalidate,x=E().invalidate,$=E().invalidate,P="bb",C={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},U={Success:"success",Cancel:"cancel",Error:"error"},I={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function _(e,t){let r;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");r=new URL(e),r.search=""}catch{r=new URL("https://localhost")}return r.searchParams.set(P,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function A(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}}const F="saas-auth-intent";function T(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}const O={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:"฿"},W={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function N(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return O[t]??t.toUpperCase()}const B=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],J=B.map(e=>({value:e,label:`${e.toUpperCase()} (${N(e)})`}));function L(e,t){return N(t)+(e/100).toFixed(2)}const M={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};const D={included:"included",then:"then"};const q={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"};function V(e,t){const r=e.pricingVariants;if(!r?.length)return null;const s=t.toLowerCase();return r.find(e=>e.currency?.toLowerCase()===s)??null}function K(e,t,r){const s=V(e,t);if(!s?.basePricing)return null;const n=s.basePricing[r];return null!=n?n:null}function z(e,t,r,s){const n=V(e,t),o=n?.quotaOverages?.[r];if(o)return o[s]}function j(e,t){const r=V(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function G(e,t,r){const s=j(e,t);return s?.perSeat?s.perSeat[r]??null:null}function H(e,t){return Math.max(0,e-(t||0))}function Q(e,t,r,s){const n=j(e,t);if(!n)return null;return H(s,n.includedSeats)*(G(e,t,r)??0)}const Y={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"},Z=Object.values(Y),X={admin:Z.filter(e=>e!==Y.WORKSPACE_DELETE),member:[Y.WORKSPACE_SETTINGS_VIEW,Y.WORKSPACE_MEMBERS_VIEW,Y.WORKSPACE_FEATURES_VIEW,Y.WORKSPACE_BILLING_VIEW,Y.WORKSPACE_USAGE_VIEW],viewer:[Y.WORKSPACE_SETTINGS_VIEW,Y.WORKSPACE_MEMBERS_VIEW]};function ee(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function te(e){const{userId:t,workspace:r,settings:s,appPermissions:n}=e;if(!r||!t)return new Set;if(function(e,t){if(!t)return!1;const r=(s=e.createdBy)?"string"==typeof s?s:"object"==typeof s&&"_id"in s&&"string"==typeof s._id?s._id:null:null;var s;return null!==r&&r===t}(r,t)){const e=new Set(Z);if(n)for(const t of ee(n))e.add(t);if(r.permissions)for(const t of ee(r.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of ee(s.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 r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}(r,t);if(!o)return new Set;const i=r.permissions,a=s?.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=X[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=X[s?.workspace?.defaultRole??"member"]??X.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,r){if(!r?.workspace)return;const{canInviteMembers:s}=r.workspace;(!1===s||"admin-only"===s&&"admin"!==t)&&e.delete(Y.WORKSPACE_MEMBERS_INVITE)}(f,o,s),f}function re(e,t){const r=te(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}var se;exports.AuthStatus=void 0,(se=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",se.redirecting="redirecting",se.authenticated="authenticated",se.unauthenticated="unauthenticated",se.authenticating="authenticating";const ne=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]),oe=(e,t)=>e>>>t|e<<32-t;function ie(e){let t=1779033703,r=3144134277,s=1013904242,n=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 r=e+4*t;w[t]=p[r]<<24|p[r+1]<<16|p[r+2]<<8|p[r+3]}for(let e=16;e<64;e++){const t=oe(w[e-15],7)^oe(w[e-15],18)^w[e-15]>>>3,r=oe(w[e-2],17)^oe(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+r>>>0}let u=t,l=r,d=s,h=n,f=o,g=i,y=a,m=c;for(let e=0;e<64;e++){const t=m+(oe(f,6)^oe(f,11)^oe(f,25))+(f&g^~f&y)+ne[e]+w[e]>>>0,r=u&l^u&d^l&d;m=y,y=g,g=f,f=h+t>>>0,h=d,d=l,l=u,u=t+((oe(u,2)^oe(u,13)^oe(u,22))+r>>>0)>>>0}t=t+u>>>0,r=r+l>>>0,s=s+d>>>0,n=n+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,r,s,n,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 ae(e){return(new TextEncoder).encode(e)}function ce(e,t){let r=e;r.length>64&&(r=ie(r));const s=new Uint8Array(64),n=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<r.length?r[e]:0;s[e]=54^t,n[e]=92^t}const o=ie(le(s,t));return ie(le(n,o))}function ue(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e[s]^t[s];return 0===r}function le(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}function de(e){const{body:t,signature:r,timestamp:s,secret:n,maxAgeSeconds:o=300}=e;if(!(r&&s&&n&&t))return!1;const i="sha256=";if(!r.startsWith(i))return!1;const a=r.slice(7);if(o>0){const e=parseInt(s,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 r=0;r<t.length;r++){const s=parseInt(e.slice(2*r,2*r+2),16);if(Number.isNaN(s))return null;t[r]=s}return t}(a);if(!c)return!1;const u=ce(ae(n),ae(`${s}.${t}`));return c.length===u.length&&ue(c,u)}const pe=300,he="/.well-known/oauth-protected-resource",fe="/.well-known/agent-skills",ge="/.well-known/api-catalog",we="/.well-known/mcp/server-card.json",ye="application/json",me="text/markdown; charset=utf-8",ke="text/plain; charset=utf-8";function be(e){return e.replace(/\/+$/,"")}function Se(e){return`public, max-age=${e}, s-maxage=${e}`}function ve(e){return"sha256:"+function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(ie(ae(e)))}const Ee=new Map;async function Re(e){const t=e.cacheTtlSeconds??pe,r=`${be(e.serverUrl)}::${e.orgId}`,s=Ee.get(r);if(s&&s.expiresAt>Date.now())return s.value;const n=e.fetch??fetch,o=`${be(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const e=await n(o,{headers:{Accept:ye}});if(e.ok){const t=await e.json();t&&"object"==typeof t&&(i=t)}}catch{}return Ee.set(r,{value:i,expiresAt:Date.now()+1e3*t}),i}function xe(e,t){const r=be(e.siteUrl),s={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:he};t.authorizationServer?.metadataUrl&&(s.oauth_authorization_server=t.authorizationServer.metadataUrl),(t.authorizationServer||e.authMd)&&(s.auth="/auth.md"),e.skills?.length&&(s.agent_skills=`${fe}/index.json`),e.apiCatalog?.length&&(s.api_catalog=ge),e.mcpServerCard&&(s.mcp_server_card=we);return Fe({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:r,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:r},capabilities:s,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function $e(e,t,r){const s=r.protectedResources??[];if(!s.length)return null;const n=e.replace(/\/+$/,"")||he,o=s.find(e=>function(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const r="/"===t?"":t.replace(/\/+$/,"");return he+r}(e.resource)===n);return o?Fe(o.metadata,t):n===he&&1===s.length?Fe(s[0].metadata,t):null}function Pe(e){const t=e.skills??[];if(!t.length)return null;const r=be(e.siteUrl);return Fe({$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:`${r}${Ce(e)}`,digest:ve(e.content)}))},e)}function Ce(e){return e.path??`${fe}/${e.name}/SKILL.md`}function Ue(e,t){const r=(t.skills??[]).find(t=>Ce(t)===e);return r?{status:200,contentType:"text/markdown; charset=utf-8",body:r.content,cacheControl:Se(t.cacheTtlSeconds??pe)}:null}function Ie(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:ke,body:t.join("\n")+"\n",cacheControl:Se(e.cacheTtlSeconds??pe)}}function _e(e){const t=e.apiCatalog??[];if(!t.length)return null;const r=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:r},null,2),cacheControl:Se(e.cacheTtlSeconds??pe)}}function Ae(e){const t=e.mcpServerCard;return t?Fe({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 Fe(e,t){return{status:200,contentType:ye,body:JSON.stringify(e,null,2),cacheControl:Se(t.cacheTtlSeconds??pe)}}class Te extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function Oe(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4==0?"":"=".repeat(4-t.length%4),s=atob(t+r),n=new Uint8Array(s.length);for(let e=0;e<s.length;e++)n[e]=s.charCodeAt(e);return n}function We(e){return JSON.parse((new TextDecoder).decode(Oe(e)))}function Ne(e,t,r=60){if(!e||!t)throw new Te("invalid_token","Missing token or client secret");const s=e.split(".");if(3!==s.length)throw new Te("invalid_token","Malformed JWT");const[n,o,i]=s,a=ce(ae(t),ae(`${n}.${o}`));let c,u,l;try{c=Oe(i)}catch{throw new Te("invalid_signature","Unreadable JWT signature")}if(!ue(a,c))throw new Te("invalid_signature","JWT signature verification failed");try{u=We(n),l=We(o)}catch{throw new Te("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new Te("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const d=Math.floor(Date.now()/1e3);if("number"==typeof l.exp&&d>l.exp+r)throw new Te("token_expired","JWT has expired");if("number"==typeof l.nbf&&d+r<l.nbf)throw new Te("token_not_yet_valid","JWT is not yet valid");return l}function Be(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function Je(e){const t=Be(e.authorization);if(!t)throw new Te("invalid_token","Missing Bearer token");return Ne(t,e.clientSecret,e.clockToleranceSec)}function Le(e){const t=Be(e.authorization);if(!t)throw new Te("invalid_token","Missing Bearer token");return Ne(t,e.clientSecret,e.clockToleranceSec)}function Me(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function De(e){return{success:!1,token:"",message:e}}function qe(e){const{serverUrl:t,orgId:r,version:s="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(!r)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:s,orgId:r,sessionId:e,...d};return{workspace:new k(n),user:new m(n),settings:new y(n),push:new w(n)}},h=new k({serverUrl:t,version:s,orgId:r,...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,r)=>(await e()).workspace.updateWorkspace(t,r),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,r,s)=>(await e()).workspace.addUser(t,{email:r,role:s}),remove:async(t,r)=>(await e()).workspace.removeUser(t,r),updateRole:async(t,r,s)=>(await e()).workspace.updateUser(t,r,{role:s}),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,r)=>(await e()).workspace.createCheckoutSession(t,r),update:async(t,r)=>(await e()).workspace.updateSubscription(t,r),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,r)=>(await e()).workspace.createBillingPortalSession(t,r)},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,r,s)=>(await e()).workspace.listInvoices(t,r,s),get:async(t,r)=>(await e()).workspace.getInvoice(t,r)},usage:{record:async(t,r)=>(await e()).workspace.recordUsage(t,r),recordBatch:async(t,r)=>(await e()).workspace.recordUsageBatch(t,r),getQuota:async(t,r)=>(await e()).workspace.getQuotaUsageStatus(t,r),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,r)=>(await e()).workspace.getUsageLogs(t,r)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,r,s)=>(await e()).workspace.updateFeature(t,r,s)},notification:{send:async(t,r,s,n)=>(await e()).workspace.sendNotification(t,r,s,n)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,r)=>(await e()).workspace.consumeCredits(t,r),purchase:async(t,r)=>(await e()).workspace.purchaseCredits(t,r),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,r)=>(await e()).workspace.getCreditTransactions(t,r),getBuckets:async(t,r)=>(await e()).workspace.getCreditBuckets(t,r),getExpiring:async(t,r)=>(await e()).workspace.getExpiringCredits(t,r),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,r,s)=>{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)===r);return re(s,{userId:r,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,r)=>{const s=await e(),[n,o,i]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return te({userId:r,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}}exports.AppBridgeError=Te,exports.AuthApi=class extends f{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,r=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return r.ok||await this.throwResponseError(r,"Failed to initiate authentication"),r.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}},exports.BBAction=C,exports.BBScreen=I,exports.BBStatus=U,exports.BB_PARAM=P,exports.BaseApi=f,exports.BetaForm=class{constructor(e){this.api=new g(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},r=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),s=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),n=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),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:r,language:s,timezone:n,currency:o}})}},exports.BillingIntervals=q,exports.BuildBase=qe,exports.CURRENCY_DISPLAY=O,exports.CURRENCY_FLAG=W,exports.CreditBucketSource={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},exports.CreditBucketStatus={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},exports.CreditTransactionType={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"},exports.DEFAULT_ROLE_PERMISSIONS=X,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EventEmitter=S,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.PLAN_CURRENCY_CODES=B,exports.PLAN_CURRENCY_OPTIONS=J,exports.PUSH_SERVICE_WORKER_SCRIPT="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n try {\n const payload = event.data.json();\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n",exports.Permission=Y,exports.PushApi=w,exports.SDKEvent=b,exports.SettingsApi=y,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},exports.UserApi=m,exports.WorkspaceApi=k,exports.appTokenFailure=De,exports.appTokenSuccess=Me,exports.bearerChallenge=function(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"})}},exports.buildAgentCard=xe,exports.buildAgentSkillsIndex=Pe,exports.buildApiCatalog=_e,exports.buildAuthMd=function(e,t){const r=Se(e.cacheTtlSeconds??pe);if(e.authMd)return{status:200,contentType:me,body:e.authMd,cacheControl:r};const s=t.authorizationServer;if(!s)return null;const n=(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: \`${s.issuer}\`\n- Metadata (RFC 8414): ${s.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${n||"- 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:me,body:i,cacheControl:r}},exports.buildLlmsTxt=function(e,t){return t.llmsTxt?{status:200,contentType:ke,body:t.llmsTxt,cacheControl:Se(e.cacheTtlSeconds??pe)}:null},exports.buildMcpServerCard=Ae,exports.buildProtectedResourceMetadata=$e,exports.buildSecurityTxt=Ie,exports.buildSkillMd=Ue,exports.calculateBillableSeats=H,exports.calculateSeatOverageCents=Q,exports.calculateTotalSubscriptionCents=function(e,t,r,s){const n=K(e,t,r);return null===n?null:void 0===s?n:n+(Q(e,t,r,s)??0)},exports.cleanBBParams=function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(P)&&(e.searchParams.delete(P),window.history.replaceState({},"",e.toString()))}catch{}},exports.clearAgentReadinessCache=function(){Ee.clear()},exports.clearAuthIntent=function(){c(F)},exports.consumeAuthIntent=function(){const e=function(e,t){const r=a(e);if(!r)return null;try{const s=JSON.parse(r);return t&&!t(s)?(i(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):s}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(F,T);return c(F),e?Date.now()-e.createdAt>6e5?null:A(e.returnUrl):null},exports.createBBUrl=_,exports.createCheckoutRedirectUrls=function(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:_({action:C.Checkout,status:U.Success,ws:e,screen:I.Subscription},r),cancelUrl:_({action:C.Checkout,status:U.Cancel,ws:e,screen:I.Subscription},r)}},exports.createCreditPurchaseRedirectUrls=function(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:_({action:C.CreditPurchase,status:U.Success,ws:e,screen:I.Credits},r),cancelUrl:_({action:C.CreditPurchase,status:U.Cancel,ws:e,screen:I.Credits},r)}},exports.default=qe,exports.eventEmitter=v,exports.extractBearerToken=Be,exports.fetchAgentReadiness=Re,exports.formatCents=L,exports.formatOverageRate=function(e,t,r,s){if(null==e||e<0)return null;const n={...M,...s},o=null!=t&&t>=1?t:1,i=N(r),a=(e/100).toFixed(2);return 1===o?`${i}${a}/${n.unit}`:`${i}${a}/${o.toLocaleString()} ${n.units}`},exports.formatOverageRateWithLabel=function(e,t,r,s,n,o){if(null==e||e<0)return null;const i={...M,...o},a=null!=t&&t>=1?t:1,c=N(s),u=(e/100).toFixed(2);if(r){const e=n??(r.endsWith("s")?r:`${r}s`);return a>=2?`${c}${u}/${a.toLocaleString()} ${e}`:`${c}${u}/${r}`}return 1===a?`${c}${u}/${i.unit}`:`${c}${u}/${a.toLocaleString()} ${i.units}`},exports.formatQuotaIncludedOverage=function(e,t,r,s,n,o,i,a){const c={...M,...i};if(!1===a)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=o??(r.endsWith("s")?r:`${r}s`),l=null!=n&&n>=2?`${n.toLocaleString()} ${u}`:r;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${L(t,s)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${L(t,s)}/${l}`:"—"},exports.formatQuotaWithPrice=function(e,t,r={}){const{overageInCents:s=!0,currency:n}=r,o=r.labels??D,i=r.currencySymbol??N(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=s?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}`},exports.getAvailableCurrenciesFromPlans=function(e){const t=new Set;for(const r of e)r.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()},exports.getBasePriceCents=K,exports.getBillingIntervalAndCurrencyFromPriceId=function(e,t){if(!e)return null;for(const r of t){const t=r.pricingVariants;if(t?.length)for(const r of t){const t=r.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:r.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:r.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:r.currency}}}}return null},exports.getCurrencyFlag=function(e){return e&&e.trim()?W[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=N,exports.getDisplayCurrency=function(e,t){const r=V(e,t);return r?r.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=G,exports.getPricingVariant=V,exports.getQuotaDisplayValue=function(e,t){if(null==e)return null;const r=e[t??"monthly"];return r?{included:r.included,...void 0!==r.overage&&{overage:r.overage},...void 0!==r.unitSize&&{unitSize:r.unitSize},allowOverage:!1!==e.allowOverage}:null},exports.getQuotaDisplayWithVariant=function(e,t,r,s){const n=e.quotas?.[r];if(null==n)return null;const o=n[s];if(!o)return null;const i=z(e,t,r,s);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==n.allowOverage}},exports.getQuotaOverageCents=z,exports.getQuotaUnitLabelFromName=function(e,t="unit"){const r=(e||"").trim().toLowerCase();if(!r)return t;const s=r.split(/\s+/)[0]??r;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(s)?s:s.endsWith("ies")&&s.length>3?s.slice(0,-3)+"y":s.endsWith("ses")||s.endsWith("xes")||s.endsWith("zes")||s.endsWith("ches")||s.endsWith("shes")?s.slice(0,-2):s.endsWith("s")&&!s.endsWith("ss")&&s.length>1?s.slice(0,-1):s||t},exports.getSeatPricing=j,exports.getStripePriceIdForInterval=function(e,t,r){const s=V(e,t);if(!s?.stripePrices)return null;const n=r===q.Monthly?"monthlyPriceId":r===q.Yearly?"yearlyPriceId":"quarterlyPriceId",o=r===q.Monthly?"monthly":r===q.Yearly?"yearly":void 0;return s.stripePrices[n]??(o?s.stripePrices[o]:void 0)??null},exports.handleAppRevokeRequest=async function(e){let t;try{t=Le(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof Te?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}},exports.handleAppTokenRequest=async function(e){let t;try{t=Je(e)}catch(e){return{status:401,body:De(e instanceof Te?e.code:"invalid_token")}}return{status:200,body:Me(await e.mintToken(t))}},exports.hasPermission=re,exports.invalidateCreditBalance=R,exports.invalidateQuotaUsage=x,exports.invalidateSubscription=$,exports.parseWebhookEvent=function(e){if(!de(e))return null;try{return JSON.parse(e.body)}catch{return null}},exports.provideWebMcpTools=function(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)},exports.readBBParams=function(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(P);if(!e)return null;const t=function(e){const t={};if(!e)return t;const r=e.split(",");for(const e of r){const r=e.indexOf(":");if(-1===r)continue;const s=decodeURIComponent(e.slice(0,r)),n=decodeURIComponent(e.slice(r+1));s&&(t[s]=n)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}},exports.resolveMaxUsers=function(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:s}=e;if(t){const e=j(t,r);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=s&&s>0?{maxUsers:s,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}},exports.resolvePermissions=te,exports.resolveWellKnown=async function(e,t){const r=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===r){return xe(t,await Re(t))}if("/.well-known/security.txt"===r)return Ie(t);if(r===`${fe}/index.json`)return Pe(t);if(r.startsWith(`${fe}/`)&&r.endsWith("SKILL.md"))return Ue(r,t);if("/.well-known/oauth-authorization-server"===r){const e=await Re(t),r=e.authorizationServer?.metadataUrl;return r?Fe({...e.authorizationServer?.issuer?{issuer:e.authorizationServer.issuer}:{},oauth_authorization_server_metadata:r},t):null}if(r===ge)return _e(t);if(r===we)return Ae(t);if(r.startsWith(he)){return $e(r,t,await Re(t))}return null},exports.safeRedirect=function(e,t="/"){if("undefined"==typeof window||!window.location)return!1;const r=A(e);return window.location.href=r??t,!0},exports.saveAuthIntent=function(e){A(e)&&u(F,{returnUrl:e,createdAt:Date.now()})},exports.sha256Digest=ve,exports.validateInvite=function(e){const{memberCount:t,maxUsersConfig:r,hasSubscription:s=!0,requireSubscription:n=!1}=e;if(n&&!s)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:o,source:i}=r;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}},exports.validateRedirectUrl=A,exports.verifyAppRevokeRequest=Le,exports.verifyAppTokenRequest=Je,exports.verifyClientJwt=Ne,exports.verifyWebhookSignature=de;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});let e=!0;function t(t,...r){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...r)}async function r(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 s(e,t="Request failed"){if(!e.ok){let s=t;try{const t=await r(e);s=t.message||t.error||s}catch{s=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(s)}try{return await r(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,r,s){super(e),this.code=t,this.context=r,this.originalError=s,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,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,r={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const s=e instanceof Error?e:new n("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",r),o=s instanceof n?s:new n(s.message,"SDK_ERROR",r,s);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${r.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,r)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(o,r)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function 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 p(){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 d=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=p(),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){d.has(e)||(d.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}async executeFetchUrl(e,t,r){const s=(t.method??"GET").toUpperCase(),n=r??e,o=this.buildHeaders(t),i={...t,headers:o};let a,c;if(this._timeout>0){c=new AbortController;const e=c;a=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const s=new AbortController,n=e=>{s.signal.aborted||s.abort(e.reason)};for(const r of[e,t]){if(r.aborted){n(r);break}r.addEventListener("abort",()=>n(r),{once:!0})}return s.signal}(t.signal,e.signal):e.signal}const u=async r=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const t=this._fetch.bind(globalThis),n=await t(e,i);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&r<this._maxRetries){const e=Math.min(1e3*Math.pow(2,r),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${r+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),u(r+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(c?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${n}`);throw this.reportError(e,{method:s,path:n}),e}throw e}if(r<this._maxRetries){const e=Math.min(1e3*Math.pow(2,r),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${r+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),u(r+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:n}),e}};try{return await u(0)}finally{void 0!==a&&clearTimeout(a)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await s(n,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw new Error(r)}apiPath(e,...t){return e.reduce((e,r,s)=>e+r+(s<t.length?encodeURIComponent(String(t[s])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class g 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 w 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 y extends f{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class m 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 r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class k 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(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`);return t.ok||await this.throwResponseError(t,"Failed to fetch subscription"),this.unwrapResponse(t,"Failed to fetch subscription")}async getPlanGroup(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group"),this.unwrapResponse(t,"Failed to fetch plan group")}async getPlanGroupByVersion(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch plan group version"),this.unwrapResponse(r,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group/versions`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group versions"),this.unwrapResponse(t,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plans"),this.unwrapResponse(t,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(this.apiPath`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const t=await this.fetchResponse(this.apiPath`plan-group-versions/${e}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async createCheckoutSession(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create checkout session"),this.unwrapResponse(r,"Failed to create checkout session")}async selectFreePlan(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return r.ok||await this.throwResponseError(r,"Failed to select free plan"),r.json()}async updateSubscription(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to update subscription"),this.unwrapResponse(r,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,r){const s=new URLSearchParams;s.append("limit",t.toString()),r&&s.append("starting_after",r);const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoices"),this.unwrapResponse(n,"Failed to fetch invoices")}async getInvoice(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices/${t}`);return r.ok||await this.throwResponseError(r,"Failed to fetch invoice"),this.unwrapResponse(r,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to cancel subscription"),this.unwrapResponse(t,"Failed to cancel subscription")}async resumeSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to resume subscription"),this.unwrapResponse(t,"Failed to resume subscription")}async recordUsage(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record usage"),this.unwrapResponse(r,"Failed to record usage")}async recordUsageBatch(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record batch usage"),this.unwrapResponse(r,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch quota usage status"),this.unwrapResponse(r,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:""),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,r,s){const n={event:t};return r&&(n.userId=r),s&&(n.data=s),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(n)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create credit purchase checkout"),this.unwrapResponse(r,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const r=await this.unwrapResponse(t,"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:""),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 r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:""),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 r=t?`?days=${t}`:"",s=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/expiring`+r);return s.ok||await this.throwResponseError(s,"Failed to fetch expiring credits"),this.unwrapResponse(s,"Failed to fetch expiring credits")}}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const b={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 S{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(b.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(b.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(b.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(b.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,r){await this.emit(b.WorkspaceUserAdded,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRemoved(e,t,r){await this.emit(b.WorkspaceUserRemoved,{userId:e,workspace:t,role:r})}async emitWorkspaceUserRoleChanged(e,t,r,s){await this.emit(b.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:r,newRole:s})}async emitWorkspaceCreated(e){await this.emit(b.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(b.WorkspaceDeleted,{workspace:e})}}const v=new S;function E(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const P=E().invalidate,R=E().invalidate,x=E().invalidate,$="bb",C={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},U={Success:"success",Cancel:"cancel",Error:"error"},I={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function _(e,t){let r;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");r=new URL(e),r.search=""}catch{r=new URL("https://localhost")}return r.searchParams.set($,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function A(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}}const F="saas-auth-intent";function T(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}const O={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:"฿"},W={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function N(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return O[t]??t.toUpperCase()}const B=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],J=B.map(e=>({value:e,label:`${e.toUpperCase()} (${N(e)})`}));function L(e,t){return N(t)+(e/100).toFixed(2)}const M={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};const D={included:"included",then:"then"};const q={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"};function V(e,t){const r=e.pricingVariants;if(!r?.length)return null;const s=t.toLowerCase();return r.find(e=>e.currency?.toLowerCase()===s)??null}function K(e,t,r){const s=V(e,t);if(!s?.basePricing)return null;const n=s.basePricing[r];return null!=n?n:null}function z(e,t,r,s){const n=V(e,t),o=n?.quotaOverages?.[r];if(o)return o[s]}function j(e,t){const r=V(e,t);return r?.seatPricing?.enabled?r.seatPricing:null}function G(e,t,r){const s=j(e,t);return s?.perSeat?s.perSeat[r]??null:null}function H(e,t){return Math.max(0,e-(t||0))}function Q(e,t,r,s){const n=j(e,t);if(!n)return null;return H(s,n.includedSeats)*(G(e,t,r)??0)}const Y={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"},Z=Object.values(Y),X={admin:Z.filter(e=>e!==Y.WORKSPACE_DELETE),member:[Y.WORKSPACE_SETTINGS_VIEW,Y.WORKSPACE_MEMBERS_VIEW,Y.WORKSPACE_FEATURES_VIEW,Y.WORKSPACE_BILLING_VIEW,Y.WORKSPACE_USAGE_VIEW],viewer:[Y.WORKSPACE_SETTINGS_VIEW,Y.WORKSPACE_MEMBERS_VIEW]};function ee(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function te(e){const{userId:t,workspace:r,settings:s,appPermissions:n}=e;if(!r||!t)return new Set;if(function(e,t){if(!t)return!1;const r=(s=e.createdBy)?"string"==typeof s?s:"object"==typeof s&&"_id"in s&&"string"==typeof s._id?s._id:null:null;var s;return null!==r&&r===t}(r,t)){const e=new Set(Z);if(n)for(const t of ee(n))e.add(t);if(r.permissions)for(const t of ee(r.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of ee(s.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 r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}(r,t);if(!o)return new Set;const i=r.permissions,a=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=i?.[o]?c(i[o]):[],p=a?.[o]?c(a[o]):[],d=X[o]??[];let h;if(l.length>0)h=l;else if(p.length>0)h=p;else if(d.length>0)h=d;else{h=X[s?.workspace?.defaultRole??"member"]??X.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,r){if(!r?.workspace)return;const{canInviteMembers:s}=r.workspace;(!1===s||"admin-only"===s&&"admin"!==t)&&e.delete(Y.WORKSPACE_MEMBERS_INVITE)}(f,o,s),f}function re(e,t){const r=te(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}var se;exports.AuthStatus=void 0,(se=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",se.redirecting="redirecting",se.authenticated="authenticated",se.unauthenticated="unauthenticated",se.authenticating="authenticating";const ne=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]),oe=(e,t)=>e>>>t|e<<32-t;function ie(e){let t=1779033703,r=3144134277,s=1013904242,n=2773480762,o=1359893119,i=2600822924,a=528734635,c=1541459225;const u=e.length,l=u+1,p=l+(56-l%64+64)%64+8,d=new Uint8Array(p);d.set(e,0),d[u]=128;const h=8*u,f=Math.floor(h/4294967296),g=h>>>0;d[p-8]=f>>>24&255,d[p-7]=f>>>16&255,d[p-6]=f>>>8&255,d[p-5]=255&f,d[p-4]=g>>>24&255,d[p-3]=g>>>16&255,d[p-2]=g>>>8&255,d[p-1]=255&g;const w=new Uint32Array(64);for(let e=0;e<p;e+=64){for(let t=0;t<16;t++){const r=e+4*t;w[t]=d[r]<<24|d[r+1]<<16|d[r+2]<<8|d[r+3]}for(let e=16;e<64;e++){const t=oe(w[e-15],7)^oe(w[e-15],18)^w[e-15]>>>3,r=oe(w[e-2],17)^oe(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+r>>>0}let u=t,l=r,p=s,h=n,f=o,g=i,y=a,m=c;for(let e=0;e<64;e++){const t=m+(oe(f,6)^oe(f,11)^oe(f,25))+(f&g^~f&y)+ne[e]+w[e]>>>0,r=u&l^u&p^l&p;m=y,y=g,g=f,f=h+t>>>0,h=p,p=l,l=u,u=t+((oe(u,2)^oe(u,13)^oe(u,22))+r>>>0)>>>0}t=t+u>>>0,r=r+l>>>0,s=s+p>>>0,n=n+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,r,s,n,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 ae(e){return(new TextEncoder).encode(e)}function ce(e,t){let r=e;r.length>64&&(r=ie(r));const s=new Uint8Array(64),n=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<r.length?r[e]:0;s[e]=54^t,n[e]=92^t}const o=ie(le(s,t));return ie(le(n,o))}function ue(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e[s]^t[s];return 0===r}function le(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}function pe(e){const{body:t,signature:r,timestamp:s,secret:n,maxAgeSeconds:o=300}=e;if(!(r&&s&&n&&t))return!1;const i="sha256=";if(!r.startsWith(i))return!1;const a=r.slice(7);if(o>0){const e=parseInt(s,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 r=0;r<t.length;r++){const s=parseInt(e.slice(2*r,2*r+2),16);if(Number.isNaN(s))return null;t[r]=s}return t}(a);if(!c)return!1;const u=ce(ae(n),ae(`${s}.${t}`));return c.length===u.length&&ue(c,u)}const de=300,he="/.well-known/oauth-protected-resource",fe="/.well-known/agent-skills",ge="/.well-known/api-catalog",we="/.well-known/mcp/server-card.json",ye="application/json",me="text/markdown; charset=utf-8",ke="text/plain; charset=utf-8";function be(e){return e.replace(/\/+$/,"")}function Se(e){return`public, max-age=${e}, s-maxage=${e}`}function ve(e){return"sha256:"+function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(ie(ae(e)))}const Ee=new Map;async function Pe(e){const t=e.cacheTtlSeconds??de,r=`${be(e.serverUrl)}::${e.orgId}`,s=Ee.get(r);if(s&&s.expiresAt>Date.now())return s.value;const n=e.fetch??fetch,o=`${be(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const e=await n(o,{headers:{Accept:ye}});if(e.ok){const t=await e.json();t&&"object"==typeof t&&(i=t)}}catch{}return Ee.set(r,{value:i,expiresAt:Date.now()+1e3*t}),i}function Re(e,t){const r=be(e.siteUrl),s={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:he};t.authorizationServer?.metadataUrl&&(s.oauth_authorization_server=t.authorizationServer.metadataUrl),(t.authorizationServer||e.authMd)&&(s.auth="/auth.md"),e.skills?.length&&(s.agent_skills=`${fe}/index.json`),e.apiCatalog?.length&&(s.api_catalog=ge),e.mcpServerCard&&(s.mcp_server_card=we);return Fe({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:r,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:r},capabilities:s,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function xe(e,t,r){const s=r.protectedResources??[];if(!s.length)return null;const n=e.replace(/\/+$/,"")||he,o=s.find(e=>function(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const r="/"===t?"":t.replace(/\/+$/,"");return he+r}(e.resource)===n);return o?Fe(o.metadata,t):n===he&&1===s.length?Fe(s[0].metadata,t):null}function $e(e){const t=e.skills??[];if(!t.length)return null;const r=be(e.siteUrl);return Fe({$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:`${r}${Ce(e)}`,digest:ve(e.content)}))},e)}function Ce(e){return e.path??`${fe}/${e.name}/SKILL.md`}function Ue(e,t){const r=(t.skills??[]).find(t=>Ce(t)===e);return r?{status:200,contentType:"text/markdown; charset=utf-8",body:r.content,cacheControl:Se(t.cacheTtlSeconds??de)}:null}function Ie(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:ke,body:t.join("\n")+"\n",cacheControl:Se(e.cacheTtlSeconds??de)}}function _e(e){const t=e.apiCatalog??[];if(!t.length)return null;const r=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:r},null,2),cacheControl:Se(e.cacheTtlSeconds??de)}}function Ae(e){const t=e.mcpServerCard;return t?Fe({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 Fe(e,t){return{status:200,contentType:ye,body:JSON.stringify(e,null,2),cacheControl:Se(t.cacheTtlSeconds??de)}}class Te extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function Oe(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4==0?"":"=".repeat(4-t.length%4),s=atob(t+r),n=new Uint8Array(s.length);for(let e=0;e<s.length;e++)n[e]=s.charCodeAt(e);return n}function We(e){return JSON.parse((new TextDecoder).decode(Oe(e)))}function Ne(e,t,r=60){if(!e||!t)throw new Te("invalid_token","Missing token or client secret");const s=e.split(".");if(3!==s.length)throw new Te("invalid_token","Malformed JWT");const[n,o,i]=s,a=ce(ae(t),ae(`${n}.${o}`));let c,u,l;try{c=Oe(i)}catch{throw new Te("invalid_signature","Unreadable JWT signature")}if(!ue(a,c))throw new Te("invalid_signature","JWT signature verification failed");try{u=We(n),l=We(o)}catch{throw new Te("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new Te("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const p=Math.floor(Date.now()/1e3);if("number"==typeof l.exp&&p>l.exp+r)throw new Te("token_expired","JWT has expired");if("number"==typeof l.nbf&&p+r<l.nbf)throw new Te("token_not_yet_valid","JWT is not yet valid");return l}function Be(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function Je(e){const t=Be(e.authorization);if(!t)throw new Te("invalid_token","Missing Bearer token");return Ne(t,e.clientSecret,e.clockToleranceSec)}function Le(e){const t=Be(e.authorization);if(!t)throw new Te("invalid_token","Missing Bearer token");return Ne(t,e.clientSecret,e.clockToleranceSec)}function Me(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function De(e){return{success:!1,token:"",message:e}}function qe(e){const{serverUrl:t,orgId:r,version:s="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(!r)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},d=e=>{const n={serverUrl:t,version:s,orgId:r,sessionId:e,...p};return{workspace:new k(n),user:new m(n),settings:new y(n),push:new w(n)}},h=new k({serverUrl:t,version:s,orgId:r,...p}),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,r)=>(await e()).workspace.updateWorkspace(t,r),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,r,s)=>(await e()).workspace.addUser(t,{email:r,role:s}),remove:async(t,r)=>(await e()).workspace.removeUser(t,r),updateRole:async(t,r,s)=>(await e()).workspace.updateUser(t,r,{role:s}),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,r)=>(await e()).workspace.createCheckoutSession(t,r),update:async(t,r)=>(await e()).workspace.updateSubscription(t,r),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,r)=>(await e()).workspace.createBillingPortalSession(t,r)},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,r,s)=>(await e()).workspace.listInvoices(t,r,s),get:async(t,r)=>(await e()).workspace.getInvoice(t,r)},usage:{record:async(t,r)=>(await e()).workspace.recordUsage(t,r),recordBatch:async(t,r)=>(await e()).workspace.recordUsageBatch(t,r),getQuota:async(t,r)=>(await e()).workspace.getQuotaUsageStatus(t,r),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,r)=>(await e()).workspace.getUsageLogs(t,r)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,r,s)=>(await e()).workspace.updateFeature(t,r,s)},notification:{send:async(t,r,s,n)=>(await e()).workspace.sendNotification(t,r,s,n)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,r)=>(await e()).workspace.consumeCredits(t,r),purchase:async(t,r)=>(await e()).workspace.purchaseCredits(t,r),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,r)=>(await e()).workspace.getCreditTransactions(t,r),getBuckets:async(t,r)=>(await e()).workspace.getCreditBuckets(t,r),getExpiring:async(t,r)=>(await e()).workspace.getExpiringCredits(t,r),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,r,s)=>{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)===r);return re(s,{userId:r,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,r)=>{const s=await e(),[n,o,i]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return te({userId:r,workspaceRole:a?.role??null,workspace:n,settings:o})}}}),g=f(async()=>d(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=d(e);return f(async()=>t)},client:{forSession:d},...g}}exports.AppBridgeError=Te,exports.AuthApi=class extends f{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,r=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return r.ok||await this.throwResponseError(r,"Failed to initiate authentication"),r.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}},exports.BBAction=C,exports.BBScreen=I,exports.BBStatus=U,exports.BB_PARAM=$,exports.BaseApi=f,exports.BetaForm=class{constructor(e){this.api=new g(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},r=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),s=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),n=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),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:r,language:s,timezone:n,currency:o}})}},exports.BillingIntervals=q,exports.BuildBase=qe,exports.CURRENCY_DISPLAY=O,exports.CURRENCY_FLAG=W,exports.CreditBucketSource={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},exports.CreditBucketStatus={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},exports.CreditTransactionType={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"},exports.DEFAULT_ROLE_PERMISSIONS=X,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EventEmitter=S,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.PLAN_CURRENCY_CODES=B,exports.PLAN_CURRENCY_OPTIONS=J,exports.PUSH_SERVICE_WORKER_SCRIPT="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n try {\n const payload = event.data.json();\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n",exports.Permission=Y,exports.PushApi=w,exports.SDKEvent=b,exports.SettingsApi=y,exports.SubscriptionItemType={Feature:"feature",Limit:"limit",Quota:"quota"},exports.SubscriptionStatus={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},exports.UserApi=m,exports.WorkspaceApi=k,exports.appTokenFailure=De,exports.appTokenSuccess=Me,exports.bearerChallenge=function(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"})}},exports.buildAgentCard=Re,exports.buildAgentSkillsIndex=$e,exports.buildApiCatalog=_e,exports.buildAuthMd=function(e,t){const r=Se(e.cacheTtlSeconds??de);if(e.authMd)return{status:200,contentType:me,body:e.authMd,cacheControl:r};const s=t.authorizationServer;if(!s)return null;const n=(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: \`${s.issuer}\`\n- Metadata (RFC 8414): ${s.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${n||"- 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:me,body:i,cacheControl:r}},exports.buildLlmsTxt=function(e,t){return t.llmsTxt?{status:200,contentType:ke,body:t.llmsTxt,cacheControl:Se(e.cacheTtlSeconds??de)}:null},exports.buildMcpServerCard=Ae,exports.buildProtectedResourceMetadata=xe,exports.buildSecurityTxt=Ie,exports.buildSkillMd=Ue,exports.calculateBillableSeats=H,exports.calculateSeatOverageCents=Q,exports.calculateTotalSubscriptionCents=function(e,t,r,s){const n=K(e,t,r);return null===n?null:void 0===s?n:n+(Q(e,t,r,s)??0)},exports.cleanBBParams=function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has($)&&(e.searchParams.delete($),window.history.replaceState({},"",e.toString()))}catch{}},exports.clearAgentReadinessCache=function(){Ee.clear()},exports.clearAuthIntent=function(){c(F)},exports.consumeAuthIntent=function(){const e=function(e,t){const r=a(e);if(!r)return null;try{const s=JSON.parse(r);return t&&!t(s)?(i(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):s}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(F,T);return c(F),e?Date.now()-e.createdAt>6e5?null:A(e.returnUrl):null},exports.createBBUrl=_,exports.createCheckoutRedirectUrls=function(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:_({action:C.Checkout,status:U.Success,ws:e,screen:I.Subscription},r),cancelUrl:_({action:C.Checkout,status:U.Cancel,ws:e,screen:I.Subscription},r)}},exports.createCreditPurchaseRedirectUrls=function(e,t){const r=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:_({action:C.CreditPurchase,status:U.Success,ws:e,screen:I.Credits},r),cancelUrl:_({action:C.CreditPurchase,status:U.Cancel,ws:e,screen:I.Credits},r)}},exports.default=qe,exports.eventEmitter=v,exports.extractBearerToken=Be,exports.fetchAgentReadiness=Pe,exports.formatCents=L,exports.formatOverageRate=function(e,t,r,s){if(null==e||e<0)return null;const n={...M,...s},o=null!=t&&t>=1?t:1,i=N(r),a=(e/100).toFixed(2);return 1===o?`${i}${a}/${n.unit}`:`${i}${a}/${o.toLocaleString()} ${n.units}`},exports.formatOverageRateWithLabel=function(e,t,r,s,n,o){if(null==e||e<0)return null;const i={...M,...o},a=null!=t&&t>=1?t:1,c=N(s),u=(e/100).toFixed(2);if(r){const e=n??(r.endsWith("s")?r:`${r}s`);return a>=2?`${c}${u}/${a.toLocaleString()} ${e}`:`${c}${u}/${r}`}return 1===a?`${c}${u}/${i.unit}`:`${c}${u}/${a.toLocaleString()} ${i.units}`},exports.formatQuotaIncludedOverage=function(e,t,r,s,n,o,i,a){const c={...M,...i};if(!1===a)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=o??(r.endsWith("s")?r:`${r}s`),l=null!=n&&n>=2?`${n.toLocaleString()} ${u}`:r;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${L(t,s)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${L(t,s)}/${l}`:"—"},exports.formatQuotaWithPrice=function(e,t,r={}){const{overageInCents:s=!0,currency:n}=r,o=r.labels??D,i=r.currencySymbol??N(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=s?c/100:c,p="number"==typeof l&&Number.isFinite(l)?l.toFixed(2):String(c),d=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${o.then} ${i}${p}${d}`},exports.getAvailableCurrenciesFromPlans=function(e){const t=new Set;for(const r of e)r.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()},exports.getBasePriceCents=K,exports.getBillingIntervalAndCurrencyFromPriceId=function(e,t){if(!e)return null;for(const r of t){const t=r.pricingVariants;if(t?.length)for(const r of t){const t=r.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:r.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:r.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:r.currency}}}}return null},exports.getCurrencyFlag=function(e){return e&&e.trim()?W[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=N,exports.getDisplayCurrency=function(e,t){const r=V(e,t);return r?r.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=G,exports.getPricingVariant=V,exports.getQuotaDisplayValue=function(e,t){if(null==e)return null;const r=e[t??"monthly"];return r?{included:r.included,...void 0!==r.overage&&{overage:r.overage},...void 0!==r.unitSize&&{unitSize:r.unitSize},allowOverage:!1!==e.allowOverage}:null},exports.getQuotaDisplayWithVariant=function(e,t,r,s){const n=e.quotas?.[r];if(null==n)return null;const o=n[s];if(!o)return null;const i=z(e,t,r,s);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==n.allowOverage}},exports.getQuotaOverageCents=z,exports.getQuotaUnitLabelFromName=function(e,t="unit"){const r=(e||"").trim().toLowerCase();if(!r)return t;const s=r.split(/\s+/)[0]??r;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(s)?s:s.endsWith("ies")&&s.length>3?s.slice(0,-3)+"y":s.endsWith("ses")||s.endsWith("xes")||s.endsWith("zes")||s.endsWith("ches")||s.endsWith("shes")?s.slice(0,-2):s.endsWith("s")&&!s.endsWith("ss")&&s.length>1?s.slice(0,-1):s||t},exports.getSeatPricing=j,exports.getStripePriceIdForInterval=function(e,t,r){const s=V(e,t);if(!s?.stripePrices)return null;const n=r===q.Monthly?"monthlyPriceId":r===q.Yearly?"yearlyPriceId":"quarterlyPriceId",o=r===q.Monthly?"monthly":r===q.Yearly?"yearly":void 0;return s.stripePrices[n]??(o?s.stripePrices[o]:void 0)??null},exports.handleAppRevokeRequest=async function(e){let t;try{t=Le(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof Te?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}},exports.handleAppTokenRequest=async function(e){let t;try{t=Je(e)}catch(e){return{status:401,body:De(e instanceof Te?e.code:"invalid_token")}}return{status:200,body:Me(await e.mintToken(t))}},exports.hasPermission=re,exports.invalidateCreditBalance=P,exports.invalidateQuotaUsage=R,exports.invalidateSubscription=x,exports.parseWebhookEvent=function(e){if(!pe(e))return null;try{return JSON.parse(e.body)}catch{return null}},exports.provideWebMcpTools=function(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)},exports.readBBParams=function(){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 r=e.split(",");for(const e of r){const r=e.indexOf(":");if(-1===r)continue;const s=decodeURIComponent(e.slice(0,r)),n=decodeURIComponent(e.slice(r+1));s&&(t[s]=n)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}},exports.resolveMaxUsers=function(e){const{planVersion:t,currency:r="usd",settingsMaxUsers:s}=e;if(t){const e=j(t,r);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=s&&s>0?{maxUsers:s,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}},exports.resolvePermissions=te,exports.resolveWellKnown=async function(e,t){const r=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===r){return Re(t,await Pe(t))}if("/.well-known/security.txt"===r)return Ie(t);if(r===`${fe}/index.json`)return $e(t);if(r.startsWith(`${fe}/`)&&r.endsWith("SKILL.md"))return Ue(r,t);if("/.well-known/oauth-authorization-server"===r){const e=await Pe(t),r=e.authorizationServer?.metadataUrl;return r?Fe({...e.authorizationServer?.issuer?{issuer:e.authorizationServer.issuer}:{},oauth_authorization_server_metadata:r},t):null}if(r===ge)return _e(t);if(r===we)return Ae(t);if(r.startsWith(he)){return xe(r,t,await Pe(t))}return null},exports.safeRedirect=function(e,t="/"){if("undefined"==typeof window||!window.location)return!1;const r=A(e);return window.location.href=r??t,!0},exports.saveAuthIntent=function(e){A(e)&&u(F,{returnUrl:e,createdAt:Date.now()})},exports.sha256Digest=ve,exports.validateInvite=function(e){const{memberCount:t,maxUsersConfig:r,hasSubscription:s=!0,requireSubscription:n=!1}=e;if(n&&!s)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:o,source:i}=r;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}},exports.validateRedirectUrl=A,exports.verifyAppRevokeRequest=Le,exports.verifyAppTokenRequest=Je,exports.verifyClientJwt=Ne,exports.verifyWebhookSignature=pe;
package/dist/index.d.ts CHANGED
@@ -1139,6 +1139,15 @@ declare abstract class BaseApi {
1139
1139
  * Tries to parse JSON error body; falls back to status-based message.
1140
1140
  */
1141
1141
  protected throwResponseError(response: Response, defaultMsg: string): Promise<never>;
1142
+ /**
1143
+ * Tagged template that URI-encodes interpolated path segments, so IDs
1144
+ * containing `/ ? # ..` can't retarget the request path.
1145
+ * Use for PATH segments only — never for pre-built query strings.
1146
+ *
1147
+ * @example
1148
+ * this.apiPath`workspaces/${workspaceId}/users/${userId}`
1149
+ */
1150
+ protected apiPath(strings: TemplateStringsArray, ...values: Array<string | number>): string;
1142
1151
  /**
1143
1152
  * Parse JSON and unwrap `{ success, data }` envelope if present.
1144
1153
  * Throws if `success` is explicitly `false`.