@buildbase/sdk 0.0.76 → 0.0.77
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 +31 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +11 -1
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -1
- package/dist/mcp/index.mjs +1 -1
- package/dist/react/chunks/{SettingsDialog-CYfoa5vT.mjs → SettingsDialog-jJxOT6-j.mjs} +1 -1
- package/dist/react/chunks/{SettingsDialog-CmDJLV6U.cjs → SettingsDialog-oJ031H7P.cjs} +1 -1
- package/dist/react/chunks/SubscriptionDialog-CDBtbbJi.mjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-DgBEfcU8.cjs +2 -0
- package/dist/react/chunks/react-4qMM6kB7.mjs +2 -0
- package/dist/react/chunks/react-6MIS8oUC.cjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +11 -1
- package/dist/react/index.mjs +1 -1
- package/dist/server/next/index.cjs +1 -1
- package/dist/server/next/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/react/chunks/SubscriptionDialog-DFn-IyC2.cjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-DfryE1jl.mjs +0 -2
- package/dist/react/chunks/react-FgrZjc24.mjs +0 -2
- package/dist/react/chunks/react-KC1YFLkh.cjs +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.0.77] - 2026-10-04
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **The plan picker offers only the billing intervals the plans actually
|
|
15
|
+
price.** It always drew Monthly, Quarterly and Yearly, so an organization
|
|
16
|
+
that sells monthly only showed two tabs that priced nothing - and the yearly
|
|
17
|
+
one carried a "Save" badge over no saving. The selector is now built from the
|
|
18
|
+
plans' own `pricingVariants` for the chosen currency, hides itself when there
|
|
19
|
+
is nothing to choose, and moves off an interval that stops being sold. New
|
|
20
|
+
`getAvailableBillingIntervals(planVersions, currency)` is exported for apps
|
|
21
|
+
that draw their own pricing table.
|
|
22
|
+
|
|
23
|
+
- **Content webhooks no longer warn on Next.js 16.** `createNextWebhookHandler`
|
|
24
|
+
called `revalidateTag(tag)`, which Next.js 16 deprecates and warns about for
|
|
25
|
+
every tag of every webhook. It now passes the `'max'` cache-life profile. In
|
|
26
|
+
a Route Handler, which a webhook is, that is the only profile Next.js 16
|
|
27
|
+
accepts, and `updateTag` - the call that drops the entry outright - is
|
|
28
|
+
refused outside a Server Action. So on Next.js 16 the first read after a
|
|
29
|
+
published edit is still served from the cache while it refreshes behind the
|
|
30
|
+
reader, and the next one has the new content. Next.js 13 to 15 take one
|
|
31
|
+
argument, ignore the second, and expire the entry immediately.
|
|
32
|
+
|
|
33
|
+
- **A refused request keeps its HTTP status and the server's code.** Calls
|
|
34
|
+
made through `fetchJson` (most of `WorkspaceApi`, including
|
|
35
|
+
`updateMyNotificationPreferences`) threw a bare `Error` with only the
|
|
36
|
+
message, so the documented `409` with `code: 'NOTIFICATION_PREFERENCE_REQUIRED'`
|
|
37
|
+
for a required event could not be told apart from an outage without parsing
|
|
38
|
+
text. The error now carries `status`, and `code` when the server sent one,
|
|
39
|
+
as errors from `BaseApi.throwResponseError` already did.
|
|
40
|
+
|
|
10
41
|
## [0.0.76] - 2026-10-02
|
|
11
42
|
|
|
12
43
|
### Fixed
|
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)}function n(e,...t){console.error(e,...t)}async function r(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function s(e,t="Request failed"){if(!e.ok){let n=t;try{const t=await r(e);n=t.message||t.error||n}catch{n=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(n)}try{return await r(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class i 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,i)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,r={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const s=e instanceof Error?e:new i("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",r),o=s instanceof i?s:new i(s.message,"SDK_ERROR",r,s);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${r.component||"Unknown"}:`,{message:o.message,code:o.code,context:o.context,originalError:o.originalError,stack:o.stack}),this.config.onError)try{this.config.onError(o,r)}catch(e){n("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(o,r)}catch(e){n("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(o,r)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...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 a(e,t={}){o.handleError(e,t)}function c(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return a(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function l(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){a(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function u(e,t){const n=c(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(a(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),l(e),null):r}catch(t){return a(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),l(e),null}}function d(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){a(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){a(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const p="saas-session-id",h="saas-device-id";function f(){return function(){if("undefined"==typeof window)return null;try{return c(p)}catch(e){return a(e,{component:"auth-utils",action:"getSessionId",metadata:{key:p}}),null}}()}function g(){const e=f(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return c(h)??null}catch(e){return a(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:h}}),null}}();return n&&(t["x-device-id"]=n),t}const w=new WeakSet,y=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),m="SDK is not ready (missing serverUrl, version, or orgId)";class k{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(m);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(m)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:g()}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){w.has(e)||(w.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=y.has(r);let c,l;if(this._timeout>0){l=new AbortController;const e=l;c=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?function(e,t){const 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 u=e=>{if(l?.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 k.delay(e,o.signal),d(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw u(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 k.delay(e,o.signal)}catch(e){throw u(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 r=await this.executeFetch(e,t);return await s(r,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 Object.assign(new Error(n),{status:e.status})}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 v extends k{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 k{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")}}function S(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))void 0!==r&&""!==r&&!1!==r&&t.set(n,String(r));const n=t.toString();return n?`?${n}`:""}const x=e=>JSON.stringify(e?{workspaceId:e}:{});class E extends k{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 I extends k{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 P extends k{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class A extends k{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:{}}}const $={NOT_FOUND:"INVITATION_NOT_FOUND",EXPIRED:"INVITATION_EXPIRED",ALREADY_HANDLED:"INVITATION_ALREADY_HANDLED",EMAIL_MISMATCH:"INVITATION_EMAIL_MISMATCH",EMAIL_NOT_VERIFIED:"EMAIL_NOT_VERIFIED",INVITES_DISABLED:"WORKSPACE_INVITES_DISABLED",RATE_LIMITED:"INVITATION_RATE_LIMITED",EMAIL_FAILED:"INVITATION_EMAIL_FAILED",SEAT_LIMIT:"SEAT_LIMIT_REACHED",USER_BLOCKED:"USER_BLOCKED",NO_SENDER_CONFIGURED:"NO_SENDER_CONFIGURED"},U={402:$.SEAT_LIMIT,404:$.NOT_FOUND,409:$.ALREADY_HANDLED,410:$.EXPIRED,429:$.RATE_LIMITED,502:$.EMAIL_FAILED,503:$.NO_SENDER_CONFIGURED};function C(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function T(e){return"string"==typeof e&&e?e:void 0}async function _(e,t){let n=null;try{n=await e.json()}catch{n=null}return function(e,t,n){const r=t&&"object"==typeof t?t:{},s=T(r.message)??T(r.error)??n,i={status:e,code:T(r.code)??U[e]??`HTTP_${e}`,currentUserCount:C(r.currentUserCount),limit:C(r.limit),retryAfterSeconds:C(r.retryAfterSeconds),invitedEmail:T(r.invitedEmail),invitationId:T(r.invitationId),invitationStatus:T(r.status)};return Object.assign(new Error(s),i)}(e.status,n,t)}class R extends k{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}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 fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await _(r,n);return s(r,n)}async listInvitations(e,t){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{signal:t},"Failed to fetch invitations")}async inviteMember(e,t,n){const r={email:t.email,role:t.role};return t.landingUrl&&(r.landingUrl=t.landingUrl),this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{method:"POST",body:JSON.stringify(r),signal:n},"Failed to send invitation")}async resendInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}/resend`,{method:"POST",signal:n},"Failed to resend invitation")}async revokeInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}`,{method:"DELETE",signal:n},"Failed to revoke invitation")}async myInvitations(e){return this.fetchInvitation("invitations",{signal:e},"Failed to fetch your invitations")}async acceptInvitation(e,t,n){return this.fetchInvitation(this.apiPath`invitations/${e}/accept`,{method:"PATCH",signal:n,...t?.token?{body:JSON.stringify({token:t.token})}:{}},"Failed to accept invitation")}async declineInvitation(e,t){return this.fetchInvitation(this.apiPath`invitations/${e}/reject`,{method:"PATCH",signal:t},"Failed to decline invitation")}async previewInvitation(e,t){if(!this.orgId)throw new Error("orgId is required for previewInvitation");return this.fetchInvitation(this.apiPath`${this.orgId}/invitations/preview/${e}`,{signal:t},"Failed to load invitation")}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 getMyPermissions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/permissions/me`,{signal:t},"Failed to fetch 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 getMyNotificationPreferences(e,t){const n=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{signal:t},"Failed to fetch your notification preferences");return{defaults:n?.defaults??{},mine:n?.mine??{}}}async updateMyNotificationPreferences(e,t,n){const r=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update your notification preferences");return{defaults:r?.defaults??{},mine:r?.mine??{}}}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 O={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",WorkspaceInvitationSent:"workspace:invitation-sent",WorkspaceInvitationAccepted:"workspace:invitation-accepted",WorkspaceInvitationDeclined:"workspace:invitation-declined",WorkspaceInvitationRevoked:"workspace:invitation-revoked"};class N{constructor(){this.callbacks=null,this.listeners=new Map}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){a(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const n=this.listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch(t){a(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(O.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(O.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(O.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(O.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(O.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(O.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(O.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(O.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(O.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(O.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(O.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(O.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(O.WorkspaceDeleted,{workspace:e})}}const F=new N,W=globalThis;function D(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=W[t]??(W[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const L=D("credit-balance").invalidate,J=D("quota-usage").invalidate,M=D("subscription").invalidate,B="bb",j={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},V={Success:"success",Cancel:"cancel",Error:"error"},q={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function K(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(B,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}const z="__buildbaseBeforeLeave",G=globalThis,H=G[z]??(G[z]=new Set);function Q(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 Y="saas-auth-intent";function X(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}const Z={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:"฿"},ee={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function te(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Z[t]??t.toUpperCase()}const ne=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],re=ne.map(e=>({value:e,label:`${e.toUpperCase()} (${te(e)})`})),se=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),ie=new Set(["bhd","jod","kwd","omr","tnd"]),oe=new Map;function ae(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(se.has(t))return 0;if(ie.has(t))return 3;if("isk"===t)return 2;let n=oe.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}oe.set(t,n)}return n}function ce(e,t){const n=ae(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function le(e,t){return te(t)+ce(e,t)}const ue={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const de={included:"included",then:"then",hardLimit:"hard limit"};const pe={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"};function he(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 fe(e,t,n){const r=he(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function ge(e,t,n,r){const s=he(e,t),i=s?.quotaOverages?.[n];if(i)return i[r]}function we(e,t){const n=he(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function ye(e,t,n){const r=we(e,t);return r?.perSeat?r.perSeat[n]??null:null}function me(e,t){return Math.max(0,e-(t||0))}function ke(e,t,n,r){const s=we(e,t);if(!s)return null;return me(r,s.includedSeats)*(ye(e,t,n)??0)}const ve={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",WORKSPACE_USAGE_RECORD:"workspace:usage:record"},be=Object.values(ve),Se={admin:be.filter(e=>e!==ve.WORKSPACE_DELETE),editor:[ve.WORKSPACE_SETTINGS_VIEW,ve.WORKSPACE_MEMBERS_VIEW,ve.WORKSPACE_FEATURES_VIEW,ve.WORKSPACE_BILLING_VIEW,ve.WORKSPACE_USAGE_VIEW,ve.WORKSPACE_USAGE_RECORD],viewer:[ve.WORKSPACE_SETTINGS_VIEW,ve.WORKSPACE_MEMBERS_VIEW]},xe="viewer";function Ee(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 Ie(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(be);if(s)for(const t of Ee(s))e.add(t);if(n.permissions)for(const t of Ee(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of Ee(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);return i?Pe(i,e):new Set}function Pe(e,t,n={}){const{workspace:r,settings:s,appPermissions:i}=t;if(!r)return new Set;const o=r.permissions,a=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=e=>!!o&&e in o,d=e=>!!a&&e in a,p=e=>u(e)||d(e)||e in Se;let h,f=e;if(!p(e)){const e=s?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;f=e}h=u(f)?c(o[f]):d(f)?c(a[f]):Se[f]??[];const g=new Set(h),w=new Set((s?.workspace?.customPermissions??[]).map(e=>e.key)),y=i?.[f]?l(i[f]).filter(e=>!w.has(e)):[];let m;m=u(f)?l(o[f]):d(f)?[...l(a[f]),...y]:i?.[f]?l(i[f]):[];for(const e of m)g.add(e);if("admin"===f){for(const e of Se.admin)g.add(e);for(const e of w)g.add(e);if(i)for(const e of l(Ee(i)))g.add(e)}return!1!==n.applyRestrictions&&function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(ve.WORKSPACE_MEMBERS_INVITE)}(g,f,s),g}function Ae(e,t){const n=Ie(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const $e="App";var Ue;function Ce(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function Te(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||Ce(n.invitedAt)-Ce(e.invitedAt))}function _e(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||Ce(e.validTill)>t.getTime())}exports.AuthStatus=void 0,(Ue=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",Ue.redirecting="redirecting",Ue.authenticated="authenticated",Ue.unauthenticated="unauthenticated",Ue.authenticating="authenticating";const Re="saas-pending-invite",Oe=/^[0-9a-f]{64}$/;function Ne(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}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]),We=(e,t)=>e>>>t|e<<32-t;function De(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,o=2600822924,a=528734635,c=1541459225;const l=e.length,u=l+1,d=u+(56-u%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[l]=128;const h=8*l,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const w=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;w[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=We(w[e-15],7)^We(w[e-15],18)^w[e-15]>>>3,n=We(w[e-2],17)^We(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+n>>>0}let l=t,u=n,d=r,h=s,f=i,g=o,y=a,m=c;for(let e=0;e<64;e++){const t=m+(We(f,6)^We(f,11)^We(f,25))+(f&g^~f&y)+Fe[e]+w[e]>>>0,n=l&u^l&d^u&d;m=y,y=g,g=f,f=h+t>>>0,h=d,d=u,u=l,l=t+((We(l,2)^We(l,13)^We(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+u>>>0,r=r+d>>>0,s=s+h>>>0,i=i+f>>>0,o=o+g>>>0,a=a+y>>>0,c=c+m>>>0}const y=new Uint8Array(32),m=[t,n,r,s,i,o,a,c];for(let e=0;e<8;e++)y[4*e]=m[e]>>>24&255,y[4*e+1]=m[e]>>>16&255,y[4*e+2]=m[e]>>>8&255,y[4*e+3]=255&m[e];return y}function Le(e){return(new TextEncoder).encode(e)}function Je(e,t){let n=e;n.length>64&&(n=De(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=De(Be(r,t));return De(Be(s,i))}function Me(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 Be(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function je(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 l=Je(Le(s),Le(`${r}.${t}`));return c.length===l.length&&Me(c,l)}const Ve=300,qe="/.well-known/oauth-protected-resource",Ke="/.well-known/agent-skills",ze="/.well-known/api-catalog",Ge="/.well-known/mcp/server-card.json",He="/.well-known/agent-card.json",Qe="application/json",Ye="application/linkset+json",Xe="text/markdown; charset=utf-8",Ze="text/plain; charset=utf-8",et="application/xml; charset=utf-8",tt=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function nt(e){return e.replace(/\/+$/,"")}function rt(e){return`public, max-age=${e}, s-maxage=${e}`}function st(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}(De(Le(e)))}const it=new Map;async function ot(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 at(e){const t=e.cacheTtlSeconds??Ve,n=`${nt(e.serverUrl)}::${e.orgId}`,r=it.get(n);if(r&&r.expiresAt>Date.now())return r.value;const s=e.fetch??fetch,i=`${nt(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let o={enabled:!1};try{const t=await ot(s,i,{headers:{Accept:Qe}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(o=e)}}catch{}return it.set(n,{value:o,expiresAt:Date.now()+1e3*t}),o}const ct=new Map;function lt(e,t){const n=nt(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:qe};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=ze),e.mcpServerCard&&(r.mcp_server_card=Ge),!1!==e.a2aCard&&(r.a2a_agent_card=He),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return Pt({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 ut(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return qe+n}function dt(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||qe,i=n??`${nt(t.serverUrl)}/org/${t.orgId}`,o=t.scopes?.map(e=>e.name),a=r.map(e=>{const n=e.resource??nt(t.siteUrl),r=e.scopes??o;return{path:ut(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?Pt(c.metadata,t):s===qe&&1===a.length?Pt(a[0].metadata,t):null}function pt(e){const t=e.skills??[];if(!t.length)return null;const n=nt(e.siteUrl);return Pt({$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}${ht(e)}`,digest:st(e.content)}))},e)}function ht(e){return e.path??`${Ke}/${e.name}/SKILL.md`}function ft(e,t){const n=(t.skills??[]).find(t=>ht(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:rt(t.cacheTtlSeconds??Ve)}:null}function gt(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:Ze,body:t.join("\n")+"\n",cacheControl:rt(e.cacheTtlSeconds??Ve)}}function wt(e){return e.llmsTxt?{status:200,contentType:Ze,body:e.llmsTxt,cacheControl:rt(e.cacheTtlSeconds??Ve)}:null}function yt(e){return e.llmsFullTxt?{status:200,contentType:Ze,body:e.llmsFullTxt,cacheControl:rt(e.cacheTtlSeconds??Ve)}:null}function mt(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=nt(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 Pt({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 kt(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:rt(e.cacheTtlSeconds??Ve)}:null}function vt(e){return e.endsWith(".json")||e.includes(".well-known/")?Qe:e.endsWith(".md")?Xe:e.endsWith(".xml")?et:Ze}function bt(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:Ye,body:JSON.stringify({linkset:n},null,2),cacheControl:rt(e.cacheTtlSeconds??Ve)}}function St(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 xt(e){const t=e.mcpServerCard;return t?Pt({$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:St(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function Et(e){const t=e.mcpServerCard;if(!t)return null;const n=nt(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${ut(t.endpoint)}`}}catch{}return Pt({$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:St(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${Ge}`,...r?{authentication:r}:{}}]},e)}function It(e,t){const n=rt(e.cacheTtlSeconds??Ve);if(e.authMd)return{status:200,contentType:Xe,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const s=`# 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:Xe,body:s,cacheControl:n}}function Pt(e,t){return{status:200,contentType:Qe,body:JSON.stringify(e,null,2),cacheControl:rt(t.cacheTtlSeconds??Ve)}}function At(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function $t(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${At(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: ${At(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${At(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${At(e.crawlDelay)}`),n.join("\n")}function Ut(e){const t=e.robots??{},n=nt(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",i="allow"===s?[{userAgent:[...tt],allow:["/"]}]:"deny"===s?[{userAgent:[...tt],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)=>$t(e,0===n?t.contentSignals:void 0)),...i.map(e=>$t(e)),...o.length?[o.map(e=>`Sitemap: ${At(e)}`).join("\n")]:[]];return{status:200,contentType:Ze,body:a.join("\n\n")+"\n",cacheControl:rt(e.cacheTtlSeconds??Ve)}}function Ct(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Tt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function _t(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=nt(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>${Tt(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Tt(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Tt(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:et,body:r,cacheControl:rt(e.cacheTtlSeconds??Ve)}}function Rt(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 Ot(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return lt(t,await at(t))}if(n===He)return mt(t);if("/.well-known/http-message-signatures-directory"===n)return kt(t);if("/.well-known/security.txt"===n)return gt(t);if(n===`${Ke}/index.json`)return pt(t);if(n.startsWith(`${Ke}/`)&&n.endsWith("SKILL.md"))return ft(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await at(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??Ve,r=ct.get(e);if(r&&r.expiresAt>Date.now())return r.value;const s=t.fetch??fetch;let i=null;try{const n=await ot(s,e,{headers:{Accept:Qe}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(i=e)}}catch{}return ct.set(e,{value:i,expiresAt:Date.now()+1e3*n}),i}(e.metadataUrl,t);return Pt(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===ze)return bt(t);if(n===Ge)return xt(t);if("/.well-known/mcp.json"===n)return Et(t);if(n.startsWith(qe)){const e=await at(t);return dt(n,t,e.authorizationServer?.issuer)}return null}function Nt(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 Wt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function Dt(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 Lt(e,t,n={}){const r=n.clockToleranceSec??60,s=n.requireExp??!0;if(!e||!t)throw new Wt("invalid_token","Missing token or client secret");const i=e.split(".");if(3!==i.length)throw new Wt("invalid_token","Malformed JWT");const[o,a,c]=i;let l,u;try{l=Dt(o),u=Dt(a)}catch{throw new Wt("invalid_token","Unreadable JWT segments")}if("HS256"!==l.alg)throw new Wt("invalid_algorithm",`Unexpected JWT alg: ${String(l.alg)}`);const d=Je(Le(t),Le(`${o}.${a}`));let p;try{p=Ft(c)}catch{throw new Wt("invalid_signature","Unreadable JWT signature")}if(!Me(d,p))throw new Wt("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 Wt("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 Wt("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 Wt("invalid_token","JWT aud claim must be a string or string array")}(u);const h=Math.floor(Date.now()/1e3);if(s&&"number"!=typeof u.exp)throw new Wt("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof u.exp&&h>u.exp+r)throw new Wt("token_expired","JWT has expired");if("number"==typeof u.nbf&&h+r<u.nbf)throw new Wt("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&u.iss!==n.issuer)throw new Wt("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=u.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new Wt("invalid_audience","JWT audience mismatch")}return u}function Jt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function Mt(e){return Nt(Le(JSON.stringify(e)))}function Bt(e,t,n){if(!t)throw new Wt("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),s={iat:r,exp:r+(n?.expiresInSec??3600),...e},i=`${Mt({alg:"HS256",typ:"JWT"})}.${Mt(s)}`;return`${i}.${Nt(Je(Le(t),Le(i)))}`}function jt(e){const t=Jt(e.authorization);if(!t)throw new Wt("invalid_token","Missing Bearer token");return Lt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function Vt(e){const t=Jt(e.authorization);if(!t)throw new Wt("invalid_token","Missing Bearer token");return Lt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function qt(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 zt(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}const Gt=12,Ht=16;function Qt(){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 Yt=new Map;function Xt(e){let t=Yt.get(e);return t||(t=(async()=>{const t=await Qt().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return Qt().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),Yt.set(e,t)),t}function Zt(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(Gt)),r=await Xt(e),s=new Uint8Array(await Qt().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),i=s.subarray(s.length-Ht),o=s.subarray(0,s.length-Ht),a=new Uint8Array(28+o.length);return a.set(n,0),a.set(i,Gt),a.set(o,28),Nt(a)},async decryptSessionRef(t){try{const n=Ft(t);if(n.length<=28)return null;const r=n.slice(0,Gt),s=n.subarray(Gt,28),i=n.subarray(28),o=new Uint8Array(i.length+Ht);o.set(i,0),o.set(s,i.length);const a=await Xt(e),c=await Qt().decrypt({name:"AES-GCM",iv:r},a,o);return(new TextDecoder).decode(c)}catch{return null}}}}function en(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 tn(e){const{serverUrl:t,orgId:n,version:r="v1",getSessionId:s,timeout:i,maxRetries:o,debug:a,headers:c,onError:l,fetch:u}=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},...l&&{onError:l},...u&&{fetch:u}},p=e=>{const s={serverUrl:t,version:r,orgId:n,sessionId:e,...d};return{workspace:new R(s),user:new A(s),settings:new P(s),push:new E(s),devices:new b(s),sessions:new I(s)}},h=new R({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),permissions:async t=>(await e()).workspace.getMyPermissions(t),can:async(t,n)=>{const{permissions:r}=await(await e()).workspace.getMyPermissions(t),s=new Set(r);return(Array.isArray(n)?n:[n]).every(e=>s.has(e))}},invitations:{list:async t=>(await e()).workspace.listInvitations(t),create:async(t,n,r,s)=>(await e()).workspace.inviteMember(t,{email:n,role:r,landingUrl:s}),resend:async(t,n)=>(await e()).workspace.resendInvitation(t,n),revoke:async(t,n)=>(await e()).workspace.revokeInvitation(t,n)},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 Ae(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 Ie({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=tt,exports.APP_PERMISSION_FALLBACK_GROUP=$e,exports.AppBridgeError=Wt,exports.AuthApi=class extends k{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let s=await r(e);if(400===s.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:i,invitationToken:o,...a}=e;s=await r(a)}return s.ok||await this.throwResponseError(s,n),this.unwrapResponse(s,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""}}async logout(e,t,n){await this.fetchJson("logout",{method:"POST",...e?{headers:{"x-session-id":e}}:{},...t?.all?{body:JSON.stringify({all:!0})}:{},signal:n},"Failed to sign out")}},exports.BBAction=j,exports.BBScreen=q,exports.BBStatus=V,exports.BB_PARAM=B,exports.BaseApi=k,exports.BetaForm=class{constructor(e){this.api=new v(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=pe,exports.BuildBase=tn,exports.CURRENCY_DISPLAY=Z,exports.CURRENCY_FLAG=ee,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=Se,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EventEmitter=N,exports.FALLBACK_WORKSPACE_ROLE=xe,exports.INVITATION_ERROR_CODE=$,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.NotificationsApi=class extends k{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${S({workspaceId:e.workspaceId,unread:e.unread,archived:e.archived,page:e.page,limit:e.limit})}`,{signal:t},"Failed to load notifications");return{notifications:n?.notifications??[],page:n?.page??e.page??1,limit:n?.limit??e.limit??20,total:n?.total??0,hasNextPage:Boolean(n?.hasNextPage)}}async counts(e,t){const n=await this.fetchJson(`notifications/unread-count${S({workspaceId:e})}`,{signal:t},"Failed to load notification count");return{unread:n?.unread??0,unseen:n?.unseen??0}}markRead(e){return this.itemAction(this.apiPath`notifications/${e}/read`,"POST",!0)}markUnread(e){return this.itemAction(this.apiPath`notifications/${e}/unread`,"POST")}archive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"POST")}unarchive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"DELETE")}async markAllRead(e){await this.fetchJson("notifications/read-all",{method:"POST",body:x(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:x(e)},"Failed to mark notifications seen")}async itemAction(e,t,n=!1){return this.fetchJson(e,n?{method:t,keepalive:n}:{method:t},"Failed to update notification")}},exports.PLAN_CURRENCY_CODES=ne,exports.PLAN_CURRENCY_OPTIONS=re,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=ve,exports.PushApi=E,exports.SDKEvent=O,exports.SettingsApi=P,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=A,exports.WorkspaceApi=R,exports.actionableInvitations=function(e,t=new Date){return Te(e.filter(e=>_e(e,t)))},exports.appPermissionCatalogue=function(e,t){const n=e?.workspace?.customPermissions??[],r=new Map;for(const e of n)e?.key&&!e.key.startsWith("workspace:")&&r.set(e.key,{key:e.key,label:e.label||e.key,group:e.group||$e});for(const e of Object.values(t??{}))for(const t of e??[])t.startsWith("workspace:")||r.has(t)||r.set(t,{key:t,label:t,group:$e});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))},exports.appTokenFailure=Kt,exports.appTokenSuccess=qt,exports.bearerChallenge=function(e){const t=[`Bearer resource_metadata="${zt(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${zt(e.error)}"`),e.errorDescription&&t.push(`error_description="${zt(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}},exports.buildA2AAgentCard=mt,exports.buildAgentCard=lt,exports.buildAgentSkillsIndex=pt,exports.buildApiCatalog=bt,exports.buildAuthMd=It,exports.buildDiscoveryLinkHeader=function(e){const t=nt(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}${He}>; 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}${ze}>; rel="api-catalog"; type="${Ye}"`),e.mcpServerCard&&n.push(`<${t}${Ge}>; 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=yt,exports.buildLlmsTxt=wt,exports.buildMcpDiscoveryManifest=Et,exports.buildMcpServerCard=xt,exports.buildProtectedResourceMetadata=dt,exports.buildRobotsTxt=Ut,exports.buildSecurityTxt=gt,exports.buildSitemap=_t,exports.buildSkillMd=ft,exports.buildWebBotAuthDirectory=kt,exports.buildbaseAuth=function(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=Zt(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=Lt(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 en(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return en(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=me,exports.calculateSeatOverageCents=ke,exports.calculateTotalSubscriptionCents=function(e,t,n,r){const s=fe(e,t,n);return null===s?null:void 0===r?s:s+(ke(e,t,n,r)??0)},exports.cleanBBParams=function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(B)&&(e.searchParams.delete(B),window.history.replaceState({},"",e.toString()))}catch{}},exports.clearAgentReadinessCache=function(){it.clear(),ct.clear()},exports.clearAuthIntent=function(){l(Y)},exports.clearPendingInvite=function(){l(Re)},exports.consumeAuthIntent=function(){const e=u(Y,X);return l(Y),e?Date.now()-e.createdAt>6e5?null:Q(e.returnUrl,{sameOrigin:!0}):null},exports.createBBUrl=K,exports.createCheckoutRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:K({action:j.Checkout,status:V.Success,ws:e,screen:q.Subscription},n),cancelUrl:K({action:j.Checkout,status:V.Cancel,ws:e,screen:q.Subscription},n)}},exports.createCreditPurchaseRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:K({action:j.CreditPurchase,status:V.Success,ws:e,screen:q.Credits},n),cancelUrl:K({action:j.CreditPurchase,status:V.Cancel,ws:e,screen:q.Credits},n)}},exports.createSessionRefCrypto=Zt,exports.default=tn,exports.eventEmitter=F,exports.extractBearerToken=Jt,exports.fetchAgentReadiness=at,exports.formatCents=le,exports.formatMinorAmountIntl=function(e,t,n="en-US"){const r=(t??"").trim(),s=ae(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 te(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={...ue,...r},o=null!=t&&t>=1?t:1,a=te(n),c=ce(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={...ue,...i},c=null!=t&&t>=1?t:1,l=te(r),u=ce(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${u}/${c.toLocaleString(o)} ${e}`:`${l}${u}/${n}`}return 1===c?`${l}${u}/${a.unit}`:`${l}${u}/${c.toLocaleString(o)} ${a.units}`},exports.formatQuotaIncludedOverage=function(e,t,n,r,s,i,o,a,c){const l={...ue,...o};if(!1===a)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:o?.hardLimit??"Hard limit";const u=i??(n.endsWith("s")?n:`${n}s`),d=null!=s&&s>=2?`${s.toLocaleString(c)} ${u}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${le(t,r)}/${d}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${le(t,r)}/${d}`:"—"},exports.formatQuotaWithPrice=function(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,i={...de,...n.labels},o=n.currencySymbol??te(s??"");if(null==e)return"—";const{included:a,overage:c}=e,l=`${a} ${i.included}`;if(!1===e.allowOverage)return`${l} (${i.hardLimit})`;if(null==c)return l;const u=ae(s),d=r&&u>0?c/10**u:c,p="number"==typeof d&&Number.isFinite(d)?0===u?d.toLocaleString("en-US"):d.toFixed(u):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${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=fe,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=ae,exports.getCurrencyFlag=function(e){return e&&e.trim()?ee[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=te,exports.getDisplayCurrency=function(e,t){const n=he(e,t);return n?n.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=ye,exports.getPricingVariant=he,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=ge(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=ge,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=we,exports.getStripePriceIdForInterval=function(e,t,n){const r=he(e,t);if(!r?.stripePrices)return null;const s=n===pe.Monthly?"monthlyPriceId":n===pe.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===pe.Monthly?"monthly":n===pe.Yearly?"yearly":void 0;return r.stripePrices[s]??(i?r.stripePrices[i]:void 0)??null},exports.handleAppRevokeRequest=async function(e){let t;try{t=Vt(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof Wt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}},exports.handleAppTokenRequest=async function(e){let t;try{t=jt(e)}catch(e){return{status:401,body:Kt(e instanceof Wt?e.code:"invalid_token")}}return{status:200,body:qt(await e.mintToken(t))}},exports.hasPermission=Ae,exports.invalidateCreditBalance=L,exports.invalidateQuotaUsage=J,exports.invalidateSubscription=M,exports.inviterNameOf=function(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null},exports.isInvitationActionable=_e,exports.isInvitationError=function(e){return e instanceof Error&&"number"==typeof e.status},exports.isInvitationLapsed=function(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!_e(e,t)},exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===ae(e)},exports.minorAmountToDisplay=ce,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 Zt(n).encryptSessionRef(t.sessionId):void 0;return{token:Bt({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=Rt(e);return{status:200,contentType:r?Xe:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:rt(n?.cacheTtlSeconds??Ve),vary:"Accept"}},exports.parkPendingInvite=function(e,t){Oe.test(e)&&t&&d(Re,{token:e,orgId:t,createdAt:Date.now()})},exports.parseWebhookEvent=function(e){if(!je(e))return null;try{return JSON.parse(e.body)}catch{return null}},exports.pickDefaultRole=function(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(xe)?xe:e.find(e=>"admin"!==e)??""},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(B);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.readPendingInvite=function(e,t=Date.now()){const n=u(Re,Ne);return n?t-n.createdAt>864e5?(l(Re),null):n.orgId!==e?null:Oe.test(n.token)?n.token:(l(Re),null):null},exports.resendCooldownSeconds=function(e,t=new Date){const n=Ce(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0},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??vt(e),body:r.body,cacheControl:r.cacheControl??rt(t.cacheTtlSeconds??Ve)}}(n,t);return r||("/robots.txt"===n?Ut(t):"/llms-full.txt"===n?yt(t):"/sitemap.xml"===n?_t(t):"/llms.txt"===n?wt(t):"/auth.md"===n?It(t,await at(t)):"/security.txt"===n?gt(t):n.startsWith("/.well-known")?Ot(n,t):null)},exports.resolveMaxUsers=function(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=we(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=Ie,exports.resolveRolePermissions=Pe,exports.resolveWellKnown=Ot,exports.safeRedirect=function(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=Q(e,n)??Q(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===H.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of H)try{e()}catch{}}(r),window.location.href=r,!0},exports.saveAuthIntent=function(e){Q(e,{sameOrigin:!0})&&d(Y,{returnUrl:e,createdAt:Date.now()})},exports.sha256Digest=st,exports.signClientJwt=Bt,exports.sortInvitations=Te,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=Q,exports.verifyAppRevokeRequest=Vt,exports.verifyAppTokenRequest=jt,exports.verifyClientJwt=Lt,exports.verifyWebhookSignature=je,exports.wantsMarkdown=Rt,exports.workspaceIdOf=function(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace},exports.workspaceNameOf=function(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""};
|
|
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)}function n(e,...t){console.error(e,...t)}async function r(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function s(e,t="Request failed"){if(!e.ok){let n,s=t;try{const t=await r(e);s=t.message||t.error||s,"string"==typeof t.code&&(n=t.code)}catch{s=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 Object.assign(new Error(s),{status:e.status,...n?{code:n}:{}})}try{return await r(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class i 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,i)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,r={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const s=e instanceof Error?e:new i("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",r),o=s instanceof i?s:new i(s.message,"SDK_ERROR",r,s);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${r.component||"Unknown"}:`,{message:o.message,code:o.code,context:o.context,originalError:o.originalError,stack:o.stack}),this.config.onError)try{this.config.onError(o,r)}catch(e){n("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(o,r)}catch(e){n("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(o,r)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...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 a(e,t={}){o.handleError(e,t)}function c(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return a(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function l(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){a(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function u(e,t){const n=c(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(a(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),l(e),null):r}catch(t){return a(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),l(e),null}}function d(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){a(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){a(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const p="saas-session-id",h="saas-device-id";function f(){return function(){if("undefined"==typeof window)return null;try{return c(p)}catch(e){return a(e,{component:"auth-utils",action:"getSessionId",metadata:{key:p}}),null}}()}function g(){const e=f(),t={};e&&(t["x-session-id"]=e);const n=function(){if("undefined"==typeof window)return null;try{return c(h)??null}catch(e){return a(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:h}}),null}}();return n&&(t["x-device-id"]=n),t}const w=new WeakSet,y=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),m="SDK is not ready (missing serverUrl, version, or orgId)";class k{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(m);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(m)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:g()}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){w.has(e)||(w.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=y.has(r);let c,l;if(this._timeout>0){l=new AbortController;const e=l;c=setTimeout(()=>e.abort(),this._timeout),o.signal=t.signal?function(e,t){const 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 u=e=>{if(l?.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 k.delay(e,o.signal),d(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw u(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 k.delay(e,o.signal)}catch(e){throw u(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 r=await this.executeFetch(e,t);return await s(r,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 Object.assign(new Error(n),{status:e.status})}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 v extends k{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 k{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")}}function S(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))void 0!==r&&""!==r&&!1!==r&&t.set(n,String(r));const n=t.toString();return n?`?${n}`:""}const x=e=>JSON.stringify(e?{workspaceId:e}:{});class E extends k{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 I extends k{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 P extends k{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class A extends k{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:{}}}const $={NOT_FOUND:"INVITATION_NOT_FOUND",EXPIRED:"INVITATION_EXPIRED",ALREADY_HANDLED:"INVITATION_ALREADY_HANDLED",EMAIL_MISMATCH:"INVITATION_EMAIL_MISMATCH",EMAIL_NOT_VERIFIED:"EMAIL_NOT_VERIFIED",INVITES_DISABLED:"WORKSPACE_INVITES_DISABLED",RATE_LIMITED:"INVITATION_RATE_LIMITED",EMAIL_FAILED:"INVITATION_EMAIL_FAILED",SEAT_LIMIT:"SEAT_LIMIT_REACHED",USER_BLOCKED:"USER_BLOCKED",NO_SENDER_CONFIGURED:"NO_SENDER_CONFIGURED"},U={402:$.SEAT_LIMIT,404:$.NOT_FOUND,409:$.ALREADY_HANDLED,410:$.EXPIRED,429:$.RATE_LIMITED,502:$.EMAIL_FAILED,503:$.NO_SENDER_CONFIGURED};function C(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function T(e){return"string"==typeof e&&e?e:void 0}async function _(e,t){let n=null;try{n=await e.json()}catch{n=null}return function(e,t,n){const r=t&&"object"==typeof t?t:{},s=T(r.message)??T(r.error)??n,i={status:e,code:T(r.code)??U[e]??`HTTP_${e}`,currentUserCount:C(r.currentUserCount),limit:C(r.limit),retryAfterSeconds:C(r.retryAfterSeconds),invitedEmail:T(r.invitedEmail),invitationId:T(r.invitationId),invitationStatus:T(r.status)};return Object.assign(new Error(s),i)}(e.status,n,t)}class R extends k{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){try{return await this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}catch(n){const r=n?.status;if(400===r&&e.trackingAttribution){const{trackingAttribution:n,...r}=e;return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(r),signal:t},"Failed to create workspace")}throw n}}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 fetchInvitation(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);if(!r.ok)throw await _(r,n);return s(r,n)}async listInvitations(e,t){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{signal:t},"Failed to fetch invitations")}async inviteMember(e,t,n){const r={email:t.email,role:t.role};return t.landingUrl&&(r.landingUrl=t.landingUrl),this.fetchInvitation(this.apiPath`workspaces/${e}/invitations`,{method:"POST",body:JSON.stringify(r),signal:n},"Failed to send invitation")}async resendInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}/resend`,{method:"POST",signal:n},"Failed to resend invitation")}async revokeInvitation(e,t,n){return this.fetchInvitation(this.apiPath`workspaces/${e}/invitations/${t}`,{method:"DELETE",signal:n},"Failed to revoke invitation")}async myInvitations(e){return this.fetchInvitation("invitations",{signal:e},"Failed to fetch your invitations")}async acceptInvitation(e,t,n){return this.fetchInvitation(this.apiPath`invitations/${e}/accept`,{method:"PATCH",signal:n,...t?.token?{body:JSON.stringify({token:t.token})}:{}},"Failed to accept invitation")}async declineInvitation(e,t){return this.fetchInvitation(this.apiPath`invitations/${e}/reject`,{method:"PATCH",signal:t},"Failed to decline invitation")}async previewInvitation(e,t){if(!this.orgId)throw new Error("orgId is required for previewInvitation");return this.fetchInvitation(this.apiPath`${this.orgId}/invitations/preview/${e}`,{signal:t},"Failed to load invitation")}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 getMyPermissions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/permissions/me`,{signal:t},"Failed to fetch 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 getMyNotificationPreferences(e,t){const n=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{signal:t},"Failed to fetch your notification preferences");return{defaults:n?.defaults??{},mine:n?.mine??{}}}async updateMyNotificationPreferences(e,t,n){const r=await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences/me`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update your notification preferences");return{defaults:r?.defaults??{},mine:r?.mine??{}}}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 O={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",WorkspaceInvitationSent:"workspace:invitation-sent",WorkspaceInvitationAccepted:"workspace:invitation-accepted",WorkspaceInvitationDeclined:"workspace:invitation-declined",WorkspaceInvitationRevoked:"workspace:invitation-revoked"};class N{constructor(){this.callbacks=null,this.listeners=new Map}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){a(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}const n=this.listeners.get(e);if(n)for(const r of[...n])try{r(t)}catch(t){a(t,{component:"EventEmitter",action:"notifyListener",metadata:{eventType:e}})}}on(e,t){const n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{this.listeners.get(e)?.delete(t)}}async emitUserCreated(e){await this.emit(O.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(O.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(O.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(O.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(O.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceInvitationSent(e,t){await this.emit(O.WorkspaceInvitationSent,{invitation:e,workspaceId:t})}async emitWorkspaceInvitationAccepted(e,t){await this.emit(O.WorkspaceInvitationAccepted,{invitation:e,workspace:t})}async emitWorkspaceInvitationDeclined(e){await this.emit(O.WorkspaceInvitationDeclined,{invitation:e})}async emitWorkspaceInvitationRevoked(e,t){await this.emit(O.WorkspaceInvitationRevoked,{invitationId:e,workspaceId:t})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(O.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(O.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(O.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(O.WorkspaceDeleted,{workspace:e})}}const F=new N,W=globalThis;function D(e){const t=Symbol.for(`@buildbase/sdk.invalidation.${e}`),n=W[t]??(W[t]=new Set);return{subscribe:e=>(n.add(e),()=>{n.delete(e)}),invalidate(){n.forEach(e=>e())},reset(){n.clear()}}}const L=D("credit-balance").invalidate,M=D("quota-usage").invalidate,J=D("subscription").invalidate,B="bb",j={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},V={Success:"success",Cancel:"cancel",Error:"error"},q={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function K(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(B,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}const z="__buildbaseBeforeLeave",G=globalThis,H=G[z]??(G[z]=new Set);function Q(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 Y="saas-auth-intent";function X(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}const Z={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:"฿"},ee={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function te(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return Z[t]??t.toUpperCase()}const ne=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],re=ne.map(e=>({value:e,label:`${e.toUpperCase()} (${te(e)})`})),se=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]),ie=new Set(["bhd","jod","kwd","omr","tnd"]),oe=new Map;function ae(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(se.has(t))return 0;if(ie.has(t))return 3;if("isk"===t)return 2;let n=oe.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}oe.set(t,n)}return n}function ce(e,t){const n=ae(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function le(e,t){return te(t)+ce(e,t)}const ue={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};const de={included:"included",then:"then",hardLimit:"hard limit"};const pe={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"};function he(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 fe(e,t,n){const r=he(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function ge(e,t,n,r){const s=he(e,t),i=s?.quotaOverages?.[n];if(i)return i[r]}function we(e,t){const n=he(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function ye(e,t,n){const r=we(e,t);return r?.perSeat?r.perSeat[n]??null:null}function me(e,t){return Math.max(0,e-(t||0))}function ke(e,t,n,r){const s=we(e,t);if(!s)return null;return me(r,s.includedSeats)*(ye(e,t,n)??0)}const ve={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",WORKSPACE_USAGE_RECORD:"workspace:usage:record"},be=Object.values(ve),Se={admin:be.filter(e=>e!==ve.WORKSPACE_DELETE),editor:[ve.WORKSPACE_SETTINGS_VIEW,ve.WORKSPACE_MEMBERS_VIEW,ve.WORKSPACE_FEATURES_VIEW,ve.WORKSPACE_BILLING_VIEW,ve.WORKSPACE_USAGE_VIEW,ve.WORKSPACE_USAGE_RECORD],viewer:[ve.WORKSPACE_SETTINGS_VIEW,ve.WORKSPACE_MEMBERS_VIEW]},xe="viewer";function Ee(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 Ie(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(be);if(s)for(const t of Ee(s))e.add(t);if(n.permissions)for(const t of Ee(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of Ee(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);return i?Pe(i,e):new Set}function Pe(e,t,n={}){const{workspace:r,settings:s,appPermissions:i}=t;if(!r)return new Set;const o=r.permissions,a=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),l=e=>e.filter(e=>!e.startsWith("workspace:")),u=e=>!!o&&e in o,d=e=>!!a&&e in a,p=e=>u(e)||d(e)||e in Se;let h,f=e;if(!p(e)){const e=s?.workspace?.defaultRole;if(!e||"admin"===e||!p(e))return new Set;f=e}h=u(f)?c(o[f]):d(f)?c(a[f]):Se[f]??[];const g=new Set(h),w=new Set((s?.workspace?.customPermissions??[]).map(e=>e.key)),y=i?.[f]?l(i[f]).filter(e=>!w.has(e)):[];let m;m=u(f)?l(o[f]):d(f)?[...l(a[f]),...y]:i?.[f]?l(i[f]):[];for(const e of m)g.add(e);if("admin"===f){for(const e of Se.admin)g.add(e);for(const e of w)g.add(e);if(i)for(const e of l(Ee(i)))g.add(e)}return!1!==n.applyRestrictions&&function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(ve.WORKSPACE_MEMBERS_INVITE)}(g,f,s),g}function Ae(e,t){const n=Ie(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const $e="App";var Ue;function Ce(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isNaN(t)?0:t}function Te(e){const t=e=>"invited"===e.status?0:1;return[...e].sort((e,n)=>t(e)-t(n)||Ce(n.invitedAt)-Ce(e.invitedAt))}function _e(e,t=new Date){return"invited"===e.status&&(null===e.validTill||void 0===e.validTill||Ce(e.validTill)>t.getTime())}exports.AuthStatus=void 0,(Ue=exports.AuthStatus||(exports.AuthStatus={})).loading="loading",Ue.redirecting="redirecting",Ue.authenticated="authenticated",Ue.unauthenticated="unauthenticated",Ue.authenticating="authenticating";const Re="saas-pending-invite",Oe=/^[0-9a-f]{64}$/;function Ne(e){return"object"==typeof e&&null!==e&&"string"==typeof e.token&&"string"==typeof e.orgId&&"number"==typeof e.createdAt}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]),We=(e,t)=>e>>>t|e<<32-t;function De(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,o=2600822924,a=528734635,c=1541459225;const l=e.length,u=l+1,d=u+(56-u%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[l]=128;const h=8*l,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const w=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;w[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=We(w[e-15],7)^We(w[e-15],18)^w[e-15]>>>3,n=We(w[e-2],17)^We(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+n>>>0}let l=t,u=n,d=r,h=s,f=i,g=o,y=a,m=c;for(let e=0;e<64;e++){const t=m+(We(f,6)^We(f,11)^We(f,25))+(f&g^~f&y)+Fe[e]+w[e]>>>0,n=l&u^l&d^u&d;m=y,y=g,g=f,f=h+t>>>0,h=d,d=u,u=l,l=t+((We(l,2)^We(l,13)^We(l,22))+n>>>0)>>>0}t=t+l>>>0,n=n+u>>>0,r=r+d>>>0,s=s+h>>>0,i=i+f>>>0,o=o+g>>>0,a=a+y>>>0,c=c+m>>>0}const y=new Uint8Array(32),m=[t,n,r,s,i,o,a,c];for(let e=0;e<8;e++)y[4*e]=m[e]>>>24&255,y[4*e+1]=m[e]>>>16&255,y[4*e+2]=m[e]>>>8&255,y[4*e+3]=255&m[e];return y}function Le(e){return(new TextEncoder).encode(e)}function Me(e,t){let n=e;n.length>64&&(n=De(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=De(Be(r,t));return De(Be(s,i))}function Je(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 Be(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function je(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 l=Me(Le(s),Le(`${r}.${t}`));return c.length===l.length&&Je(c,l)}const Ve=300,qe="/.well-known/oauth-protected-resource",Ke="/.well-known/agent-skills",ze="/.well-known/api-catalog",Ge="/.well-known/mcp/server-card.json",He="/.well-known/agent-card.json",Qe="application/json",Ye="application/linkset+json",Xe="text/markdown; charset=utf-8",Ze="text/plain; charset=utf-8",et="application/xml; charset=utf-8",tt=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function nt(e){return e.replace(/\/+$/,"")}function rt(e){return`public, max-age=${e}, s-maxage=${e}`}function st(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}(De(Le(e)))}const it=new Map;async function ot(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 at(e){const t=e.cacheTtlSeconds??Ve,n=`${nt(e.serverUrl)}::${e.orgId}`,r=it.get(n);if(r&&r.expiresAt>Date.now())return r.value;const s=e.fetch??fetch,i=`${nt(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let o={enabled:!1};try{const t=await ot(s,i,{headers:{Accept:Qe}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(o=e)}}catch{}return it.set(n,{value:o,expiresAt:Date.now()+1e3*t}),o}const ct=new Map;function lt(e,t){const n=nt(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:qe};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=ze),e.mcpServerCard&&(r.mcp_server_card=Ge),!1!==e.a2aCard&&(r.a2a_agent_card=He),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return Pt({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 ut(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return qe+n}function dt(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||qe,i=n??`${nt(t.serverUrl)}/org/${t.orgId}`,o=t.scopes?.map(e=>e.name),a=r.map(e=>{const n=e.resource??nt(t.siteUrl),r=e.scopes??o;return{path:ut(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?Pt(c.metadata,t):s===qe&&1===a.length?Pt(a[0].metadata,t):null}function pt(e){const t=e.skills??[];if(!t.length)return null;const n=nt(e.siteUrl);return Pt({$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}${ht(e)}`,digest:st(e.content)}))},e)}function ht(e){return e.path??`${Ke}/${e.name}/SKILL.md`}function ft(e,t){const n=(t.skills??[]).find(t=>ht(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:rt(t.cacheTtlSeconds??Ve)}:null}function gt(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:Ze,body:t.join("\n")+"\n",cacheControl:rt(e.cacheTtlSeconds??Ve)}}function wt(e){return e.llmsTxt?{status:200,contentType:Ze,body:e.llmsTxt,cacheControl:rt(e.cacheTtlSeconds??Ve)}:null}function yt(e){return e.llmsFullTxt?{status:200,contentType:Ze,body:e.llmsFullTxt,cacheControl:rt(e.cacheTtlSeconds??Ve)}:null}function mt(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=nt(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 Pt({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 kt(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:rt(e.cacheTtlSeconds??Ve)}:null}function vt(e){return e.endsWith(".json")||e.includes(".well-known/")?Qe:e.endsWith(".md")?Xe:e.endsWith(".xml")?et:Ze}function bt(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:Ye,body:JSON.stringify({linkset:n},null,2),cacheControl:rt(e.cacheTtlSeconds??Ve)}}function St(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 xt(e){const t=e.mcpServerCard;return t?Pt({$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:St(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function Et(e){const t=e.mcpServerCard;if(!t)return null;const n=nt(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${ut(t.endpoint)}`}}catch{}return Pt({$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:St(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${Ge}`,...r?{authentication:r}:{}}]},e)}function It(e,t){const n=rt(e.cacheTtlSeconds??Ve);if(e.authMd)return{status:200,contentType:Xe,body:e.authMd,cacheControl:n};const r=t.authorizationServer;if(!r)return null;const s=`# 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:Xe,body:s,cacheControl:n}}function Pt(e,t){return{status:200,contentType:Qe,body:JSON.stringify(e,null,2),cacheControl:rt(t.cacheTtlSeconds??Ve)}}function At(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function $t(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${At(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: ${At(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${At(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${At(e.crawlDelay)}`),n.join("\n")}function Ut(e){const t=e.robots??{},n=nt(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",i="allow"===s?[{userAgent:[...tt],allow:["/"]}]:"deny"===s?[{userAgent:[...tt],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)=>$t(e,0===n?t.contentSignals:void 0)),...i.map(e=>$t(e)),...o.length?[o.map(e=>`Sitemap: ${At(e)}`).join("\n")]:[]];return{status:200,contentType:Ze,body:a.join("\n\n")+"\n",cacheControl:rt(e.cacheTtlSeconds??Ve)}}function Ct(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Tt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function _t(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=nt(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>${Tt(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Tt(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Tt(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:et,body:r,cacheControl:rt(e.cacheTtlSeconds??Ve)}}function Rt(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 Ot(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return lt(t,await at(t))}if(n===He)return mt(t);if("/.well-known/http-message-signatures-directory"===n)return kt(t);if("/.well-known/security.txt"===n)return gt(t);if(n===`${Ke}/index.json`)return pt(t);if(n.startsWith(`${Ke}/`)&&n.endsWith("SKILL.md"))return ft(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await at(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??Ve,r=ct.get(e);if(r&&r.expiresAt>Date.now())return r.value;const s=t.fetch??fetch;let i=null;try{const n=await ot(s,e,{headers:{Accept:Qe}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(i=e)}}catch{}return ct.set(e,{value:i,expiresAt:Date.now()+1e3*n}),i}(e.metadataUrl,t);return Pt(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===ze)return bt(t);if(n===Ge)return xt(t);if("/.well-known/mcp.json"===n)return Et(t);if(n.startsWith(qe)){const e=await at(t);return dt(n,t,e.authorizationServer?.issuer)}return null}function Nt(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 Wt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function Dt(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 Lt(e,t,n={}){const r=n.clockToleranceSec??60,s=n.requireExp??!0;if(!e||!t)throw new Wt("invalid_token","Missing token or client secret");const i=e.split(".");if(3!==i.length)throw new Wt("invalid_token","Malformed JWT");const[o,a,c]=i;let l,u;try{l=Dt(o),u=Dt(a)}catch{throw new Wt("invalid_token","Unreadable JWT segments")}if("HS256"!==l.alg)throw new Wt("invalid_algorithm",`Unexpected JWT alg: ${String(l.alg)}`);const d=Me(Le(t),Le(`${o}.${a}`));let p;try{p=Ft(c)}catch{throw new Wt("invalid_signature","Unreadable JWT signature")}if(!Je(d,p))throw new Wt("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 Wt("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 Wt("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 Wt("invalid_token","JWT aud claim must be a string or string array")}(u);const h=Math.floor(Date.now()/1e3);if(s&&"number"!=typeof u.exp)throw new Wt("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof u.exp&&h>u.exp+r)throw new Wt("token_expired","JWT has expired");if("number"==typeof u.nbf&&h+r<u.nbf)throw new Wt("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&u.iss!==n.issuer)throw new Wt("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=u.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new Wt("invalid_audience","JWT audience mismatch")}return u}function Mt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function Jt(e){return Nt(Le(JSON.stringify(e)))}function Bt(e,t,n){if(!t)throw new Wt("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),s={iat:r,exp:r+(n?.expiresInSec??3600),...e},i=`${Jt({alg:"HS256",typ:"JWT"})}.${Jt(s)}`;return`${i}.${Nt(Me(Le(t),Le(i)))}`}function jt(e){const t=Mt(e.authorization);if(!t)throw new Wt("invalid_token","Missing Bearer token");return Lt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function Vt(e){const t=Mt(e.authorization);if(!t)throw new Wt("invalid_token","Missing Bearer token");return Lt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function qt(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 zt(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}const Gt=12,Ht=16;function Qt(){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 Yt=new Map;function Xt(e){let t=Yt.get(e);return t||(t=(async()=>{const t=await Qt().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return Qt().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),Yt.set(e,t)),t}function Zt(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(Gt)),r=await Xt(e),s=new Uint8Array(await Qt().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),i=s.subarray(s.length-Ht),o=s.subarray(0,s.length-Ht),a=new Uint8Array(28+o.length);return a.set(n,0),a.set(i,Gt),a.set(o,28),Nt(a)},async decryptSessionRef(t){try{const n=Ft(t);if(n.length<=28)return null;const r=n.slice(0,Gt),s=n.subarray(Gt,28),i=n.subarray(28),o=new Uint8Array(i.length+Ht);o.set(i,0),o.set(s,i.length);const a=await Xt(e),c=await Qt().decrypt({name:"AES-GCM",iv:r},a,o);return(new TextDecoder).decode(c)}catch{return null}}}}function en(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 tn(e){const{serverUrl:t,orgId:n,version:r="v1",getSessionId:s,timeout:i,maxRetries:o,debug:a,headers:c,onError:l,fetch:u}=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},...l&&{onError:l},...u&&{fetch:u}},p=e=>{const s={serverUrl:t,version:r,orgId:n,sessionId:e,...d};return{workspace:new R(s),user:new A(s),settings:new P(s),push:new E(s),devices:new b(s),sessions:new I(s)}},h=new R({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),permissions:async t=>(await e()).workspace.getMyPermissions(t),can:async(t,n)=>{const{permissions:r}=await(await e()).workspace.getMyPermissions(t),s=new Set(r);return(Array.isArray(n)?n:[n]).every(e=>s.has(e))}},invitations:{list:async t=>(await e()).workspace.listInvitations(t),create:async(t,n,r,s)=>(await e()).workspace.inviteMember(t,{email:n,role:r,landingUrl:s}),resend:async(t,n)=>(await e()).workspace.resendInvitation(t,n),revoke:async(t,n)=>(await e()).workspace.revokeInvitation(t,n)},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 Ae(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 Ie({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=tt,exports.APP_PERMISSION_FALLBACK_GROUP=$e,exports.AppBridgeError=Wt,exports.AuthApi=class extends k{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=e=>this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});let s=await r(e);if(400===s.status&&(e.trackingConsent||e.trackingIdentity||e.trackingAttribution||e.invitationToken)){const{trackingConsent:t,trackingIdentity:n,trackingAttribution:i,invitationToken:o,...a}=e;s=await r(a)}return s.ok||await this.throwResponseError(s,n),this.unwrapResponse(s,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""}}async logout(e,t,n){await this.fetchJson("logout",{method:"POST",...e?{headers:{"x-session-id":e}}:{},...t?.all?{body:JSON.stringify({all:!0})}:{},signal:n},"Failed to sign out")}},exports.BBAction=j,exports.BBScreen=q,exports.BBStatus=V,exports.BB_PARAM=B,exports.BaseApi=k,exports.BetaForm=class{constructor(e){this.api=new v(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=pe,exports.BuildBase=tn,exports.CURRENCY_DISPLAY=Z,exports.CURRENCY_FLAG=ee,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=Se,exports.DunningState={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},exports.EventEmitter=N,exports.FALLBACK_WORKSPACE_ROLE=xe,exports.INVITATION_ERROR_CODE=$,exports.InvoiceStatuses={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},exports.NotificationsApi=class extends k{constructor(e){super(e)}async list(e={},t){const n=await this.fetchJson(`notifications${S({workspaceId:e.workspaceId,unread:e.unread,archived:e.archived,page:e.page,limit:e.limit})}`,{signal:t},"Failed to load notifications");return{notifications:n?.notifications??[],page:n?.page??e.page??1,limit:n?.limit??e.limit??20,total:n?.total??0,hasNextPage:Boolean(n?.hasNextPage)}}async counts(e,t){const n=await this.fetchJson(`notifications/unread-count${S({workspaceId:e})}`,{signal:t},"Failed to load notification count");return{unread:n?.unread??0,unseen:n?.unseen??0}}markRead(e){return this.itemAction(this.apiPath`notifications/${e}/read`,"POST",!0)}markUnread(e){return this.itemAction(this.apiPath`notifications/${e}/unread`,"POST")}archive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"POST")}unarchive(e){return this.itemAction(this.apiPath`notifications/${e}/archive`,"DELETE")}async markAllRead(e){await this.fetchJson("notifications/read-all",{method:"POST",body:x(e)},"Failed to mark notifications read")}async markSeen(e){await this.fetchJson("notifications/seen",{method:"POST",body:x(e)},"Failed to mark notifications seen")}async itemAction(e,t,n=!1){return this.fetchJson(e,n?{method:t,keepalive:n}:{method:t},"Failed to update notification")}},exports.PLAN_CURRENCY_CODES=ne,exports.PLAN_CURRENCY_OPTIONS=re,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=ve,exports.PushApi=E,exports.SDKEvent=O,exports.SettingsApi=P,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=A,exports.WorkspaceApi=R,exports.actionableInvitations=function(e,t=new Date){return Te(e.filter(e=>_e(e,t)))},exports.appPermissionCatalogue=function(e,t){const n=e?.workspace?.customPermissions??[],r=new Map;for(const e of n)e?.key&&!e.key.startsWith("workspace:")&&r.set(e.key,{key:e.key,label:e.label||e.key,group:e.group||$e});for(const e of Object.values(t??{}))for(const t of e??[])t.startsWith("workspace:")||r.has(t)||r.set(t,{key:t,label:t,group:$e});return[...r.values()].sort((e,t)=>(e.group??"").localeCompare(t.group??"")||e.key.localeCompare(t.key))},exports.appTokenFailure=Kt,exports.appTokenSuccess=qt,exports.bearerChallenge=function(e){const t=[`Bearer resource_metadata="${zt(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${zt(e.error)}"`),e.errorDescription&&t.push(`error_description="${zt(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}},exports.buildA2AAgentCard=mt,exports.buildAgentCard=lt,exports.buildAgentSkillsIndex=pt,exports.buildApiCatalog=bt,exports.buildAuthMd=It,exports.buildDiscoveryLinkHeader=function(e){const t=nt(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}${He}>; 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}${ze}>; rel="api-catalog"; type="${Ye}"`),e.mcpServerCard&&n.push(`<${t}${Ge}>; 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=yt,exports.buildLlmsTxt=wt,exports.buildMcpDiscoveryManifest=Et,exports.buildMcpServerCard=xt,exports.buildProtectedResourceMetadata=dt,exports.buildRobotsTxt=Ut,exports.buildSecurityTxt=gt,exports.buildSitemap=_t,exports.buildSkillMd=ft,exports.buildWebBotAuthDirectory=kt,exports.buildbaseAuth=function(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=Zt(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=Lt(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 en(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return en(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=me,exports.calculateSeatOverageCents=ke,exports.calculateTotalSubscriptionCents=function(e,t,n,r){const s=fe(e,t,n);return null===s?null:void 0===r?s:s+(ke(e,t,n,r)??0)},exports.cleanBBParams=function(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(B)&&(e.searchParams.delete(B),window.history.replaceState({},"",e.toString()))}catch{}},exports.clearAgentReadinessCache=function(){it.clear(),ct.clear()},exports.clearAuthIntent=function(){l(Y)},exports.clearPendingInvite=function(){l(Re)},exports.consumeAuthIntent=function(){const e=u(Y,X);return l(Y),e?Date.now()-e.createdAt>6e5?null:Q(e.returnUrl,{sameOrigin:!0}):null},exports.createBBUrl=K,exports.createCheckoutRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:K({action:j.Checkout,status:V.Success,ws:e,screen:q.Subscription},n),cancelUrl:K({action:j.Checkout,status:V.Cancel,ws:e,screen:q.Subscription},n)}},exports.createCreditPurchaseRedirectUrls=function(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:K({action:j.CreditPurchase,status:V.Success,ws:e,screen:q.Credits},n),cancelUrl:K({action:j.CreditPurchase,status:V.Cancel,ws:e,screen:q.Credits},n)}},exports.createSessionRefCrypto=Zt,exports.default=tn,exports.eventEmitter=F,exports.extractBearerToken=Mt,exports.fetchAgentReadiness=at,exports.formatCents=le,exports.formatMinorAmountIntl=function(e,t,n="en-US"){const r=(t??"").trim(),s=ae(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 te(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={...ue,...r},o=null!=t&&t>=1?t:1,a=te(n),c=ce(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={...ue,...i},c=null!=t&&t>=1?t:1,l=te(r),u=ce(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${l}${u}/${c.toLocaleString(o)} ${e}`:`${l}${u}/${n}`}return 1===c?`${l}${u}/${a.unit}`:`${l}${u}/${c.toLocaleString(o)} ${a.units}`},exports.formatQuotaIncludedOverage=function(e,t,n,r,s,i,o,a,c){const l={...ue,...o};if(!1===a)return null!=e?`${l.included}: ${e.toLocaleString(c)} (${l.hardLimit})`:o?.hardLimit??"Hard limit";const u=i??(n.endsWith("s")?n:`${n}s`),d=null!=s&&s>=2?`${s.toLocaleString(c)} ${u}`:n;return null!=e&&null!=t?`${l.included}: ${e.toLocaleString(c)}, ${l.afterThat} ${le(t,r)}/${d}`:null!=e?`${l.included}: ${e.toLocaleString(c)}`:null!=t?`${l.afterIncluded}: ${le(t,r)}/${d}`:"—"},exports.formatQuotaWithPrice=function(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,i={...de,...n.labels},o=n.currencySymbol??te(s??"");if(null==e)return"—";const{included:a,overage:c}=e,l=`${a} ${i.included}`;if(!1===e.allowOverage)return`${l} (${i.hardLimit})`;if(null==c)return l;const u=ae(s),d=r&&u>0?c/10**u:c,p="number"==typeof d&&Number.isFinite(d)?0===u?d.toLocaleString("en-US"):d.toFixed(u):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${l}, ${i.then} ${o}${p}${h}`},exports.getAvailableBillingIntervals=function(e,t){return[pe.Monthly,pe.Quarterly,pe.Yearly].filter(n=>n===pe.Monthly||e.some(e=>null!=fe(e,t,n)))},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=fe,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=ae,exports.getCurrencyFlag=function(e){return e&&e.trim()?ee[e.trim().toLowerCase()]??"":""},exports.getCurrencySymbol=te,exports.getDisplayCurrency=function(e,t){const n=he(e,t);return n?n.currency:e.plan?.currency??""},exports.getPerSeatPriceCents=ye,exports.getPricingVariant=he,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=ge(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=ge,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=we,exports.getStripePriceIdForInterval=function(e,t,n){const r=he(e,t);if(!r?.stripePrices)return null;const s=n===pe.Monthly?"monthlyPriceId":n===pe.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===pe.Monthly?"monthly":n===pe.Yearly?"yearly":void 0;return r.stripePrices[s]??(i?r.stripePrices[i]:void 0)??null},exports.handleAppRevokeRequest=async function(e){let t;try{t=Vt(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof Wt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}},exports.handleAppTokenRequest=async function(e){let t;try{t=jt(e)}catch(e){return{status:401,body:Kt(e instanceof Wt?e.code:"invalid_token")}}return{status:200,body:qt(await e.mintToken(t))}},exports.hasPermission=Ae,exports.invalidateCreditBalance=L,exports.invalidateQuotaUsage=M,exports.invalidateSubscription=J,exports.inviterNameOf=function(e){const t=e.invitedBy;return t&&"string"!=typeof t&&(t.name||t.email)||null},exports.isInvitationActionable=_e,exports.isInvitationError=function(e){return e instanceof Error&&"number"==typeof e.status},exports.isInvitationLapsed=function(e,t=new Date){return"expired"===e.status||"invited"===e.status&&!_e(e,t)},exports.isZeroDecimalCurrency=function(e){return""!==(e??"").trim()&&0===ae(e)},exports.minorAmountToDisplay=ce,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 Zt(n).encryptSessionRef(t.sessionId):void 0;return{token:Bt({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=Rt(e);return{status:200,contentType:r?Xe:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:rt(n?.cacheTtlSeconds??Ve),vary:"Accept"}},exports.parkPendingInvite=function(e,t){Oe.test(e)&&t&&d(Re,{token:e,orgId:t,createdAt:Date.now()})},exports.parseWebhookEvent=function(e){if(!je(e))return null;try{return JSON.parse(e.body)}catch{return null}},exports.pickDefaultRole=function(e,t){return t&&"admin"!==t&&e.includes(t)?t:e.includes(xe)?xe:e.find(e=>"admin"!==e)??""},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(B);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.readPendingInvite=function(e,t=Date.now()){const n=u(Re,Ne);return n?t-n.createdAt>864e5?(l(Re),null):n.orgId!==e?null:Oe.test(n.token)?n.token:(l(Re),null):null},exports.resendCooldownSeconds=function(e,t=new Date){const n=Ce(e.resendAvailableAt);return n?Math.max(0,Math.ceil((n-t.getTime())/1e3)):0},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??vt(e),body:r.body,cacheControl:r.cacheControl??rt(t.cacheTtlSeconds??Ve)}}(n,t);return r||("/robots.txt"===n?Ut(t):"/llms-full.txt"===n?yt(t):"/sitemap.xml"===n?_t(t):"/llms.txt"===n?wt(t):"/auth.md"===n?It(t,await at(t)):"/security.txt"===n?gt(t):n.startsWith("/.well-known")?Ot(n,t):null)},exports.resolveMaxUsers=function(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=we(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=Ie,exports.resolveRolePermissions=Pe,exports.resolveWellKnown=Ot,exports.safeRedirect=function(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=Q(e,n)??Q(t)??"/";return function(e){if("undefined"==typeof window||!window.location||0===H.size)return;let t;try{t=new URL(e,window.location.href).origin}catch{return}if(t!==window.location.origin)for(const e of H)try{e()}catch{}}(r),window.location.href=r,!0},exports.saveAuthIntent=function(e){Q(e,{sameOrigin:!0})&&d(Y,{returnUrl:e,createdAt:Date.now()})},exports.sha256Digest=st,exports.signClientJwt=Bt,exports.sortInvitations=Te,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=Q,exports.verifyAppRevokeRequest=Vt,exports.verifyAppTokenRequest=jt,exports.verifyClientJwt=Lt,exports.verifyWebhookSignature=je,exports.wantsMarkdown=Rt,exports.workspaceIdOf=function(e){return"object"==typeof e.workspace&&e.workspace?e.workspace._id:e.workspace},exports.workspaceNameOf=function(e){return"object"==typeof e.workspace&&e.workspace&&e.workspace.name||""};
|
package/dist/index.d.ts
CHANGED
|
@@ -2746,6 +2746,16 @@ declare function validateInvite(opts: {
|
|
|
2746
2746
|
hasSubscription?: boolean;
|
|
2747
2747
|
requireSubscription?: boolean;
|
|
2748
2748
|
}): InviteValidation;
|
|
2749
|
+
/**
|
|
2750
|
+
* The billing intervals a group of plans actually prices in a currency.
|
|
2751
|
+
*
|
|
2752
|
+
* The subscription dialog used to offer Monthly, Quarterly and Yearly always,
|
|
2753
|
+
* so an organization that prices monthly only showed two tabs that priced
|
|
2754
|
+
* nothing - and the yearly one even carried a "Save" badge. An interval is
|
|
2755
|
+
* offered when at least one of these plan versions has a base price for it.
|
|
2756
|
+
* Monthly is always included, so the selector never empties; order is stable.
|
|
2757
|
+
*/
|
|
2758
|
+
declare function getAvailableBillingIntervals(planVersions: IPlanVersion[], currency: string): BillingInterval[];
|
|
2749
2759
|
|
|
2750
2760
|
/** Minimal workspace shape needed for ownership/role checks. Extended by `permissions.WorkspaceLike`. */
|
|
2751
2761
|
interface WorkspaceLike$1 {
|
|
@@ -5194,5 +5204,5 @@ declare function buildbaseAuth(options: BuildBaseAuthOptions): {
|
|
|
5194
5204
|
resourceMetadataUrl?: string;
|
|
5195
5205
|
};
|
|
5196
5206
|
|
|
5197
|
-
export { AI_BOT_USER_AGENTS, APP_PERMISSION_FALLBACK_GROUP, ApiVersion, AppBridgeError, AuthApi, AuthStatus, BBAction, BBScreen, BBStatus, BB_PARAM, BaseApi, BetaForm, BillingIntervals, BuildBase, CURRENCY_DISPLAY, CURRENCY_FLAG, CreditBucketSource, CreditBucketStatus, CreditTransactionType, DEFAULT_ROLE_PERMISSIONS, DunningState, EventEmitter, FALLBACK_WORKSPACE_ROLE, INVITATION_ERROR_CODE, InvoiceStatuses, NotificationsApi, PLAN_CURRENCY_CODES, PLAN_CURRENCY_OPTIONS, PUSH_SERVICE_WORKER_SCRIPT, Permission, PushApi, SDKEvent, SettingsApi, SubscriptionItemType, SubscriptionStatus, UserApi, WorkspaceApi, actionableInvitations, appPermissionCatalogue, appTokenFailure, appTokenSuccess, bearerChallenge, buildA2AAgentCard, buildAgentCard, buildAgentSkillsIndex, buildApiCatalog, buildAuthMd, buildDiscoveryLinkHeader, buildDnsAidRecords, buildLlmsFullTxt, buildLlmsTxt, buildMcpDiscoveryManifest, buildMcpServerCard, buildProtectedResourceMetadata, buildRobotsTxt, buildSecurityTxt, buildSitemap, buildSkillMd, buildWebBotAuthDirectory, buildbaseAuth, calculateBillableSeats, calculateSeatOverageCents, calculateTotalSubscriptionCents, cleanBBParams, clearAgentReadinessCache, clearAuthIntent, clearPendingInvite, consumeAuthIntent, createBBUrl, createCheckoutRedirectUrls, createCreditPurchaseRedirectUrls, createSessionRefCrypto, BuildBase as default, eventEmitter, extractBearerToken, fetchAgentReadiness, formatCents, formatMinorAmountIntl, formatOverageRate, formatOverageRateWithLabel, formatQuotaIncludedOverage, formatQuotaWithPrice, getAvailableCurrenciesFromPlans, getBasePriceCents, getBillingIntervalAndCurrencyFromPriceId, getCurrencyDecimals, getCurrencyFlag, getCurrencySymbol, getDisplayCurrency, getPerSeatPriceCents, getPricingVariant, getQuotaDisplayValue, getQuotaDisplayWithVariant, getQuotaOverageCents, getQuotaUnitLabelFromName, getSeatPricing, getStripePriceIdForInterval, handleAppRevokeRequest, handleAppTokenRequest, hasPermission, invalidateCreditBalance, invalidateQuotaUsage, invalidateSubscription, inviterNameOf, isInvitationActionable, isInvitationError, isInvitationLapsed, isZeroDecimalCurrency, minorAmountToDisplay, mintAgentToken, negotiateMarkdown, parkPendingInvite, parseWebhookEvent, pickDefaultRole, provideWebMcpTools, readBBParams, readPendingInvite, resendCooldownSeconds, resolveAgentPath, resolveMaxUsers, resolvePermissions, resolveRolePermissions, resolveWellKnown, safeRedirect, saveAuthIntent, sha256Digest, signClientJwt, sortInvitations, validateInvite, validateRedirectUrl, verifyAppRevokeRequest, verifyAppTokenRequest, verifyClientJwt, verifyWebhookSignature, wantsMarkdown, workspaceIdOf, workspaceNameOf };
|
|
5207
|
+
export { AI_BOT_USER_AGENTS, APP_PERMISSION_FALLBACK_GROUP, ApiVersion, AppBridgeError, AuthApi, AuthStatus, BBAction, BBScreen, BBStatus, BB_PARAM, BaseApi, BetaForm, BillingIntervals, BuildBase, CURRENCY_DISPLAY, CURRENCY_FLAG, CreditBucketSource, CreditBucketStatus, CreditTransactionType, DEFAULT_ROLE_PERMISSIONS, DunningState, EventEmitter, FALLBACK_WORKSPACE_ROLE, INVITATION_ERROR_CODE, InvoiceStatuses, NotificationsApi, PLAN_CURRENCY_CODES, PLAN_CURRENCY_OPTIONS, PUSH_SERVICE_WORKER_SCRIPT, Permission, PushApi, SDKEvent, SettingsApi, SubscriptionItemType, SubscriptionStatus, UserApi, WorkspaceApi, actionableInvitations, appPermissionCatalogue, appTokenFailure, appTokenSuccess, bearerChallenge, buildA2AAgentCard, buildAgentCard, buildAgentSkillsIndex, buildApiCatalog, buildAuthMd, buildDiscoveryLinkHeader, buildDnsAidRecords, buildLlmsFullTxt, buildLlmsTxt, buildMcpDiscoveryManifest, buildMcpServerCard, buildProtectedResourceMetadata, buildRobotsTxt, buildSecurityTxt, buildSitemap, buildSkillMd, buildWebBotAuthDirectory, buildbaseAuth, calculateBillableSeats, calculateSeatOverageCents, calculateTotalSubscriptionCents, cleanBBParams, clearAgentReadinessCache, clearAuthIntent, clearPendingInvite, consumeAuthIntent, createBBUrl, createCheckoutRedirectUrls, createCreditPurchaseRedirectUrls, createSessionRefCrypto, BuildBase as default, eventEmitter, extractBearerToken, fetchAgentReadiness, formatCents, formatMinorAmountIntl, formatOverageRate, formatOverageRateWithLabel, formatQuotaIncludedOverage, formatQuotaWithPrice, getAvailableBillingIntervals, getAvailableCurrenciesFromPlans, getBasePriceCents, getBillingIntervalAndCurrencyFromPriceId, getCurrencyDecimals, getCurrencyFlag, getCurrencySymbol, getDisplayCurrency, getPerSeatPriceCents, getPricingVariant, getQuotaDisplayValue, getQuotaDisplayWithVariant, getQuotaOverageCents, getQuotaUnitLabelFromName, getSeatPricing, getStripePriceIdForInterval, handleAppRevokeRequest, handleAppTokenRequest, hasPermission, invalidateCreditBalance, invalidateQuotaUsage, invalidateSubscription, inviterNameOf, isInvitationActionable, isInvitationError, isInvitationLapsed, isZeroDecimalCurrency, minorAmountToDisplay, mintAgentToken, negotiateMarkdown, parkPendingInvite, parseWebhookEvent, pickDefaultRole, provideWebMcpTools, readBBParams, readPendingInvite, resendCooldownSeconds, resolveAgentPath, resolveMaxUsers, resolvePermissions, resolveRolePermissions, resolveWellKnown, safeRedirect, saveAuthIntent, sha256Digest, signClientJwt, sortInvitations, validateInvite, validateRedirectUrl, verifyAppRevokeRequest, verifyAppTokenRequest, verifyClientJwt, verifyWebhookSignature, wantsMarkdown, workspaceIdOf, workspaceNameOf };
|
|
5198
5208
|
export type { A2ACardConfig, A2ACardSkill, AgentReadinessBundle, AgentReadyConfig, AgentSkill, ApiCatalogApi, AppRevokeRequestClaims, AppScope, AppTokenRequestClaims, AppTokenResponseBody, AppTokenResult, BBActionType, BBScreenType, BBStatusType, BetaFormData, BetaFormResponse, BillingInterval, BuildBaseAuthOptions, BuildBaseConfig, BuildBaseResult, BuildBaseSession, CheckoutResult, ContentSignals, CreditActions, CreditBucketSourceType, CreditBucketStatusType, CreditTransactionTypeValue, DiscoveryDocument, DnsAidRecord, DunningStateType, EventData, EventType, FeatureActions, FormatQuotaWithPriceOptions, GetCheckoutStripeParams, HandlerResult, IAllQuotaUsageResponse, IBaseApiConfig, IBasePricing, IBetaConfig, ICheckoutSessionRequest, ICheckoutSessionResponse, ICheckoutStripeOptions, IConsumeCreditsRequest, IConsumeCreditsResponse, ICreditBalance, ICreditBucket, ICreditBucketsQuery, ICreditBucketsResponse, ICreditPackage, ICreditPackagePricingVariant, ICreditPurchaseRequest, ICreditPurchaseResponse, ICreditTransaction, ICreditTransactionsQuery, ICreditTransactionsResponse, IEventCallbacks, IExpiringCreditsResponse, IInvoice, IInvoiceListResponse, IInvoiceResponse, INotificationItem, IOsConfig, IOsState, IPlan, IPlanGroup, IPlanGroupInfo, IPlanGroupLatestVersion, IPlanGroupResponse, IPlanGroupVersion, IPlanGroupVersionWithPlans, IPlanGroupVersionsResponse, IPlanVersion, IPlanVersionSummary, IPlanVersionWithPlan, IPricingVariant, IPublicCreditPackage, IPublicCreditPackagesResponse, IPublicPlanItem, IPublicPlanItemCategory, IPublicPlanVersion, IPublicPlansResponse, IQuotaByInterval, IQuotaIntervalValue, IQuotaOveragePriceIdsByInterval, IQuotaOveragesByInterval, IQuotaUsageStatus, IQuotaUsageStatusResponse, IRecordUsageRequest, IRecordUsageResponse, ISettings, IStripePricesByInterval, ISubscription, ISubscriptionItem, ISubscriptionResponse, ISubscriptionUpdateRequest, ISubscriptionUpdateResponse, IUsageLogEntry, IUsageLogsQuery, IUsageLogsResponse, IUser, IWorkspace, IWorkspaceInvitation, IWorkspaceInvitationPreview, IWorkspaceInvitationStatus, InvitationActions, InvitationError, InvitationErrorCode, InvitationErrorFields, InviteBlockReason, InviteValidation, InvoiceActions, InvoiceStatus, InvoiceStatusType, MaxUsersConfig, McpServerCard, MintAgentTokenOptions, MyNotificationPreferences, NotificationChannelPreference, NotificationCounts, NotificationData, NotificationEvent, NotificationListParams, NotificationPage, NotificationResult, NotificationScope, OnWorkspaceChangeParams, PermissionActions, PermissionContext, PermissionKey, PlanActions, PlanVersionWithPricingVariants, QuotaDisplayValue, QuotaDisplayWithOverage, RedirectValidationOptions, RobotsConfig, RobotsPolicy, RolePermissionMap, ScopedActions, SessionRefCrypto, SettingsActions, SitemapUrl, SubscriptionActions, SubscriptionItemTypeValue, SubscriptionStatusType, TranslationKey, UsageActions, UserActions, UserCreatedEventData, UserUpdatedEventData, WebMcpTool, WorkspaceActions, WorkspaceChangedEventData, WorkspaceCreatedEventData, WorkspaceDeletedEventData, WorkspaceInvitationAcceptedEventData, WorkspaceInvitationDeclinedEventData, WorkspaceInvitationRevokedEventData, WorkspaceInvitationSentEventData, WorkspaceMemberPermissions, WorkspaceNotificationDefault, WorkspacePermissionDefinition, WorkspaceUpdatedEventData, WorkspaceUserAddedEventData, WorkspaceUserRemovedEventData, WorkspaceUserRoleChangedEventData };
|