@buildbase/sdk 0.0.55 → 0.0.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +92 -5
- package/dist/css/styles.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +178 -0
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -1
- package/dist/mcp/index.d.ts +106 -0
- package/dist/mcp/index.mjs +1 -1
- package/dist/react/chunks/SettingsDialog-CGFO1AGh.mjs +2 -0
- package/dist/react/chunks/SettingsDialog-DhxNGiZI.cjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-Csy020_n.mjs +2 -0
- package/dist/react/chunks/{SubscriptionDialog-CfDLoOzW.cjs → SubscriptionDialog-DQjHsKth.cjs} +1 -1
- package/dist/react/chunks/ar-CGbuXEeR.cjs +2 -0
- package/dist/react/chunks/ar-DnShbYvQ.mjs +2 -0
- package/dist/react/chunks/de-C3iuiLAz.mjs +2 -0
- package/dist/react/chunks/{de-X9mfnMFM.mjs → de-a1mX2rR4.cjs} +1 -1
- package/dist/react/chunks/es-D4T7YE7x.cjs +2 -0
- package/dist/react/chunks/es-u9vKMeaX.mjs +2 -0
- package/dist/react/chunks/fr-Bnnz2yJZ.cjs +2 -0
- package/dist/react/chunks/fr-DjgpP202.mjs +2 -0
- package/dist/react/chunks/hi-B8Mjr8rU.cjs +2 -0
- package/dist/react/chunks/hi-Cu_9iCjb.mjs +2 -0
- package/dist/react/chunks/{ja-4hLI6wMX.cjs → ja-B0eCVKdZ.cjs} +1 -1
- package/dist/react/chunks/{ja-CIGOj3vV.mjs → ja-DfJ5WUrG.mjs} +1 -1
- package/dist/react/chunks/react-B0kptNqP.cjs +2 -0
- package/dist/react/chunks/react-VshTnwaW.mjs +2 -0
- package/dist/react/chunks/zh-BnPZ0j4w.cjs +2 -0
- package/dist/react/chunks/zh-JjoMmHmK.mjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +289 -15
- package/dist/react/index.mjs +1 -1
- package/docs/MCP-AND-AGENT-READINESS.md +1 -3
- package/package.json +1 -1
- package/dist/react/chunks/SettingsDialog-B6DhyNae.cjs +0 -2
- package/dist/react/chunks/SettingsDialog-K38BI74F.mjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-BidcQ_vc.mjs +0 -2
- package/dist/react/chunks/ar-CCKONfUU.mjs +0 -2
- package/dist/react/chunks/ar-DrHMtT1E.cjs +0 -2
- package/dist/react/chunks/de-Dhtorn10.cjs +0 -2
- package/dist/react/chunks/es--8iZ7Trv.mjs +0 -2
- package/dist/react/chunks/es-CUR7LB6a.cjs +0 -2
- package/dist/react/chunks/fr-BqMs_F5g.cjs +0 -2
- package/dist/react/chunks/fr-rUp34NG7.mjs +0 -2
- package/dist/react/chunks/hi-B_IiucJZ.mjs +0 -2
- package/dist/react/chunks/hi-C2i1_hdv.cjs +0 -2
- package/dist/react/chunks/react-BXTDLnE8.cjs +0 -2
- package/dist/react/chunks/react-CXCk05WI.mjs +0 -2
- package/dist/react/chunks/zh-BSgd6ai5.cjs +0 -2
- package/dist/react/chunks/zh-DyVvcYFC.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,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}async function n(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function r(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await n(e);r=t.message||t.error||r}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw new Error(r)}try{return await n(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class s extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,s)}}const i=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,n={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new s("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",n),i=r instanceof s?r:new s(r.message,"SDK_ERROR",n,r);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${n.component||"Unknown"}:`,{message:i.message,code:i.code,context:i.context,originalError:i.originalError,stack:i.stack}),this.config.onError)try{this.config.onError(i,n)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(i,n)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function o(e,t={}){i.handleError(e,t)}function a(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return o(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){o(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){o(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){o(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 o(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}const p=new WeakSet,h=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),f="SDK is not ready (missing serverUrl, version, or orgId)";class g{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(f);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(f)}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)}static delay(e,t){return new Promise((n,r)=>{const s=()=>{clearTimeout(i),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const i=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,n){const r=(t.method??"GET").toUpperCase(),s=n??e,i=this.buildHeaders(t),o={...t,headers:i},a=h.has(r);let c,u;if(this._timeout>0){u=new AbortController;const e=u;c=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?function(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,s=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){s(n);break}n.addEventListener("abort",()=>s(n),{once:!0})}return r.signal}(t.signal,e.signal):e.signal}const l=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${r} ${s}`);return this.reportError(e,{method:r,path:s}),e}return e},d=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),s=await n(e,o);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&a&&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 g.delay(e,o.signal),d(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await g.delay(e,o.signal)}catch(e){throw l(e)}return d(t+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:s}),e}};try{return await d(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await r(s,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw new Error(n)}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class y extends g{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 m extends g{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 w extends g{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class b extends g{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}class k extends g{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,n){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const s=new URLSearchParams;return s.append("limit",t.toString()),n&&s.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,s){const i={event:t};return n&&(i.userId=n),r&&(i.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(i),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const S={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 v{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){o(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(S.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(S.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(S.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(S.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(S.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(S.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(S.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(S.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(S.WorkspaceDeleted,{workspace:e})}}const x=new v;function U(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const $=U().invalidate,P=U().invalidate,E=U().invalidate,C="bb",A={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},I={Success:"success",Cancel:"cancel",Error:"error"},_={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function T(e,t){const n=t??("undefined"!=typeof window?window.location.href:"https://localhost");let r;try{r=new URL(n)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(n)}`)}return r.search="",r.searchParams.set(C,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function R(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let n;try{n=new URL(e)}catch{return null}const r="https:"===n.protocol,s="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!s)return null;const{sameOrigin:i,allowedOrigins:o}=t;return i||o?.length?i&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||o?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}const O="saas-auth-intent";function W(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}const F={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:"฿"},N={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function B(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return F[t]??t.toUpperCase()}const J=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],L=J.map(e=>({value:e,label:`${e.toUpperCase()} (${B(e)})`})),M=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),D=new Set(["bhd","jod","kwd","omr","tnd"]),j=new Map;function q(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(M.has(t))return 0;if(D.has(t))return 3;if("isk"===t)return 2;let n=j.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}j.set(t,n)}return n}function V(e,t){const n=q(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function z(e,t){return B(t)+V(e,t)}const K={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const G={included:"included",then:"then",hardLimit:"hard limit"};const H={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"};function Q(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function Y(e,t,n){const r=Q(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function Z(e,t,n,r){const s=Q(e,t),i=s?.quotaOverages?.[n];if(i)return i[r]}function X(e,t){const n=Q(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function ee(e,t,n){const r=X(e,t);return r?.perSeat?r.perSeat[n]??null:null}function te(e,t){return Math.max(0,e-(t||0))}function ne(e,t,n,r){const s=X(e,t);if(!s)return null;return te(r,s.includedSeats)*(ee(e,t,n)??0)}const re={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"},se=Object.values(re),ie={admin:se.filter(e=>e!==re.WORKSPACE_DELETE),member:[re.WORKSPACE_SETTINGS_VIEW,re.WORKSPACE_MEMBERS_VIEW,re.WORKSPACE_FEATURES_VIEW,re.WORKSPACE_BILLING_VIEW,re.WORKSPACE_USAGE_VIEW],viewer:[re.WORKSPACE_SETTINGS_VIEW,re.WORKSPACE_MEMBERS_VIEW]};function oe(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function ae(e){const{userId:t,workspace:n,settings:r,appPermissions:s}=e;if(!n||!t)return new Set;if(function(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}(n,t)){const e=new Set(se);if(s)for(const t of oe(s))e.add(t);if(n.permissions)for(const t of oe(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of oe(r.workspace.permissions))e.add(t);return e}const i=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);if(!i)return new Set;const o=n.permissions,a=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!o&&i in o,d=!!a&&i in a,p=i in ie;let h;if(l)h=c(o[i]);else if(d)h=c(a[i]);else if(p)h=ie[i];else{const e=r?.workspace?.defaultRole;h=e&&e in ie?ie[e]:[]}const f=new Set(h),g=l?u(o[i]):[],y=s?.[i]?u(s[i]):[],m=l?g:y;for(const e of m)f.add(e);return function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(re.WORKSPACE_MEMBERS_INVITE)}(f,i,r),f}function ce(e,t){const n=ae(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}var ue;exports.AuthStatus=void 0,(ue=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",ue.redirecting="redirecting",ue.authenticated="authenticated",ue.unauthenticated="unauthenticated",ue.authenticating="authenticating";const le=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]),de=(e,t)=>e>>>t|e<<32-t;function pe(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,o=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 y=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;y[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=de(y[e-15],7)^de(y[e-15],18)^y[e-15]>>>3,n=de(y[e-2],17)^de(y[e-2],19)^y[e-2]>>>10;y[e]=y[e-16]+t+y[e-7]+n>>>0}let u=t,l=n,d=r,h=s,f=i,g=o,m=a,w=c;for(let e=0;e<64;e++){const t=w+(de(f,6)^de(f,11)^de(f,25))+(f&g^~f&m)+le[e]+y[e]>>>0,n=u&l^u&d^l&d;w=m,m=g,g=f,f=h+t>>>0,h=d,d=l,l=u,u=t+((de(u,2)^de(u,13)^de(u,22))+n>>>0)>>>0}t=t+u>>>0,n=n+l>>>0,r=r+d>>>0,s=s+h>>>0,i=i+f>>>0,o=o+g>>>0,a=a+m>>>0,c=c+w>>>0}const m=new Uint8Array(32),w=[t,n,r,s,i,o,a,c];for(let e=0;e<8;e++)m[4*e]=w[e]>>>24&255,m[4*e+1]=w[e]>>>16&255,m[4*e+2]=w[e]>>>8&255,m[4*e+3]=255&w[e];return m}function he(e){return(new TextEncoder).encode(e)}function fe(e,t){let n=e;n.length>64&&(n=pe(n));const r=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,s[e]=92^t}const i=pe(ye(r,t));return pe(ye(s,i))}function ge(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}function ye(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function me(e){const{body:t,signature:n,timestamp:r,secret:s,maxAgeSeconds:i=300}=e;if(!(n&&r&&s&&t))return!1;const o="sha256=";if(!n.startsWith(o))return!1;const a=n.slice(7);if(i>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>i)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(a);if(!c)return!1;const u=fe(he(s),he(`${r}.${t}`));return c.length===u.length&&ge(c,u)}const we=300,be="/.well-known/oauth-protected-resource",ke="/.well-known/agent-skills",Se="/.well-known/api-catalog",ve="/.well-known/mcp/server-card.json",xe="/.well-known/agent-card.json",Ue="application/json",$e="application/linkset+json",Pe="text/markdown; charset=utf-8",Ee="text/plain; charset=utf-8",Ce="application/xml; charset=utf-8",Ae=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function Ie(e){return e.replace(/\/+$/,"")}function _e(e){return`public, max-age=${e}, s-maxage=${e}`}function Te(e){return"sha256:"+function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(pe(he(e)))}const Re=new Map;async function Oe(e,t,n,r){if(!r||r<=0)return e(t,n);const s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await e(t,{...n,signal:s.signal})}finally{clearTimeout(i)}}async function We(e){const t=e.cacheTtlSeconds??we,n=`${Ie(e.serverUrl)}::${e.orgId}`,r=Re.get(n);if(r&&r.expiresAt>Date.now())return r.value;const s=e.fetch??fetch,i=`${Ie(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let o={enabled:!1};try{const t=await Oe(s,i,{headers:{Accept:Ue}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(o=e)}}catch{}return Re.set(n,{value:o,expiresAt:Date.now()+1e3*t}),o}const Fe=new Map;function Ne(e,t){const n=Ie(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:be};t.authorizationServer?.metadataUrl&&(r.oauth_authorization_server=t.authorizationServer.metadataUrl,r.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(r.auth="/auth.md"),e.skills?.length&&(r.agent_skills=`${ke}/index.json`),e.apiCatalog?.length&&(r.api_catalog=Se),e.mcpServerCard&&(r.mcp_server_card=ve),!1!==e.a2aCard&&(r.a2a_agent_card=xe),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return et({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:n,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:n},capabilities:r,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function Be(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return be+n}function Je(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||be,i=n??`${Ie(t.serverUrl)}/org/${t.orgId}`,o=t.scopes?.map(e=>e.name),a=r.map(e=>{const n=e.resource??Ie(t.siteUrl),r=e.scopes??o;return{path:Be(n),metadata:{resource:n,authorization_servers:[i],bearer_methods_supported:e.bearerMethods??["header"],...r?.length?{scopes_supported:r}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=a.find(e=>e.path===s);return c?et(c.metadata,t):s===be&&1===a.length?et(a[0].metadata,t):null}function Le(e){const t=e.skills??[];if(!t.length)return null;const n=Ie(e.siteUrl);return et({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${n}${Me(e)}`,digest:Te(e.content)}))},e)}function Me(e){return e.path??`${ke}/${e.name}/SKILL.md`}function De(e,t){const n=(t.skills??[]).find(t=>Me(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:_e(t.cacheTtlSeconds??we)}:null}function je(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:Ee,body:t.join("\n")+"\n",cacheControl:_e(e.cacheTtlSeconds??we)}}function qe(e){return e.llmsTxt?{status:200,contentType:Ee,body:e.llmsTxt,cacheControl:_e(e.cacheTtlSeconds??we)}:null}function Ve(e){return e.llmsFullTxt?{status:200,contentType:Ee,body:e.llmsFullTxt,cacheControl:_e(e.cacheTtlSeconds??we)}:null}function ze(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=Ie(e.siteUrl),r=t.serviceUrl??n,s=t.transportProtocol??"http",i=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return et({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:r,preferredTransport:s,supportedInterfaces:[{serviceUrl:r,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:n},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:i,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}function Ke(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:_e(e.cacheTtlSeconds??we)}:null}function Ge(e){return e.endsWith(".json")||e.includes(".well-known/")?Ue:e.endsWith(".md")?Pe:e.endsWith(".xml")?Ce:Ee}function He(e){const t=e.apiCatalog??[];if(!t.length)return null;const n=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:$e,body:JSON.stringify({linkset:n},null,2),cacheControl:_e(e.cacheTtlSeconds??we)}}function Qe(e){const t=e??{tools:!0},n={tools:!1,resources:!1,prompts:!1};for(const[e,r]of Object.entries(t))n[e]=!1!==r&&null!=r;return n}function Ye(e){const t=e.mcpServerCard;return t?et({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:Qe(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function Ze(e){const t=e.mcpServerCard;if(!t)return null;const n=Ie(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${Be(t.endpoint)}`}}catch{}return et({$schema:"https://modelcontextprotocol.io/schemas/mcp-discovery/v1.0",version:"1.0",servers:[{name:t.name,...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},version:t.version,capabilities:Qe(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${ve}`,...r?{authentication:r}:{}}]},e)}function Xe(e,t){const n=_e(e.cacheTtlSeconds??we);if(e.authMd)return{status:200,contentType:Pe,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const s=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${r.issuer}\`\n- Metadata (RFC 8414): ${r.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, supported grant types / PKCE methods, and — when the app allows it — the dynamic client \`registration_endpoint\` (RFC 7591).\n\n## Protected resources (RFC 9728)\nSee \`/.well-known/oauth-protected-resource\`, which lists the resource, its supported scopes, and the authorization server(s) that can issue tokens for it.\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. Register a client (dynamic registration) or use a pre-issued client_id.\n4. Run the authorization-code flow with PKCE (S256), requesting the scopes and target \`resource\`.\n5. 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:Pe,body:s,cacheControl:n}}function et(e,t){return{status:200,contentType:Ue,body:JSON.stringify(e,null,2),cacheControl:_e(t.cacheTtlSeconds??we)}}function tt(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function nt(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${tt(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&n.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])n.push(`Allow: ${tt(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${tt(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${tt(e.crawlDelay)}`),n.join("\n")}function rt(e){const t=e.robots??{},n=Ie(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",i="allow"===s?[{userAgent:[...Ae],allow:["/"]}]:"deny"===s?[{userAgent:[...Ae],disallow:["/"]}]:s,o=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...r.map((e,n)=>nt(e,0===n?t.contentSignals:void 0)),...i.map(e=>nt(e)),...o.length?[o.map(e=>`Sitemap: ${tt(e)}`).join("\n")]:[]];return{status:200,contentType:Ee,body:a.join("\n\n")+"\n",cacheControl:_e(e.cacheTtlSeconds??we)}}function st(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function it(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ot(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=Ie(e.siteUrl),r='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${it(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${it(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${it(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${st(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:Ce,body:r,cacheControl:_e(e.cacheTtlSeconds??we)}}function at(e){if(!e)return!1;let t=0,n=0;for(const r of e.split(",")){const[e,...s]=r.trim().split(";"),i=e.trim().toLowerCase();let o=1;for(const e of s){const[t,n]=e.split("=").map(e=>e.trim());if("q"===t){const e=Number(n);Number.isNaN(e)||(o=e)}}"text/markdown"===i||"text/x-markdown"===i?t=Math.max(t,o):"text/html"!==i&&"text/*"!==i&&"*/*"!==i||(n=Math.max(n,o))}return t>0&&t>=n}async function ct(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return Ne(t,await We(t))}if(n===xe)return ze(t);if("/.well-known/http-message-signatures-directory"===n)return Ke(t);if("/.well-known/security.txt"===n)return je(t);if(n===`${ke}/index.json`)return Le(t);if(n.startsWith(`${ke}/`)&&n.endsWith("SKILL.md"))return De(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await We(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??we,r=Fe.get(e);if(r&&r.expiresAt>Date.now())return r.value;const s=t.fetch??fetch;let i=null;try{const n=await Oe(s,e,{headers:{Accept:Ue}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(i=e)}}catch{}return Fe.set(e,{value:i,expiresAt:Date.now()+1e3*n}),i}(e.metadataUrl,t);return et(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===Se)return He(t);if(n===ve)return Ye(t);if("/.well-known/mcp.json"===n)return Ze(t);if(n.startsWith(be)){const e=await We(t);return Je(n,t,e.authorizationServer?.issuer)}return null}function ut(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function lt(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+n),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}class dt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function pt(e){const t=JSON.parse((new TextDecoder).decode(lt(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function ht(e,t,n={}){const r=n.clockToleranceSec??60,s=n.requireExp??!0;if(!e||!t)throw new dt("invalid_token","Missing token or client secret");const i=e.split(".");if(3!==i.length)throw new dt("invalid_token","Malformed JWT");const[o,a,c]=i;let u,l;try{u=pt(o),l=pt(a)}catch{throw new dt("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new dt("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const d=fe(he(t),he(`${o}.${a}`));let p;try{p=lt(c)}catch{throw new dt("invalid_signature","Unreadable JWT signature")}if(!ge(d,p))throw new dt("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new dt("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const n=e[t];if(void 0!==n&&("number"!=typeof n||!Number.isFinite(n)))throw new dt("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new dt("invalid_token","JWT aud claim must be a string or string array")}(l);const h=Math.floor(Date.now()/1e3);if(s&&"number"!=typeof l.exp)throw new dt("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof l.exp&&h>l.exp+r)throw new dt("token_expired","JWT has expired");if("number"==typeof l.nbf&&h+r<l.nbf)throw new dt("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&l.iss!==n.issuer)throw new dt("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=l.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new dt("invalid_audience","JWT audience mismatch")}return l}function ft(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function gt(e){return ut(he(JSON.stringify(e)))}function yt(e,t,n){if(!t)throw new dt("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),s={iat:r,exp:r+(n?.expiresInSec??3600),...e},i=`${gt({alg:"HS256",typ:"JWT"})}.${gt(s)}`;return`${i}.${ut(fe(he(t),he(i)))}`}function mt(e){const t=ft(e.authorization);if(!t)throw new dt("invalid_token","Missing Bearer token");return ht(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function wt(e){const t=ft(e.authorization);if(!t)throw new dt("invalid_token","Missing Bearer token");return ht(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function bt(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function kt(e){return{success:!1,token:"",message:e}}function St(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}const vt=12,xt=16;function Ut(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("WebCrypto is unavailable in this runtime — agent-auth session encryption requires globalThis.crypto.subtle (Node 18+, Bun, Deno, edge, browsers).");return e.subtle}const $t=new Map;function Pt(e){let t=$t.get(e);return t||(t=(async()=>{const t=await Ut().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return Ut().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),$t.set(e,t)),t}function Et(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(vt)),r=await Pt(e),s=new Uint8Array(await Ut().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),i=s.subarray(s.length-xt),o=s.subarray(0,s.length-xt),a=new Uint8Array(28+o.length);return a.set(n,0),a.set(i,vt),a.set(o,28),ut(a)},async decryptSessionRef(t){try{const n=lt(t);if(n.length<=28)return null;const r=n.slice(0,vt),s=n.subarray(vt,28),i=n.subarray(28),o=new Uint8Array(i.length+xt);o.set(i,0),o.set(s,i.length);const a=await Pt(e),c=await Ut().decrypt({name:"AES-GCM",iv:r},a,o);return(new TextDecoder).decode(c)}catch{return null}}}}function Ct(e,t,n){const r=globalThis.process?.env;"1"===r?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${n}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function At(e){const{serverUrl:t,orgId:n,version:r="v1",getSessionId:s,timeout:i,maxRetries:o,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const d={...void 0!==i&&{timeout:i},...void 0!==o&&{maxRetries:o},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},p=e=>{const s={serverUrl:t,version:r,orgId:n,sessionId:e,...d};return{workspace:new k(s),user:new b(s),settings:new w(s),push:new m(s)}},h=new k({serverUrl:t,version:r,orgId:n,...d}),f=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,r)=>(await e()).workspace.addUser(t,{email:n,role:r}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,r)=>(await e()).workspace.updateUser(t,n,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,n)=>(await e()).workspace.createCheckoutSession(t,n),update:async(t,n)=>(await e()).workspace.updateSubscription(t,n),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,n)=>(await e()).workspace.createBillingPortalSession(t,n)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,n,r)=>(await e()).workspace.listInvoices(t,n,r),get:async(t,n)=>(await e()).workspace.getInvoice(t,n)},usage:{record:async(t,n)=>(await e()).workspace.recordUsage(t,n),recordBatch:async(t,n)=>(await e()).workspace.recordUsageBatch(t,n),getQuota:async(t,n)=>(await e()).workspace.getQuotaUsageStatus(t,n),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,n)=>(await e()).workspace.getUsageLogs(t,n)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,n,r)=>(await e()).workspace.updateFeature(t,n,r)},notification:{send:async(t,n,r,s)=>(await e()).workspace.sendNotification(t,n,r,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,n)=>(await e()).workspace.consumeCredits(t,n),purchase:async(t,n)=>(await e()).workspace.purchaseCredits(t,n),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,n)=>(await e()).workspace.getCreditTransactions(t,n),getBuckets:async(t,n)=>(await e()).workspace.getCreditBuckets(t,n),getExpiring:async(t,n)=>(await e()).workspace.getExpiringCredits(t,n),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,n,r)=>{const s=await e(),[i,o,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return ce(r,{userId:n,workspaceRole:c?.role??null,workspace:i,settings:o})},resolve:async(t,n)=>{const r=await e(),[s,i,o]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),a=o.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return ae({userId:n,workspaceRole:a?.role??null,workspace:s,settings:i})}}}),g=f(async()=>p(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=p(e);return f(async()=>t)},client:{forSession:p},...g}}exports.AI_BOT_USER_AGENTS=Ae,exports.AppBridgeError=dt,exports.AuthApi=class extends g{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}},exports.BBAction=A,exports.BBScreen=_,exports.BBStatus=I,exports.BB_PARAM=C,exports.BaseApi=g,exports.BetaForm=class{constructor(e){this.api=new y(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),s=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),i=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:s,currency:i}})}},exports.BillingIntervals=H,exports.BuildBase=At,exports.CURRENCY_DISPLAY=F,exports.CURRENCY_FLAG=N,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=ie,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EventEmitter=v,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.PLAN_CURRENCY_CODES=J,exports.PLAN_CURRENCY_OPTIONS=L,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 // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n 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=re,exports.PushApi=m,exports.SDKEvent=S,exports.SettingsApi=w,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=b,exports.WorkspaceApi=k,exports.appTokenFailure=kt,exports.appTokenSuccess=bt,exports.bearerChallenge=function(e){const t=[`Bearer resource_metadata="${St(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${St(e.error)}"`),e.errorDescription&&t.push(`error_description="${St(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}},exports.buildA2AAgentCard=ze,exports.buildAgentCard=Ne,exports.buildAgentSkillsIndex=Le,exports.buildApiCatalog=He,exports.buildAuthMd=Xe,exports.buildDiscoveryLinkHeader=function(e){const t=Ie(e.siteUrl),n=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&n.push(`<${t}${xe}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const r=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;n.push(`<${r}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&n.push(`<${t}${Se}>; rel="api-catalog"; type="${$e}"`),e.mcpServerCard&&n.push(`<${t}${ve}>; rel="mcp-server"; type="application/json"`),n.join(", ")},exports.buildDnsAidRecords=function(e){let t;try{t=new URL(e.siteUrl).hostname}catch{return[]}const n=[{name:`_index._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}];if(!1!==e.a2aCard&&n.push({name:`_a2a._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}),e.mcpServerCard){let r=t;try{r=new URL(e.mcpServerCard.endpoint).hostname}catch{}n.push({name:`_mcp._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${r}. alpn="h2" port=443`})}return n},exports.buildLlmsFullTxt=Ve,exports.buildLlmsTxt=qe,exports.buildMcpDiscoveryManifest=Ze,exports.buildMcpServerCard=Ye,exports.buildProtectedResourceMetadata=Je,exports.buildRobotsTxt=rt,exports.buildSecurityTxt=je,exports.buildSitemap=ot,exports.buildSkillMd=De,exports.buildWebBotAuthDirectory=Ke,exports.buildbaseAuth=function(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=Et(t),r=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&r.length)try{const e=new URL(r[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let i;try{i=ht(s,t,{...e.verify})}catch{return null}if(r.length){const t=i.aud?Array.isArray(i.aud)?i.aud:[i.aud]:[];if(!t.length&&e.requireAudience)return Ct(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return Ct(t,r,"aud does not include this resource"),null}const o="string"==typeof i.sid?await n.decryptSessionRef(i.sid):null,a=Array.isArray(i.scope)?i.scope.filter(e=>"string"==typeof e):"string"==typeof i.scope?i.scope.split(" ").filter(Boolean):void 0;return{sessionId:o??"",userId:"string"==typeof i.userId?i.userId:"string"==typeof i.sub?i.sub:void 0,workspaceId:"string"==typeof i.workspaceId?i.workspaceId:void 0,scopes:a,claims:i}}}},exports.calculateBillableSeats=te,exports.calculateSeatOverageCents=ne,exports.calculateTotalSubscriptionCents=function(e,t,n,r){const s=Y(e,t,n);return null===s?null:void 0===r?s:s+(ne(e,t,n,r)??0)},exports.cleanBBParams=function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(C)&&(e.searchParams.delete(C),window.history.replaceState({},"",e.toString()))}catch{}},exports.clearAgentReadinessCache=function(){Re.clear(),Fe.clear()},exports.clearAuthIntent=function(){c(O)},exports.consumeAuthIntent=function(){const e=function(e,t){const n=a(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(o(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):r}catch(t){return o(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(O,W);return c(O),e?Date.now()-e.createdAt>6e5?null:R(e.returnUrl,{sameOrigin:!0}):null},exports.createBBUrl=T,exports.createCheckoutRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:T({action:A.Checkout,status:I.Success,ws:e,screen:_.Subscription},n),cancelUrl:T({action:A.Checkout,status:I.Cancel,ws:e,screen:_.Subscription},n)}},exports.createCreditPurchaseRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:T({action:A.CreditPurchase,status:I.Success,ws:e,screen:_.Credits},n),cancelUrl:T({action:A.CreditPurchase,status:I.Cancel,ws:e,screen:_.Credits},n)}},exports.createSessionRefCrypto=Et,exports.default=At,exports.eventEmitter=x,exports.extractBearerToken=ft,exports.fetchAgentReadiness=We,exports.formatCents=z,exports.formatMinorAmountIntl=function(e,t,n="en-US"){const r=(t??"").trim(),s=q(r),i=e/10**s;if(!r)return i.toFixed(s);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:s,maximumFractionDigits:s}).format(i)}catch{return B(r)+(0===s?i.toLocaleString("en-US"):i.toFixed(s))}},exports.formatOverageRate=function(e,t,n,r,s){if(null==e||e<0)return null;const i={...K,...r},o=null!=t&&t>=1?t:1,a=B(n),c=V(e,n);return 1===o?`${a}${c}/${i.unit}`:`${a}${c}/${o.toLocaleString(s)} ${i.units}`},exports.formatOverageRateWithLabel=function(e,t,n,r,s,i,o){if(null==e||e<0)return null;const a={...K,...i},c=null!=t&&t>=1?t:1,u=B(r),l=V(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${u}${l}/${c.toLocaleString(o)} ${e}`:`${u}${l}/${n}`}return 1===c?`${u}${l}/${a.unit}`:`${u}${l}/${c.toLocaleString(o)} ${a.units}`},exports.formatQuotaIncludedOverage=function(e,t,n,r,s,i,o,a,c){const u={...K,...o};if(!1===a)return null!=e?`${u.included}: ${e.toLocaleString(c)} (${u.hardLimit})`:o?.hardLimit??"Hard limit";const l=i??(n.endsWith("s")?n:`${n}s`),d=null!=s&&s>=2?`${s.toLocaleString(c)} ${l}`:n;return null!=e&&null!=t?`${u.included}: ${e.toLocaleString(c)}, ${u.afterThat} ${z(t,r)}/${d}`:null!=e?`${u.included}: ${e.toLocaleString(c)}`:null!=t?`${u.afterIncluded}: ${z(t,r)}/${d}`:"—"},exports.formatQuotaWithPrice=function(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,i={...G,...n.labels},o=n.currencySymbol??B(s??"");if(null==e)return"—";const{included:a,overage:c}=e,u=`${a} ${i.included}`;if(!1===e.allowOverage)return`${u} (${i.hardLimit})`;if(null==c)return u;const l=q(s),d=r&&l>0?c/10**l:c,p="number"==typeof d&&Number.isFinite(d)?0===l?d.toLocaleString("en-US"):d.toFixed(l):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${i.then} ${o}${p}${h}`},exports.getAvailableCurrenciesFromPlans=function(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()},exports.getBasePriceCents=Y,exports.getBillingIntervalAndCurrencyFromPriceId=function(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null},exports.getCurrencyDecimals=q,exports.getCurrencyFlag=function(e){return e&&e.trim()?N[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=B,exports.getDisplayCurrency=function(e,t){const n=Q(e,t);return n?n.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=ee,exports.getPricingVariant=Q,exports.getQuotaDisplayValue=function(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null},exports.getQuotaDisplayWithVariant=function(e,t,n,r){const s=e.quotas?.[n];if(null==s)return null;const i=s[r];if(!i)return null;const o=Z(e,t,n,r);return{included:i.included,...void 0!==i.unitSize&&{unitSize:i.unitSize},...void 0!==o&&{overage:o},allowOverage:!1!==s.allowOverage}},exports.getQuotaOverageCents=Z,exports.getQuotaUnitLabelFromName=function(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t},exports.getSeatPricing=X,exports.getStripePriceIdForInterval=function(e,t,n){const r=Q(e,t);if(!r?.stripePrices)return null;const s=n===H.Monthly?"monthlyPriceId":n===H.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===H.Monthly?"monthly":n===H.Yearly?"yearly":void 0;return r.stripePrices[s]??(i?r.stripePrices[i]:void 0)??null},exports.handleAppRevokeRequest=async function(e){let t;try{t=wt(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof dt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}},exports.handleAppTokenRequest=async function(e){let t;try{t=mt(e)}catch(e){return{status:401,body:kt(e instanceof dt?e.code:"invalid_token")}}return{status:200,body:bt(await e.mintToken(t))}},exports.hasPermission=ce,exports.invalidateCreditBalance=$,exports.invalidateQuotaUsage=P,exports.invalidateSubscription=E,exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===q(e)},exports.minorAmountToDisplay=V,exports.mintAgentToken=async function(e){const{claims:t,secret:n}=e,r=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,i=t.sessionId?await Et(n).encryptSessionRef(t.sessionId):void 0;return{token:yt({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...i?{sid:i}:{},...e.extraClaims},n,{expiresInSec:r}),expiresIn:r}},exports.negotiateMarkdown=function(e,t,n){const r=at(e);return{status:200,contentType:r?Pe:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:_e(n?.cacheTtlSeconds??we),vary:"Accept"}},exports.parseWebhookEvent=function(e){if(!me(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(C);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),s=decodeURIComponent(e.slice(n+1));r&&(t[r]=s)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}},exports.resolveAgentPath=async function(e,t){const n=e.replace(/\/+$/,"")||e,r=function(e,t){const n=t.extraPaths?.[e];if(void 0===n)return null;const r="string"==typeof n?{body:n}:n;return{status:r.status??200,contentType:r.contentType??Ge(e),body:r.body,cacheControl:r.cacheControl??_e(t.cacheTtlSeconds??we)}}(n,t);return r||("/robots.txt"===n?rt(t):"/llms-full.txt"===n?Ve(t):"/sitemap.xml"===n?ot(t):"/llms.txt"===n?qe(t):"/auth.md"===n?Xe(t,await We(t)):"/security.txt"===n?je(t):n.startsWith("/.well-known")?ct(n,t):null)},exports.resolveMaxUsers=function(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=X(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}},exports.resolvePermissions=ae,exports.resolveWellKnown=ct,exports.safeRedirect=function(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=R(e,n);return window.location.href=r??R(t)??"/",!0},exports.saveAuthIntent=function(e){R(e,{sameOrigin:!0})&&u(O,{returnUrl:e,createdAt:Date.now()})},exports.sha256Digest=Te,exports.signClientJwt=yt,exports.validateInvite=function(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:i,source:o}=n;if(i<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=i){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[o]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[o]??"users.memberLimitMessage",blockMessageValues:{maxUsers:i}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}},exports.validateRedirectUrl=R,exports.verifyAppRevokeRequest=wt,exports.verifyAppTokenRequest=mt,exports.verifyClientJwt=ht,exports.verifyWebhookSignature=me,exports.wantsMarkdown=at;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});let e=!0;function t(t,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}async function n(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function r(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await n(e);r=t.message||t.error||r}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw new Error(r)}try{return await n(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class s extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,s)}}const i=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,n={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new s("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",n),i=r instanceof s?r:new s(r.message,"SDK_ERROR",n,r);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${n.component||"Unknown"}:`,{message:i.message,code:i.code,context:i.context,originalError:i.originalError,stack:i.stack}),this.config.onError)try{this.config.onError(i,n)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(i,n)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function o(e,t={}){i.handleError(e,t)}function a(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return o(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){o(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){o(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){o(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const l="saas-session-id",d="saas-device-id";function p(){return function(){if("undefined"==typeof window)return null;try{return a(l)}catch(e){return o(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}function h(){const e=p(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return a(d)??null}catch(e){return o(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:d}}),null}}();return n&&(t["x-device-id"]=n),t}const f=new WeakSet,g=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),y="SDK is not ready (missing serverUrl, version, or orgId)";class w{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(y);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(y)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:h()}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){f.has(e)||(f.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((n,r)=>{const s=()=>{clearTimeout(i),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const i=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,n){const r=(t.method??"GET").toUpperCase(),s=n??e,i=this.buildHeaders(t),o={...t,headers:i},a=g.has(r);let c,u;if(this._timeout>0){u=new AbortController;const e=u;c=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?function(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,s=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){s(n);break}n.addEventListener("abort",()=>s(n),{once:!0})}return r.signal}(t.signal,e.signal):e.signal}const l=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${r} ${s}`);return this.reportError(e,{method:r,path:s}),e}return e},d=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),s=await n(e,o);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&a&&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 w.delay(e,o.signal),d(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await w.delay(e,o.signal)}catch(e){throw l(e)}return d(t+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:s}),e}};try{return await d(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await r(s,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw new Error(n)}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class m extends w{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 b extends w{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,n){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}class k extends w{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 v extends w{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class S extends w{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class x extends w{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}class $ extends w{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,n){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const s=new URLSearchParams;return s.append("limit",t.toString()),n&&s.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,s){const i={event:t};return n&&(i.userId=n),r&&(i.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(i),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}exports.ApiVersion=void 0,(exports.ApiVersion||(exports.ApiVersion={})).V1="v1";const P={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 U{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){o(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(P.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(P.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(P.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(P.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(P.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(P.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(P.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(P.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(P.WorkspaceDeleted,{workspace:e})}}const E=new U;function C(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const A=C().invalidate,T=C().invalidate,I=C().invalidate,_="bb",R={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},O={Success:"success",Cancel:"cancel",Error:"error"},W={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function F(e,t){const n=t??("undefined"!=typeof window?window.location.href:"https://localhost");let r;try{r=new URL(n)}catch{throw new Error(`createBBUrl: invalid base URL: ${JSON.stringify(n)}`)}return r.search="",r.searchParams.set(_,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function N(e,t={}){if(!e||"string"!=typeof e)return null;if(/^\/(?![/\\])/.test(e))return e;let n;try{n=new URL(e)}catch{return null}const r="https:"===n.protocol,s="http:"===n.protocol&&("localhost"===n.hostname||"127.0.0.1"===n.hostname||"[::1]"===n.hostname);if(!r&&!s)return null;const{sameOrigin:i,allowedOrigins:o}=t;return i||o?.length?i&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||o?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}const J="saas-auth-intent";function B(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}const L={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:"฿"},M={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function D(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return L[t]??t.toUpperCase()}const j=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],q=j.map(e=>({value:e,label:`${e.toUpperCase()} (${D(e)})`})),V=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),z=new Set(["bhd","jod","kwd","omr","tnd"]),K=new Map;function G(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(V.has(t))return 0;if(z.has(t))return 3;if("isk"===t)return 2;let n=K.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}K.set(t,n)}return n}function H(e,t){const n=G(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function Q(e,t){return D(t)+H(e,t)}const Y={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const Z={included:"included",then:"then",hardLimit:"hard limit"};const X={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"};function ee(e,t){const n=e.pricingVariants;if(!n?.length)return null;const r=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===r)??null}function te(e,t,n){const r=ee(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function ne(e,t,n,r){const s=ee(e,t),i=s?.quotaOverages?.[n];if(i)return i[r]}function re(e,t){const n=ee(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function se(e,t,n){const r=re(e,t);return r?.perSeat?r.perSeat[n]??null:null}function ie(e,t){return Math.max(0,e-(t||0))}function oe(e,t,n,r){const s=re(e,t);if(!s)return null;return ie(r,s.includedSeats)*(se(e,t,n)??0)}const ae={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"},ce=Object.values(ae),ue={admin:ce.filter(e=>e!==ae.WORKSPACE_DELETE),member:[ae.WORKSPACE_SETTINGS_VIEW,ae.WORKSPACE_MEMBERS_VIEW,ae.WORKSPACE_FEATURES_VIEW,ae.WORKSPACE_BILLING_VIEW,ae.WORKSPACE_USAGE_VIEW],viewer:[ae.WORKSPACE_SETTINGS_VIEW,ae.WORKSPACE_MEMBERS_VIEW]};function le(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function de(e){const{userId:t,workspace:n,settings:r,appPermissions:s}=e;if(!n||!t)return new Set;if(function(e,t){if(!t)return!1;const n=(r=e.createdBy)?"string"==typeof r?r:"object"==typeof r&&"_id"in r&&"string"==typeof r._id?r._id:null:null;var r;return null!==n&&n===t}(n,t)){const e=new Set(ce);if(s)for(const t of le(s))e.add(t);if(n.permissions)for(const t of le(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of le(r.workspace.permissions))e.add(t);return e}const i=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);if(!i)return new Set;const o=n.permissions,a=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!o&&i in o,d=!!a&&i in a,p=i in ue;let h;if(l)h=c(o[i]);else if(d)h=c(a[i]);else if(p)h=ue[i];else{const e=r?.workspace?.defaultRole;h=e&&e in ue?ue[e]:[]}const f=new Set(h),g=l?u(o[i]):[],y=s?.[i]?u(s[i]):[],w=l?g:y;for(const e of w)f.add(e);return function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(ae.WORKSPACE_MEMBERS_INVITE)}(f,i,r),f}function pe(e,t){const n=de(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}var he;exports.AuthStatus=void 0,(he=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",he.redirecting="redirecting",he.authenticated="authenticated",he.unauthenticated="unauthenticated",he.authenticating="authenticating";const fe=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]),ge=(e,t)=>e>>>t|e<<32-t;function ye(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,o=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 y=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;y[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=ge(y[e-15],7)^ge(y[e-15],18)^y[e-15]>>>3,n=ge(y[e-2],17)^ge(y[e-2],19)^y[e-2]>>>10;y[e]=y[e-16]+t+y[e-7]+n>>>0}let u=t,l=n,d=r,h=s,f=i,g=o,w=a,m=c;for(let e=0;e<64;e++){const t=m+(ge(f,6)^ge(f,11)^ge(f,25))+(f&g^~f&w)+fe[e]+y[e]>>>0,n=u&l^u&d^l&d;m=w,w=g,g=f,f=h+t>>>0,h=d,d=l,l=u,u=t+((ge(u,2)^ge(u,13)^ge(u,22))+n>>>0)>>>0}t=t+u>>>0,n=n+l>>>0,r=r+d>>>0,s=s+h>>>0,i=i+f>>>0,o=o+g>>>0,a=a+w>>>0,c=c+m>>>0}const w=new Uint8Array(32),m=[t,n,r,s,i,o,a,c];for(let e=0;e<8;e++)w[4*e]=m[e]>>>24&255,w[4*e+1]=m[e]>>>16&255,w[4*e+2]=m[e]>>>8&255,w[4*e+3]=255&m[e];return w}function we(e){return(new TextEncoder).encode(e)}function me(e,t){let n=e;n.length>64&&(n=ye(n));const r=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,s[e]=92^t}const i=ye(ke(r,t));return ye(ke(s,i))}function be(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}function ke(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function ve(e){const{body:t,signature:n,timestamp:r,secret:s,maxAgeSeconds:i=300}=e;if(!(n&&r&&s&&t))return!1;const o="sha256=";if(!n.startsWith(o))return!1;const a=n.slice(7);if(i>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>i)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(a);if(!c)return!1;const u=me(we(s),we(`${r}.${t}`));return c.length===u.length&&be(c,u)}const Se=300,xe="/.well-known/oauth-protected-resource",$e="/.well-known/agent-skills",Pe="/.well-known/api-catalog",Ue="/.well-known/mcp/server-card.json",Ee="/.well-known/agent-card.json",Ce="application/json",Ae="application/linkset+json",Te="text/markdown; charset=utf-8",Ie="text/plain; charset=utf-8",_e="application/xml; charset=utf-8",Re=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function Oe(e){return e.replace(/\/+$/,"")}function We(e){return`public, max-age=${e}, s-maxage=${e}`}function Fe(e){return"sha256:"+function(e){let t="";for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,"0");return t}(ye(we(e)))}const Ne=new Map;async function Je(e,t,n,r){if(!r||r<=0)return e(t,n);const s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await e(t,{...n,signal:s.signal})}finally{clearTimeout(i)}}async function Be(e){const t=e.cacheTtlSeconds??Se,n=`${Oe(e.serverUrl)}::${e.orgId}`,r=Ne.get(n);if(r&&r.expiresAt>Date.now())return r.value;const s=e.fetch??fetch,i=`${Oe(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let o={enabled:!1};try{const t=await Je(s,i,{headers:{Accept:Ce}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(o=e)}}catch{}return Ne.set(n,{value:o,expiresAt:Date.now()+1e3*t}),o}const Le=new Map;function Me(e,t){const n=Oe(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:xe};t.authorizationServer?.metadataUrl&&(r.oauth_authorization_server=t.authorizationServer.metadataUrl,r.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(r.auth="/auth.md"),e.skills?.length&&(r.agent_skills=`${$e}/index.json`),e.apiCatalog?.length&&(r.api_catalog=Pe),e.mcpServerCard&&(r.mcp_server_card=Ue),!1!==e.a2aCard&&(r.a2a_agent_card=Ee),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return st({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:n,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:n},capabilities:r,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function De(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return xe+n}function je(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||xe,i=n??`${Oe(t.serverUrl)}/org/${t.orgId}`,o=t.scopes?.map(e=>e.name),a=r.map(e=>{const n=e.resource??Oe(t.siteUrl),r=e.scopes??o;return{path:De(n),metadata:{resource:n,authorization_servers:[i],bearer_methods_supported:e.bearerMethods??["header"],...r?.length?{scopes_supported:r}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=a.find(e=>e.path===s);return c?st(c.metadata,t):s===xe&&1===a.length?st(a[0].metadata,t):null}function qe(e){const t=e.skills??[];if(!t.length)return null;const n=Oe(e.siteUrl);return st({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${n}${Ve(e)}`,digest:Fe(e.content)}))},e)}function Ve(e){return e.path??`${$e}/${e.name}/SKILL.md`}function ze(e,t){const n=(t.skills??[]).find(t=>Ve(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:We(t.cacheTtlSeconds??Se)}:null}function Ke(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:Ie,body:t.join("\n")+"\n",cacheControl:We(e.cacheTtlSeconds??Se)}}function Ge(e){return e.llmsTxt?{status:200,contentType:Ie,body:e.llmsTxt,cacheControl:We(e.cacheTtlSeconds??Se)}:null}function He(e){return e.llmsFullTxt?{status:200,contentType:Ie,body:e.llmsFullTxt,cacheControl:We(e.cacheTtlSeconds??Se)}:null}function Qe(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=Oe(e.siteUrl),r=t.serviceUrl??n,s=t.transportProtocol??"http",i=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return st({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:r,preferredTransport:s,supportedInterfaces:[{serviceUrl:r,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:n},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:i,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}function Ye(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:We(e.cacheTtlSeconds??Se)}:null}function Ze(e){return e.endsWith(".json")||e.includes(".well-known/")?Ce:e.endsWith(".md")?Te:e.endsWith(".xml")?_e:Ie}function Xe(e){const t=e.apiCatalog??[];if(!t.length)return null;const n=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:Ae,body:JSON.stringify({linkset:n},null,2),cacheControl:We(e.cacheTtlSeconds??Se)}}function et(e){const t=e??{tools:!0},n={tools:!1,resources:!1,prompts:!1};for(const[e,r]of Object.entries(t))n[e]=!1!==r&&null!=r;return n}function tt(e){const t=e.mcpServerCard;return t?st({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:et(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function nt(e){const t=e.mcpServerCard;if(!t)return null;const n=Oe(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${De(t.endpoint)}`}}catch{}return st({$schema:"https://modelcontextprotocol.io/schemas/mcp-discovery/v1.0",version:"1.0",servers:[{name:t.name,...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},version:t.version,capabilities:et(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${Ue}`,...r?{authentication:r}:{}}]},e)}function rt(e,t){const n=We(e.cacheTtlSeconds??Se);if(e.authMd)return{status:200,contentType:Te,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const s=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${r.issuer}\`\n- Metadata (RFC 8414): ${r.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, supported grant types / PKCE methods, and — when the app allows it — the dynamic client \`registration_endpoint\` (RFC 7591).\n\n## Protected resources (RFC 9728)\nSee \`/.well-known/oauth-protected-resource\`, which lists the resource, its supported scopes, and the authorization server(s) that can issue tokens for it.\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. Register a client (dynamic registration) or use a pre-issued client_id.\n4. Run the authorization-code flow with PKCE (S256), requesting the scopes and target \`resource\`.\n5. 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:Te,body:s,cacheControl:n}}function st(e,t){return{status:200,contentType:Ce,body:JSON.stringify(e,null,2),cacheControl:We(t.cacheTtlSeconds??Se)}}function it(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function ot(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${it(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&n.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])n.push(`Allow: ${it(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${it(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${it(e.crawlDelay)}`),n.join("\n")}function at(e){const t=e.robots??{},n=Oe(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",i="allow"===s?[{userAgent:[...Re],allow:["/"]}]:"deny"===s?[{userAgent:[...Re],disallow:["/"]}]:s,o=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...r.map((e,n)=>ot(e,0===n?t.contentSignals:void 0)),...i.map(e=>ot(e)),...o.length?[o.map(e=>`Sitemap: ${it(e)}`).join("\n")]:[]];return{status:200,contentType:Ie,body:a.join("\n\n")+"\n",cacheControl:We(e.cacheTtlSeconds??Se)}}function ct(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function ut(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function lt(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=Oe(e.siteUrl),r='<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${ut(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${ut(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${ut(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${ct(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:_e,body:r,cacheControl:We(e.cacheTtlSeconds??Se)}}function dt(e){if(!e)return!1;let t=0,n=0;for(const r of e.split(",")){const[e,...s]=r.trim().split(";"),i=e.trim().toLowerCase();let o=1;for(const e of s){const[t,n]=e.split("=").map(e=>e.trim());if("q"===t){const e=Number(n);Number.isNaN(e)||(o=e)}}"text/markdown"===i||"text/x-markdown"===i?t=Math.max(t,o):"text/html"!==i&&"text/*"!==i&&"*/*"!==i||(n=Math.max(n,o))}return t>0&&t>=n}async function pt(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return Me(t,await Be(t))}if(n===Ee)return Qe(t);if("/.well-known/http-message-signatures-directory"===n)return Ye(t);if("/.well-known/security.txt"===n)return Ke(t);if(n===`${$e}/index.json`)return qe(t);if(n.startsWith(`${$e}/`)&&n.endsWith("SKILL.md"))return ze(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await Be(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??Se,r=Le.get(e);if(r&&r.expiresAt>Date.now())return r.value;const s=t.fetch??fetch;let i=null;try{const n=await Je(s,e,{headers:{Accept:Ce}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(i=e)}}catch{}return Le.set(e,{value:i,expiresAt:Date.now()+1e3*n}),i}(e.metadataUrl,t);return st(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===Pe)return Xe(t);if(n===Ue)return tt(t);if("/.well-known/mcp.json"===n)return nt(t);if(n.startsWith(xe)){const e=await Be(t);return je(n,t,e.authorizationServer?.issuer)}return null}function ht(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ft(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+n),s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return s}class gt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function yt(e){const t=JSON.parse((new TextDecoder).decode(ft(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function wt(e,t,n={}){const r=n.clockToleranceSec??60,s=n.requireExp??!0;if(!e||!t)throw new gt("invalid_token","Missing token or client secret");const i=e.split(".");if(3!==i.length)throw new gt("invalid_token","Malformed JWT");const[o,a,c]=i;let u,l;try{u=yt(o),l=yt(a)}catch{throw new gt("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new gt("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const d=me(we(t),we(`${o}.${a}`));let p;try{p=ft(c)}catch{throw new gt("invalid_signature","Unreadable JWT signature")}if(!be(d,p))throw new gt("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new gt("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const n=e[t];if(void 0!==n&&("number"!=typeof n||!Number.isFinite(n)))throw new gt("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new gt("invalid_token","JWT aud claim must be a string or string array")}(l);const h=Math.floor(Date.now()/1e3);if(s&&"number"!=typeof l.exp)throw new gt("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof l.exp&&h>l.exp+r)throw new gt("token_expired","JWT has expired");if("number"==typeof l.nbf&&h+r<l.nbf)throw new gt("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&l.iss!==n.issuer)throw new gt("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=l.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new gt("invalid_audience","JWT audience mismatch")}return l}function mt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function bt(e){return ht(we(JSON.stringify(e)))}function kt(e,t,n){if(!t)throw new gt("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),s={iat:r,exp:r+(n?.expiresInSec??3600),...e},i=`${bt({alg:"HS256",typ:"JWT"})}.${bt(s)}`;return`${i}.${ht(me(we(t),we(i)))}`}function vt(e){const t=mt(e.authorization);if(!t)throw new gt("invalid_token","Missing Bearer token");return wt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function St(e){const t=mt(e.authorization);if(!t)throw new gt("invalid_token","Missing Bearer token");return wt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function xt(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function $t(e){return{success:!1,token:"",message:e}}function Pt(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}const Ut=12,Et=16;function Ct(){const e=globalThis.crypto;if(!e?.subtle)throw new Error("WebCrypto is unavailable in this runtime — agent-auth session encryption requires globalThis.crypto.subtle (Node 18+, Bun, Deno, edge, browsers).");return e.subtle}const At=new Map;function Tt(e){let t=At.get(e);return t||(t=(async()=>{const t=await Ct().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return Ct().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),At.set(e,t)),t}function It(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(Ut)),r=await Tt(e),s=new Uint8Array(await Ct().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),i=s.subarray(s.length-Et),o=s.subarray(0,s.length-Et),a=new Uint8Array(28+o.length);return a.set(n,0),a.set(i,Ut),a.set(o,28),ht(a)},async decryptSessionRef(t){try{const n=ft(t);if(n.length<=28)return null;const r=n.slice(0,Ut),s=n.subarray(Ut,28),i=n.subarray(28),o=new Uint8Array(i.length+Et);o.set(i,0),o.set(s,i.length);const a=await Tt(e),c=await Ct().decrypt({name:"AES-GCM",iv:r},a,o);return(new TextDecoder).decode(c)}catch{return null}}}}function _t(e,t,n){const r=globalThis.process?.env;"1"===r?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${n}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function Rt(e){const{serverUrl:t,orgId:n,version:r="v1",getSessionId:s,timeout:i,maxRetries:o,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const d={...void 0!==i&&{timeout:i},...void 0!==o&&{maxRetries:o},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},p=e=>{const s={serverUrl:t,version:r,orgId:n,sessionId:e,...d};return{workspace:new $(s),user:new x(s),settings:new S(s),push:new k(s),devices:new b(s),sessions:new v(s)}},h=new $({serverUrl:t,version:r,orgId:n,...d}),f=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,r)=>(await e()).workspace.addUser(t,{email:n,role:r}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,r)=>(await e()).workspace.updateUser(t,n,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,n)=>(await e()).workspace.createCheckoutSession(t,n),update:async(t,n)=>(await e()).workspace.updateSubscription(t,n),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,n)=>(await e()).workspace.createBillingPortalSession(t,n)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,n,r)=>(await e()).workspace.listInvoices(t,n,r),get:async(t,n)=>(await e()).workspace.getInvoice(t,n)},usage:{record:async(t,n)=>(await e()).workspace.recordUsage(t,n),recordBatch:async(t,n)=>(await e()).workspace.recordUsageBatch(t,n),getQuota:async(t,n)=>(await e()).workspace.getQuotaUsageStatus(t,n),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,n)=>(await e()).workspace.getUsageLogs(t,n)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,n,r)=>(await e()).workspace.updateFeature(t,n,r)},notification:{send:async(t,n,r,s)=>(await e()).workspace.sendNotification(t,n,r,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,n)=>(await e()).workspace.consumeCredits(t,n),purchase:async(t,n)=>(await e()).workspace.purchaseCredits(t,n),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,n)=>(await e()).workspace.getCreditTransactions(t,n),getBuckets:async(t,n)=>(await e()).workspace.getCreditBuckets(t,n),getExpiring:async(t,n)=>(await e()).workspace.getExpiringCredits(t,n),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,n,r)=>{const s=await e(),[i,o,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return pe(r,{userId:n,workspaceRole:c?.role??null,workspace:i,settings:o})},resolve:async(t,n)=>{const r=await e(),[s,i,o]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),a=o.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return de({userId:n,workspaceRole:a?.role??null,workspace:s,settings:i})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,n)=>(await e()).devices.rename(t,n),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),g=f(async()=>p(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=p(e);return f(async()=>t)},client:{forSession:p},...g}}exports.AI_BOT_USER_AGENTS=Re,exports.AppBridgeError=gt,exports.AuthApi=class extends w{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}async getDeviceToken(e,t){try{const n=await this.fetchUnwrapped("device-token",{headers:{"x-session-id":e},signal:t},"Failed to fetch device token");return n?.deviceToken??""}catch{return""}}},exports.BBAction=R,exports.BBScreen=W,exports.BBStatus=O,exports.BB_PARAM=_,exports.BaseApi=w,exports.BetaForm=class{constructor(e){this.api=new m(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),s=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),i=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:s,currency:i}})}},exports.BillingIntervals=X,exports.BuildBase=Rt,exports.CURRENCY_DISPLAY=L,exports.CURRENCY_FLAG=M,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=ue,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EventEmitter=U,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.PLAN_CURRENCY_CODES=j,exports.PLAN_CURRENCY_OPTIONS=q,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 // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n 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=ae,exports.PushApi=k,exports.SDKEvent=P,exports.SettingsApi=S,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=x,exports.WorkspaceApi=$,exports.appTokenFailure=$t,exports.appTokenSuccess=xt,exports.bearerChallenge=function(e){const t=[`Bearer resource_metadata="${Pt(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${Pt(e.error)}"`),e.errorDescription&&t.push(`error_description="${Pt(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}},exports.buildA2AAgentCard=Qe,exports.buildAgentCard=Me,exports.buildAgentSkillsIndex=qe,exports.buildApiCatalog=Xe,exports.buildAuthMd=rt,exports.buildDiscoveryLinkHeader=function(e){const t=Oe(e.siteUrl),n=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&n.push(`<${t}${Ee}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const r=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;n.push(`<${r}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&n.push(`<${t}${Pe}>; rel="api-catalog"; type="${Ae}"`),e.mcpServerCard&&n.push(`<${t}${Ue}>; rel="mcp-server"; type="application/json"`),n.join(", ")},exports.buildDnsAidRecords=function(e){let t;try{t=new URL(e.siteUrl).hostname}catch{return[]}const n=[{name:`_index._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}];if(!1!==e.a2aCard&&n.push({name:`_a2a._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${t}. alpn="h2" port=443`}),e.mcpServerCard){let r=t;try{r=new URL(e.mcpServerCard.endpoint).hostname}catch{}n.push({name:`_mcp._agents.${t}`,type:"HTTPS",ttl:3600,data:`1 ${r}. alpn="h2" port=443`})}return n},exports.buildLlmsFullTxt=He,exports.buildLlmsTxt=Ge,exports.buildMcpDiscoveryManifest=nt,exports.buildMcpServerCard=tt,exports.buildProtectedResourceMetadata=je,exports.buildRobotsTxt=at,exports.buildSecurityTxt=Ke,exports.buildSitemap=lt,exports.buildSkillMd=ze,exports.buildWebBotAuthDirectory=Ye,exports.buildbaseAuth=function(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=It(t),r=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&r.length)try{const e=new URL(r[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let i;try{i=wt(s,t,{...e.verify})}catch{return null}if(r.length){const t=i.aud?Array.isArray(i.aud)?i.aud:[i.aud]:[];if(!t.length&&e.requireAudience)return _t(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return _t(t,r,"aud does not include this resource"),null}const o="string"==typeof i.sid?await n.decryptSessionRef(i.sid):null,a=Array.isArray(i.scope)?i.scope.filter(e=>"string"==typeof e):"string"==typeof i.scope?i.scope.split(" ").filter(Boolean):void 0;return{sessionId:o??"",userId:"string"==typeof i.userId?i.userId:"string"==typeof i.sub?i.sub:void 0,workspaceId:"string"==typeof i.workspaceId?i.workspaceId:void 0,scopes:a,claims:i}}}},exports.calculateBillableSeats=ie,exports.calculateSeatOverageCents=oe,exports.calculateTotalSubscriptionCents=function(e,t,n,r){const s=te(e,t,n);return null===s?null:void 0===r?s:s+(oe(e,t,n,r)??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(){Ne.clear(),Le.clear()},exports.clearAuthIntent=function(){c(J)},exports.consumeAuthIntent=function(){const e=function(e,t){const n=a(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(o(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):r}catch(t){return o(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(J,B);return c(J),e?Date.now()-e.createdAt>6e5?null:N(e.returnUrl,{sameOrigin:!0}):null},exports.createBBUrl=F,exports.createCheckoutRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:F({action:R.Checkout,status:O.Success,ws:e,screen:W.Subscription},n),cancelUrl:F({action:R.Checkout,status:O.Cancel,ws:e,screen:W.Subscription},n)}},exports.createCreditPurchaseRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:F({action:R.CreditPurchase,status:O.Success,ws:e,screen:W.Credits},n),cancelUrl:F({action:R.CreditPurchase,status:O.Cancel,ws:e,screen:W.Credits},n)}},exports.createSessionRefCrypto=It,exports.default=Rt,exports.eventEmitter=E,exports.extractBearerToken=mt,exports.fetchAgentReadiness=Be,exports.formatCents=Q,exports.formatMinorAmountIntl=function(e,t,n="en-US"){const r=(t??"").trim(),s=G(r),i=e/10**s;if(!r)return i.toFixed(s);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:s,maximumFractionDigits:s}).format(i)}catch{return D(r)+(0===s?i.toLocaleString("en-US"):i.toFixed(s))}},exports.formatOverageRate=function(e,t,n,r,s){if(null==e||e<0)return null;const i={...Y,...r},o=null!=t&&t>=1?t:1,a=D(n),c=H(e,n);return 1===o?`${a}${c}/${i.unit}`:`${a}${c}/${o.toLocaleString(s)} ${i.units}`},exports.formatOverageRateWithLabel=function(e,t,n,r,s,i,o){if(null==e||e<0)return null;const a={...Y,...i},c=null!=t&&t>=1?t:1,u=D(r),l=H(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${u}${l}/${c.toLocaleString(o)} ${e}`:`${u}${l}/${n}`}return 1===c?`${u}${l}/${a.unit}`:`${u}${l}/${c.toLocaleString(o)} ${a.units}`},exports.formatQuotaIncludedOverage=function(e,t,n,r,s,i,o,a,c){const u={...Y,...o};if(!1===a)return null!=e?`${u.included}: ${e.toLocaleString(c)} (${u.hardLimit})`:o?.hardLimit??"Hard limit";const l=i??(n.endsWith("s")?n:`${n}s`),d=null!=s&&s>=2?`${s.toLocaleString(c)} ${l}`:n;return null!=e&&null!=t?`${u.included}: ${e.toLocaleString(c)}, ${u.afterThat} ${Q(t,r)}/${d}`:null!=e?`${u.included}: ${e.toLocaleString(c)}`:null!=t?`${u.afterIncluded}: ${Q(t,r)}/${d}`:"—"},exports.formatQuotaWithPrice=function(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,i={...Z,...n.labels},o=n.currencySymbol??D(s??"");if(null==e)return"—";const{included:a,overage:c}=e,u=`${a} ${i.included}`;if(!1===e.allowOverage)return`${u} (${i.hardLimit})`;if(null==c)return u;const l=G(s),d=r&&l>0?c/10**l:c,p="number"==typeof d&&Number.isFinite(d)?0===l?d.toLocaleString("en-US"):d.toFixed(l):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${i.then} ${o}${p}${h}`},exports.getAvailableCurrenciesFromPlans=function(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()},exports.getBasePriceCents=te,exports.getBillingIntervalAndCurrencyFromPriceId=function(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null},exports.getCurrencyDecimals=G,exports.getCurrencyFlag=function(e){return e&&e.trim()?M[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=D,exports.getDisplayCurrency=function(e,t){const n=ee(e,t);return n?n.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=se,exports.getPricingVariant=ee,exports.getQuotaDisplayValue=function(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null},exports.getQuotaDisplayWithVariant=function(e,t,n,r){const s=e.quotas?.[n];if(null==s)return null;const i=s[r];if(!i)return null;const o=ne(e,t,n,r);return{included:i.included,...void 0!==i.unitSize&&{unitSize:i.unitSize},...void 0!==o&&{overage:o},allowOverage:!1!==s.allowOverage}},exports.getQuotaOverageCents=ne,exports.getQuotaUnitLabelFromName=function(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t},exports.getSeatPricing=re,exports.getStripePriceIdForInterval=function(e,t,n){const r=ee(e,t);if(!r?.stripePrices)return null;const s=n===X.Monthly?"monthlyPriceId":n===X.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===X.Monthly?"monthly":n===X.Yearly?"yearly":void 0;return r.stripePrices[s]??(i?r.stripePrices[i]:void 0)??null},exports.handleAppRevokeRequest=async function(e){let t;try{t=St(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof gt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}},exports.handleAppTokenRequest=async function(e){let t;try{t=vt(e)}catch(e){return{status:401,body:$t(e instanceof gt?e.code:"invalid_token")}}return{status:200,body:xt(await e.mintToken(t))}},exports.hasPermission=pe,exports.invalidateCreditBalance=A,exports.invalidateQuotaUsage=T,exports.invalidateSubscription=I,exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===G(e)},exports.minorAmountToDisplay=H,exports.mintAgentToken=async function(e){const{claims:t,secret:n}=e,r=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,i=t.sessionId?await It(n).encryptSessionRef(t.sessionId):void 0;return{token:kt({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...i?{sid:i}:{},...e.extraClaims},n,{expiresInSec:r}),expiresIn:r}},exports.negotiateMarkdown=function(e,t,n){const r=dt(e);return{status:200,contentType:r?Te:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:We(n?.cacheTtlSeconds??Se),vary:"Accept"}},exports.parseWebhookEvent=function(e){if(!ve(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 n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),s=decodeURIComponent(e.slice(n+1));r&&(t[r]=s)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}},exports.resolveAgentPath=async function(e,t){const n=e.replace(/\/+$/,"")||e,r=function(e,t){const n=t.extraPaths?.[e];if(void 0===n)return null;const r="string"==typeof n?{body:n}:n;return{status:r.status??200,contentType:r.contentType??Ze(e),body:r.body,cacheControl:r.cacheControl??We(t.cacheTtlSeconds??Se)}}(n,t);return r||("/robots.txt"===n?at(t):"/llms-full.txt"===n?He(t):"/sitemap.xml"===n?lt(t):"/llms.txt"===n?Ge(t):"/auth.md"===n?rt(t,await Be(t)):"/security.txt"===n?Ke(t):n.startsWith("/.well-known")?pt(n,t):null)},exports.resolveMaxUsers=function(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=re(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}},exports.resolvePermissions=de,exports.resolveWellKnown=pt,exports.safeRedirect=function(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=N(e,n);return window.location.href=r??N(t)??"/",!0},exports.saveAuthIntent=function(e){N(e,{sameOrigin:!0})&&u(J,{returnUrl:e,createdAt:Date.now()})},exports.sha256Digest=Fe,exports.signClientJwt=kt,exports.validateInvite=function(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:i,source:o}=n;if(i<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=i){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[o]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[o]??"users.memberLimitMessage",blockMessageValues:{maxUsers:i}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}},exports.validateRedirectUrl=N,exports.verifyAppRevokeRequest=St,exports.verifyAppTokenRequest=vt,exports.verifyClientJwt=wt,exports.verifyWebhookSignature=ve,exports.wantsMarkdown=dt;
|
package/dist/index.d.ts
CHANGED
|
@@ -1207,6 +1207,13 @@ declare class AuthApi extends BaseApi {
|
|
|
1207
1207
|
requestAuth(params: AuthRequestParams): Promise<AuthRequestResponse>;
|
|
1208
1208
|
/** Fetch user profile with the given session ID (used after OAuth redirect or from storage). */
|
|
1209
1209
|
getProfile(sessionId: string, signal?: AbortSignal): Promise<IUser>;
|
|
1210
|
+
/**
|
|
1211
|
+
* Fetch the signed device token bound to this session's device. The SDK calls
|
|
1212
|
+
* this automatically after login/hydration and persists the result, so
|
|
1213
|
+
* `x-device-id` is echoed on every request WITHOUT the app implementor
|
|
1214
|
+
* handling device identity. Returns '' for agent/machine sessions (no device).
|
|
1215
|
+
*/
|
|
1216
|
+
getDeviceToken(sessionId: string, signal?: AbortSignal): Promise<string>;
|
|
1210
1217
|
}
|
|
1211
1218
|
|
|
1212
1219
|
interface IScreenDetail {
|
|
@@ -1255,6 +1262,75 @@ declare class BetaForm {
|
|
|
1255
1262
|
}): Promise<ApiResponse>;
|
|
1256
1263
|
}
|
|
1257
1264
|
|
|
1265
|
+
/**
|
|
1266
|
+
* API client for the signed-in user's devices — the browsers/apps they have
|
|
1267
|
+
* signed in from. Session-authed (x-session-id + x-device-id), scoped to the
|
|
1268
|
+
* current user. Extends BaseApi for shared URL/auth/request handling.
|
|
1269
|
+
*
|
|
1270
|
+
* A device row is login history. Signing a device out revokes its live sessions
|
|
1271
|
+
* but keeps the row (shown as signed-out); "forget" also removes the row.
|
|
1272
|
+
*/
|
|
1273
|
+
|
|
1274
|
+
/** Coarse geo/network info resolved from the request IP (a lightweight subset). */
|
|
1275
|
+
interface IIpInfoLite {
|
|
1276
|
+
ip?: string;
|
|
1277
|
+
hostname?: string;
|
|
1278
|
+
country?: string;
|
|
1279
|
+
city?: string;
|
|
1280
|
+
region?: string;
|
|
1281
|
+
/** "lat,long" string, as provided by the IP lookup. */
|
|
1282
|
+
loc?: string;
|
|
1283
|
+
timezone?: string;
|
|
1284
|
+
}
|
|
1285
|
+
/** A device the current user has signed in from. */
|
|
1286
|
+
interface IDeviceView {
|
|
1287
|
+
/** Stable per-browser/app identifier (the `x-device-id` the client sends). */
|
|
1288
|
+
deviceId: string;
|
|
1289
|
+
/** User-editable label (falls back to a derived name). */
|
|
1290
|
+
name: string;
|
|
1291
|
+
/** IP the device was last seen from. */
|
|
1292
|
+
ip: string;
|
|
1293
|
+
/** Resolved geo/network info for `ip`, when available. */
|
|
1294
|
+
ipInfo: IIpInfoLite | null;
|
|
1295
|
+
userAgent: string;
|
|
1296
|
+
origin: string;
|
|
1297
|
+
/** Whether the user marked this device trusted (longer sessions, fewer prompts). */
|
|
1298
|
+
trusted: boolean;
|
|
1299
|
+
/** ISO string — first time this device was seen. */
|
|
1300
|
+
firstSeenAt?: string;
|
|
1301
|
+
/** ISO string — most recent activity from this device. */
|
|
1302
|
+
lastActiveAt?: string;
|
|
1303
|
+
/** True when this is the device the request came from. */
|
|
1304
|
+
current: boolean;
|
|
1305
|
+
/** Number of live sessions currently on this device. */
|
|
1306
|
+
activeSessions: number;
|
|
1307
|
+
/** Whether this device has an active push-notification subscription. */
|
|
1308
|
+
pushEnabled: boolean;
|
|
1309
|
+
}
|
|
1310
|
+
declare class DevicesApi extends BaseApi {
|
|
1311
|
+
constructor(config: Pick<IOsConfig, 'serverUrl' | 'version'> & {
|
|
1312
|
+
sessionId?: string;
|
|
1313
|
+
});
|
|
1314
|
+
/** List the devices the current user has signed in from. */
|
|
1315
|
+
list(signal?: AbortSignal): Promise<IDeviceView[]>;
|
|
1316
|
+
/** Rename a device (its user-facing label). */
|
|
1317
|
+
rename(deviceId: string, name: string, signal?: AbortSignal): Promise<void>;
|
|
1318
|
+
/**
|
|
1319
|
+
* Sign a device out: revoke every live session born on it. The device stays
|
|
1320
|
+
* in the list as a signed-out device. Returns the number of sessions revoked.
|
|
1321
|
+
*/
|
|
1322
|
+
signOut(deviceId: string, signal?: AbortSignal): Promise<{
|
|
1323
|
+
revokedSessions: number;
|
|
1324
|
+
}>;
|
|
1325
|
+
/**
|
|
1326
|
+
* Forget a device: sign it out AND remove the history row entirely.
|
|
1327
|
+
* Returns the number of sessions revoked in the process.
|
|
1328
|
+
*/
|
|
1329
|
+
forget(deviceId: string, signal?: AbortSignal): Promise<{
|
|
1330
|
+
revokedSessions: number;
|
|
1331
|
+
}>;
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1258
1334
|
declare class PushApi extends BaseApi {
|
|
1259
1335
|
constructor(config: Pick<IBaseApiConfig, 'serverUrl' | 'version' | 'orgId' | 'sessionId'>);
|
|
1260
1336
|
getVapidPublicKey(): Promise<{
|
|
@@ -1270,6 +1346,51 @@ declare class PushApi extends BaseApi {
|
|
|
1270
1346
|
unsubscribe(endpoint: string): Promise<void>;
|
|
1271
1347
|
}
|
|
1272
1348
|
|
|
1349
|
+
/**
|
|
1350
|
+
* API client for the signed-in user's active sessions. Session-authed
|
|
1351
|
+
* (x-session-id), scoped to the current user. Extends BaseApi for shared
|
|
1352
|
+
* URL/auth/request handling.
|
|
1353
|
+
*
|
|
1354
|
+
* The raw session id is never exposed — a session's public handle is its
|
|
1355
|
+
* mirror-row id (`ISessionView.id`), which is what `revoke` takes.
|
|
1356
|
+
* "Sign out everywhere" / "sign out current" stay on the auth logout flow.
|
|
1357
|
+
*/
|
|
1358
|
+
|
|
1359
|
+
/** One live session of the current user, joined to its device's label. */
|
|
1360
|
+
interface ISessionView {
|
|
1361
|
+
/** Public handle (mirror-row id) — NOT the raw session id. Use for `revoke`. */
|
|
1362
|
+
id: string;
|
|
1363
|
+
/** The device this session was born on. */
|
|
1364
|
+
deviceId: string;
|
|
1365
|
+
/** OAuth client id, or 'first-party' for a normal app sign-in. */
|
|
1366
|
+
clientId: string;
|
|
1367
|
+
ip: string;
|
|
1368
|
+
ipInfo: IIpInfoLite | null;
|
|
1369
|
+
userAgent: string;
|
|
1370
|
+
origin: string;
|
|
1371
|
+
/** ISO string. */
|
|
1372
|
+
createdAt?: string;
|
|
1373
|
+
/** ISO string. */
|
|
1374
|
+
lastActiveAt?: string;
|
|
1375
|
+
/** ISO string — when the session expires (reflects the org session policy). */
|
|
1376
|
+
expiresAt?: string;
|
|
1377
|
+
/** True when this is the session making the request. */
|
|
1378
|
+
current: boolean;
|
|
1379
|
+
/** The device's label only; ip/userAgent/etc. live on the session itself. */
|
|
1380
|
+
device: {
|
|
1381
|
+
name: string;
|
|
1382
|
+
} | null;
|
|
1383
|
+
}
|
|
1384
|
+
declare class SessionsApi extends BaseApi {
|
|
1385
|
+
constructor(config: Pick<IOsConfig, 'serverUrl' | 'version'> & {
|
|
1386
|
+
sessionId?: string;
|
|
1387
|
+
});
|
|
1388
|
+
/** List the current user's live sessions (each joined to its device label). */
|
|
1389
|
+
list(signal?: AbortSignal): Promise<ISessionView[]>;
|
|
1390
|
+
/** Sign out one session by its public handle (`ISessionView.id`). */
|
|
1391
|
+
revoke(id: string, signal?: AbortSignal): Promise<void>;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1273
1394
|
/**
|
|
1274
1395
|
* Centralized API client for organization (OS) settings.
|
|
1275
1396
|
* Extends BaseApi for shared URL/auth/request handling.
|
|
@@ -2357,11 +2478,41 @@ interface SDKMessages {
|
|
|
2357
2478
|
renamePlaceholder: string;
|
|
2358
2479
|
lastUsed: string;
|
|
2359
2480
|
added: string;
|
|
2481
|
+
devicesTitle: string;
|
|
2482
|
+
devicesDescription: string;
|
|
2483
|
+
devicesEmpty: string;
|
|
2484
|
+
devicesLoadFailed: string;
|
|
2485
|
+
deviceCurrent: string;
|
|
2486
|
+
deviceTrusted: string;
|
|
2487
|
+
deviceActiveSessions: string;
|
|
2488
|
+
devicePushEnabled: string;
|
|
2489
|
+
deviceLastActive: string;
|
|
2490
|
+
deviceRename: string;
|
|
2491
|
+
deviceRenamePlaceholder: string;
|
|
2492
|
+
deviceRenameFailed: string;
|
|
2493
|
+
deviceSave: string;
|
|
2494
|
+
deviceCancel: string;
|
|
2495
|
+
deviceSignOut: string;
|
|
2496
|
+
deviceSignOutFailed: string;
|
|
2497
|
+
deviceForget: string;
|
|
2498
|
+
deviceForgetFailed: string;
|
|
2499
|
+
deviceForgetConfirmTitle: string;
|
|
2500
|
+
deviceForgetConfirmBody: string;
|
|
2501
|
+
sessionsTitle: string;
|
|
2502
|
+
sessionsDescription: string;
|
|
2503
|
+
sessionsEmpty: string;
|
|
2504
|
+
sessionsLoadFailed: string;
|
|
2505
|
+
sessionCurrent: string;
|
|
2506
|
+
sessionExpires: string;
|
|
2507
|
+
sessionLastActive: string;
|
|
2508
|
+
sessionSignOut: string;
|
|
2509
|
+
sessionSignOutFailed: string;
|
|
2360
2510
|
};
|
|
2361
2511
|
settings: {
|
|
2362
2512
|
titles: {
|
|
2363
2513
|
profile: string;
|
|
2364
2514
|
security: string;
|
|
2515
|
+
devices: string;
|
|
2365
2516
|
general: string;
|
|
2366
2517
|
users: string;
|
|
2367
2518
|
subscription: string;
|
|
@@ -2377,6 +2528,7 @@ interface SDKMessages {
|
|
|
2377
2528
|
workspace: string;
|
|
2378
2529
|
profile: string;
|
|
2379
2530
|
security: string;
|
|
2531
|
+
devices: string;
|
|
2380
2532
|
general: string;
|
|
2381
2533
|
users: string;
|
|
2382
2534
|
subscription: string;
|
|
@@ -4019,6 +4171,28 @@ interface PermissionActions {
|
|
|
4019
4171
|
/** Resolve all permissions for a user in a workspace. Returns both platform and app permissions. */
|
|
4020
4172
|
resolve(workspaceId: string, userId: string): Promise<Set<string>>;
|
|
4021
4173
|
}
|
|
4174
|
+
/** Manage the signed-in user's devices (login history + per-device sign-out). */
|
|
4175
|
+
interface DeviceActions {
|
|
4176
|
+
/** List the devices the user has signed in from. */
|
|
4177
|
+
list(): Promise<IDeviceView[]>;
|
|
4178
|
+
/** Rename a device's user-facing label. */
|
|
4179
|
+
rename(deviceId: string, name: string): Promise<void>;
|
|
4180
|
+
/** Sign a device out (revoke its live sessions; keep the history row). */
|
|
4181
|
+
signOut(deviceId: string): Promise<{
|
|
4182
|
+
revokedSessions: number;
|
|
4183
|
+
}>;
|
|
4184
|
+
/** Sign a device out AND remove its history row ("forget"). */
|
|
4185
|
+
forget(deviceId: string): Promise<{
|
|
4186
|
+
revokedSessions: number;
|
|
4187
|
+
}>;
|
|
4188
|
+
}
|
|
4189
|
+
/** Manage the signed-in user's active sessions. */
|
|
4190
|
+
interface SessionActions {
|
|
4191
|
+
/** List the user's live sessions (each joined to its device label). */
|
|
4192
|
+
list(): Promise<ISessionView[]>;
|
|
4193
|
+
/** Sign out one session by its public handle (`ISessionView.id`). */
|
|
4194
|
+
revoke(id: string): Promise<void>;
|
|
4195
|
+
}
|
|
4022
4196
|
interface NotificationActions {
|
|
4023
4197
|
/**
|
|
4024
4198
|
* Send a notification to a user or all workspace members.
|
|
@@ -4075,6 +4249,8 @@ interface ScopedActions {
|
|
|
4075
4249
|
permissions: PermissionActions;
|
|
4076
4250
|
notification: NotificationActions;
|
|
4077
4251
|
credits: CreditActions;
|
|
4252
|
+
devices: DeviceActions;
|
|
4253
|
+
sessions: SessionActions;
|
|
4078
4254
|
}
|
|
4079
4255
|
interface BuildBaseResult extends ScopedActions {
|
|
4080
4256
|
/**
|
|
@@ -4118,6 +4294,8 @@ interface BuildBaseResult extends ScopedActions {
|
|
|
4118
4294
|
user: UserApi;
|
|
4119
4295
|
settings: SettingsApi;
|
|
4120
4296
|
push: PushApi;
|
|
4297
|
+
devices: DevicesApi;
|
|
4298
|
+
sessions: SessionsApi;
|
|
4121
4299
|
};
|
|
4122
4300
|
};
|
|
4123
4301
|
}
|