@buildbase/sdk 0.0.51 → 0.0.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +24 -8
- package/CHANGELOG.md +102 -0
- package/README.md +283 -33
- package/dist/css/styles.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1248 -76
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -0
- package/dist/mcp/index.d.ts +1956 -0
- package/dist/mcp/index.mjs +1 -0
- package/dist/react/chunks/{SettingsDialog-DitAiAqr.cjs → SettingsDialog-B28WJsAr.cjs} +1 -1
- package/dist/react/chunks/{SettingsDialog-uVKFxlal.mjs → SettingsDialog-blhppbNm.mjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-P0GlXEyn.mjs → SubscriptionDialog-BTWVX3cH.mjs} +1 -1
- package/dist/react/chunks/{SubscriptionDialog-Cg-qYVKr.cjs → SubscriptionDialog-QKmwvJU1.cjs} +1 -1
- package/dist/react/chunks/ar-1Z1MOGAP.mjs +2 -0
- package/dist/react/chunks/ar-VGzBv3AZ.cjs +2 -0
- package/dist/react/chunks/de-BjdDg60Y.cjs +2 -0
- package/dist/react/chunks/de-CXUItplO.mjs +2 -0
- package/dist/react/chunks/es-BBPsSZUp.cjs +2 -0
- package/dist/react/chunks/es-BTbzVutz.mjs +2 -0
- package/dist/react/chunks/fr-Cax48X_S.cjs +2 -0
- package/dist/react/chunks/fr-DPMeOQu3.mjs +2 -0
- package/dist/react/chunks/hi-BJqvpG6d.cjs +2 -0
- package/dist/react/chunks/hi-JfJx-LV7.mjs +2 -0
- package/dist/react/chunks/ja-CDGtLzTk.mjs +2 -0
- package/dist/react/chunks/ja-DvVyj5xX.cjs +2 -0
- package/dist/react/chunks/react-6QJCOE-D.cjs +2 -0
- package/dist/react/chunks/react-CC6T7Zky.mjs +2 -0
- package/dist/react/chunks/zh-BAcqxkxk.cjs +2 -0
- package/dist/react/chunks/zh-BNZ2Ooe8.mjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +98 -43
- package/dist/react/index.mjs +1 -1
- package/package.json +20 -5
- package/dist/react/chunks/ar-SrPOJXdL.mjs +0 -2
- package/dist/react/chunks/ar-a3aRbPCs.cjs +0 -2
- package/dist/react/chunks/de-DE3_z7r0.cjs +0 -2
- package/dist/react/chunks/de-xnPl61SS.mjs +0 -2
- package/dist/react/chunks/es-C_xcyGtp.cjs +0 -2
- package/dist/react/chunks/es-CyuBtosP.mjs +0 -2
- package/dist/react/chunks/fr-BMu7Bk4k.cjs +0 -2
- package/dist/react/chunks/fr-CxuDLZ27.mjs +0 -2
- package/dist/react/chunks/hi-CQ215yc9.cjs +0 -2
- package/dist/react/chunks/hi-CpuvyorS.mjs +0 -2
- package/dist/react/chunks/ja-DIJ_xCIi.mjs +0 -2
- package/dist/react/chunks/ja-DK6Buuws.cjs +0 -2
- package/dist/react/chunks/react-C2ikFWBG.cjs +0 -2
- package/dist/react/chunks/react-CCukNQ4q.mjs +0 -2
- package/dist/react/chunks/zh-CYQwZiBL.mjs +0 -2
- package/dist/react/chunks/zh-Dt-apS2s.cjs +0 -2
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
let e=!0;function t(t,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}async function n(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function s(e,t="Request failed"){if(!e.ok){let s=t;try{const t=await n(e);s=t.message||t.error||s}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 new Error(s)}try{return await n(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class r extends Error{constructor(e,t,n,s){super(e),this.code=t,this.context=n,this.originalError=s,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,r)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,n={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const s=e instanceof Error?e:new r("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",n),o=s instanceof r?s:new r(s.message,"SDK_ERROR",n,s);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${n.component||"Unknown"}:`,{message:o.message,code:o.code,context:o.context,originalError:o.originalError,stack:o.stack}),this.config.onError)try{this.config.onError(o,n)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(o,n)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function i(e,t={}){o.handleError(e,t)}function a(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return i(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){i(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function u(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){i(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){i(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const l="saas-session-id";function d(){return function(){if("undefined"==typeof window)return null;try{return a(l)}catch(e){return i(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}const h=new WeakSet,p="SDK is not ready (missing serverUrl, version, or orgId)";class f{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(p);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(p)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=d(),t={};return e&&(t["x-session-id"]=e),t}()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){h.has(e)||(h.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}async executeFetchUrl(e,t,n){const s=(t.method??"GET").toUpperCase(),r=n??e,o=this.buildHeaders(t),i={...t,headers:o};let a,c;if(this._timeout>0){c=new AbortController;const e=c;a=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const s=new AbortController,r=e=>{s.signal.aborted||s.abort(e.reason)};for(const n of[e,t]){if(n.aborted){r(n);break}n.addEventListener("abort",()=>r(n),{once:!0})}return s.signal}(t.signal,e.signal):e.signal}const u=async n=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const t=this._fetch.bind(globalThis),r=await t(e,i);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${r.status}`),401===r.status&&this._onUnauthorized&&this._onUnauthorized(),r.status>=500&&n<this._maxRetries){const e=Math.min(1e3*Math.pow(2,n),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${n+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),u(n+1)}return r}catch(e){if(e instanceof Error&&"AbortError"===e.name){if(c?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${r}`);throw this.reportError(e,{method:s,path:r}),e}throw e}if(n<this._maxRetries){const e=Math.min(1e3*Math.pow(2,n),1e4);return this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${n+1}/${this._maxRetries})`),await new Promise(t=>setTimeout(t,e)),u(n+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:r}),e}};try{return await u(0)}finally{void 0!==a&&clearTimeout(a)}}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 fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw new Error(n)}apiPath(e,...t){return e.reduce((e,n,s)=>e+n+(s<t.length?encodeURIComponent(String(t[s])):""),"")}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 g extends f{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return n.ok||await this.throwResponseError(n,"Failed to initiate authentication"),n.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class w extends f{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}class y{constructor(e){this.api=new w(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),s=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),r=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),o=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:s,timezone:r,currency:o}})}}class m extends f{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class k extends f{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class b extends f{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}class S extends f{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`);return t.ok||await this.throwResponseError(t,"Failed to fetch subscription"),this.unwrapResponse(t,"Failed to fetch subscription")}async getPlanGroup(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group"),this.unwrapResponse(t,"Failed to fetch plan group")}async getPlanGroupByVersion(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`);return n.ok||await this.throwResponseError(n,"Failed to fetch plan group version"),this.unwrapResponse(n,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group/versions`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group versions"),this.unwrapResponse(t,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plans"),this.unwrapResponse(t,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(this.apiPath`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const t=await this.fetchResponse(this.apiPath`plan-group-versions/${e}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async createCheckoutSession(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to create checkout session"),this.unwrapResponse(n,"Failed to create checkout session")}async selectFreePlan(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return n.ok||await this.throwResponseError(n,"Failed to select free plan"),n.json()}async updateSubscription(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to update subscription"),this.unwrapResponse(n,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,n){const s=new URLSearchParams;s.append("limit",t.toString()),n&&s.append("starting_after",n);const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`);return r.ok||await this.throwResponseError(r,"Failed to fetch invoices"),this.unwrapResponse(r,"Failed to fetch invoices")}async getInvoice(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices/${t}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoice"),this.unwrapResponse(n,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to cancel subscription"),this.unwrapResponse(t,"Failed to cancel subscription")}async resumeSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to resume subscription"),this.unwrapResponse(t,"Failed to resume subscription")}async recordUsage(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to record usage"),this.unwrapResponse(n,"Failed to record usage")}async recordUsageBatch(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to record batch usage"),this.unwrapResponse(n,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`);return n.ok||await this.throwResponseError(n,"Failed to fetch quota usage status"),this.unwrapResponse(n,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){const n=new URLSearchParams;t?.quotaSlug&&n.append("quotaSlug",t.quotaSlug),t?.from&&n.append("from",t.from),t?.to&&n.append("to",t.to),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),r=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:""),o=await this.fetchResponse(r);return o.ok||await this.throwResponseError(o,"Failed to fetch usage logs"),this.unwrapResponse(o,"Failed to fetch usage logs")}async sendNotification(e,t,n,s){const r={event:t};return n&&(r.userId=n),s&&(r.data=s),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(r)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!n.ok){if(402===n.status){const e=await n.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(n,"Failed to consume credits")}return this.unwrapResponse(n,"Failed to consume credits")}async purchaseCredits(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to create credit purchase checkout"),this.unwrapResponse(n,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const n=await this.unwrapResponse(t,"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t){const n=new URLSearchParams;t?.type&&n.append("type",t.type),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),r=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:""),o=await this.fetchResponse(r);return o.ok||await this.throwResponseError(o,"Failed to fetch credit transactions"),this.unwrapResponse(o,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const n=new URLSearchParams;t?.status&&n.append("status",t.status),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const s=n.toString(),r=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:""),o=await this.fetchResponse(r);return o.ok||await this.throwResponseError(o,"Failed to fetch credit buckets"),this.unwrapResponse(o,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const n=t?`?days=${t}`:"",s=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/expiring`+n);return s.ok||await this.throwResponseError(s,"Failed to fetch expiring credits"),this.unwrapResponse(s,"Failed to fetch expiring credits")}}var v;!function(e){e.V1="v1"}(v||(v={}));const E={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted"};class P{constructor(){this.callbacks=null}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){i(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(E.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(E.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(E.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(E.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(E.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(E.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,s){await this.emit(E.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:s})}async emitWorkspaceCreated(e){await this.emit(E.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(E.WorkspaceDeleted,{workspace:e})}}const R=new P;function $(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const U=$().invalidate,C=$().invalidate,I=$().invalidate,_="bb",F={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},A={Success:"success",Cancel:"cancel",Error:"error"},W={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function O(e,t){let n;try{const e=t||("undefined"!=typeof window?window.location.href:"https://localhost");n=new URL(e),n.search=""}catch{n=new URL("https://localhost")}return n.searchParams.set(_,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),n.toString()}function T(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:O({action:F.Checkout,status:A.Success,ws:e,screen:W.Subscription},n),cancelUrl:O({action:F.Checkout,status:A.Cancel,ws:e,screen:W.Subscription},n)}}function x(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:O({action:F.CreditPurchase,status:A.Success,ws:e,screen:W.Credits},n),cancelUrl:O({action:F.CreditPurchase,status:A.Cancel,ws:e,screen:W.Credits},n)}}function N(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(_);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const s=decodeURIComponent(e.slice(0,n)),r=decodeURIComponent(e.slice(n+1));s&&(t[s]=r)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function J(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(_)&&(e.searchParams.delete(_),window.history.replaceState({},"",e.toString()))}catch{}}function L(e){if(!e||"string"!=typeof e)return null;try{const t=new URL(e);return"https:"===t.protocol?e:"http:"!==t.protocol||"localhost"!==t.hostname&&"127.0.0.1"!==t.hostname&&"::1"!==t.hostname?null:e}catch{return null}}function B(e,t="/"){if("undefined"==typeof window||!window.location)return!1;const n=L(e);return window.location.href=n??t,!0}const M="saas-auth-intent";function D(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function z(e){L(e)&&u(M,{returnUrl:e,createdAt:Date.now()})}function q(){const e=function(e,t){const n=a(e);if(!n)return null;try{const s=JSON.parse(n);return t&&!t(s)?(i(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):s}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(M,D);return c(M),e?Date.now()-e.createdAt>6e5?null:L(e.returnUrl):null}function K(){c(M)}const j={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},V={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function G(e){return e&&e.trim()?V[e.trim().toLowerCase()]??"":""}function H(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return j[t]??t.toUpperCase()}const Q=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Y=Q.map(e=>({value:e,label:`${e.toUpperCase()} (${H(e)})`}));function Z(e,t){return H(t)+(e/100).toFixed(2)}const X={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};function ee(e,t,n,s){if(null==e||e<0)return null;const r={...X,...s},o=null!=t&&t>=1?t:1,i=H(n),a=(e/100).toFixed(2);return 1===o?`${i}${a}/${r.unit}`:`${i}${a}/${o.toLocaleString()} ${r.units}`}function te(e,t,n,s,r,o){if(null==e||e<0)return null;const i={...X,...o},a=null!=t&&t>=1?t:1,c=H(s),u=(e/100).toFixed(2);if(n){const e=r??(n.endsWith("s")?n:`${n}s`);return a>=2?`${c}${u}/${a.toLocaleString()} ${e}`:`${c}${u}/${n}`}return 1===a?`${c}${u}/${i.unit}`:`${c}${u}/${a.toLocaleString()} ${i.units}`}function ne(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const s=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(s)?s:s.endsWith("ies")&&s.length>3?s.slice(0,-3)+"y":s.endsWith("ses")||s.endsWith("xes")||s.endsWith("zes")||s.endsWith("ches")||s.endsWith("shes")?s.slice(0,-2):s.endsWith("s")&&!s.endsWith("ss")&&s.length>1?s.slice(0,-1):s||t}function se(e,t,n,s,r,o,i,a){const c={...X,...i};if(!1===a)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=o??(n.endsWith("s")?n:`${n}s`),l=null!=r&&r>=2?`${r.toLocaleString()} ${u}`:n;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${Z(t,s)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${Z(t,s)}/${l}`:"—"}function re(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null}const oe={included:"included",then:"then"};function ie(e,t,n={}){const{overageInCents:s=!0,currency:r}=n,o=n.labels??oe,i=n.currencySymbol??H(r??"");if(null==e)return"—";const{included:a,overage:c}=e,u=`${a} ${o.included}`;if(!1===e.allowOverage)return`${u} (hard limit)`;if(null==c)return u;const l=s?c/100:c,d="number"==typeof l&&Number.isFinite(l)?l.toFixed(2):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${o.then} ${i}${d}${h}`}const ae={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},ce={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},ue={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},le={Feature:"feature",Limit:"limit",Quota:"quota"},de={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},he={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},pe={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},fe={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function ge(e,t){const n=e.pricingVariants;if(!n?.length)return null;const s=t.toLowerCase();return n.find(e=>e.currency?.toLowerCase()===s)??null}function we(e,t,n){const s=ge(e,t);if(!s?.basePricing)return null;const r=s.basePricing[n];return null!=r?r:null}function ye(e,t,n){const s=ge(e,t);if(!s?.stripePrices)return null;const r=n===ae.Monthly?"monthlyPriceId":n===ae.Yearly?"yearlyPriceId":"quarterlyPriceId",o=n===ae.Monthly?"monthly":n===ae.Yearly?"yearly":void 0;return s.stripePrices[r]??(o?s.stripePrices[o]:void 0)??null}function me(e,t,n,s){const r=ge(e,t),o=r?.quotaOverages?.[n];if(o)return o[s]}function ke(e,t){const n=ge(e,t);return n?n.currency:e.plan?.currency??""}function be(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function Se(e,t,n,s){const r=e.quotas?.[n];if(null==r)return null;const o=r[s];if(!o)return null;const i=me(e,t,n,s);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==r.allowOverage}}function ve(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null}function Ee(e,t){const n=ge(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Pe(e,t,n){const s=Ee(e,t);return s?.perSeat?s.perSeat[n]??null:null}function Re(e,t){return Math.max(0,e-(t||0))}function $e(e,t,n,s){const r=Ee(e,t);if(!r)return null;return Re(s,r.includedSeats)*(Pe(e,t,n)??0)}function Ue(e,t,n,s){const r=we(e,t,n);if(null===r)return null;if(void 0===s)return r;return r+($e(e,t,n,s)??0)}function Ce(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:s}=e;if(t){const e=Ee(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=s&&s>0?{maxUsers:s,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function Ie(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:s=!0,requireSubscription:r=!1}=e;if(r&&!s)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:o,source:i}=n;if(o<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=o){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:o}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const _e={WORKSPACE_SETTINGS_VIEW:"workspace:settings:view",WORKSPACE_SETTINGS_EDIT:"workspace:settings:edit",WORKSPACE_DELETE:"workspace:delete",WORKSPACE_MEMBERS_VIEW:"workspace:members:view",WORKSPACE_MEMBERS_INVITE:"workspace:members:invite",WORKSPACE_MEMBERS_REMOVE:"workspace:members:remove",WORKSPACE_MEMBERS_ROLE_CHANGE:"workspace:members:role-change",WORKSPACE_FEATURES_VIEW:"workspace:features:view",WORKSPACE_FEATURES_EDIT:"workspace:features:edit",WORKSPACE_BILLING_VIEW:"workspace:billing:view",WORKSPACE_BILLING_MANAGE:"workspace:billing:manage",WORKSPACE_USAGE_VIEW:"workspace:usage:view"},Fe=Object.values(_e),Ae={admin:Fe.filter(e=>e!==_e.WORKSPACE_DELETE),member:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW,_e.WORKSPACE_FEATURES_VIEW,_e.WORKSPACE_BILLING_VIEW,_e.WORKSPACE_USAGE_VIEW],viewer:[_e.WORKSPACE_SETTINGS_VIEW,_e.WORKSPACE_MEMBERS_VIEW]};function We(e){const t=new Set;for(const n of Object.values(e))for(const e of n)t.add(e);return Array.from(t)}function Oe(e){const{userId:t,workspace:n,settings:s,appPermissions:r}=e;if(!n||!t)return new Set;if(function(e,t){if(!t)return!1;const n=(s=e.createdBy)?"string"==typeof s?s:"object"==typeof s&&"_id"in s&&"string"==typeof s._id?s._id:null:null;var s;return null!==n&&n===t}(n,t)){const e=new Set(Fe);if(r)for(const t of We(r))e.add(t);if(n.permissions)for(const t of We(n.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of We(s.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);if(!o)return new Set;const i=n.permissions,a=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=i?.[o]?c(i[o]):[],d=a?.[o]?c(a[o]):[],h=Ae[o]??[];let p;if(l.length>0)p=l;else if(d.length>0)p=d;else if(h.length>0)p=h;else{p=Ae[s?.workspace?.defaultRole??"member"]??Ae.member??[]}const f=new Set(p),g=i?.[o]?u(i[o]):[],w=r?.[o]?u(r[o]):[],y=g.length>0?g:w;for(const e of y)f.add(e);return function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:s}=n.workspace;(!1===s||"admin-only"===s&&"admin"!==t)&&e.delete(_e.WORKSPACE_MEMBERS_INVITE)}(f,o,s),f}function Te(e,t){const n=Oe(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const xe="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n try {\n const payload = event.data.json();\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n";var Ne;!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Ne||(Ne={}));const Je=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Le=(e,t)=>e>>>t|e<<32-t;function Be(e){let t=1779033703,n=3144134277,s=1013904242,r=2773480762,o=1359893119,i=2600822924,a=528734635,c=1541459225;const u=e.length,l=u+1,d=l+(56-l%64+64)%64+8,h=new Uint8Array(d);h.set(e,0),h[u]=128;const p=8*u,f=Math.floor(p/4294967296),g=p>>>0;h[d-8]=f>>>24&255,h[d-7]=f>>>16&255,h[d-6]=f>>>8&255,h[d-5]=255&f,h[d-4]=g>>>24&255,h[d-3]=g>>>16&255,h[d-2]=g>>>8&255,h[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]=h[n]<<24|h[n+1]<<16|h[n+2]<<8|h[n+3]}for(let e=16;e<64;e++){const t=Le(w[e-15],7)^Le(w[e-15],18)^w[e-15]>>>3,n=Le(w[e-2],17)^Le(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+n>>>0}let u=t,l=n,d=s,p=r,f=o,g=i,y=a,m=c;for(let e=0;e<64;e++){const t=m+(Le(f,6)^Le(f,11)^Le(f,25))+(f&g^~f&y)+Je[e]+w[e]>>>0,n=u&l^u&d^l&d;m=y,y=g,g=f,f=p+t>>>0,p=d,d=l,l=u,u=t+((Le(u,2)^Le(u,13)^Le(u,22))+n>>>0)>>>0}t=t+u>>>0,n=n+l>>>0,s=s+d>>>0,r=r+p>>>0,o=o+f>>>0,i=i+g>>>0,a=a+y>>>0,c=c+m>>>0}const y=new Uint8Array(32),m=[t,n,s,r,o,i,a,c];for(let e=0;e<8;e++)y[4*e]=m[e]>>>24&255,y[4*e+1]=m[e]>>>16&255,y[4*e+2]=m[e]>>>8&255,y[4*e+3]=255&m[e];return y}function Me(e){return(new TextEncoder).encode(e)}function De(e,t){let n=e;n.length>64&&(n=Be(n));const s=new Uint8Array(64),r=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;s[e]=54^t,r[e]=92^t}const o=Be(qe(s,t));return Be(qe(r,o))}function ze(e,t){if(e.length!==t.length)return!1;let n=0;for(let s=0;s<e.length;s++)n|=e[s]^t[s];return 0===n}function qe(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Ke(e){const{body:t,signature:n,timestamp:s,secret:r,maxAgeSeconds:o=300}=e;if(!(n&&s&&r&&t))return!1;const i="sha256=";if(!n.startsWith(i))return!1;const a=n.slice(7);if(o>0){const e=parseInt(s,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>o)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const s=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(s))return null;t[n]=s}return t}(a);if(!c)return!1;const u=De(Me(r),Me(`${s}.${t}`));return c.length===u.length&&ze(c,u)}function je(e){if(!Ke(e))return null;try{return JSON.parse(e.body)}catch{return null}}const Ve=300,Ge="/.well-known/oauth-protected-resource",He="/.well-known/agent-skills",Qe="/.well-known/api-catalog",Ye="/.well-known/mcp/server-card.json",Ze="application/json",Xe="text/markdown; charset=utf-8",et="text/plain; charset=utf-8";function tt(e){return e.replace(/\/+$/,"")}function nt(e){return`public, max-age=${e}, s-maxage=${e}`}function 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}(Be(Me(e)))}const rt=new Map;async function ot(e){const t=e.cacheTtlSeconds??Ve,n=`${tt(e.serverUrl)}::${e.orgId}`,s=rt.get(n);if(s&&s.expiresAt>Date.now())return s.value;const r=e.fetch??fetch,o=`${tt(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const e=await r(o,{headers:{Accept:Ze}});if(e.ok){const t=await e.json();t&&"object"==typeof t&&(i=t)}}catch{}return rt.set(n,{value:i,expiresAt:Date.now()+1e3*t}),i}function it(){rt.clear()}function at(e,t){const n=tt(e.siteUrl),s={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:Ge};t.authorizationServer?.metadataUrl&&(s.oauth_authorization_server=t.authorizationServer.metadataUrl),(t.authorizationServer||e.authMd)&&(s.auth="/auth.md"),e.skills?.length&&(s.agent_skills=`${He}/index.json`),e.apiCatalog?.length&&(s.api_catalog=Qe),e.mcpServerCard&&(s.mcp_server_card=Ye);return yt({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:n,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:n},capabilities:s,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}function ct(e,t,n){const s=n.protectedResources??[];if(!s.length)return null;const r=e.replace(/\/+$/,"")||Ge,o=s.find(e=>function(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return Ge+n}(e.resource)===r);return o?yt(o.metadata,t):r===Ge&&1===s.length?yt(s[0].metadata,t):null}function ut(e){const t=e.skills??[];if(!t.length)return null;const n=tt(e.siteUrl);return yt({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${n}${lt(e)}`,digest:st(e.content)}))},e)}function lt(e){return e.path??`${He}/${e.name}/SKILL.md`}function dt(e,t){const n=(t.skills??[]).find(t=>lt(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:nt(t.cacheTtlSeconds??Ve)}:null}function ht(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:et,body:t.join("\n")+"\n",cacheControl:nt(e.cacheTtlSeconds??Ve)}}function pt(e,t){return t.llmsTxt?{status:200,contentType:et,body:t.llmsTxt,cacheControl:nt(e.cacheTtlSeconds??Ve)}:null}function ft(e){const t=e.apiCatalog??[];if(!t.length)return null;const n=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:"application/linkset+json",body:JSON.stringify({linkset:n},null,2),cacheControl:nt(e.cacheTtlSeconds??Ve)}}function gt(e){const t=e.mcpServerCard;return t?yt({schema_version:"2024-11-05",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",endpoint:t.endpoint},capabilities:t.capabilities??{tools:{}},...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function wt(e,t){const n=nt(e.cacheTtlSeconds??Ve);if(e.authMd)return{status:200,contentType:Xe,body:e.authMd,cacheControl:n};const s=t.authorizationServer;if(!s)return null;const r=(t.protectedResources??[]).map(e=>`- \`${e.resource}\``).join("\n"),o=Array.from(new Set((t.protectedResources??[]).flatMap(e=>e.metadata?.scopes_supported??[]))),i=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${s.issuer}\`\n- Metadata (RFC 8414): ${s.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, and supported grant types / PKCE methods.\n\n## Protected resources (RFC 9728)\n${r||"- See `/.well-known/oauth-protected-resource`"}\n\nEach resource publishes its metadata at \`/.well-known/oauth-protected-resource\`, listing the authorization server(s) that can issue tokens for it.\n${o.length?`\n## Scopes\n${o.map(e=>`- \`${e}\``).join("\n")}\n`:""}\n## How an agent authenticates\n1. Discover this document and \`/.well-known/oauth-protected-resource\`.\n2. Fetch the authorization-server metadata for the endpoints.\n3. Run the authorization-code flow with PKCE (S256), requesting the scopes above and the target \`resource\`.\n4. Exchange the code for an access token and call the API with \`Authorization: Bearer <token>\`.\n\nDocumentation: ${e.site.documentationUrl??e.siteUrl}\n`;return{status:200,contentType:Xe,body:i,cacheControl:n}}function yt(e,t){return{status:200,contentType:Ze,body:JSON.stringify(e,null,2),cacheControl:nt(t.cacheTtlSeconds??Ve)}}async function mt(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return at(t,await ot(t))}if("/.well-known/security.txt"===n)return ht(t);if(n===`${He}/index.json`)return ut(t);if(n.startsWith(`${He}/`)&&n.endsWith("SKILL.md"))return dt(n,t);if("/.well-known/oauth-authorization-server"===n){const e=await ot(t),n=e.authorizationServer?.metadataUrl;return n?yt({...e.authorizationServer?.issuer?{issuer:e.authorizationServer.issuer}:{},oauth_authorization_server_metadata:n},t):null}if(n===Qe)return ft(t);if(n===Ye)return gt(t);if(n.startsWith(Ge)){return ct(n,t,await ot(t))}return null}function kt(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)}class bt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function St(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4==0?"":"=".repeat(4-t.length%4),s=atob(t+n),r=new Uint8Array(s.length);for(let e=0;e<s.length;e++)r[e]=s.charCodeAt(e);return r}function vt(e){return JSON.parse((new TextDecoder).decode(St(e)))}function Et(e,t,n=60){if(!e||!t)throw new bt("invalid_token","Missing token or client secret");const s=e.split(".");if(3!==s.length)throw new bt("invalid_token","Malformed JWT");const[r,o,i]=s,a=De(Me(t),Me(`${r}.${o}`));let c,u,l;try{c=St(i)}catch{throw new bt("invalid_signature","Unreadable JWT signature")}if(!ze(a,c))throw new bt("invalid_signature","JWT signature verification failed");try{u=vt(r),l=vt(o)}catch{throw new bt("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new bt("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const d=Math.floor(Date.now()/1e3);if("number"==typeof l.exp&&d>l.exp+n)throw new bt("token_expired","JWT has expired");if("number"==typeof l.nbf&&d+n<l.nbf)throw new bt("token_not_yet_valid","JWT is not yet valid");return l}function Pt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function Rt(e){const t=Pt(e.authorization);if(!t)throw new bt("invalid_token","Missing Bearer token");return Et(t,e.clientSecret,e.clockToleranceSec)}function $t(e){const t=Pt(e.authorization);if(!t)throw new bt("invalid_token","Missing Bearer token");return Et(t,e.clientSecret,e.clockToleranceSec)}function Ut(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function Ct(e){return{success:!1,token:"",message:e}}async function It(e){let t;try{t=Rt(e)}catch(e){return{status:401,body:Ct(e instanceof bt?e.code:"invalid_token")}}return{status:200,body:Ut(await e.mintToken(t))}}async function _t(e){let t;try{t=$t(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof bt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}}function Ft(e){const t=[`Bearer resource_metadata="${e.resourceMetadataUrl}"`];return e.error&&t.push(`error="${e.error}"`),e.errorDescription&&t.push(`error_description="${e.errorDescription}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}function At(e){const{serverUrl:t,orgId:n,version:s="v1",getSessionId:r,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const d={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},h=e=>{const r={serverUrl:t,version:s,orgId:n,sessionId:e,...d};return{workspace:new S(r),user:new b(r),settings:new k(r),push:new m(r)}},p=new S({serverUrl:t,version:s,orgId:n,...d}),f=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,s)=>(await e()).workspace.addUser(t,{email:n,role:s}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,s)=>(await e()).workspace.updateUser(t,n,{role:s}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,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=>p.getPublicPlans(e),getVersion:e=>p.getPlanGroupVersion(e)},invoices:{list:async(t,n,s)=>(await e()).workspace.listInvoices(t,n,s),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,s)=>(await e()).workspace.updateFeature(t,n,s)},notification:{send:async(t,n,s,r)=>(await e()).workspace.sendNotification(t,n,s,r)},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:()=>p.getPublicCreditPackages()},permissions:{check:async(t,n,s)=>{const r=await e(),[o,i,a]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return Te(s,{userId:n,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,n)=>{const s=await e(),[r,o,i]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return Oe({userId:n,workspaceRole:a?.role??null,workspace:r,settings:o})}}}),g=f(async()=>h(await(async()=>{if(!r)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 r();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!r)return null;const e=await r();return e?{sessionId:e}:null},withSession:e=>{const t=h(e);return f(async()=>t)},client:{forSession:h},...g}}export{v as ApiVersion,bt as AppBridgeError,g as AuthApi,Ne as AuthStatus,F as BBAction,W as BBScreen,A as BBStatus,_ as BB_PARAM,f as BaseApi,y as BetaForm,ae as BillingIntervals,At as BuildBase,j as CURRENCY_DISPLAY,V as CURRENCY_FLAG,he as CreditBucketSource,pe as CreditBucketStatus,fe as CreditTransactionType,Ae as DEFAULT_ROLE_PERMISSIONS,de as DunningState,P as EventEmitter,ue as InvoiceStatuses,Q as PLAN_CURRENCY_CODES,Y as PLAN_CURRENCY_OPTIONS,xe as PUSH_SERVICE_WORKER_SCRIPT,_e as Permission,m as PushApi,E as SDKEvent,k as SettingsApi,le as SubscriptionItemType,ce as SubscriptionStatus,b as UserApi,S as WorkspaceApi,Ct as appTokenFailure,Ut as appTokenSuccess,Ft as bearerChallenge,at as buildAgentCard,ut as buildAgentSkillsIndex,ft as buildApiCatalog,wt as buildAuthMd,pt as buildLlmsTxt,gt as buildMcpServerCard,ct as buildProtectedResourceMetadata,ht as buildSecurityTxt,dt as buildSkillMd,Re as calculateBillableSeats,$e as calculateSeatOverageCents,Ue as calculateTotalSubscriptionCents,J as cleanBBParams,it as clearAgentReadinessCache,K as clearAuthIntent,q as consumeAuthIntent,O as createBBUrl,T as createCheckoutRedirectUrls,x as createCreditPurchaseRedirectUrls,At as default,R as eventEmitter,Pt as extractBearerToken,ot as fetchAgentReadiness,Z as formatCents,ee as formatOverageRate,te as formatOverageRateWithLabel,se as formatQuotaIncludedOverage,ie as formatQuotaWithPrice,be as getAvailableCurrenciesFromPlans,we as getBasePriceCents,ve as getBillingIntervalAndCurrencyFromPriceId,G as getCurrencyFlag,H as getCurrencySymbol,ke as getDisplayCurrency,Pe as getPerSeatPriceCents,ge as getPricingVariant,re as getQuotaDisplayValue,Se as getQuotaDisplayWithVariant,me as getQuotaOverageCents,ne as getQuotaUnitLabelFromName,Ee as getSeatPricing,ye as getStripePriceIdForInterval,_t as handleAppRevokeRequest,It as handleAppTokenRequest,Te as hasPermission,U as invalidateCreditBalance,C as invalidateQuotaUsage,I as invalidateSubscription,je as parseWebhookEvent,kt as provideWebMcpTools,N as readBBParams,Ce as resolveMaxUsers,Oe as resolvePermissions,mt as resolveWellKnown,B as safeRedirect,z as saveAuthIntent,st as sha256Digest,Ie as validateInvite,L as validateRedirectUrl,$t as verifyAppRevokeRequest,Rt as verifyAppTokenRequest,Et as verifyClientJwt,Ke as verifyWebhookSignature};
|
|
1
|
+
let e=!0;function t(t,...n){e&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(t,...n)}async function n(e){const t=await e.text();if(!t)throw new Error("Empty response body");try{return JSON.parse(t)}catch(e){throw new Error(`Invalid JSON response: ${t.substring(0,100)}${t.length>100?"...":""}`)}}async function r(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await n(e);r=t.message||t.error||r}catch{r=function(e,t){const n={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${n})`)}(e,t).message}throw new Error(r)}try{return await n(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class s extends Error{constructor(e,t,n,r){super(e),this.code=t,this.context=n,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,s)}}const o=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,n={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new s("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",n),o=r instanceof s?r:new s(r.message,"SDK_ERROR",n,r);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${n.component||"Unknown"}:`,{message:o.message,code:o.code,context:o.context,originalError:o.originalError,stack:o.stack}),this.config.onError)try{this.config.onError(o,n)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(o,n)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function i(e,t={}){o.handleError(e,t)}function a(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return i(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){i(t,{component:"storage",action:"removeStorageItem",metadata:{key:e}})}}function u(e,t){try{!function(e,t){if("undefined"!=typeof window)try{localStorage.setItem(e,t)}catch(t){i(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){i(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const l="saas-session-id";function d(){return function(){if("undefined"==typeof window)return null;try{return a(l)}catch(e){return i(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}const p=new WeakSet,h=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),f="SDK is not ready (missing serverUrl, version, or orgId)";class g{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(f);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(f)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=d(),t={};return e&&(t["x-session-id"]=e),t}()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){p.has(e)||(p.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((n,r)=>{const s=()=>{clearTimeout(o),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const o=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,o=this.buildHeaders(t),i={...t,headers:o},a=h.has(r);let c,u;if(this._timeout>0){u=new AbortController;const e=u;c=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const n=AbortSignal.any;if("function"==typeof n)return n([e,t]);const r=new AbortController,s=e=>{r.signal.aborted||r.abort(e.reason)};for(const n of[e,t]){if(n.aborted){s(n);break}n.addEventListener("abort",()=>s(n),{once:!0})}return r.signal}(t.signal,e.signal):e.signal}const l=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${r} ${s}`);return this.reportError(e,{method:r,path:s}),e}return e},d=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const n=this._fetch.bind(globalThis),s=await n(e,i);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await g.delay(e,i.signal),d(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await g.delay(e,i.signal)}catch(e){throw l(e)}return d(t+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:s}),e}};try{return await d(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await r(s,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw new Error(n)}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class w extends g{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return n.ok||await this.throwResponseError(n,"Failed to initiate authentication"),n.json()}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}class y extends g{constructor(e){super({...e,basePath:"beta",requireOrgId:!0})}getAuthHeaders(){return{}}async fetchConfig(){return this.fetchJson(`config?orgId=${encodeURIComponent(this.orgId)}`,{},"Failed to fetch beta form configuration")}async submitBetaUser(e){return this.fetchJson("submit",{method:"POST",body:JSON.stringify(e)},"Failed to submit beta user request")}}class m{constructor(e){this.api=new y(e),this.orgId=e.orgId}async fetchConfig(){return this.api.fetchConfig()}async submitBetaUser(e){const t=e?.context??{},n=t?.country??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[1]:void 0),r=t?.language??("undefined"!=typeof navigator&&navigator.language?navigator.language.split("-")[0]:void 0),s=t?.timezone??("undefined"!=typeof Intl&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),o=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:s,currency:o}})}}class k extends g{constructor(e){super({...e,requireOrgId:!0})}async getVapidPublicKey(){return this.fetchJson("push/vapid-public-key")}async subscribe(e,t){await this.fetchJson("push/subscribe",{method:"POST",body:JSON.stringify({endpoint:e.endpoint,keys:e.keys,userAgent:t})})}async unsubscribe(e){await this.fetchJson("push/unsubscribe",{method:"DELETE",body:JSON.stringify({endpoint:e})})}}class b extends g{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class S extends g{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const n=await this.unwrapResponse(t,"Failed to fetch user attributes");return n&&"object"==typeof n&&!Array.isArray(n)?n:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const n=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof n&&null!==n?n:{}}}class v extends g{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`);return t.ok||await this.throwResponseError(t,"Failed to fetch subscription"),this.unwrapResponse(t,"Failed to fetch subscription")}async getPlanGroup(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group"),this.unwrapResponse(t,"Failed to fetch plan group")}async getPlanGroupByVersion(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`);return n.ok||await this.throwResponseError(n,"Failed to fetch plan group version"),this.unwrapResponse(n,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group/versions`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group versions"),this.unwrapResponse(t,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plans"),this.unwrapResponse(t,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(this.apiPath`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const t=await this.fetchResponse(this.apiPath`plan-group-versions/${e}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async createCheckoutSession(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to create checkout session"),this.unwrapResponse(n,"Failed to create checkout session")}async selectFreePlan(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return n.ok||await this.throwResponseError(n,"Failed to select free plan"),n.json()}async updateSubscription(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to update subscription"),this.unwrapResponse(n,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,n){const r=new URLSearchParams;r.append("limit",t.toString()),n&&r.append("starting_after",n);const s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices`+`?${r.toString()}`);return s.ok||await this.throwResponseError(s,"Failed to fetch invoices"),this.unwrapResponse(s,"Failed to fetch invoices")}async getInvoice(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices/${t}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoice"),this.unwrapResponse(n,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to cancel subscription"),this.unwrapResponse(t,"Failed to cancel subscription")}async resumeSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to resume subscription"),this.unwrapResponse(t,"Failed to resume subscription")}async recordUsage(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to record usage"),this.unwrapResponse(n,"Failed to record usage")}async recordUsageBatch(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to record batch usage"),this.unwrapResponse(n,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`);return n.ok||await this.throwResponseError(n,"Failed to fetch quota usage status"),this.unwrapResponse(n,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){const n=new URLSearchParams;t?.quotaSlug&&n.append("quotaSlug",t.quotaSlug),t?.from&&n.append("from",t.from),t?.to&&n.append("to",t.to),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const r=n.toString(),s=this.apiPath`workspaces/${e}/subscription/usage/logs`+(r?`?${r}`:""),o=await this.fetchResponse(s);return o.ok||await this.throwResponseError(o,"Failed to fetch usage logs"),this.unwrapResponse(o,"Failed to fetch usage logs")}async sendNotification(e,t,n,r){const s={event:t};return n&&(s.userId=n),r&&(s.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(s)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!n.ok){if(402===n.status){const e=await n.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(n,"Failed to consume credits")}return this.unwrapResponse(n,"Failed to consume credits")}async purchaseCredits(e,t){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return n.ok||await this.throwResponseError(n,"Failed to create credit purchase checkout"),this.unwrapResponse(n,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const n=await this.unwrapResponse(t,"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t){const n=new URLSearchParams;t?.type&&n.append("type",t.type),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const r=n.toString(),s=this.apiPath`workspaces/${e}/credits/transactions`+(r?`?${r}`:""),o=await this.fetchResponse(s);return o.ok||await this.throwResponseError(o,"Failed to fetch credit transactions"),this.unwrapResponse(o,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const n=new URLSearchParams;t?.status&&n.append("status",t.status),t?.source&&n.append("source",t.source),t?.page&&n.append("page",t.page.toString()),t?.limit&&n.append("limit",t.limit.toString());const r=n.toString(),s=this.apiPath`workspaces/${e}/credits/buckets`+(r?`?${r}`:""),o=await this.fetchResponse(s);return o.ok||await this.throwResponseError(o,"Failed to fetch credit buckets"),this.unwrapResponse(o,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const n=t?`?days=${t}`:"",r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/expiring`+n);return r.ok||await this.throwResponseError(r,"Failed to fetch expiring credits"),this.unwrapResponse(r,"Failed to fetch expiring credits")}}var $;!function(e){e.V1="v1"}($||($={}));const E={UserCreated:"user:created",UserUpdated:"user:updated",WorkspaceChanged:"workspace:changed",WorkspaceUpdated:"workspace:updated",WorkspaceUserAdded:"workspace:user-added",WorkspaceUserRemoved:"workspace:user-removed",WorkspaceUserRoleChanged:"workspace:user-role-changed",WorkspaceCreated:"workspace:created",WorkspaceDeleted:"workspace:deleted"};class P{constructor(){this.callbacks=null}setCallbacks(e){this.callbacks=e}getCallbacks(){return this.callbacks}async emit(e,t){if(this.callbacks?.handleEvent)try{await this.callbacks.handleEvent(e,t)}catch(t){i(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(E.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(E.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(E.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(E.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(E.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(E.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(E.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(E.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(E.WorkspaceDeleted,{workspace:e})}}const R=new P;function U(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const C=U().invalidate,x=U().invalidate,_=U().invalidate,I="bb",T={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},A={Success:"success",Cancel:"cancel",Error:"error"},F={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function O(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(I,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function W(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:O({action:T.Checkout,status:A.Success,ws:e,screen:F.Subscription},n),cancelUrl:O({action:T.Checkout,status:A.Cancel,ws:e,screen:F.Subscription},n)}}function N(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:O({action:T.CreditPurchase,status:A.Success,ws:e,screen:F.Credits},n),cancelUrl:O({action:T.CreditPurchase,status:A.Cancel,ws:e,screen:F.Credits},n)}}function J(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(I);if(!e)return null;const t=function(e){const t={};if(!e)return t;const n=e.split(",");for(const e of n){const n=e.indexOf(":");if(-1===n)continue;const r=decodeURIComponent(e.slice(0,n)),s=decodeURIComponent(e.slice(n+1));r&&(t[r]=s)}return t}(e);return Object.keys(t).length>0?t:null}catch{return null}}function L(){if("undefined"!=typeof window)try{const e=new URL(window.location.href);e.searchParams.has(I)&&(e.searchParams.delete(I),window.history.replaceState({},"",e.toString()))}catch{}}function M(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:o,allowedOrigins:i}=t;return o||i?.length?o&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||i?.some(e=>e.replace(/\/+$/,"")===n.origin)?e:null:e}function B(e,t="/",n={}){if("undefined"==typeof window||!window.location)return!1;const r=M(e,n);return window.location.href=r??M(t)??"/",!0}const j="saas-auth-intent";function D(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function q(e){M(e,{sameOrigin:!0})&&u(j,{returnUrl:e,createdAt:Date.now()})}function z(){const e=function(e,t){const n=a(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(i(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):r}catch(t){return i(t,{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null}}(j,D);return c(j),e?Date.now()-e.createdAt>6e5?null:M(e.returnUrl,{sameOrigin:!0}):null}function K(){c(j)}const V={usd:"$",eur:"€",gbp:"£",jpy:"¥",cad:"CA$",aud:"A$",chf:"CHF",cny:"¥",hkd:"HK$",sgd:"S$",inr:"₹",mxn:"MX$",brl:"R$",nzd:"NZ$",sek:"kr",nok:"kr",dkk:"kr",pln:"zł",thb:"฿"},G={usd:"🇺🇸",eur:"🇪🇺",gbp:"🇬🇧",jpy:"🇯🇵",cad:"🇨🇦",aud:"🇦🇺",chf:"🇨🇭",cny:"🇨🇳",hkd:"🇭🇰",sgd:"🇸🇬",inr:"🇮🇳",mxn:"🇲🇽",brl:"🇧🇷",nzd:"🇳🇿",sek:"🇸🇪",nok:"🇳🇴",dkk:"🇩🇰",pln:"🇵🇱",thb:"🇹🇭"};function H(e){return e&&e.trim()?G[e.trim().toLowerCase()]??"":""}function Q(e){if(!e||!e.trim())return"";const t=e.trim().toLowerCase();return V[t]??t.toUpperCase()}const Y=["usd","eur","gbp","jpy","cad","aud","chf","cny","hkd","sgd","inr","mxn","brl","nzd","sek","nok","dkk","pln","thb"],Z=Y.map(e=>({value:e,label:`${e.toUpperCase()} (${Q(e)})`})),X=new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"]);function ee(e){return X.has((e??"").trim().toLowerCase())}function te(e,t){return ee(t)?e.toLocaleString("en-US"):(e/100).toFixed(2)}function ne(e,t){return Q(t)+te(e,t)}const re={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included"};function se(e,t,n,r){if(null==e||e<0)return null;const s={...re,...r},o=null!=t&&t>=1?t:1,i=Q(n),a=te(e,n);return 1===o?`${i}${a}/${s.unit}`:`${i}${a}/${o.toLocaleString()} ${s.units}`}function oe(e,t,n,r,s,o){if(null==e||e<0)return null;const i={...re,...o},a=null!=t&&t>=1?t:1,c=Q(r),u=te(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return a>=2?`${c}${u}/${a.toLocaleString()} ${e}`:`${c}${u}/${n}`}return 1===a?`${c}${u}/${i.unit}`:`${c}${u}/${a.toLocaleString()} ${i.units}`}function ie(e,t="unit"){const n=(e||"").trim().toLowerCase();if(!n)return t;const r=n.split(/\s+/)[0]??n;return new Set(["series","species","status","analysis","basis","bus","campus","corpus","axis"]).has(r)?r:r.endsWith("ies")&&r.length>3?r.slice(0,-3)+"y":r.endsWith("ses")||r.endsWith("xes")||r.endsWith("zes")||r.endsWith("ches")||r.endsWith("shes")?r.slice(0,-2):r.endsWith("s")&&!r.endsWith("ss")&&r.length>1?r.slice(0,-1):r||t}function ae(e,t,n,r,s,o,i,a){const c={...re,...i};if(!1===a)return null!=e?`${c.included}: ${e.toLocaleString()} (${c.hardLimit??"hard limit"})`:c.hardLimit??"Hard limit";const u=o??(n.endsWith("s")?n:`${n}s`),l=null!=s&&s>=2?`${s.toLocaleString()} ${u}`:n;return null!=e&&null!=t?`${c.included}: ${e.toLocaleString()}, ${c.afterThat} ${ne(t,r)}/${l}`:null!=e?`${c.included}: ${e.toLocaleString()}`:null!=t?`${c.afterIncluded}: ${ne(t,r)}/${l}`:"—"}function ce(e,t){if(null==e)return null;const n=e[t??"monthly"];return n?{included:n.included,...void 0!==n.overage&&{overage:n.overage},...void 0!==n.unitSize&&{unitSize:n.unitSize},allowOverage:!1!==e.allowOverage}:null}const ue={included:"included",then:"then"};function le(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,o=n.labels??ue,i=n.currencySymbol??Q(s??"");if(null==e)return"—";const{included:a,overage:c}=e,u=`${a} ${o.included}`;if(!1===e.allowOverage)return`${u} (hard limit)`;if(null==c)return u;const l=ee(s),d=r&&!l?c/100:c,p="number"==typeof d&&Number.isFinite(d)?l?d.toLocaleString("en-US"):d.toFixed(2):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${o.then} ${i}${p}${h}`}const de={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},pe={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},he={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},fe={Feature:"feature",Limit:"limit",Quota:"quota"},ge={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},we={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},ye={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},me={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function ke(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 be(e,t,n){const r=ke(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function Se(e,t,n){const r=ke(e,t);if(!r?.stripePrices)return null;const s=n===de.Monthly?"monthlyPriceId":n===de.Yearly?"yearlyPriceId":"quarterlyPriceId",o=n===de.Monthly?"monthly":n===de.Yearly?"yearly":void 0;return r.stripePrices[s]??(o?r.stripePrices[o]:void 0)??null}function ve(e,t,n,r){const s=ke(e,t),o=s?.quotaOverages?.[n];if(o)return o[r]}function $e(e,t){const n=ke(e,t);return n?n.currency:e.plan?.currency??""}function Ee(e){const t=new Set;for(const n of e)n.pricingVariants?.forEach(e=>{e.currency&&t.add(e.currency.toLowerCase())});return Array.from(t).sort()}function Pe(e,t,n,r){const s=e.quotas?.[n];if(null==s)return null;const o=s[r];if(!o)return null;const i=ve(e,t,n,r);return{included:o.included,...void 0!==o.unitSize&&{unitSize:o.unitSize},...void 0!==i&&{overage:i},allowOverage:!1!==s.allowOverage}}function Re(e,t){if(!e)return null;for(const n of t){const t=n.pricingVariants;if(t?.length)for(const n of t){const t=n.stripePrices;if(t){if(t.monthlyPriceId===e||t.monthly===e)return{interval:"monthly",currency:n.currency};if(t.yearlyPriceId===e||t.yearly===e)return{interval:"yearly",currency:n.currency};if(t.quarterlyPriceId===e)return{interval:"quarterly",currency:n.currency}}}}return null}function Ue(e,t){const n=ke(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Ce(e,t,n){const r=Ue(e,t);return r?.perSeat?r.perSeat[n]??null:null}function xe(e,t){return Math.max(0,e-(t||0))}function _e(e,t,n,r){const s=Ue(e,t);if(!s)return null;return xe(r,s.includedSeats)*(Ce(e,t,n)??0)}function Ie(e,t,n,r){const s=be(e,t,n);if(null===s)return null;if(void 0===r)return s;return s+(_e(e,t,n,r)??0)}function Te(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=Ue(t,n);if(e)return{maxUsers:e.maxSeats??0,source:"seat_pricing",includedSeats:e.includedSeats??0,hasSeatPricing:!0}}return null!=r&&r>0?{maxUsers:r,source:"settings",includedSeats:0,hasSeatPricing:!1}:{maxUsers:0,source:"none",includedSeats:0,hasSeatPricing:!1}}function Ae(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:o,source:i}=n;if(o<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=o){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[i]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[i]??"users.memberLimitMessage",blockMessageValues:{maxUsers:o}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const Fe={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"},Oe=Object.values(Fe),We={admin:Oe.filter(e=>e!==Fe.WORKSPACE_DELETE),member:[Fe.WORKSPACE_SETTINGS_VIEW,Fe.WORKSPACE_MEMBERS_VIEW,Fe.WORKSPACE_FEATURES_VIEW,Fe.WORKSPACE_BILLING_VIEW,Fe.WORKSPACE_USAGE_VIEW],viewer:[Fe.WORKSPACE_SETTINGS_VIEW,Fe.WORKSPACE_MEMBERS_VIEW]};function Ne(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 Je(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(Oe);if(s)for(const t of Ne(s))e.add(t);if(n.permissions)for(const t of Ne(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of Ne(r.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);if(!o)return new Set;const i=n.permissions,a=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!i&&o in i,d=!!a&&o in a,p=o in We;let h;if(l)h=c(i[o]);else if(d)h=c(a[o]);else if(p)h=We[o];else{const e=r?.workspace?.defaultRole;h=e&&e in We?We[e]:[]}const f=new Set(h),g=l?u(i[o]):[],w=s?.[o]?u(s[o]):[],y=l?g:w;for(const e of y)f.add(e);return function(e,t,n){if(!n?.workspace)return;const{canInviteMembers:r}=n.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(Fe.WORKSPACE_MEMBERS_INVITE)}(f,o,r),f}function Le(e,t){const n=Je(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const Me="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n try {\n const payload = event.data.json();\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n";var Be;!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(Be||(Be={}));const je=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),De=(e,t)=>e>>>t|e<<32-t;function qe(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,o=1359893119,i=2600822924,a=528734635,c=1541459225;const u=e.length,l=u+1,d=l+(56-l%64+64)%64+8,p=new Uint8Array(d);p.set(e,0),p[u]=128;const h=8*u,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const w=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;w[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=De(w[e-15],7)^De(w[e-15],18)^w[e-15]>>>3,n=De(w[e-2],17)^De(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+n>>>0}let u=t,l=n,d=r,h=s,f=o,g=i,y=a,m=c;for(let e=0;e<64;e++){const t=m+(De(f,6)^De(f,11)^De(f,25))+(f&g^~f&y)+je[e]+w[e]>>>0,n=u&l^u&d^l&d;m=y,y=g,g=f,f=h+t>>>0,h=d,d=l,l=u,u=t+((De(u,2)^De(u,13)^De(u,22))+n>>>0)>>>0}t=t+u>>>0,n=n+l>>>0,r=r+d>>>0,s=s+h>>>0,o=o+f>>>0,i=i+g>>>0,a=a+y>>>0,c=c+m>>>0}const y=new Uint8Array(32),m=[t,n,r,s,o,i,a,c];for(let e=0;e<8;e++)y[4*e]=m[e]>>>24&255,y[4*e+1]=m[e]>>>16&255,y[4*e+2]=m[e]>>>8&255,y[4*e+3]=255&m[e];return y}function ze(e){return(new TextEncoder).encode(e)}function Ke(e,t){let n=e;n.length>64&&(n=qe(n));const r=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,s[e]=92^t}const o=qe(Ge(r,t));return qe(Ge(s,o))}function Ve(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 Ge(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function He(e){const{body:t,signature:n,timestamp:r,secret:s,maxAgeSeconds:o=300}=e;if(!(n&&r&&s&&t))return!1;const i="sha256=";if(!n.startsWith(i))return!1;const a=n.slice(7);if(o>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>o)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(a);if(!c)return!1;const u=Ke(ze(s),ze(`${r}.${t}`));return c.length===u.length&&Ve(c,u)}function Qe(e){if(!He(e))return null;try{return JSON.parse(e.body)}catch{return null}}const Ye=300,Ze="/.well-known/oauth-protected-resource",Xe="/.well-known/agent-skills",et="/.well-known/api-catalog",tt="/.well-known/mcp/server-card.json",nt="/.well-known/agent-card.json",rt="application/json",st="application/linkset+json",ot="text/markdown; charset=utf-8",it="text/plain; charset=utf-8",at="application/xml; charset=utf-8",ct=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ut(e){return e.replace(/\/+$/,"")}function lt(e){return`public, max-age=${e}, s-maxage=${e}`}function dt(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}(qe(ze(e)))}const pt=new Map;async function ht(e,t,n,r){if(!r||r<=0)return e(t,n);const s=new AbortController,o=setTimeout(()=>s.abort(),r);try{return await e(t,{...n,signal:s.signal})}finally{clearTimeout(o)}}async function ft(e){const t=e.cacheTtlSeconds??Ye,n=`${ut(e.serverUrl)}::${e.orgId}`,r=pt.get(n);if(r&&r.expiresAt>Date.now())return r.value;const s=e.fetch??fetch,o=`${ut(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const t=await ht(s,o,{headers:{Accept:rt}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(i=e)}}catch{}return pt.set(n,{value:i,expiresAt:Date.now()+1e3*t}),i}const gt=new Map;function wt(){pt.clear(),gt.clear()}function yt(e,t){const n=ut(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:Ze};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=`${Xe}/index.json`),e.apiCatalog?.length&&(r.api_catalog=et),e.mcpServerCard&&(r.mcp_server_card=tt),!1!==e.a2aCard&&(r.a2a_agent_card=nt),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return Ot({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 mt(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return Ze+n}function kt(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||Ze,o=n??`${ut(t.serverUrl)}/org/${t.orgId}`,i=t.scopes?.map(e=>e.name),a=r.map(e=>{const n=e.resource??ut(t.siteUrl),r=e.scopes??i;return{path:mt(n),metadata:{resource:n,authorization_servers:[o],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?Ot(c.metadata,t):s===Ze&&1===a.length?Ot(a[0].metadata,t):null}function bt(e){const t=e.skills??[];if(!t.length)return null;const n=ut(e.siteUrl);return Ot({$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}${St(e)}`,digest:dt(e.content)}))},e)}function St(e){return e.path??`${Xe}/${e.name}/SKILL.md`}function vt(e,t){const n=(t.skills??[]).find(t=>St(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:lt(t.cacheTtlSeconds??Ye)}:null}function $t(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:it,body:t.join("\n")+"\n",cacheControl:lt(e.cacheTtlSeconds??Ye)}}function Et(e){return e.llmsTxt?{status:200,contentType:it,body:e.llmsTxt,cacheControl:lt(e.cacheTtlSeconds??Ye)}:null}function Pt(e){return e.llmsFullTxt?{status:200,contentType:it,body:e.llmsFullTxt,cacheControl:lt(e.cacheTtlSeconds??Ye)}:null}function Rt(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=ut(e.siteUrl),r=t.serviceUrl??n,s=t.transportProtocol??"http",o=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 Ot({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:o,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}function Ut(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:lt(e.cacheTtlSeconds??Ye)}:null}function Ct(e){return e.endsWith(".json")||e.includes(".well-known/")?rt:e.endsWith(".md")?ot:e.endsWith(".xml")?at:it}function xt(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}function _t(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:st,body:JSON.stringify({linkset:n},null,2),cacheControl:lt(e.cacheTtlSeconds??Ye)}}function It(e){const t=e??{tools:!0},n={tools:!1,resources:!1,prompts:!1};for(const[e,r]of Object.entries(t))n[e]=!1!==r&&null!=r;return n}function Tt(e){const t=e.mcpServerCard;return t?Ot({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-06-18",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:It(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function At(e){const t=e.mcpServerCard;if(!t)return null;const n=ut(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${mt(t.endpoint)}`}}catch{}return Ot({$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:It(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${tt}`,...r?{authentication:r}:{}}]},e)}function Ft(e,t){const n=lt(e.cacheTtlSeconds??Ye);if(e.authMd)return{status:200,contentType:ot,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:ot,body:s,cacheControl:n}}function Ot(e,t){return{status:200,contentType:rt,body:JSON.stringify(e,null,2),cacheControl:lt(t.cacheTtlSeconds??Ye)}}function Wt(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Nt(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Wt(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: ${Wt(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${Wt(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${Wt(e.crawlDelay)}`),n.join("\n")}function Jt(e){const t=e.robots??{},n=ut(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",o="allow"===s?[{userAgent:[...ct],allow:["/"]}]:"deny"===s?[{userAgent:[...ct],disallow:["/"]}]:s,i=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...r.map((e,n)=>Nt(e,0===n?t.contentSignals:void 0)),...o.map(e=>Nt(e)),...i.length?[i.map(e=>`Sitemap: ${Wt(e)}`).join("\n")]:[]];return{status:200,contentType:it,body:a.join("\n\n")+"\n",cacheControl:lt(e.cacheTtlSeconds??Ye)}}function Lt(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Mt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Bt(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=ut(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>${Mt(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Mt(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Mt(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Lt(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:at,body:r,cacheControl:lt(e.cacheTtlSeconds??Ye)}}function jt(e){if(!e)return!1;let t=0,n=0;for(const r of e.split(",")){const[e,...s]=r.trim().split(";"),o=e.trim().toLowerCase();let i=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)||(i=e)}}"text/markdown"===o||"text/x-markdown"===o?t=Math.max(t,i):"text/html"!==o&&"text/*"!==o&&"*/*"!==o||(n=Math.max(n,i))}return t>0&&t>=n}function Dt(e,t,n){const r=jt(e);return{status:200,contentType:r?ot:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:lt(n?.cacheTtlSeconds??Ye),vary:"Accept"}}function qt(e){const t=ut(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}${nt}>; 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}${et}>; rel="api-catalog"; type="${st}"`),e.mcpServerCard&&n.push(`<${t}${tt}>; rel="mcp-server"; type="application/json"`),n.join(", ")}async function zt(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return yt(t,await ft(t))}if(n===nt)return Rt(t);if("/.well-known/http-message-signatures-directory"===n)return Ut(t);if("/.well-known/security.txt"===n)return $t(t);if(n===`${Xe}/index.json`)return bt(t);if(n.startsWith(`${Xe}/`)&&n.endsWith("SKILL.md"))return vt(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await ft(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??Ye,r=gt.get(e);if(r&&r.expiresAt>Date.now())return r.value;const s=t.fetch??fetch;let o=null;try{const n=await ht(s,e,{headers:{Accept:rt}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(o=e)}}catch{}return gt.set(e,{value:o,expiresAt:Date.now()+1e3*n}),o}(e.metadataUrl,t);return Ot(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===et)return _t(t);if(n===tt)return Tt(t);if("/.well-known/mcp.json"===n)return At(t);if(n.startsWith(Ze)){const e=await ft(t);return kt(n,t,e.authorizationServer?.issuer)}return null}async function Kt(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??Ct(e),body:r.body,cacheControl:r.cacheControl??lt(t.cacheTtlSeconds??Ye)}}(n,t);return r||("/robots.txt"===n?Jt(t):"/llms-full.txt"===n?Pt(t):"/sitemap.xml"===n?Bt(t):"/llms.txt"===n?Et(t):"/auth.md"===n?Ft(t,await ft(t)):"/security.txt"===n?$t(t):n.startsWith("/.well-known")?zt(n,t):null)}function Vt(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)}function Gt(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 Ht(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 Qt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function Yt(e){return JSON.parse((new TextDecoder).decode(Ht(e)))}function Zt(e,t,n={}){const r=n.clockToleranceSec??60,s=n.requireExp??!0;if(!e||!t)throw new Qt("invalid_token","Missing token or client secret");const o=e.split(".");if(3!==o.length)throw new Qt("invalid_token","Malformed JWT");const[i,a,c]=o;let u,l;try{u=Yt(i),l=Yt(a)}catch{throw new Qt("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new Qt("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const d=Ke(ze(t),ze(`${i}.${a}`));let p;try{p=Ht(c)}catch{throw new Qt("invalid_signature","Unreadable JWT signature")}if(!Ve(d,p))throw new Qt("invalid_signature","JWT signature verification failed");const h=Math.floor(Date.now()/1e3);if(s&&"number"!=typeof l.exp)throw new Qt("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof l.exp&&h>l.exp+r)throw new Qt("token_expired","JWT has expired");if("number"==typeof l.nbf&&h+r<l.nbf)throw new Qt("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&l.iss!==n.issuer)throw new Qt("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=l.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new Qt("invalid_audience","JWT audience mismatch")}return l}function Xt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function en(e){return Gt(ze(JSON.stringify(e)))}function tn(e,t,n){if(!t)throw new Qt("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),s={iat:r,exp:r+(n?.expiresInSec??3600),...e},o=`${en({alg:"HS256",typ:"JWT"})}.${en(s)}`;return`${o}.${Gt(Ke(ze(t),ze(o)))}`}function nn(e){const t=Xt(e.authorization);if(!t)throw new Qt("invalid_token","Missing Bearer token");return Zt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function rn(e){const t=Xt(e.authorization);if(!t)throw new Qt("invalid_token","Missing Bearer token");return Zt(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function sn(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function on(e){return{success:!1,token:"",message:e}}async function an(e){let t;try{t=nn(e)}catch(e){return{status:401,body:on(e instanceof Qt?e.code:"invalid_token")}}return{status:200,body:sn(await e.mintToken(t))}}async function cn(e){let t;try{t=rn(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof Qt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}}function un(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function ln(e){const t=[`Bearer resource_metadata="${un(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${un(e.error)}"`),e.errorDescription&&t.push(`error_description="${un(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const dn=12,pn=16;function hn(){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 fn=new Map;function gn(e){let t=fn.get(e);return t||(t=(async()=>{const t=await hn().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return hn().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),fn.set(e,t)),t}function wn(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(dn)),r=await gn(e),s=new Uint8Array(await hn().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),o=s.subarray(s.length-pn),i=s.subarray(0,s.length-pn),a=new Uint8Array(28+i.length);return a.set(n,0),a.set(o,dn),a.set(i,28),Gt(a)},async decryptSessionRef(t){try{const n=Ht(t);if(n.length<=28)return null;const r=n.slice(0,dn),s=n.subarray(dn,28),o=n.subarray(28),i=new Uint8Array(o.length+pn);i.set(o,0),i.set(s,o.length);const a=await gn(e),c=await hn().decrypt({name:"AES-GCM",iv:r},a,i);return(new TextDecoder).decode(c)}catch{return null}}}}async function yn(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,o=t.sessionId?await wn(n).encryptSessionRef(t.sessionId):void 0;return{token:tn({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...o?{sid:o}:{},...e.extraClaims},n,{expiresInSec:r}),expiresIn:r}}function mn(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 kn(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=wn(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 o;try{o=Zt(s,t,{...e.verify})}catch{return null}if(r.length){const t=o.aud?Array.isArray(o.aud)?o.aud:[o.aud]:[];if(!t.length&&e.requireAudience)return mn(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return mn(t,r,"aud does not include this resource"),null}const i="string"==typeof o.sid?await n.decryptSessionRef(o.sid):null,a=Array.isArray(o.scope)?o.scope:"string"==typeof o.scope?o.scope.split(" ").filter(Boolean):void 0;return{sessionId:i??"",userId:"string"==typeof o.userId?o.userId:"string"==typeof o.sub?o.sub:void 0,workspaceId:"string"==typeof o.workspaceId?o.workspaceId:void 0,scopes:a,claims:o}}}}function bn(e){const{serverUrl:t,orgId:n,version:r="v1",getSessionId:s,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const d={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},p=e=>{const s={serverUrl:t,version:r,orgId:n,sessionId:e,...d};return{workspace:new v(s),user:new S(s),settings:new b(s),push:new k(s)}},h=new v({serverUrl:t,version:r,orgId:n,...d}),f=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,n)=>(await e()).workspace.updateWorkspace(t,n),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,n,r)=>(await e()).workspace.addUser(t,{email:n,role:r}),remove:async(t,n)=>(await e()).workspace.removeUser(t,n),updateRole:async(t,n,r)=>(await e()).workspace.updateUser(t,n,{role:r}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,n)=>(await e()).workspace.createCheckoutSession(t,n),update:async(t,n)=>(await e()).workspace.updateSubscription(t,n),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,n)=>(await e()).workspace.createBillingPortalSession(t,n)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,n,r)=>(await e()).workspace.listInvoices(t,n,r),get:async(t,n)=>(await e()).workspace.getInvoice(t,n)},usage:{record:async(t,n)=>(await e()).workspace.recordUsage(t,n),recordBatch:async(t,n)=>(await e()).workspace.recordUsageBatch(t,n),getQuota:async(t,n)=>(await e()).workspace.getQuotaUsageStatus(t,n),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,n)=>(await e()).workspace.getUsageLogs(t,n)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,n,r)=>(await e()).workspace.updateFeature(t,n,r)},notification:{send:async(t,n,r,s)=>(await e()).workspace.sendNotification(t,n,r,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,n)=>(await e()).workspace.consumeCredits(t,n),purchase:async(t,n)=>(await e()).workspace.purchaseCredits(t,n),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,n)=>(await e()).workspace.getCreditTransactions(t,n),getBuckets:async(t,n)=>(await e()).workspace.getCreditBuckets(t,n),getExpiring:async(t,n)=>(await e()).workspace.getExpiringCredits(t,n),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,n,r)=>{const s=await e(),[o,i,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return Le(r,{userId:n,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,n)=>{const r=await e(),[s,o,i]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return Je({userId:n,workspaceRole:a?.role??null,workspace:s,settings:o})}}}),g=f(async()=>p(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=p(e);return f(async()=>t)},client:{forSession:p},...g}}export{ct as AI_BOT_USER_AGENTS,$ as ApiVersion,Qt as AppBridgeError,w as AuthApi,Be as AuthStatus,T as BBAction,F as BBScreen,A as BBStatus,I as BB_PARAM,g as BaseApi,m as BetaForm,de as BillingIntervals,bn as BuildBase,V as CURRENCY_DISPLAY,G as CURRENCY_FLAG,we as CreditBucketSource,ye as CreditBucketStatus,me as CreditTransactionType,We as DEFAULT_ROLE_PERMISSIONS,ge as DunningState,P as EventEmitter,he as InvoiceStatuses,Y as PLAN_CURRENCY_CODES,Z as PLAN_CURRENCY_OPTIONS,Me as PUSH_SERVICE_WORKER_SCRIPT,Fe as Permission,k as PushApi,E as SDKEvent,b as SettingsApi,fe as SubscriptionItemType,pe as SubscriptionStatus,S as UserApi,v as WorkspaceApi,on as appTokenFailure,sn as appTokenSuccess,ln as bearerChallenge,Rt as buildA2AAgentCard,yt as buildAgentCard,bt as buildAgentSkillsIndex,_t as buildApiCatalog,Ft as buildAuthMd,qt as buildDiscoveryLinkHeader,xt as buildDnsAidRecords,Pt as buildLlmsFullTxt,Et as buildLlmsTxt,At as buildMcpDiscoveryManifest,Tt as buildMcpServerCard,kt as buildProtectedResourceMetadata,Jt as buildRobotsTxt,$t as buildSecurityTxt,Bt as buildSitemap,vt as buildSkillMd,Ut as buildWebBotAuthDirectory,kn as buildbaseAuth,xe as calculateBillableSeats,_e as calculateSeatOverageCents,Ie as calculateTotalSubscriptionCents,L as cleanBBParams,wt as clearAgentReadinessCache,K as clearAuthIntent,z as consumeAuthIntent,O as createBBUrl,W as createCheckoutRedirectUrls,N as createCreditPurchaseRedirectUrls,wn as createSessionRefCrypto,bn as default,R as eventEmitter,Xt as extractBearerToken,ft as fetchAgentReadiness,ne as formatCents,se as formatOverageRate,oe as formatOverageRateWithLabel,ae as formatQuotaIncludedOverage,le as formatQuotaWithPrice,Ee as getAvailableCurrenciesFromPlans,be as getBasePriceCents,Re as getBillingIntervalAndCurrencyFromPriceId,H as getCurrencyFlag,Q as getCurrencySymbol,$e as getDisplayCurrency,Ce as getPerSeatPriceCents,ke as getPricingVariant,ce as getQuotaDisplayValue,Pe as getQuotaDisplayWithVariant,ve as getQuotaOverageCents,ie as getQuotaUnitLabelFromName,Ue as getSeatPricing,Se as getStripePriceIdForInterval,cn as handleAppRevokeRequest,an as handleAppTokenRequest,Le as hasPermission,C as invalidateCreditBalance,x as invalidateQuotaUsage,_ as invalidateSubscription,ee as isZeroDecimalCurrency,te as minorAmountToDisplay,yn as mintAgentToken,Dt as negotiateMarkdown,Qe as parseWebhookEvent,Vt as provideWebMcpTools,J as readBBParams,Kt as resolveAgentPath,Te as resolveMaxUsers,Je as resolvePermissions,zt as resolveWellKnown,B as safeRedirect,q as saveAuthIntent,dt as sha256Digest,tn as signClientJwt,Ae as validateInvite,M as validateRedirectUrl,rn as verifyAppRevokeRequest,nn as verifyAppTokenRequest,Zt as verifyClientJwt,He as verifyWebhookSignature,jt as wantsMarkdown};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("zod");function t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function r(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4==0?"":"=".repeat(4-t.length%4),s=atob(t+r),n=new Uint8Array(s.length);for(let e=0;e<s.length;e++)n[e]=s.charCodeAt(e);return n}const s=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]),n=(e,t)=>e>>>t|e<<32-t;function o(e){let t=1779033703,r=3144134277,o=1013904242,a=2773480762,i=1359893119,c=2600822924,u=528734635,l=1541459225;const p=e.length,d=p+1,h=d+(56-d%64+64)%64+8,g=new Uint8Array(h);g.set(e,0),g[p]=128;const w=8*p,f=Math.floor(w/4294967296),m=w>>>0;g[h-8]=f>>>24&255,g[h-7]=f>>>16&255,g[h-6]=f>>>8&255,g[h-5]=255&f,g[h-4]=m>>>24&255,g[h-3]=m>>>16&255,g[h-2]=m>>>8&255,g[h-1]=255&m;const y=new Uint32Array(64);for(let e=0;e<h;e+=64){for(let t=0;t<16;t++){const r=e+4*t;y[t]=g[r]<<24|g[r+1]<<16|g[r+2]<<8|g[r+3]}for(let e=16;e<64;e++){const t=n(y[e-15],7)^n(y[e-15],18)^y[e-15]>>>3,r=n(y[e-2],17)^n(y[e-2],19)^y[e-2]>>>10;y[e]=y[e-16]+t+y[e-7]+r>>>0}let p=t,d=r,h=o,w=a,f=i,m=c,b=u,k=l;for(let e=0;e<64;e++){const t=k+(n(f,6)^n(f,11)^n(f,25))+(f&m^~f&b)+s[e]+y[e]>>>0,r=p&d^p&h^d&h;k=b,b=m,m=f,f=w+t>>>0,w=h,h=d,d=p,p=t+((n(p,2)^n(p,13)^n(p,22))+r>>>0)>>>0}t=t+p>>>0,r=r+d>>>0,o=o+h>>>0,a=a+w>>>0,i=i+f>>>0,c=c+m>>>0,u=u+b>>>0,l=l+k>>>0}const b=new Uint8Array(32),k=[t,r,o,a,i,c,u,l];for(let e=0;e<8;e++)b[4*e]=k[e]>>>24&255,b[4*e+1]=k[e]>>>16&255,b[4*e+2]=k[e]>>>8&255,b[4*e+3]=255&k[e];return b}function a(e){return(new TextEncoder).encode(e)}function i(e,t){let r=e;r.length>64&&(r=o(r));const s=new Uint8Array(64),n=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<r.length?r[e]:0;s[e]=54^t,n[e]=92^t}const a=o(c(s,t));return o(c(n,a))}function c(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}class u extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function l(e){return JSON.parse((new TextDecoder).decode(r(e)))}function p(e,t,s={}){const n=s.clockToleranceSec??60,o=s.requireExp??!0;if(!e||!t)throw new u("invalid_token","Missing token or client secret");const c=e.split(".");if(3!==c.length)throw new u("invalid_token","Malformed JWT");const[p,d,h]=c;let g,w;try{g=l(p),w=l(d)}catch{throw new u("invalid_token","Unreadable JWT segments")}if("HS256"!==g.alg)throw new u("invalid_algorithm",`Unexpected JWT alg: ${String(g.alg)}`);const f=i(a(t),a(`${p}.${d}`));let m;try{m=r(h)}catch{throw new u("invalid_signature","Unreadable JWT signature")}if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let s=0;s<e.length;s++)r|=e[s]^t[s];return 0===r}(f,m))throw new u("invalid_signature","JWT signature verification failed");const y=Math.floor(Date.now()/1e3);if(o&&"number"!=typeof w.exp)throw new u("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof w.exp&&y>w.exp+n)throw new u("token_expired","JWT has expired");if("number"==typeof w.nbf&&y+n<w.nbf)throw new u("token_not_yet_valid","JWT is not yet valid");if(void 0!==s.issuer&&w.iss!==s.issuer)throw new u("invalid_issuer","JWT issuer mismatch");if(void 0!==s.audience){const e=w.aud;if(!(Array.isArray(e)?e.includes(s.audience):e===s.audience))throw new u("invalid_audience","JWT audience mismatch")}return w}function d(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function h(e){return t(a(JSON.stringify(e)))}function g(e,r,s){if(!r)throw new u("invalid_secret","Missing signing secret");const n=Math.floor(Date.now()/1e3),o={iat:n,exp:n+(s?.expiresInSec??3600),...e},c=`${h({alg:"HS256",typ:"JWT"})}.${h(o)}`;return`${c}.${t(i(a(r),a(c)))}`}function w(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function f(e){const t=[`Bearer resource_metadata="${w(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${w(e.error)}"`),e.errorDescription&&t.push(`error_description="${w(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const m=e.z.string().optional().describe("Workspace id. Omit to use the workspace bound to your token.");function y(e,t){const r=e.workspaceId??t.workspaceId;if(!r)throw new Error("workspaceId is required — call list_workspaces to find one.");return r}const b={readOnlyHint:!0},k=[{name:"list_workspaces",description:"List the authenticated user's workspaces (id, name, roles).",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.workspace.list()},{name:"get_workspace",description:"Get one workspace: name, members, feature flags, quota snapshot.",inputSchema:e.z.object({workspaceId:m}),annotations:b,execute:(e,t)=>t.bb.workspace.get(y(e,t))},{name:"get_user_profile",description:"Get the authenticated user's profile.",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.users.getProfile()},{name:"list_workspace_users",description:"List the members of a workspace with their roles.",inputSchema:e.z.object({workspaceId:m}),annotations:b,execute:(e,t)=>t.bb.users.list(y(e,t))},{name:"get_subscription",description:"Get a workspace's subscription: plan, status, interval, seats.",inputSchema:e.z.object({workspaceId:m}),annotations:b,execute:(e,t)=>t.bb.subscription.get(y(e,t))},{name:"get_plans",description:"Get the plan group available to a workspace (plans, prices, quotas).",inputSchema:e.z.object({workspaceId:m}),annotations:b,execute:(e,t)=>t.bb.plans.getGroup(y(e,t))},{name:"list_invoices",description:"List a workspace's invoices (newest first).",inputSchema:e.z.object({workspaceId:m,limit:e.z.number().int().min(1).max(100).optional().describe("Max invoices to return."),startingAfter:e.z.string().optional().describe("Invoice id to paginate after.")}),annotations:b,execute:(e,t)=>t.bb.invoices.list(y(e,t),e.limit,e.startingAfter)},{name:"get_quota_usage",description:"Get usage vs. limit for one quota in a workspace.",inputSchema:e.z.object({workspaceId:m,quotaSlug:e.z.string().describe('The quota slug, e.g. "api-calls".')}),annotations:b,execute:(e,t)=>t.bb.usage.getQuota(y(e,t),e.quotaSlug)},{name:"get_all_quota_usage",description:"Get usage vs. limit for every quota in a workspace.",inputSchema:e.z.object({workspaceId:m}),annotations:b,execute:(e,t)=>t.bb.usage.getAll(y(e,t))},{name:"get_credit_balance",description:"Get a workspace's prepaid credit balance.",inputSchema:e.z.object({workspaceId:m}),annotations:b,execute:(e,t)=>t.bb.credits.getBalance(y(e,t))},{name:"list_credit_transactions",description:"Get a workspace's credit transaction history (paginated).",inputSchema:e.z.object({workspaceId:m,limit:e.z.number().int().min(1).max(100).optional(),page:e.z.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getTransactions(y(e,t),{...void 0!==e.limit?{limit:e.limit}:{},...void 0!==e.page?{page:e.page}:{}})},{name:"check_feature_flag",description:"Check whether a feature flag is enabled for a workspace.",inputSchema:e.z.object({workspaceId:m,key:e.z.string().describe("The feature slug.")}),annotations:b,execute:async(e,t)=>{const r=y(e,t),s=await t.bb.workspace.get(r),n=s.features?.[e.key];if(void 0!==n)return{key:e.key,enabled:n,source:"workspace"};const o=(await t.bb.features.list()).find(t=>t.slug===e.key);if(!o)throw new Error(`Unknown feature flag: ${e.key}`);return{key:e.key,enabled:o.defaultValue,source:"default"}}},{name:"check_permission",description:"Check whether a user has permission(s) in a workspace.",inputSchema:e.z.object({workspaceId:m,permission:e.z.union([e.z.string(),e.z.array(e.z.string())]).describe("A permission (or list — all must hold), platform or app-defined."),userId:e.z.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const s=await t.bb.permissions.check(y(e,t),r,e.permission);return{userId:r,permission:e.permission,allowed:s}}},{name:"resolve_permissions",description:"List every permission a user holds in a workspace.",inputSchema:e.z.object({workspaceId:m,userId:e.z.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const s=await t.bb.permissions.resolve(y(e,t),r);return{userId:r,permissions:Array.from(s)}}},{name:"get_invoice",description:"Get one invoice by id.",inputSchema:e.z.object({workspaceId:m,invoiceId:e.z.string().describe("The invoice id.")}),annotations:b,execute:(e,t)=>t.bb.invoices.get(y(e,t),e.invoiceId)},{name:"get_plan_versions",description:"List the plan-group versions available to a workspace.",inputSchema:e.z.object({workspaceId:m}),annotations:b,execute:(e,t)=>t.bb.plans.getVersions(y(e,t))},{name:"get_public_plans",description:"Get a public plan group by slug (no workspace / auth needed).",inputSchema:e.z.object({slug:e.z.string().describe("The plan-group slug.")}),annotations:b,execute:(e,t)=>t.bb.plans.getPublic(e.slug)},{name:"get_plan_version",description:"Get one public plan-group version by id (no auth needed).",inputSchema:e.z.object({groupVersionId:e.z.string().describe("The plan-group version id.")}),annotations:b,execute:(e,t)=>t.bb.plans.getVersion(e.groupVersionId)},{name:"get_usage_logs",description:"Get a workspace's usage log entries (paginated, filterable).",inputSchema:e.z.object({workspaceId:m,quotaSlug:e.z.string().optional(),from:e.z.string().optional().describe("ISO date lower bound."),to:e.z.string().optional().describe("ISO date upper bound."),source:e.z.string().optional(),page:e.z.number().int().min(1).optional(),limit:e.z.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...s}=e;return t.bb.usage.getLogs(y(e,t),s)}},{name:"get_settings",description:"Get the organization settings.",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.settings.get()},{name:"get_credit_packages",description:"List the credit packages a workspace can purchase.",inputSchema:e.z.object({workspaceId:m}),annotations:b,execute:(e,t)=>t.bb.credits.getPackages(y(e,t))},{name:"get_credit_buckets",description:"Get a workspace's credit buckets (paginated).",inputSchema:e.z.object({workspaceId:m,status:e.z.string().optional(),source:e.z.string().optional(),page:e.z.number().int().min(1).optional(),limit:e.z.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...s}=e;return t.bb.credits.getBuckets(y(e,t),s)}},{name:"get_expiring_credits",description:"Get credits expiring within N days (default 7).",inputSchema:e.z.object({workspaceId:m,days:e.z.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getExpiring(y(e,t),e.days)},{name:"get_public_credit_packages",description:"List credit packages publicly (no workspace / auth needed).",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.credits.getPublicPackages()}],S=[{name:"record_usage",description:"Record quota usage for a workspace (metered billing).",inputSchema:e.z.object({workspaceId:m,quotaSlug:e.z.string().describe("The quota slug to record against."),quantity:e.z.number().positive().describe("Amount of usage to record."),idempotencyKey:e.z.string().optional().describe("Dedupe key for safe retries."),metadata:e.z.record(e.z.string(),e.z.unknown()).optional()}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},execute:(e,t)=>t.bb.usage.record(y(e,t),{quotaSlug:e.quotaSlug,quantity:e.quantity,source:"mcp",...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{},...e.metadata?{metadata:e.metadata}:{}})},{name:"consume_credits",description:"Consume prepaid credits from a workspace's balance.",inputSchema:e.z.object({workspaceId:m,amount:e.z.number().positive().describe("Credits to consume."),description:e.z.string().optional().describe("What the credits were spent on."),idempotencyKey:e.z.string().optional().describe("Dedupe key for safe retries.")}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.credits.consume(y(e,t),{amount:e.amount,...e.description?{description:e.description}:{},...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{}})},{name:"send_notification",description:"Send a notification event to a workspace user (or all members when userId is omitted).",inputSchema:e.z.object({workspaceId:m,event:e.z.string().describe('The event slug, e.g. "comment_added".'),userId:e.z.string().optional().describe("Recipient. Omit to notify all members."),message:e.z.string().optional().describe("Message body (used for push).")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.notification.send(y(e,t),e.event,e.userId,e.message?{message:e.message}:void 0)},{name:"record_usage_batch",description:"Record multiple usage entries in one call (max 100 items).",inputSchema:e.z.object({workspaceId:m,items:e.z.array(e.z.object({quotaSlug:e.z.string(),quantity:e.z.number().positive(),idempotencyKey:e.z.string().optional(),metadata:e.z.record(e.z.string(),e.z.unknown()).optional()})).min(1).max(100)}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.usage.recordBatch(y(e,t),{items:e.items.map(e=>({...e,source:"mcp"}))})},{name:"create_workspace",description:"Create a new workspace.",inputSchema:e.z.object({name:e.z.string().describe("Workspace name."),image:e.z.string().optional().describe("Image URL.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.workspace.create({name:e.name,...e.image?{image:e.image}:{}})},{name:"update_workspace",description:"Update a workspace's editable fields (name, image).",inputSchema:e.z.object({workspaceId:m,name:e.z.string().min(1).optional().describe("New workspace name."),image:e.z.string().optional().describe("New image URL.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};return void 0!==e.name&&(r.name=e.name),void 0!==e.image&&(r.image=e.image),t.bb.workspace.update(y(e,t),r)}},{name:"delete_workspace",description:"Delete a workspace. Irreversible.",inputSchema:e.z.object({workspaceId:m}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.workspace.delete(y(e,t))},{name:"invite_workspace_user",description:"Invite a user to a workspace with a role.",inputSchema:e.z.object({workspaceId:m,email:e.z.string().describe("Invitee email."),role:e.z.string().describe("Role to grant.")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.users.invite(y(e,t),e.email,e.role)},{name:"remove_workspace_user",description:"Remove a user from a workspace. Irreversible.",inputSchema:e.z.object({workspaceId:m,userId:e.z.string().describe("The user to remove.")}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.users.remove(y(e,t),e.userId)},{name:"update_workspace_user_role",description:"Change a workspace member's role.",inputSchema:e.z.object({workspaceId:m,userId:e.z.string(),role:e.z.string().describe("The new role.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.users.updateRole(y(e,t),e.userId,e.role)},{name:"update_user_profile",description:"Update the authenticated user's own profile (name, image, country, timezone, language, currency).",inputSchema:e.z.object({name:e.z.string().min(1).optional(),image:e.z.string().optional().describe("Profile image URL."),country:e.z.string().optional().describe("ISO country code."),timezone:e.z.string().optional().describe("IANA timezone."),language:e.z.string().optional().describe("Language code."),currency:e.z.string().optional().describe("Currency code.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};for(const t of["name","image","country","timezone","language","currency"]){const s=e[t];void 0!==s&&(r[t]=s)}return t.bb.users.updateProfile(r)}},{name:"update_feature_flag",description:"Set a feature flag on/off for a workspace.",inputSchema:e.z.object({workspaceId:m,key:e.z.string().describe("The feature slug."),value:e.z.boolean().describe("Enabled?")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.features.update(y(e,t),e.key,e.value)},{name:"create_subscription_checkout",description:"Create a Stripe checkout session to subscribe a workspace to a plan.",inputSchema:e.z.object({workspaceId:m,planVersionId:e.z.string(),billingInterval:e.z.string().optional(),currency:e.z.string().optional(),successUrl:e.z.string().optional(),cancelUrl:e.z.string().optional()}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...s}=e;return t.bb.subscription.checkout(y(e,t),s)}},{name:"update_subscription",description:"Change a workspace's subscription plan.",inputSchema:e.z.object({workspaceId:m,planVersionId:e.z.string(),billingInterval:e.z.string().optional(),successUrl:e.z.string().optional(),cancelUrl:e.z.string().optional()}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const{workspaceId:r,...s}=e;return t.bb.subscription.update(y(e,t),s)}},{name:"cancel_subscription",description:"Cancel a workspace's subscription.",inputSchema:e.z.object({workspaceId:m}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.subscription.cancel(y(e,t))},{name:"resume_subscription",description:"Resume a workspace's canceled subscription.",inputSchema:e.z.object({workspaceId:m}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.subscription.resume(y(e,t))},{name:"get_billing_portal_url",description:"Get a Stripe billing-portal URL for a workspace.",inputSchema:e.z.object({workspaceId:m,returnUrl:e.z.string().optional()}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.subscription.getBillingPortalUrl(y(e,t),e.returnUrl)},{name:"purchase_credits",description:"Create a Stripe checkout session to buy a credit package.",inputSchema:e.z.object({workspaceId:m,creditPackageId:e.z.string(),currency:e.z.string().optional(),successUrl:e.z.string().describe("Redirect URL on success."),cancelUrl:e.z.string().describe("Redirect URL on cancel.")}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...s}=e;return t.bb.credits.purchase(y(e,t),s)}}],v=new Map([...k,...S].map(e=>[e.name,e]));function E(e){if(!1===e)return[];if("readonly"===e)return[...k];if("all"===e)return[...k,...S];const t=e.include?e.include.map(e=>{const t=v.get(e);if(!t)throw new Error(`Unknown built-in MCP tool: ${e}`);return t}):[...k],r=new Set(e.exclude??[]);return t.filter(e=>!r.has(e.name))}const I=["2025-06-18","2025-03-26","2024-11-05"],_=I[0],R="application/json",P=/^[a-zA-Z0-9_-]{1,128}$/,x=-32700,$=-32600,T=-32601,U=-32602,C=-32603;function A(e,t){const r=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===r)return e[t]}function z(e,t){return{status:e,headers:{"Content-Type":R},body:JSON.stringify(t)}}function O(e,t){return z(200,{jsonrpc:"2.0",id:e??null,result:t})}function F(e,t,r,s=200,n){return z(s,{jsonrpc:"2.0",id:e??null,error:{code:t,message:r,...void 0!==n?{data:n}:{}}})}function j(e){return"object"==typeof e&&null!==e&&"function"==typeof e.safeParse}function W(e){return e instanceof Error?e.message:"string"==typeof e?e:JSON.stringify(e)}function N(t){const r=t.serverInfo??{name:"buildbase-mcp",version:"1.0.0"};t.auth&&!t.auth.resourceMetadataUrl&&console.warn("[buildbase/mcp] auth is enabled but `auth.resourceMetadataUrl` is unset — 401 responses will carry no WWW-Authenticate/resource_metadata pointer, so MCP clients cannot discover your authorization server. Set it to your /.well-known/oauth-protected-resource URL.");const s=e=>e.trim().toLowerCase().replace(/\/+$/,""),n=t.allowedOrigins?new Set(t.allowedOrigins.map(s)):null,o=e=>!!e&&!!n&&n.has(s(e)),a=t.builtinTools??(!!t.buildbase&&"readonly"),i=t.maxRequestBytes??1048576;if(!1!==a&&!t.buildbase)throw new Error("builtinTools require a `buildbase` client — pass one to createMcpHandler, or set builtinTools: false.");const c=new Map;for(const e of E(a))c.set(e.name,e);const u=new Set;for(const e of t.tools??[]){if(!P.test(e.name))throw new Error(`Invalid MCP tool name: "${e.name}" (want ${String(P)})`);if(u.has(e.name))throw new Error(`Duplicate MCP tool name: "${e.name}"`);u.add(e.name),c.set(e.name,e)}const l=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`No \`buildbase\` client configured — pass one to createMcpHandler to use bb.${t} in tools.`)}}),p=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`This tool needs an authenticated BuildBase session, but the token carried none (bb.${t}). Re-authenticate.`)}}),h=new Map;function g(t){const r=h.get(t.name);if(r)return r;let s;try{s=j(t.inputSchema)?e.z.toJSONSchema(t.inputSchema,{target:"draft-2020-12"}):t.inputSchema}catch(e){m(e,{method:"tools/list",tool:t.name}),s={type:"object",additionalProperties:!0}}return h.set(t.name,s),s}function w(e){const t=new Set(e?.scopes??[]);return Array.from(c.values()).filter(e=>(e.requiredScopes??[]).every(e=>t.has(e)))}function m(e,r){try{t.onError?.(e instanceof Error?e:new Error(W(e)),r)}catch{}}function y(){if(t.auth&&t.auth.resourceMetadataUrl){const e=f({resourceMetadataUrl:t.auth.resourceMetadataUrl});return{status:e.status,headers:e.headers,body:e.body}}return z(401,{error:"unauthorized"})}const b=Array.isArray(t.cors)?new Set(t.cors.map(s)):null;async function k(e){const a=function(e){if(!1===t.cors)return{};const r=A(e.headers,"origin");let a;return a=b?r&&b.has(s(r))?r:null:n?o(r)?r:null:"*",a?{"Access-Control-Allow-Origin":a,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Protocol-Version, Mcp-Session-Id, Last-Event-ID","Access-Control-Expose-Headers":"MCP-Protocol-Version, Mcp-Session-Id, WWW-Authenticate","Access-Control-Max-Age":"86400",..."*"!==a?{Vary:"Origin"}:{}}:{}}(e);if("OPTIONS"===e.method.toUpperCase())return{status:204,headers:a,body:""};const c=await async function(e){const s=e.method.toUpperCase();if(n){const t=A(e.headers,"origin");if(t&&!o(t))return z(403,{error:"origin_not_allowed"})}if("POST"!==s)return{status:405,headers:{"Content-Type":R,Allow:"POST, OPTIONS"},body:JSON.stringify({error:"method_not_allowed"})};if(i>0&&"string"==typeof e.body&&e.body.length>i)return z(413,{error:"payload_too_large"});let a=null;if(!1!==t.auth){const r=d(A(e.headers,"authorization"));if(!r)return y();try{a=await t.auth.verify(r,e)}catch(e){m(e,{method:"auth"}),a=null}if(!a)return y()}if(t.rateLimit){let r;try{r=await t.rateLimit(a,e)}catch(e){m(e,{method:"rateLimit"}),r=!1}if(!("boolean"==typeof r?r:r.ok)){const e="object"==typeof r?r.retryAfter:void 0;return{status:429,headers:{"Content-Type":R,...void 0!==e?{"Retry-After":String(e)}:{}},body:JSON.stringify({error:"rate_limited"})}}}let c=e.body;if("string"==typeof e.body)try{c=JSON.parse(e.body)}catch{return F(null,x,"Invalid JSON",400)}if(Array.isArray(c))return F(null,$,"Batch requests are not supported",400);if("object"!=typeof c||null===c)return F(null,$,"Expected a JSON-RPC request object",400);const u=c,h=u.id,f="string"==typeof u.method?u.method:null;if(!f)return F(h,$,"Missing method",400);if(null==h)return{status:202,headers:{"Content-Type":R},body:""};const b=u.params??{};switch(f){case"initialize":{const e=b.protocolVersion;return O(h,{protocolVersion:"string"==typeof e&&I.includes(e)?e:_,capabilities:{tools:{listChanged:!1}},serverInfo:r,...t.instructions?{instructions:t.instructions}:{}})}case"ping":return O(h,{});case"tools/list":return O(h,{tools:w(a).map(e=>({name:e.name,description:e.description,inputSchema:g(e),...e.annotations?{annotations:e.annotations}:{}}))});case"tools/call":{const r="string"==typeof b.name?b.name:"",s=w(a).find(e=>e.name===r);if(!s)return F(h,U,`Unknown tool: ${r||"(missing name)"}`);let n,o=b.arguments??{};if(j(s.inputSchema)){const e=s.inputSchema.safeParse(o);if(!e.success)return F(h,U,`Invalid arguments for ${r}`,200,{issues:e.error.issues});o=e.data}if(t.context)try{n=await t.context(a,e)}catch(e){return m(e,{method:f,tool:r}),F(h,C,"Context initialization failed")}const i=a?.sessionId??"",c={bb:t.buildbase?i?t.buildbase.withSession(i):p:l,auth:a??{sessionId:""},workspaceId:a?.workspaceId,custom:n};try{const e=await s.execute(o,c),t="object"==typeof e&&null!==e&&!Array.isArray(e);return O(h,{content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e,null,2)}],...t?{structuredContent:e}:{},isError:!1})}catch(e){m(e,{method:f,tool:r});const s=e instanceof Error?e:new Error(W(e));return O(h,{content:[{type:"text",text:t.formatToolError?t.formatToolError(s,{tool:r}):s.message}],isError:!0})}}default:return F(h,T,`Method not found: ${f}`)}}(e);return Object.keys(a).length?{...c,headers:{...c.headers,...a}}:c}return{handle:k,fetch:async function(e){const t={};if(e.headers.forEach((e,r)=>{t[r]=e}),i>0){const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>i)return new Response(JSON.stringify({error:"payload_too_large"}),{status:413,headers:{"Content-Type":R}})}const r="POST"===e.method.toUpperCase()?await e.text():void 0,s=await k({method:e.method,headers:t,body:r});return new Response(""===s.body?null:s.body,{status:s.status,headers:s.headers})},listTools:()=>Array.from(c.values()).map(e=>({name:e.name,description:e.description,...e.annotations?{annotations:e.annotations}:{}})),serverCard:e=>({name:r.name,version:r.version,endpoint:e.endpoint,transport:"streamable-http",capabilities:{tools:{listChanged:!1}},...e.description?{description:e.description}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{}})}}const J=12,M=16;function B(){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 q=new Map;function L(e){let t=q.get(e);return t||(t=(async()=>{const t=await B().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return B().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),q.set(e,t)),t}function H(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(r){const s=globalThis.crypto.getRandomValues(new Uint8Array(J)),n=await L(e),o=new Uint8Array(await B().encrypt({name:"AES-GCM",iv:s},n,(new TextEncoder).encode(r))),a=o.subarray(o.length-M),i=o.subarray(0,o.length-M),c=new Uint8Array(28+i.length);return c.set(s,0),c.set(a,J),c.set(i,28),t(c)},async decryptSessionRef(t){try{const s=r(t);if(s.length<=28)return null;const n=s.slice(0,J),o=s.subarray(J,28),a=s.subarray(28),i=new Uint8Array(a.length+M);i.set(a,0),i.set(o,a.length);const c=await L(e),u=await B().decrypt({name:"AES-GCM",iv:n},c,i);return(new TextDecoder).decode(u)}catch{return null}}}}function D(e,t,r){const s=globalThis.process?.env;"1"===s?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${r}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function G(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const r=H(t),s=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let n=e.resourceMetadataUrl;if(!n&&s.length)try{const e=new URL(s[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");n=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:n,verify:async n=>{let o;try{o=p(n,t,{...e.verify})}catch{return null}if(s.length){const t=o.aud?Array.isArray(o.aud)?o.aud:[o.aud]:[];if(!t.length&&e.requireAudience)return D(t,s,"token carries no aud claim"),null;if(t.length&&!t.some(e=>s.includes(e)))return D(t,s,"aud does not include this resource"),null}const a="string"==typeof o.sid?await r.decryptSessionRef(o.sid):null,i=Array.isArray(o.scope)?o.scope:"string"==typeof o.scope?o.scope.split(" ").filter(Boolean):void 0;return{sessionId:a??"",userId:"string"==typeof o.userId?o.userId:"string"==typeof o.sub?o.sub:void 0,workspaceId:"string"==typeof o.workspaceId?o.workspaceId:void 0,scopes:i,claims:o}}}}const K=300,V="/.well-known/oauth-protected-resource",Q="/.well-known/agent-skills",Y="/.well-known/api-catalog",Z="/.well-known/mcp/server-card.json",X="/.well-known/agent-card.json",ee="application/json",te="application/linkset+json",re="text/markdown; charset=utf-8",se="text/plain; charset=utf-8",ne="application/xml; charset=utf-8",oe=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ae(e){return e.replace(/\/+$/,"")}function ie(e){return`public, max-age=${e}, s-maxage=${e}`}function ce(e){return"sha256:"+function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(o(a(e)))}const ue=new Map;async function le(e,t,r,s){if(!s||s<=0)return e(t,r);const n=new AbortController,o=setTimeout(()=>n.abort(),s);try{return await e(t,{...r,signal:n.signal})}finally{clearTimeout(o)}}async function pe(e){const t=e.cacheTtlSeconds??K,r=`${ae(e.serverUrl)}::${e.orgId}`,s=ue.get(r);if(s&&s.expiresAt>Date.now())return s.value;const n=e.fetch??fetch,o=`${ae(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let a={enabled:!1};try{const t=await le(n,o,{headers:{Accept:ee}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(a=e)}}catch{}return ue.set(r,{value:a,expiresAt:Date.now()+1e3*t}),a}const de=new Map;function he(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const r="/"===t?"":t.replace(/\/+$/,"");return V+r}function ge(e){return e.path??`${Q}/${e.name}/SKILL.md`}function we(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:se,body:t.join("\n")+"\n",cacheControl:ie(e.cacheTtlSeconds??K)}}function fe(e){return e.endsWith(".json")||e.includes(".well-known/")?ee:e.endsWith(".md")?re:e.endsWith(".xml")?ne:se}function me(e){const t=e??{tools:!0},r={tools:!1,resources:!1,prompts:!1};for(const[e,s]of Object.entries(t))r[e]=!1!==s&&null!=s;return r}function ye(e,t){return{status:200,contentType:ee,body:JSON.stringify(e,null,2),cacheControl:ie(t.cacheTtlSeconds??K)}}function be(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function ke(e,t){const r=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${be(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&&r.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])r.push(`Allow: ${be(t)}`);for(const t of e.disallow??[])r.push(`Disallow: ${be(t)}`);return void 0!==e.crawlDelay&&r.push(`Crawl-delay: ${be(e.crawlDelay)}`),r.join("\n")}function Se(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function ve(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ee(e){const t=ae(e.siteUrl),r=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&r.push(`<${t}${X}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const s=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;r.push(`<${s}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&r.push(`<${t}${Y}>; rel="api-catalog"; type="${te}"`),e.mcpServerCard&&r.push(`<${t}${Z}>; rel="mcp-server"; type="application/json"`),r.join(", ")}async function Ie(e,t){const r=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===r){return function(e,t){const r=ae(e.siteUrl),s={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:V};return t.authorizationServer?.metadataUrl&&(s.oauth_authorization_server=t.authorizationServer.metadataUrl,s.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(s.auth="/auth.md"),e.skills?.length&&(s.agent_skills=`${Q}/index.json`),e.apiCatalog?.length&&(s.api_catalog=Y),e.mcpServerCard&&(s.mcp_server_card=Z),!1!==e.a2aCard&&(s.a2a_agent_card=X),e.llmsFullTxt&&(s.llms_full_txt="/llms-full.txt"),ye({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:r,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:r},capabilities:s,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}(t,await pe(t))}if(r===X)return function(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},r=ae(e.siteUrl),s=t.serviceUrl??r,n=t.transportProtocol??"http",o=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 ye({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:s,preferredTransport:n,supportedInterfaces:[{serviceUrl:s,transportProtocol:n}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:r},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:o,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}(t);if("/.well-known/http-message-signatures-directory"===r)return function(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:ie(e.cacheTtlSeconds??K)}:null}(t);if("/.well-known/security.txt"===r)return we(t);if(r===`${Q}/index.json`)return function(e){const t=e.skills??[];if(!t.length)return null;const r=ae(e.siteUrl);return ye({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${r}${ge(e)}`,digest:ce(e.content)}))},e)}(t);if(r.startsWith(`${Q}/`)&&r.endsWith("SKILL.md"))return function(e,t){const r=(t.skills??[]).find(t=>ge(t)===e);return r?{status:200,contentType:"text/markdown; charset=utf-8",body:r.content,cacheControl:ie(t.cacheTtlSeconds??K)}:null}(r,t);if("/.well-known/oauth-authorization-server"===r||"/.well-known/openid-configuration"===r){const e=(await pe(t)).authorizationServer;if(!e?.metadataUrl)return null;const r=await async function(e,t){const r=t.cacheTtlSeconds??K,s=de.get(e);if(s&&s.expiresAt>Date.now())return s.value;const n=t.fetch??fetch;let o=null;try{const r=await le(n,e,{headers:{Accept:ee}},t.fetchTimeoutMs??5e3);if(r.ok){const e=await r.json();e&&"object"==typeof e&&(o=e)}}catch{}return de.set(e,{value:o,expiresAt:Date.now()+1e3*r}),o}(e.metadataUrl,t);return ye(r?r:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(r===Y)return function(e){const t=e.apiCatalog??[];if(!t.length)return null;const r=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:te,body:JSON.stringify({linkset:r},null,2),cacheControl:ie(e.cacheTtlSeconds??K)}}(t);if(r===Z)return function(e){const t=e.mcpServerCard;return t?ye({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-06-18",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:me(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}(t);if("/.well-known/mcp.json"===r)return function(e){const t=e.mcpServerCard;if(!t)return null;const r=ae(e.siteUrl);let s;try{s={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${he(t.endpoint)}`}}catch{}return ye({$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:me(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${r}${Z}`,...s?{authentication:s}:{}}]},e)}(t);if(r.startsWith(V)){const e=await pe(t);return function(e,t,r){const s=t.protectedResources??[];if(!s.length)return null;const n=e.replace(/\/+$/,"")||V,o=r??`${ae(t.serverUrl)}/org/${t.orgId}`,a=t.scopes?.map(e=>e.name),i=s.map(e=>{const r=e.resource??ae(t.siteUrl),s=e.scopes??a;return{path:he(r),metadata:{resource:r,authorization_servers:[o],bearer_methods_supported:e.bearerMethods??["header"],...s?.length?{scopes_supported:s}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=i.find(e=>e.path===n);return c?ye(c.metadata,t):n===V&&1===i.length?ye(i[0].metadata,t):null}(r,t,e.authorizationServer?.issuer)}return null}async function _e(e,t){const r=e.replace(/\/+$/,"")||e,s=function(e,t){const r=t.extraPaths?.[e];if(void 0===r)return null;const s="string"==typeof r?{body:r}:r;return{status:s.status??200,contentType:s.contentType??fe(e),body:s.body,cacheControl:s.cacheControl??ie(t.cacheTtlSeconds??K)}}(r,t);return s||("/robots.txt"===r?function(e){const t=e.robots??{},r=ae(e.siteUrl),s=t.policies??[{userAgent:"*",allow:["/"]}],n=t.aiBots??"allow",o="allow"===n?[{userAgent:[...oe],allow:["/"]}]:"deny"===n?[{userAgent:[...oe],disallow:["/"]}]:n,a=t.sitemaps??(e.sitemap?[`${r}/sitemap.xml`]:[]),i=[`# robots.txt — agent-ready. See ${r}/llms.txt and ${r}/.well-known/agent.json`,...s.map((e,r)=>ke(e,0===r?t.contentSignals:void 0)),...o.map(e=>ke(e)),...a.length?[a.map(e=>`Sitemap: ${be(e)}`).join("\n")]:[]];return{status:200,contentType:se,body:i.join("\n\n")+"\n",cacheControl:ie(e.cacheTtlSeconds??K)}}(t):"/llms-full.txt"===r?function(e){return e.llmsFullTxt?{status:200,contentType:se,body:e.llmsFullTxt,cacheControl:ie(e.cacheTtlSeconds??K)}:null}(t):"/sitemap.xml"===r?function(e){const t=e.sitemap?.urls;if(!t?.length)return null;const r=ae(e.siteUrl),s='<?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>${ve(/^https?:\/\//.test(t.loc)?t.loc:`${r}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${ve(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${ve(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Se(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:ne,body:s,cacheControl:ie(e.cacheTtlSeconds??K)}}(t):"/llms.txt"===r?function(e){return e.llmsTxt?{status:200,contentType:se,body:e.llmsTxt,cacheControl:ie(e.cacheTtlSeconds??K)}:null}(t):"/auth.md"===r?function(e,t){const r=ie(e.cacheTtlSeconds??K);if(e.authMd)return{status:200,contentType:re,body:e.authMd,cacheControl:r};const s=t.authorizationServer;if(!s)return null;const n=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${s.issuer}\`\n- Metadata (RFC 8414): ${s.metadataUrl}\n\nFetch the metadata document above for the \`authorization_endpoint\`, \`token_endpoint\`, 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:re,body:n,cacheControl:r}}(t,await pe(t)):"/security.txt"===r?we(t):r.startsWith("/.well-known")?Ie(r,t):null)}let Re=!0;function Pe(e,...t){Re&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}async function xe(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 $e(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await xe(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await xe(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Te extends Error{constructor(e,t,r,s){super(e),this.code=t,this.context=r,this.originalError=s,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,Te)}}const Ue=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(Re=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new Te("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),s=r instanceof Te?r:new Te(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&Pe(`[SDK Error] ${t.component||"Unknown"}:`,{message:s.message,code:s.code,context:s.context,originalError:s.originalError,stack:s.stack}),this.config.onError)try{this.config.onError(s,t)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(s,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function Ce(e,t={}){Ue.handleError(e,t)}const Ae="saas-session-id";function ze(){if("undefined"==typeof window)return null;try{return function(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return Ce(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}(Ae)}catch(e){return Ce(e,{component:"auth-utils",action:"getSessionId",metadata:{key:Ae}}),null}}function Oe(){const e=ze(),t={};return e&&(t["x-session-id"]=e),t}const Fe=new WeakSet,je=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),We="SDK is not ready (missing serverUrl, version, or orgId)";class Ne{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(We);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(We)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:Oe()}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){Fe.has(e)||(Fe.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((r,s)=>{const n=()=>{clearTimeout(o),s(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return n();const o=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}async executeFetchUrl(e,t,r){const s=(t.method??"GET").toUpperCase(),n=r??e,o=this.buildHeaders(t),a={...t,headers:o},i=je.has(s);let c,u;if(this._timeout>0){u=new AbortController;const e=u;c=setTimeout(()=>e.abort(),this._timeout),a.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const s=new AbortController,n=e=>{s.signal.aborted||s.abort(e.reason)};for(const r of[e,t]){if(r.aborted){n(r);break}r.addEventListener("abort",()=>n(r),{once:!0})}return s.signal}(t.signal,e.signal):e.signal}const l=e=>{if(u?.signal.aborted&&!t.signal?.aborted){const e=new Error(`Request timeout after ${this._timeout}ms: ${s} ${n}`);return this.reportError(e,{method:s,path:n}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const r=this._fetch.bind(globalThis),n=await r(e,a);if(this._debug&&console.log(`[BuildBase] ${s} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&i&&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 Ne.delay(e,a.signal),p(t+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(i&&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 Ne.delay(e,a.signal)}catch(e){throw l(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:s,path:n}),e}};try{return await p(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await $e(s,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw new Error(r)}apiPath(e,...t){return e.reduce((e,r,s)=>e+r+(s<t.length?encodeURIComponent(String(t[s])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class Je extends Ne{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 Me extends Ne{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class Be extends Ne{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class qe extends Ne{constructor(e){super({...e,requireOrgId:!0})}async getWorkspaces(){return this.fetchJson("workspaces",{},"Failed to fetch workspaces")}async createWorkspace(e){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e)},"Failed to create workspace")}async updateWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t)},"Failed to update workspace")}async deleteWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE"},"Failed to delete workspace")}async getWorkspaceUsers(e){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{},"Failed to fetch workspace users")}async addUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t)},"Failed to invite member")}async removeUser(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE"},"Failed to remove user")}async updateUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r)},"Failed to update user")}async updateSettings(e){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e)},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t})},"Failed to update workspace permissions")}async getFeatures(){return this.fetchJson("workspaces/features",{},"Failed to fetch features")}async updateFeature(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}})},"Failed to update feature")}async getWorkspace(e){return this.fetchJson(this.apiPath`workspaces/${e}`,{},"Failed to fetch workspace")}async getProfile(){return this.fetchJson("profile",{},"Failed to fetch profile")}async updateUserProfile(e){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e)},"Failed to update user profile")}async getPasskeys(){const e=await this.fetchJson("passkeys",{},"Failed to fetch passkeys");return e?.passkeys??[]}async renamePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t})},"Failed to rename passkey")}async deletePasskey(e){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE"},"Failed to remove passkey")}async getCurrentSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`);return t.ok||await this.throwResponseError(t,"Failed to fetch subscription"),this.unwrapResponse(t,"Failed to fetch subscription")}async getPlanGroup(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group"),this.unwrapResponse(t,"Failed to fetch plan group")}async getPlanGroupByVersion(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch plan group version"),this.unwrapResponse(r,"Failed to fetch plan group version")}async getPlanGroupVersions(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group/versions`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group versions"),this.unwrapResponse(t,"Failed to fetch plan group versions")}async getPublicPlans(e){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");const t=await this.fetchResponse(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plans"),this.unwrapResponse(t,"Failed to fetch plans")}async getPublicCreditPackages(){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");const e=await this.fetchResponse(this.apiPath`${this.orgId}/credit-packages`);return e.ok||await this.throwResponseError(e,"Failed to fetch credit packages"),this.unwrapResponse(e,"Failed to fetch credit packages")}async getPlanGroupVersion(e){const t=await this.fetchResponse(this.apiPath`plan-group-versions/${e}`);return t.ok||await this.throwResponseError(t,"Failed to fetch plan group version"),this.unwrapResponse(t,"Failed to fetch plan group version")}async createCheckoutSession(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create checkout session"),this.unwrapResponse(r,"Failed to create checkout session")}async selectFreePlan(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return r.ok||await this.throwResponseError(r,"Failed to select free plan"),r.json()}async updateSubscription(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to update subscription"),this.unwrapResponse(r,"Failed to update subscription")}async createBillingPortalSession(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{})})}async listInvoices(e,t=10,r){const s=new URLSearchParams;s.append("limit",t.toString()),r&&s.append("starting_after",r);const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoices"),this.unwrapResponse(n,"Failed to fetch invoices")}async getInvoice(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices/${t}`);return r.ok||await this.throwResponseError(r,"Failed to fetch invoice"),this.unwrapResponse(r,"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to cancel subscription"),this.unwrapResponse(t,"Failed to cancel subscription")}async resumeSubscription(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST"});return t.ok||await this.throwResponseError(t,"Failed to resume subscription"),this.unwrapResponse(t,"Failed to resume subscription")}async recordUsage(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record usage"),this.unwrapResponse(r,"Failed to record usage")}async recordUsageBatch(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to record batch usage"),this.unwrapResponse(r,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`);return r.ok||await this.throwResponseError(r,"Failed to fetch quota usage status"),this.unwrapResponse(r,"Failed to fetch quota usage status")}async getAllQuotaUsage(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/all`);return t.ok||await this.throwResponseError(t,"Failed to fetch all quota usage"),this.unwrapResponse(t,"Failed to fetch all quota usage")}async getUsageLogs(e,t){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:""),o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch usage logs"),this.unwrapResponse(o,"Failed to fetch usage logs")}async sendNotification(e,t,r,s){const n={event:t};return r&&(n.userId=r),s&&(n.data=s),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(n)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return r.ok||await this.throwResponseError(r,"Failed to create credit purchase checkout"),this.unwrapResponse(r,"Failed to create credit purchase checkout")}async getCreditPackages(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/packages`);t.ok||await this.throwResponseError(t,"Failed to fetch credit packages");const r=await this.unwrapResponse(t,"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:""),o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch credit transactions"),this.unwrapResponse(o,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),n=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:""),o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch credit buckets"),this.unwrapResponse(o,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const r=t?`?days=${t}`:"",s=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/expiring`+r);return s.ok||await this.throwResponseError(s,"Failed to fetch expiring credits"),this.unwrapResponse(s,"Failed to fetch expiring credits")}}const Le={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"},He=Object.values(Le),De={admin:He.filter(e=>e!==Le.WORKSPACE_DELETE),member:[Le.WORKSPACE_SETTINGS_VIEW,Le.WORKSPACE_MEMBERS_VIEW,Le.WORKSPACE_FEATURES_VIEW,Le.WORKSPACE_BILLING_VIEW,Le.WORKSPACE_USAGE_VIEW],viewer:[Le.WORKSPACE_SETTINGS_VIEW,Le.WORKSPACE_MEMBERS_VIEW]};function Ge(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function Ke(e){const{userId:t,workspace:r,settings:s,appPermissions:n}=e;if(!r||!t)return new Set;if(function(e,t){if(!t)return!1;const r=(s=e.createdBy)?"string"==typeof s?s:"object"==typeof s&&"_id"in s&&"string"==typeof s._id?s._id:null:null;var s;return null!==r&&r===t}(r,t)){const e=new Set(He);if(n)for(const t of Ge(n))e.add(t);if(r.permissions)for(const t of Ge(r.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of Ge(s.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}(r,t);if(!o)return new Set;const a=r.permissions,i=s?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!a&&o in a,p=!!i&&o in i,d=o in De;let h;if(l)h=c(a[o]);else if(p)h=c(i[o]);else if(d)h=De[o];else{const e=s?.workspace?.defaultRole;h=e&&e in De?De[e]:[]}const g=new Set(h),w=l?u(a[o]):[],f=n?.[o]?u(n[o]):[],m=l?w:f;for(const e of m)g.add(e);return function(e,t,r){if(!r?.workspace)return;const{canInviteMembers:s}=r.workspace;(!1===s||"admin-only"===s&&"admin"!==t)&&e.delete(Le.WORKSPACE_MEMBERS_INVITE)}(g,o,s),g}function Ve(e){const{serverUrl:t,orgId:r,version:s="v1",getSessionId:n,timeout:o,maxRetries:a,debug:i,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!r)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==a&&{maxRetries:a},...void 0!==i&&{debug:i},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},d=e=>{const n={serverUrl:t,version:s,orgId:r,sessionId:e,...p};return{workspace:new qe(n),user:new Be(n),settings:new Me(n),push:new Je(n)}},h=new qe({serverUrl:t,version:s,orgId:r,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,r)=>(await e()).workspace.updateWorkspace(t,r),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,r,s)=>(await e()).workspace.addUser(t,{email:r,role:s}),remove:async(t,r)=>(await e()).workspace.removeUser(t,r),updateRole:async(t,r,s)=>(await e()).workspace.updateUser(t,r,{role:s}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,r)=>(await e()).workspace.createCheckoutSession(t,r),update:async(t,r)=>(await e()).workspace.updateSubscription(t,r),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,r)=>(await e()).workspace.createBillingPortalSession(t,r)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,r,s)=>(await e()).workspace.listInvoices(t,r,s),get:async(t,r)=>(await e()).workspace.getInvoice(t,r)},usage:{record:async(t,r)=>(await e()).workspace.recordUsage(t,r),recordBatch:async(t,r)=>(await e()).workspace.recordUsageBatch(t,r),getQuota:async(t,r)=>(await e()).workspace.getQuotaUsageStatus(t,r),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,r)=>(await e()).workspace.getUsageLogs(t,r)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,r,s)=>(await e()).workspace.updateFeature(t,r,s)},notification:{send:async(t,r,s,n)=>(await e()).workspace.sendNotification(t,r,s,n)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,r)=>(await e()).workspace.consumeCredits(t,r),purchase:async(t,r)=>(await e()).workspace.purchaseCredits(t,r),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,r)=>(await e()).workspace.getCreditTransactions(t,r),getBuckets:async(t,r)=>(await e()).workspace.getCreditBuckets(t,r),getExpiring:async(t,r)=>(await e()).workspace.getExpiringCredits(t,r),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,r,s)=>{const n=await e(),[o,a,i]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),c=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return function(e,t){const r=Ke(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}(s,{userId:r,workspaceRole:c?.role??null,workspace:o,settings:a})},resolve:async(t,r)=>{const s=await e(),[n,o,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),i=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return Ke({userId:r,workspaceRole:i?.role??null,workspace:n,settings:o})}}}),w=g(async()=>d(await(async()=>{if(!n)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await n();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!n)return null;const e=await n();return e?{sessionId:e}:null},withSession:e=>{const t=d(e);return g(async()=>t)},client:{forSession:d},...w}}exports.AppBridgeError=u,exports.bearerChallenge=f,exports.buildbaseAuth=G,exports.builtinMcpTools=v,exports.createAgentStack=function(e){const t=e.siteUrl.replace(/\/+$/,""),r=e.mcp?.path??"/api/mcp",s=`${t}${r.startsWith("/")?r:`/${r}`}`,n=e.mcp?.serverInfo??{name:e.site.name,version:"1.0.0"},o=`${t}/mcp`,a=Array.from(new Set([o,s])),i=e.mcp?.auth??(e.secret?G({secret:e.secret,resource:a,resourceMetadataUrl:`${t}/.well-known/oauth-protected-resource/mcp`,requireAudience:!0}):void 0);if(void 0===i)throw new Error("createAgentStack: pass `secret` (the app token-signing secret) to derive auth, or set `mcp.auth` yourself (`false` disables auth — local development only).");const c=N({buildbase:e.mcp?.buildbase??Ve({serverUrl:e.serverUrl,orgId:e.orgId}),serverInfo:n,auth:i,tools:e.mcp?.tools,builtinTools:e.mcp?.builtinTools??"readonly",...e.mcp?.handler}),u={serverUrl:e.serverUrl,orgId:e.orgId,siteUrl:e.siteUrl,site:e.site,mcpServerCard:c.serverCard({endpoint:s,...e.site.description?{description:e.site.description}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}),...e.scopes?{scopes:e.scopes}:{},protectedResources:a.map(t=>({resource:t,...e.mcp?.scopes?.length?{scopes:e.mcp.scopes}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}})).concat([{resource:t,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}]),apiCatalog:[{anchor:s,title:`${e.site.name} MCP server`,serviceDesc:`${t}/.well-known/mcp/server-card.json`}],...e.discovery},l={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, OPTIONS"},p=e=>c.fetch(e);return{mcp:c,mcpEndpoint:s,config:u,linkHeader:Ee(u),resolvePath:e=>_e(e,u),serveAgentPath:async function(e){if("OPTIONS"===e.method.toUpperCase())return new Response(null,{status:204,headers:l});const t=await _e(new URL(e.url).pathname,u);return t?new Response(t.body,{status:t.status,headers:{"Content-Type":t.contentType,"Cache-Control":t.cacheControl,...t.vary?{Vary:t.vary}:{},...l}}):new Response(JSON.stringify({error:"not_found"}),{status:404,headers:{"Content-Type":"application/json",...l}})},routes:{GET:p,POST:p,DELETE:p,OPTIONS:p}}},exports.createMcpHandler=N,exports.createSessionRefCrypto=H,exports.defineMcpTool=function(e){return e},exports.extractBearerToken=d,exports.mintAgentToken=async function(e){const{claims:t,secret:r}=e,s=e.expiresInSec??3600,n=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,o=t.sessionId?await H(r).encryptSessionRef(t.sessionId):void 0;return{token:g({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...n?{aud:n}:{},...o?{sid:o}:{},...e.extraClaims},r,{expiresInSec:s}),expiresIn:s}},exports.selectBuiltinTools=E,exports.signClientJwt=g,exports.verifyClientJwt=p;
|