@buildbase/sdk 0.0.53 → 0.0.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/AGENTS.md +16 -6
  2. package/CHANGELOG.md +99 -0
  3. package/LICENSE +21 -0
  4. package/README.md +278 -85
  5. package/dist/css/styles.css +1 -1
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.ts +582 -114
  8. package/dist/index.mjs +1 -1
  9. package/dist/mcp/index.cjs +1 -1
  10. package/dist/mcp/index.d.ts +780 -16
  11. package/dist/mcp/index.mjs +1 -1
  12. package/dist/react/chunks/SettingsDialog-B6DhyNae.cjs +2 -0
  13. package/dist/react/chunks/SettingsDialog-K38BI74F.mjs +2 -0
  14. package/dist/react/chunks/SubscriptionDialog-BidcQ_vc.mjs +2 -0
  15. package/dist/react/chunks/SubscriptionDialog-CfDLoOzW.cjs +2 -0
  16. package/dist/react/chunks/ar-CCKONfUU.mjs +2 -0
  17. package/dist/react/chunks/ar-DrHMtT1E.cjs +2 -0
  18. package/dist/react/chunks/de-Dhtorn10.cjs +2 -0
  19. package/dist/react/chunks/de-X9mfnMFM.mjs +2 -0
  20. package/dist/react/chunks/es--8iZ7Trv.mjs +2 -0
  21. package/dist/react/chunks/es-CUR7LB6a.cjs +2 -0
  22. package/dist/react/chunks/fr-BqMs_F5g.cjs +2 -0
  23. package/dist/react/chunks/fr-rUp34NG7.mjs +2 -0
  24. package/dist/react/chunks/hi-B_IiucJZ.mjs +2 -0
  25. package/dist/react/chunks/hi-C2i1_hdv.cjs +2 -0
  26. package/dist/react/chunks/ja-4hLI6wMX.cjs +2 -0
  27. package/dist/react/chunks/ja-CIGOj3vV.mjs +2 -0
  28. package/dist/react/chunks/react-BXTDLnE8.cjs +2 -0
  29. package/dist/react/chunks/react-CXCk05WI.mjs +2 -0
  30. package/dist/react/chunks/zh-BSgd6ai5.cjs +2 -0
  31. package/dist/react/chunks/zh-DyVvcYFC.mjs +2 -0
  32. package/dist/react/index.cjs +1 -1
  33. package/dist/react/index.d.ts +507 -141
  34. package/dist/react/index.mjs +1 -1
  35. package/docs/ARCHITECTURE.md +419 -0
  36. package/docs/ERROR_CODES.md +96 -0
  37. package/docs/MCP-AND-AGENT-READINESS.md +893 -0
  38. package/docs/THEMING.md +67 -0
  39. package/docs/UI-CONFIG.md +207 -0
  40. package/package.json +17 -4
  41. package/dist/react/chunks/SettingsDialog-BxDYsie6.mjs +0 -2
  42. package/dist/react/chunks/SettingsDialog-Dy8W3NA6.cjs +0 -2
  43. package/dist/react/chunks/SubscriptionDialog-6c5dHoQd.mjs +0 -2
  44. package/dist/react/chunks/SubscriptionDialog-CpVnnXJg.cjs +0 -2
  45. package/dist/react/chunks/ar-1Z1MOGAP.mjs +0 -2
  46. package/dist/react/chunks/ar-VGzBv3AZ.cjs +0 -2
  47. package/dist/react/chunks/de-BjdDg60Y.cjs +0 -2
  48. package/dist/react/chunks/de-CXUItplO.mjs +0 -2
  49. package/dist/react/chunks/es-BBPsSZUp.cjs +0 -2
  50. package/dist/react/chunks/es-BTbzVutz.mjs +0 -2
  51. package/dist/react/chunks/fr-Cax48X_S.cjs +0 -2
  52. package/dist/react/chunks/fr-DPMeOQu3.mjs +0 -2
  53. package/dist/react/chunks/hi-BJqvpG6d.cjs +0 -2
  54. package/dist/react/chunks/hi-JfJx-LV7.mjs +0 -2
  55. package/dist/react/chunks/ja-CDGtLzTk.mjs +0 -2
  56. package/dist/react/chunks/ja-DvVyj5xX.cjs +0 -2
  57. package/dist/react/chunks/react-4SlWxHdh.cjs +0 -2
  58. package/dist/react/chunks/react-OL1uSkpr.mjs +0 -2
  59. package/dist/react/chunks/zh-BAcqxkxk.cjs +0 -2
  60. package/dist/react/chunks/zh-BNZ2Ooe8.mjs +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 p=new WeakSet,h="SDK is not ready (missing serverUrl, version, or orgId)";class f{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(h);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(h)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=d(),t={};return e&&(t["x-session-id"]=e),t}()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){p.has(e)||(p.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}async executeFetchUrl(e,t,n){const 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 ${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 P=new $;function R(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const U=R().invalidate,C=R().invalidate,_=R().invalidate,I="bb",x={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",Invite:"invite"},A={Success:"success",Cancel:"cancel",Error:"error"},T={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function F(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(I,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),n.toString()}function W(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:F({action:x.Checkout,status:A.Success,ws:e,screen:T.Subscription},n),cancelUrl:F({action:x.Checkout,status:A.Cancel,ws:e,screen:T.Subscription},n)}}function O(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:F({action:x.CreditPurchase,status:A.Success,ws:e,screen:T.Credits},n),cancelUrl:F({action:x.CreditPurchase,status:A.Cancel,ws:e,screen:T.Credits},n)}}function N(){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 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(I)&&(e.searchParams.delete(I),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 j(e){return"object"==typeof e&&null!==e&&"string"==typeof e.returnUrl&&"number"==typeof e.createdAt}function D(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,j);return c(M),e?Date.now()-e.createdAt>6e5?null:L(e.returnUrl):null}function z(){c(M)}const K={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 K[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),p=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${o.then} ${i}${d}${p}`}const ae={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},ce={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},ue={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},le={Feature:"feature",Limit:"limit",Quota:"quota"},de={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},pe={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},he={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},fe={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function ge(e,t){const n=e.pricingVariants;if(!n?.length)return null;const 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 $e(e,t,n){const s=Ee(e,t);return s?.perSeat?s.perSeat[n]??null:null}function Pe(e,t){return Math.max(0,e-(t||0))}function Re(e,t,n,s){const r=Ee(e,t);if(!r)return null;return Pe(s,r.includedSeats)*($e(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+(Re(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 _e(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 Ie={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"},xe=Object.values(Ie),Ae={admin:xe.filter(e=>e!==Ie.WORKSPACE_DELETE),member:[Ie.WORKSPACE_SETTINGS_VIEW,Ie.WORKSPACE_MEMBERS_VIEW,Ie.WORKSPACE_FEATURES_VIEW,Ie.WORKSPACE_BILLING_VIEW,Ie.WORKSPACE_USAGE_VIEW],viewer:[Ie.WORKSPACE_SETTINGS_VIEW,Ie.WORKSPACE_MEMBERS_VIEW]};function Te(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 Fe(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(xe);if(r)for(const t of Te(r))e.add(t);if(n.permissions)for(const t of Te(n.permissions))e.add(t);if(s?.workspace?.permissions)for(const t of Te(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 in i,d=!!a&&o in a,p=o in Ae;let h;if(l)h=c(i[o]);else if(d)h=c(a[o]);else if(p)h=Ae[o];else{const e=s?.workspace?.defaultRole;h=e&&e in Ae?Ae[e]:[]}const f=new Set(h),g=l?u(i[o]):[],w=r?.[o]?u(r[o]):[],y=l?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(Ie.WORKSPACE_MEMBERS_INVITE)}(f,o,s),f}function We(e,t){const n=Fe(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const Oe="\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,p=new Uint8Array(d);p.set(e,0),p[u]=128;const h=8*u,f=Math.floor(h/4294967296),g=h>>>0;p[d-8]=f>>>24&255,p[d-7]=f>>>16&255,p[d-6]=f>>>8&255,p[d-5]=255&f,p[d-4]=g>>>24&255,p[d-3]=g>>>16&255,p[d-2]=g>>>8&255,p[d-1]=255&g;const w=new Uint32Array(64);for(let e=0;e<d;e+=64){for(let t=0;t<16;t++){const n=e+4*t;w[t]=p[n]<<24|p[n+1]<<16|p[n+2]<<8|p[n+3]}for(let e=16;e<64;e++){const t=Le(w[e-15],7)^Le(w[e-15],18)^w[e-15]>>>3,n=Le(w[e-2],17)^Le(w[e-2],19)^w[e-2]>>>10;w[e]=w[e-16]+t+w[e-7]+n>>>0}let u=t,l=n,d=s,h=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=h+t>>>0,h=d,d=l,l=u,u=t+((Le(u,2)^Le(u,13)^Le(u,22))+n>>>0)>>>0}t=t+u>>>0,n=n+l>>>0,s=s+d>>>0,r=r+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,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 je(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 De(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 ze(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=je(Me(r),Me(`${s}.${t}`));return c.length===u.length&&De(c,u)}function Ke(e){if(!ze(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="application/linkset+json",et="text/markdown; charset=utf-8",tt="text/plain; charset=utf-8",nt=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function st(e){return e.replace(/\/+$/,"")}function rt(e){return`public, max-age=${e}, s-maxage=${e}`}function ot(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 it=new Map;async function at(e,t,n,s){if(!s||s<=0)return e(t,n);const r=new AbortController,o=setTimeout(()=>r.abort(),s);try{return await e(t,{...n,signal:r.signal})}finally{clearTimeout(o)}}async function ct(e){const t=e.cacheTtlSeconds??Ve,n=`${st(e.serverUrl)}::${e.orgId}`,s=it.get(n);if(s&&s.expiresAt>Date.now())return s.value;const r=e.fetch??fetch,o=`${st(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const t=await at(r,o,{headers:{Accept:Ze}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(i=e)}}catch{}return it.set(n,{value:i,expiresAt:Date.now()+1e3*t}),i}const ut=new Map;function lt(){it.clear(),ut.clear()}function dt(e,t){const n=st(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,s.openid_configuration="/.well-known/openid-configuration"),(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 vt({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 pt(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return Ge+n}function ht(e,t){const n=t.protectedResources??[];if(!n.length)return null;const s=e.replace(/\/+$/,"")||Ge,r=`${st(t.serverUrl)}/org/${t.orgId}`,o=n.map(e=>{const n=e.resource??st(t.siteUrl);return{path:pt(n),metadata:{resource:n,authorization_servers:[r],bearer_methods_supported:e.bearerMethods??["header"],...e.scopes?.length?{scopes_supported:e.scopes}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),i=o.find(e=>e.path===s);return i?vt(i.metadata,t):s===Ge&&1===o.length?vt(o[0].metadata,t):null}function ft(e){const t=e.skills??[];if(!t.length)return null;const n=st(e.siteUrl);return vt({$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}${gt(e)}`,digest:ot(e.content)}))},e)}function gt(e){return e.path??`${He}/${e.name}/SKILL.md`}function wt(e,t){const n=(t.skills??[]).find(t=>gt(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:rt(t.cacheTtlSeconds??Ve)}:null}function yt(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:tt,body:t.join("\n")+"\n",cacheControl:rt(e.cacheTtlSeconds??Ve)}}function mt(e){return e.llmsTxt?{status:200,contentType:tt,body:e.llmsTxt,cacheControl:rt(e.cacheTtlSeconds??Ve)}:null}function kt(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:Xe,body:JSON.stringify({linkset:n},null,2),cacheControl:rt(e.cacheTtlSeconds??Ve)}}function bt(e){const t=e.mcpServerCard;return t?vt({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 St(e,t){const n=rt(e.cacheTtlSeconds??Ve);if(e.authMd)return{status:200,contentType:et,body:e.authMd,cacheControl:n};const s=t.authorizationServer;if(!s)return null;const r=`# 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:et,body:r,cacheControl:n}}function vt(e,t){return{status:200,contentType:Ze,body:JSON.stringify(e,null,2),cacheControl:rt(t.cacheTtlSeconds??Ve)}}function Et(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function $t(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Et(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: ${Et(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${Et(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${Et(e.crawlDelay)}`),n.join("\n")}function Pt(e){const t=e.robots??{},n=st(e.siteUrl),s=t.policies??[{userAgent:"*",allow:["/"]}],r=t.aiBots??"allow",o="allow"===r?[{userAgent:[...nt],allow:["/"]}]:"deny"===r?[{userAgent:[...nt],disallow:["/"]}]:r,i=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...s.map((e,n)=>$t(e,0===n?t.contentSignals:void 0)),...o.map(e=>$t(e)),...i.length?[i.map(e=>`Sitemap: ${Et(e)}`).join("\n")]:[]];return{status:200,contentType:tt,body:a.join("\n\n")+"\n",cacheControl:rt(e.cacheTtlSeconds??Ve)}}function Rt(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Ut(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ct(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=st(e.siteUrl);return{status:200,contentType:"application/xml; charset=utf-8",body:'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'+t.map(e=>{const t="string"==typeof e?{loc:e}:e;return` <url>\n${[` <loc>${Ut(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Ut(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Ut(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Rt(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n",cacheControl:rt(e.cacheTtlSeconds??Ve)}}function _t(e){if(!e)return!1;let t=0,n=0;for(const s of e.split(",")){const[e,...r]=s.trim().split(";"),o=e.trim().toLowerCase();let i=1;for(const e of r){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 It(e,t,n){const s=_t(e);return{status:200,contentType:s?et:"text/html; charset=utf-8",body:s?t.markdown:t.html,cacheControl:rt(n?.cacheTtlSeconds??Ve),vary:"Accept"}}function xt(e){const t=st(e.siteUrl),n=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(e.sitemap||e.robots?.sitemaps?.length){const s=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;n.push(`<${s}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&n.push(`<${t}${Qe}>; rel="api-catalog"; type="${Xe}"`),e.mcpServerCard&&n.push(`<${t}${Ye}>; rel="mcp-server"; type="application/json"`),n.join(", ")}async function At(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return dt(t,await ct(t))}if("/.well-known/security.txt"===n)return yt(t);if(n===`${He}/index.json`)return ft(t);if(n.startsWith(`${He}/`)&&n.endsWith("SKILL.md"))return wt(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await ct(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??Ve,s=ut.get(e);if(s&&s.expiresAt>Date.now())return s.value;const r=t.fetch??fetch;let o=null;try{const n=await at(r,e,{headers:{Accept:Ze}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(o=e)}}catch{}return ut.set(e,{value:o,expiresAt:Date.now()+1e3*n}),o}(e.metadataUrl,t);return vt(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}return n===Qe?kt(t):n===Ye?bt(t):n.startsWith(Ge)?ht(n,t):null}async function Tt(e,t){const n=e.replace(/\/+$/,"")||e;return"/robots.txt"===n?Pt(t):"/sitemap.xml"===n?Ct(t):"/llms.txt"===n?mt(t):"/auth.md"===n?St(t,await ct(t)):"/security.txt"===n?yt(t):n.startsWith("/.well-known")?At(n,t):null}function Ft(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)}class Wt extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function Ot(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 Nt(e){return JSON.parse((new TextDecoder).decode(Ot(e)))}function Jt(e,t,n={}){const s="number"==typeof n?{clockToleranceSec:n}:n,r=s.clockToleranceSec??60,o=s.requireExp??!0;if(!e||!t)throw new Wt("invalid_token","Missing token or client secret");const i=e.split(".");if(3!==i.length)throw new Wt("invalid_token","Malformed JWT");const[a,c,u]=i,l=je(Me(t),Me(`${a}.${c}`));let d,p,h;try{d=Ot(u)}catch{throw new Wt("invalid_signature","Unreadable JWT signature")}if(!De(l,d))throw new Wt("invalid_signature","JWT signature verification failed");try{p=Nt(a),h=Nt(c)}catch{throw new Wt("invalid_token","Unreadable JWT segments")}if("HS256"!==p.alg)throw new Wt("invalid_algorithm",`Unexpected JWT alg: ${String(p.alg)}`);const f=Math.floor(Date.now()/1e3);if(o&&"number"!=typeof h.exp)throw new Wt("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof h.exp&&f>h.exp+r)throw new Wt("token_expired","JWT has expired");if("number"==typeof h.nbf&&f+r<h.nbf)throw new Wt("token_not_yet_valid","JWT is not yet valid");if(void 0!==s.issuer&&h.iss!==s.issuer)throw new Wt("invalid_issuer","JWT issuer mismatch");if(void 0!==s.audience){const e=h.aud;if(!(Array.isArray(e)?e.includes(s.audience):e===s.audience))throw new Wt("invalid_audience","JWT audience mismatch")}return h}function Lt(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function Bt(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 Mt(e){return Bt(Me(JSON.stringify(e)))}function jt(e,t,n){if(!t)throw new Wt("invalid_secret","Missing signing secret");const s=Math.floor(Date.now()/1e3),r={iat:s,exp:s+(n?.expiresInSec??3600),...e},o=`${Mt({alg:"HS256",typ:"JWT"})}.${Mt(r)}`;return`${o}.${Bt(je(Me(t),Me(o)))}`}function Dt(e){const t=Lt(e.authorization);if(!t)throw new Wt("invalid_token","Missing Bearer token");return Jt(t,e.clientSecret,e.clockToleranceSec)}function qt(e){const t=Lt(e.authorization);if(!t)throw new Wt("invalid_token","Missing Bearer token");return Jt(t,e.clientSecret,e.clockToleranceSec)}function zt(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function Kt(e){return{success:!1,token:"",message:e}}async function Vt(e){let t;try{t=Dt(e)}catch(e){return{status:401,body:Kt(e instanceof Wt?e.code:"invalid_token")}}return{status:200,body:zt(await e.mintToken(t))}}async function Gt(e){let t;try{t=qt(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof Wt?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}}function Ht(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function Qt(e){const t=[`Bearer resource_metadata="${Ht(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${Ht(e.error)}"`),e.errorDescription&&t.push(`error_description="${Ht(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}function Yt(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}},p=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)}},h=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=>h.getPublicPlans(e),getVersion:e=>h.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:()=>h.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 We(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 Fe({userId:n,workspaceRole:a?.role??null,workspace:r,settings:o})}}}),g=f(async()=>p(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=p(e);return f(async()=>t)},client:{forSession:p},...g}}export{nt as AI_BOT_USER_AGENTS,v as ApiVersion,Wt as AppBridgeError,g as AuthApi,Ne as AuthStatus,x as BBAction,T as BBScreen,A as BBStatus,I as BB_PARAM,f as BaseApi,y as BetaForm,ae as BillingIntervals,Yt as BuildBase,K as CURRENCY_DISPLAY,V as CURRENCY_FLAG,pe as CreditBucketSource,he as CreditBucketStatus,fe as CreditTransactionType,Ae as DEFAULT_ROLE_PERMISSIONS,de as DunningState,$ as EventEmitter,ue as InvoiceStatuses,Q as PLAN_CURRENCY_CODES,Y as PLAN_CURRENCY_OPTIONS,Oe as PUSH_SERVICE_WORKER_SCRIPT,Ie as Permission,m as PushApi,E as SDKEvent,k as SettingsApi,le as SubscriptionItemType,ce as SubscriptionStatus,b as UserApi,S as WorkspaceApi,Kt as appTokenFailure,zt as appTokenSuccess,Qt as bearerChallenge,dt as buildAgentCard,ft as buildAgentSkillsIndex,kt as buildApiCatalog,St as buildAuthMd,xt as buildDiscoveryLinkHeader,mt as buildLlmsTxt,bt as buildMcpServerCard,ht as buildProtectedResourceMetadata,Pt as buildRobotsTxt,yt as buildSecurityTxt,Ct as buildSitemap,wt as buildSkillMd,Pe as calculateBillableSeats,Re as calculateSeatOverageCents,Ue as calculateTotalSubscriptionCents,J as cleanBBParams,lt as clearAgentReadinessCache,z as clearAuthIntent,q as consumeAuthIntent,F as createBBUrl,W as createCheckoutRedirectUrls,O as createCreditPurchaseRedirectUrls,Yt as default,P as eventEmitter,Lt as extractBearerToken,ct 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,$e as getPerSeatPriceCents,ge as getPricingVariant,re as getQuotaDisplayValue,Se as getQuotaDisplayWithVariant,me as getQuotaOverageCents,ne as getQuotaUnitLabelFromName,Ee as getSeatPricing,ye as getStripePriceIdForInterval,Gt as handleAppRevokeRequest,Vt as handleAppTokenRequest,We as hasPermission,U as invalidateCreditBalance,C as invalidateQuotaUsage,_ as invalidateSubscription,It as negotiateMarkdown,Ke as parseWebhookEvent,Ft as provideWebMcpTools,N as readBBParams,Tt as resolveAgentPath,Ce as resolveMaxUsers,Fe as resolvePermissions,At as resolveWellKnown,B as safeRedirect,D as saveAuthIntent,ot as sha256Digest,jt as signClientJwt,_e as validateInvite,L as validateRedirectUrl,qt as verifyAppRevokeRequest,Dt as verifyAppTokenRequest,Jt as verifyClientJwt,ze as verifyWebhookSignature,_t as wantsMarkdown};
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 i=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(t){this.config={...this.config,...t},void 0!==t.enableConsoleLogging&&function(t){void 0!==t.enableLogging&&(e=t.enableLogging)}({enableLogging:t.enableConsoleLogging})}handleError(e,n={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new s("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",n),i=r instanceof s?r:new s(r.message,"SDK_ERROR",n,r);if(this.config.enableConsoleLogging&&t(`[SDK Error] ${n.component||"Unknown"}:`,{message:i.message,code:i.code,context:i.context,originalError:i.originalError,stack:i.stack}),this.config.onError)try{this.config.onError(i,n)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(i,n)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...n)=>e(...n).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...n)=>{try{return e(...n)}catch(e){throw this.handleError(e,t),e}}}};function a(e,t={}){i.handleError(e,t)}function o(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return a(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}function c(e){if("undefined"!=typeof window)try{localStorage.removeItem(e)}catch(t){a(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){a(t,{component:"storage",action:"setStorageItem",metadata:{key:e}})}}(e,JSON.stringify(t))}catch(t){a(t,{component:"storage",action:"setStorageJSON",metadata:{key:e}})}}const l="saas-session-id";function d(){return function(){if("undefined"==typeof window)return null;try{return o(l)}catch(e){return a(e,{component:"auth-utils",action:"getSessionId",metadata:{key:l}}),null}}()}const p=new WeakSet,h=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),f="SDK is not ready (missing serverUrl, version, or orgId)";class g{constructor(e){this.serverUrl=e.serverUrl,this.version=e.version,this.orgId=e.orgId,this.requireOrgId=e.requireOrgId??!1,this.basePath=e.basePath??"public",this._sessionId=e.sessionId,this._timeout=e.timeout??3e4,this._maxRetries=e.maxRetries??0,this._debug=e.debug??!1,this._customHeaders=e.headers??{},this._onError=e.onError,this._onUnauthorized=e.onUnauthorized,this._fetch=e.fetch??globalThis.fetch}ensureReady(){if(!this.serverUrl?.trim()||!this.version)throw new Error(f);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(f)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:function(){const e=d(),t={};return e&&(t["x-session-id"]=e),t}()}url(e){const t=e.startsWith("/")?e.slice(1):e;return`${this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}/${t}`}buildHeaders(e){const t={...this._customHeaders,...this.getAuthHeaders()};return e.headers&&Object.assign(t,e.headers),null==e.body||t["Content-Type"]||(t["Content-Type"]="application/json"),t}reportError(e,t){p.has(e)||(p.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((n,r)=>{const s=()=>{clearTimeout(i),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const i=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,n){const r=(t.method??"GET").toUpperCase(),s=n??e,i=this.buildHeaders(t),a={...t,headers:i},o=h.has(r);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 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,a);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&o&&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,a.signal),d(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(o&&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,a.signal)}catch(e){throw l(e)}return d(t+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:s}),e}};try{return await d(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},n="Request failed"){this.ensureReady();try{const s=await this.executeFetch(e,t);return await r(s,n)}catch(n){throw n instanceof Error&&this.reportError(n,{method:(t.method??"GET").toUpperCase(),path:e}),n}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},n="Request failed"){const r=await this.fetchResponse(e,t);return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let n=t;try{n=(await e.json()).message||n}catch{n=`${t} (${e.status}: ${e.statusText})`}throw new Error(n)}apiPath(e,...t){return e.reduce((e,n,r)=>e+n+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const n=await e.json();if(void 0!==n.success){if(!n.success)throw new Error(n.message||t);return void 0!==n.data?n.data:n}return n}}class w extends g{constructor(e){super(e)}async requestAuth(e){const t=`${this.serverUrl}/api/${this.version}/auth/request`,n="Failed to initiate authentication",r=await this.fetchAbsoluteUrl(t,{method:"POST",body:JSON.stringify(e)});return r.ok||await this.throwResponseError(r,n),this.unwrapResponse(r,n)}async getProfile(e,t){return this.fetchJson("profile",{headers:{"x-session-id":e},signal:t},"Failed to fetch user profile")}}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),i=t?.currency??("undefined"!=typeof Intl&&Intl.NumberFormat&&Intl.NumberFormat().resolvedOptions().currency?Intl.NumberFormat().resolvedOptions().currency:void 0);return this.api.submitBetaUser({orgId:this.orgId,formData:{...e,country:n,language:r,timezone:s,currency:i}})}}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(e){return this.fetchJson("workspaces",{signal:e},"Failed to fetch workspaces")}async createWorkspace(e,t){return this.fetchJson("workspaces",{method:"POST",body:JSON.stringify(e),signal:t},"Failed to create workspace")}async updateWorkspace(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:n},"Failed to update workspace")}async deleteWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"DELETE",signal:t},"Failed to delete workspace")}async getWorkspaceUsers(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/users`,{signal:t},"Failed to fetch workspace users")}async addUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to invite member")}async removeUser(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:n},"Failed to remove user")}async updateUser(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(n),signal:r},"Failed to update user")}async updateSettings(e,t){return this.fetchJson("workspaces/settings",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update workspace settings")}async updateWorkspacePermissions(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:n},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,n,r){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:n}}),signal:r},"Failed to update feature")}async getWorkspace(e,t){return this.fetchJson(this.apiPath`workspaces/${e}`,{signal:t},"Failed to fetch workspace")}async getProfile(e){return this.fetchJson("profile",{signal:e},"Failed to fetch profile")}async updateUserProfile(e,t){return this.fetchJson("profile",{method:"PATCH",body:JSON.stringify(e),signal:t},"Failed to update user profile")}async getPasskeys(e){const t=await this.fetchJson("passkeys",{signal:e},"Failed to fetch passkeys");return t?.passkeys??[]}async renamePasskey(e,t,n){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:n},"Failed to rename passkey")}async deletePasskey(e,t){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"DELETE",signal:t},"Failed to remove passkey")}async getCurrentSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{signal:t},"Failed to fetch subscription")}async getPlanGroup(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`,{signal:t},"Failed to fetch plan group")}async getPlanGroupByVersion(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch plan group version")}async getPlanGroupVersions(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group/versions`,{signal:t},"Failed to fetch plan group versions")}async getPublicPlans(e,t){if(!this.orgId)throw new Error("orgId is required for getPublicPlans");return this.fetchUnwrapped(this.apiPath`${this.orgId}/plans/${encodeURIComponent(e)}`,{signal:t},"Failed to fetch plans")}async getPublicCreditPackages(e){if(!this.orgId)throw new Error("orgId is required for getPublicCreditPackages");return this.fetchUnwrapped(this.apiPath`${this.orgId}/credit-packages`,{signal:e},"Failed to fetch credit packages")}async getPlanGroupVersion(e,t){return this.fetchUnwrapped(this.apiPath`plan-group-versions/${e}`,{signal:t},"Failed to fetch plan group version")}async createCheckoutSession(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create checkout session")}async selectFreePlan(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:n},"Failed to select free plan")}async updateSubscription(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:n},"Failed to update subscription")}async createBillingPortalSession(e,t,n){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:n})}async listInvoices(e,t=10,n,r){const s=new URLSearchParams;return s.append("limit",t.toString()),n&&s.append("starting_after",n),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:r},"Failed to fetch invoices")}async getInvoice(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:n},"Failed to fetch invoice")}async cancelSubscriptionAtPeriodEnd(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/cancel-at-period-end`,{method:"POST",signal:t},"Failed to cancel subscription")}async resumeSubscription(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/resume`,{method:"POST",signal:t},"Failed to resume subscription")}async recordUsage(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record usage")}async recordUsageBatch(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:n},"Failed to fetch quota usage status")}async getAllQuotaUsage(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/all`,{signal:t},"Failed to fetch all quota usage")}async getUsageLogs(e,t,n){const r=new URLSearchParams;t?.quotaSlug&&r.append("quotaSlug",t.quotaSlug),t?.from&&r.append("from",t.from),t?.to&&r.append("to",t.to),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch usage logs")}async sendNotification(e,t,n,r,s){const i={event:t};return n&&(i.userId=n),r&&(i.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(i),signal:s},"Failed to send notification")}async getNotificationEvents(e,t){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{signal:t},"Failed to fetch notification events")}async getNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{signal:t},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t,n){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:n},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e,t){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits`,{signal:t},"Failed to fetch credit balance")}async consumeCredits(e,t,n){const r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:n});if(!r.ok){if(402===r.status){const e=await r.json().catch(()=>({})),t=new Error(e.message||"Insufficient credits");throw t.available=e.available,t.requested=e.requested,t.code="INSUFFICIENT_CREDITS",t}await this.throwResponseError(r,"Failed to consume credits")}return this.unwrapResponse(r,"Failed to consume credits")}async purchaseCredits(e,t,n){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:n},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const n=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return n.docs??n}async getCreditTransactions(e,t,n){const r=new URLSearchParams;t?.type&&r.append("type",t.type),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,n){const r=new URLSearchParams;t?.status&&r.append("status",t.status),t?.source&&r.append("source",t.source),t?.page&&r.append("page",t.page.toString()),t?.limit&&r.append("limit",t.limit.toString());const s=r.toString(),i=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(i,{signal:n},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,n){const r=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+r,{signal:n},"Failed to fetch expiring credits")}}var $;!function(e){e.V1="v1"}($||($={}));const U={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){a(t,{component:"EventEmitter",action:"emit",metadata:{eventType:e}})}}async emitUserCreated(e){await this.emit(U.UserCreated,{user:e})}async emitUserUpdated(e,t){await this.emit(U.UserUpdated,{user:e,previousUser:t})}async emitWorkspaceChanged(e,t){await this.emit(U.WorkspaceChanged,{workspace:e,previousWorkspace:t})}async emitWorkspaceUpdated(e){await this.emit(U.WorkspaceUpdated,{workspace:e})}async emitWorkspaceUserAdded(e,t,n){await this.emit(U.WorkspaceUserAdded,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRemoved(e,t,n){await this.emit(U.WorkspaceUserRemoved,{userId:e,workspace:t,role:n})}async emitWorkspaceUserRoleChanged(e,t,n,r){await this.emit(U.WorkspaceUserRoleChanged,{userId:e,workspace:t,previousRole:n,newRole:r})}async emitWorkspaceCreated(e){await this.emit(U.WorkspaceCreated,{workspace:e})}async emitWorkspaceDeleted(e){await this.emit(U.WorkspaceDeleted,{workspace:e})}}const E=new P;function C(){const e=new Set;return{subscribe:t=>(e.add(t),()=>{e.delete(t)}),invalidate(){e.forEach(e=>e())},reset(){e.clear()}}}const x=C().invalidate,_=C().invalidate,I=C().invalidate,T="bb",A={Checkout:"checkout",Billing:"billing",SelectPlan:"selectPlan",CreditPurchase:"creditPurchase",OpenCreditStore:"openCreditStore",OpenConnectGuide:"openConnectGuide",Invite:"invite"},R={Success:"success",Cancel:"cancel",Error:"error"},O={Subscription:"subscription",Credits:"credits",Usage:"usage",Users:"users",Profile:"profile",General:"general",Features:"features",Notifications:"notifications",Permissions:"permissions",Danger:"danger"};function W(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(T,function(e){return Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).join(",")}(e)),r.toString()}function F(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:W({action:A.Checkout,status:R.Success,ws:e,screen:O.Subscription},n),cancelUrl:W({action:A.Checkout,status:R.Cancel,ws:e,screen:O.Subscription},n)}}function N(e,t){const n=t||("undefined"!=typeof window?window.location.href:void 0);return{successUrl:W({action:A.CreditPurchase,status:R.Success,ws:e,screen:O.Credits},n),cancelUrl:W({action:A.CreditPurchase,status:R.Cancel,ws:e,screen:O.Credits},n)}}function J(){if("undefined"==typeof window)return null;try{const e=new URLSearchParams(window.location.search).get(T);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(T)&&(e.searchParams.delete(T),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:i,allowedOrigins:a}=t;return i||a?.length?i&&"undefined"!=typeof window&&window.location&&n.origin===window.location.origin||a?.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=o(e);if(!n)return null;try{const r=JSON.parse(n);return t&&!t(r)?(a(new Error("Storage data failed validation"),{component:"storage",action:"getStorageJSON",metadata:{key:e}}),c(e),null):r}catch(t){return a(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"]),ee=new Set(["bhd","jod","kwd","omr","tnd"]),te=new Map;function ne(e){const t=(e??"").trim().toLowerCase();if(!t)return 2;if(X.has(t))return 0;if(ee.has(t))return 3;if("isk"===t)return 2;let n=te.get(t);if(void 0===n){try{n=new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).resolvedOptions().maximumFractionDigits??2}catch{n=2}te.set(t,n)}return n}function re(e){return""!==(e??"").trim()&&0===ne(e)}function se(e,t){const n=ne(t);return 0===n?e.toLocaleString("en-US"):(e/10**n).toFixed(n)}function ie(e,t,n="en-US"){const r=(t??"").trim(),s=ne(r),i=e/10**s;if(!r)return i.toFixed(s);try{return new Intl.NumberFormat(n,{style:"currency",currency:r.toUpperCase(),minimumFractionDigits:s,maximumFractionDigits:s}).format(i)}catch{return Q(r)+(0===s?i.toLocaleString("en-US"):i.toFixed(s))}}function ae(e,t){return Q(t)+se(e,t)}const oe={unit:"unit",units:"units",included:"Included",afterThat:"after that",afterIncluded:"After included",hardLimit:"hard limit"};function ce(e,t,n,r,s){if(null==e||e<0)return null;const i={...oe,...r},a=null!=t&&t>=1?t:1,o=Q(n),c=se(e,n);return 1===a?`${o}${c}/${i.unit}`:`${o}${c}/${a.toLocaleString(s)} ${i.units}`}function ue(e,t,n,r,s,i,a){if(null==e||e<0)return null;const o={...oe,...i},c=null!=t&&t>=1?t:1,u=Q(r),l=se(e,r);if(n){const e=s??(n.endsWith("s")?n:`${n}s`);return c>=2?`${u}${l}/${c.toLocaleString(a)} ${e}`:`${u}${l}/${n}`}return 1===c?`${u}${l}/${o.unit}`:`${u}${l}/${c.toLocaleString(a)} ${o.units}`}function le(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 de(e,t,n,r,s,i,a,o,c){const u={...oe,...a};if(!1===o)return null!=e?`${u.included}: ${e.toLocaleString(c)} (${u.hardLimit})`:a?.hardLimit??"Hard limit";const l=i??(n.endsWith("s")?n:`${n}s`),d=null!=s&&s>=2?`${s.toLocaleString(c)} ${l}`:n;return null!=e&&null!=t?`${u.included}: ${e.toLocaleString(c)}, ${u.afterThat} ${ae(t,r)}/${d}`:null!=e?`${u.included}: ${e.toLocaleString(c)}`:null!=t?`${u.afterIncluded}: ${ae(t,r)}/${d}`:"—"}function pe(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 he={included:"included",then:"then",hardLimit:"hard limit"};function fe(e,t,n={}){const{overageInCents:r=!0,currency:s}=n,i={...he,...n.labels},a=n.currencySymbol??Q(s??"");if(null==e)return"—";const{included:o,overage:c}=e,u=`${o} ${i.included}`;if(!1===e.allowOverage)return`${u} (${i.hardLimit})`;if(null==c)return u;const l=ne(s),d=r&&l>0?c/10**l:c,p="number"==typeof d&&Number.isFinite(d)?0===l?d.toLocaleString("en-US"):d.toFixed(l):String(c),h=t&&"unitSize"in e&&null!=e.unitSize&&e.unitSize>0?` / ${e.unitSize.toLocaleString()} ${t}`:t?` / ${t}`:"";return`${u}, ${i.then} ${a}${p}${h}`}const ge={Monthly:"monthly",Yearly:"yearly",Quarterly:"quarterly"},we={Active:"active",Trialing:"trialing",Canceled:"canceled",PastDue:"past_due",Paused:"paused",Incomplete:"incomplete",Unpaid:"unpaid"},ye={Draft:"draft",Open:"open",Paid:"paid",Uncollectible:"uncollectible",Void:"void"},me={Feature:"feature",Limit:"limit",Quota:"quota"},ke={None:"none",Notified:"notified",Warning:"warning",Final:"final",Suspended:"suspended"},be={PlanGrant:"plan_grant",CreditPackPurchase:"credit_pack_purchase",AdminGrant:"admin_grant",Refund:"refund"},Se={Pending:"pending",Active:"active",Expired:"expired",Consumed:"consumed"},ve={PlanGrant:"plan_grant",PackPurchased:"pack_purchased",Consumed:"consumed",Expired:"expired",AdminGrant:"admin_grant",AdminRevoke:"admin_revoke",Refund:"refund"};function $e(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 Ue(e,t,n){const r=$e(e,t);if(!r?.basePricing)return null;const s=r.basePricing[n];return null!=s?s:null}function Pe(e,t,n){const r=$e(e,t);if(!r?.stripePrices)return null;const s=n===ge.Monthly?"monthlyPriceId":n===ge.Yearly?"yearlyPriceId":"quarterlyPriceId",i=n===ge.Monthly?"monthly":n===ge.Yearly?"yearly":void 0;return r.stripePrices[s]??(i?r.stripePrices[i]:void 0)??null}function Ee(e,t,n,r){const s=$e(e,t),i=s?.quotaOverages?.[n];if(i)return i[r]}function Ce(e,t){const n=$e(e,t);return n?n.currency:e.plan?.currency??""}function xe(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 _e(e,t,n,r){const s=e.quotas?.[n];if(null==s)return null;const i=s[r];if(!i)return null;const a=Ee(e,t,n,r);return{included:i.included,...void 0!==i.unitSize&&{unitSize:i.unitSize},...void 0!==a&&{overage:a},allowOverage:!1!==s.allowOverage}}function Ie(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 Te(e,t){const n=$e(e,t);return n?.seatPricing?.enabled?n.seatPricing:null}function Ae(e,t,n){const r=Te(e,t);return r?.perSeat?r.perSeat[n]??null:null}function Re(e,t){return Math.max(0,e-(t||0))}function Oe(e,t,n,r){const s=Te(e,t);if(!s)return null;return Re(r,s.includedSeats)*(Ae(e,t,n)??0)}function We(e,t,n,r){const s=Ue(e,t,n);if(null===s)return null;if(void 0===r)return s;return s+(Oe(e,t,n,r)??0)}function Fe(e){const{planVersion:t,currency:n="usd",settingsMaxUsers:r}=e;if(t){const e=Te(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 Ne(e){const{memberCount:t,maxUsersConfig:n,hasSubscription:r=!0,requireSubscription:s=!1}=e;if(s&&!r)return{canInvite:!1,blockReason:"no_subscription",blockMessageKey:"users.subscriptionRequired",blockMessageValues:{}};const{maxUsers:i,source:a}=n;if(i<=0)return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null};if(t>=i){return{canInvite:!1,blockReason:{seat_pricing:"seat_limit_reached",settings:"settings_user_limit_reached"}[a]??"seat_limit_reached",blockMessageKey:{seat_pricing:"users.seatLimitMessage",settings:"users.settingsLimitMessage"}[a]??"users.memberLimitMessage",blockMessageValues:{maxUsers:i}}}return{canInvite:!0,blockReason:null,blockMessageKey:null,blockMessageValues:null}}const Je={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"},Le=Object.values(Je),Me={admin:Le.filter(e=>e!==Je.WORKSPACE_DELETE),member:[Je.WORKSPACE_SETTINGS_VIEW,Je.WORKSPACE_MEMBERS_VIEW,Je.WORKSPACE_FEATURES_VIEW,Je.WORKSPACE_BILLING_VIEW,Je.WORKSPACE_USAGE_VIEW],viewer:[Je.WORKSPACE_SETTINGS_VIEW,Je.WORKSPACE_MEMBERS_VIEW]};function Be(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(Le);if(s)for(const t of Be(s))e.add(t);if(n.permissions)for(const t of Be(n.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of Be(r.workspace.permissions))e.add(t);return e}const i=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const n=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return n&&"object"==typeof n&&"role"in n&&"string"==typeof n.role?n.role:null}(n,t);if(!i)return new Set;const a=n.permissions,o=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!a&&i in a,d=!!o&&i in o,p=i in Me;let h;if(l)h=c(a[i]);else if(d)h=c(o[i]);else if(p)h=Me[i];else{const e=r?.workspace?.defaultRole;h=e&&e in Me?Me[e]:[]}const f=new Set(h),g=l?u(a[i]):[],w=s?.[i]?u(s[i]):[],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(Je.WORKSPACE_MEMBERS_INVITE)}(f,i,r),f}function De(e,t){const n=je(t);return Array.isArray(e)?e.every(e=>n.has(e)):n.has(e)}const qe="\n// BuildBase Push Notification Service Worker\n// Place this file in your app's public directory (e.g. public/push-sw.js)\n\nself.addEventListener('push', function(event) {\n if (!event.data) return;\n\n try {\n const payload = event.data.json();\n // i18n exception: service workers run outside the SDK's translation\n // provider, so this last-resort fallback stays English. The server should\n // always send a localized payload.title.\n const title = payload.title || 'Notification';\n const options = {\n body: payload.body || '',\n icon: payload.icon || undefined,\n badge: payload.icon || undefined,\n data: { url: payload.url, ...(payload.data || {}) },\n tag: 'buildbase-push-' + Date.now(),\n };\n\n event.waitUntil(\n self.registration.showNotification(title, options)\n );\n } catch (e) {\n console.error('[PushSW] Failed to show notification:', e);\n }\n});\n\nself.addEventListener('notificationclick', function(event) {\n event.notification.close();\n\n const url = event.notification.data && event.notification.data.url;\n if (url) {\n event.waitUntil(\n clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {\n for (let i = 0; i < clientList.length; i++) {\n const client = clientList[i];\n if (client.url === url && 'focus' in client) {\n return client.focus();\n }\n }\n if (clients.openWindow) {\n return clients.openWindow(url);\n }\n })\n );\n }\n});\n";var ze;!function(e){e.loading="loading",e.redirecting="redirecting",e.authenticated="authenticated",e.unauthenticated="unauthenticated",e.authenticating="authenticating"}(ze||(ze={}));const Ke=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]),Ve=(e,t)=>e>>>t|e<<32-t;function Ge(e){let t=1779033703,n=3144134277,r=1013904242,s=2773480762,i=1359893119,a=2600822924,o=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=Ve(w[e-15],7)^Ve(w[e-15],18)^w[e-15]>>>3,n=Ve(w[e-2],17)^Ve(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=i,g=a,y=o,m=c;for(let e=0;e<64;e++){const t=m+(Ve(f,6)^Ve(f,11)^Ve(f,25))+(f&g^~f&y)+Ke[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+((Ve(u,2)^Ve(u,13)^Ve(u,22))+n>>>0)>>>0}t=t+u>>>0,n=n+l>>>0,r=r+d>>>0,s=s+h>>>0,i=i+f>>>0,a=a+g>>>0,o=o+y>>>0,c=c+m>>>0}const y=new Uint8Array(32),m=[t,n,r,s,i,a,o,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 He(e){return(new TextEncoder).encode(e)}function Qe(e,t){let n=e;n.length>64&&(n=Ge(n));const r=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<n.length?n[e]:0;r[e]=54^t,s[e]=92^t}const i=Ge(Ze(r,t));return Ge(Ze(s,i))}function Ye(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 Ze(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function Xe(e){const{body:t,signature:n,timestamp:r,secret:s,maxAgeSeconds:i=300}=e;if(!(n&&r&&s&&t))return!1;const a="sha256=";if(!n.startsWith(a))return!1;const o=n.slice(7);if(i>0){const e=parseInt(r,10);if(isNaN(e))return!1;if(Math.abs(Math.floor(Date.now()/1e3)-e)>i)return!1}const c=function(e){if(e.length%2!=0)return null;const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++){const r=parseInt(e.slice(2*n,2*n+2),16);if(Number.isNaN(r))return null;t[n]=r}return t}(o);if(!c)return!1;const u=Qe(He(s),He(`${r}.${t}`));return c.length===u.length&&Ye(c,u)}function et(e){if(!Xe(e))return null;try{return JSON.parse(e.body)}catch{return null}}const tt=300,nt="/.well-known/oauth-protected-resource",rt="/.well-known/agent-skills",st="/.well-known/api-catalog",it="/.well-known/mcp/server-card.json",at="/.well-known/agent-card.json",ot="application/json",ct="application/linkset+json",ut="text/markdown; charset=utf-8",lt="text/plain; charset=utf-8",dt="application/xml; charset=utf-8",pt=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ht(e){return e.replace(/\/+$/,"")}function ft(e){return`public, max-age=${e}, s-maxage=${e}`}function gt(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}(Ge(He(e)))}const wt=new Map;async function yt(e,t,n,r){if(!r||r<=0)return e(t,n);const s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await e(t,{...n,signal:s.signal})}finally{clearTimeout(i)}}async function mt(e){const t=e.cacheTtlSeconds??tt,n=`${ht(e.serverUrl)}::${e.orgId}`,r=wt.get(n);if(r&&r.expiresAt>Date.now())return r.value;const s=e.fetch??fetch,i=`${ht(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let a={enabled:!1};try{const t=await yt(s,i,{headers:{Accept:ot}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(a=e)}}catch{}return wt.set(n,{value:a,expiresAt:Date.now()+1e3*t}),a}const kt=new Map;function bt(){wt.clear(),kt.clear()}function St(e,t){const n=ht(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:nt};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=`${rt}/index.json`),e.apiCatalog?.length&&(r.api_catalog=st),e.mcpServerCard&&(r.mcp_server_card=it),!1!==e.a2aCard&&(r.a2a_agent_card=at),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt");return Lt({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 vt(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const n="/"===t?"":t.replace(/\/+$/,"");return nt+n}function $t(e,t,n){const r=t.protectedResources??[];if(!r.length)return null;const s=e.replace(/\/+$/,"")||nt,i=n??`${ht(t.serverUrl)}/org/${t.orgId}`,a=t.scopes?.map(e=>e.name),o=r.map(e=>{const n=e.resource??ht(t.siteUrl),r=e.scopes??a;return{path:vt(n),metadata:{resource:n,authorization_servers:[i],bearer_methods_supported:e.bearerMethods??["header"],...r?.length?{scopes_supported:r}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=o.find(e=>e.path===s);return c?Lt(c.metadata,t):s===nt&&1===o.length?Lt(o[0].metadata,t):null}function Ut(e){const t=e.skills??[];if(!t.length)return null;const n=ht(e.siteUrl);return Lt({$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}${Pt(e)}`,digest:gt(e.content)}))},e)}function Pt(e){return e.path??`${rt}/${e.name}/SKILL.md`}function Et(e,t){const n=(t.skills??[]).find(t=>Pt(t)===e);return n?{status:200,contentType:"text/markdown; charset=utf-8",body:n.content,cacheControl:ft(t.cacheTtlSeconds??tt)}:null}function Ct(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:lt,body:t.join("\n")+"\n",cacheControl:ft(e.cacheTtlSeconds??tt)}}function xt(e){return e.llmsTxt?{status:200,contentType:lt,body:e.llmsTxt,cacheControl:ft(e.cacheTtlSeconds??tt)}:null}function _t(e){return e.llmsFullTxt?{status:200,contentType:lt,body:e.llmsFullTxt,cacheControl:ft(e.cacheTtlSeconds??tt)}:null}function It(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},n=ht(e.siteUrl),r=t.serviceUrl??n,s=t.transportProtocol??"http",i=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return Lt({protocolVersion:"0.3.0",name:t.name??e.site.name,version:t.version??"1.0.0",description:t.description??e.site.description??`${e.site.name} — agent-accessible web application.`,url:r,preferredTransport:s,supportedInterfaces:[{serviceUrl:r,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:n},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:i,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}function Tt(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:ft(e.cacheTtlSeconds??tt)}:null}function At(e){return e.endsWith(".json")||e.includes(".well-known/")?ot:e.endsWith(".md")?ut:e.endsWith(".xml")?dt:lt}function Rt(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 Ot(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:ct,body:JSON.stringify({linkset:n},null,2),cacheControl:ft(e.cacheTtlSeconds??tt)}}function Wt(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 Ft(e){const t=e.mcpServerCard;return t?Lt({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-11-25",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:Wt(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}function Nt(e){const t=e.mcpServerCard;if(!t)return null;const n=ht(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${vt(t.endpoint)}`}}catch{}return Lt({$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:Wt(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${n}${it}`,...r?{authentication:r}:{}}]},e)}function Jt(e,t){const n=ft(e.cacheTtlSeconds??tt);if(e.authMd)return{status:200,contentType:ut,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:ut,body:s,cacheControl:n}}function Lt(e,t){return{status:200,contentType:ot,body:JSON.stringify(e,null,2),cacheControl:ft(t.cacheTtlSeconds??tt)}}function Mt(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Bt(e,t){const n=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Mt(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: ${Mt(t)}`);for(const t of e.disallow??[])n.push(`Disallow: ${Mt(t)}`);return void 0!==e.crawlDelay&&n.push(`Crawl-delay: ${Mt(e.crawlDelay)}`),n.join("\n")}function jt(e){const t=e.robots??{},n=ht(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",i="allow"===s?[{userAgent:[...pt],allow:["/"]}]:"deny"===s?[{userAgent:[...pt],disallow:["/"]}]:s,a=t.sitemaps??(e.sitemap?[`${n}/sitemap.xml`]:[]),o=[`# robots.txt — agent-ready. See ${n}/llms.txt and ${n}/.well-known/agent.json`,...r.map((e,n)=>Bt(e,0===n?t.contentSignals:void 0)),...i.map(e=>Bt(e)),...a.length?[a.map(e=>`Sitemap: ${Mt(e)}`).join("\n")]:[]];return{status:200,contentType:lt,body:o.join("\n\n")+"\n",cacheControl:ft(e.cacheTtlSeconds??tt)}}function Dt(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function qt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function zt(e){const t=e.sitemap?.urls;if(!t?.length)return null;const n=ht(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>${qt(/^https?:\/\//.test(t.loc)?t.loc:`${n}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${qt(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${qt(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Dt(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:dt,body:r,cacheControl:ft(e.cacheTtlSeconds??tt)}}function Kt(e){if(!e)return!1;let t=0,n=0;for(const r of e.split(",")){const[e,...s]=r.trim().split(";"),i=e.trim().toLowerCase();let a=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)||(a=e)}}"text/markdown"===i||"text/x-markdown"===i?t=Math.max(t,a):"text/html"!==i&&"text/*"!==i&&"*/*"!==i||(n=Math.max(n,a))}return t>0&&t>=n}function Vt(e,t,n){const r=Kt(e);return{status:200,contentType:r?ut:"text/html; charset=utf-8",body:r?t.markdown:t.html,cacheControl:ft(n?.cacheTtlSeconds??tt),vary:"Accept"}}function Gt(e){const t=ht(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}${at}>; 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}${st}>; rel="api-catalog"; type="${ct}"`),e.mcpServerCard&&n.push(`<${t}${it}>; rel="mcp-server"; type="application/json"`),n.join(", ")}async function Ht(e,t){const n=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===n){return St(t,await mt(t))}if(n===at)return It(t);if("/.well-known/http-message-signatures-directory"===n)return Tt(t);if("/.well-known/security.txt"===n)return Ct(t);if(n===`${rt}/index.json`)return Ut(t);if(n.startsWith(`${rt}/`)&&n.endsWith("SKILL.md"))return Et(n,t);if("/.well-known/oauth-authorization-server"===n||"/.well-known/openid-configuration"===n){const e=(await mt(t)).authorizationServer;if(!e?.metadataUrl)return null;const n=await async function(e,t){const n=t.cacheTtlSeconds??tt,r=kt.get(e);if(r&&r.expiresAt>Date.now())return r.value;const s=t.fetch??fetch;let i=null;try{const n=await yt(s,e,{headers:{Accept:ot}},t.fetchTimeoutMs??5e3);if(n.ok){const e=await n.json();e&&"object"==typeof e&&(i=e)}}catch{}return kt.set(e,{value:i,expiresAt:Date.now()+1e3*n}),i}(e.metadataUrl,t);return Lt(n?n:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(n===st)return Ot(t);if(n===it)return Ft(t);if("/.well-known/mcp.json"===n)return Nt(t);if(n.startsWith(nt)){const e=await mt(t);return $t(n,t,e.authorizationServer?.issuer)}return null}async function Qt(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??At(e),body:r.body,cacheControl:r.cacheControl??ft(t.cacheTtlSeconds??tt)}}(n,t);return r||("/robots.txt"===n?jt(t):"/llms-full.txt"===n?_t(t):"/sitemap.xml"===n?zt(t):"/llms.txt"===n?xt(t):"/auth.md"===n?Jt(t,await mt(t)):"/security.txt"===n?Ct(t):n.startsWith("/.well-known")?Ht(n,t):null)}function Yt(e){const t=globalThis.navigator;return!!t?.modelContext?.provideContext&&(t.modelContext.provideContext({tools:e}),!0)}function Zt(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 Xt(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 en extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function tn(e){const t=JSON.parse((new TextDecoder).decode(Xt(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function nn(e,t,n={}){const r=n.clockToleranceSec??60,s=n.requireExp??!0;if(!e||!t)throw new en("invalid_token","Missing token or client secret");const i=e.split(".");if(3!==i.length)throw new en("invalid_token","Malformed JWT");const[a,o,c]=i;let u,l;try{u=tn(a),l=tn(o)}catch{throw new en("invalid_token","Unreadable JWT segments")}if("HS256"!==u.alg)throw new en("invalid_algorithm",`Unexpected JWT alg: ${String(u.alg)}`);const d=Qe(He(t),He(`${a}.${o}`));let p;try{p=Xt(c)}catch{throw new en("invalid_signature","Unreadable JWT signature")}if(!Ye(d,p))throw new en("invalid_signature","JWT signature verification failed");!function(e){for(const t of["iss","sub","jti"])if(void 0!==e[t]&&"string"!=typeof e[t])throw new en("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const n=e[t];if(void 0!==n&&("number"!=typeof n||!Number.isFinite(n)))throw new en("invalid_token",`JWT ${t} claim must be a finite number`)}const t=e.aud;if(!(void 0===t||"string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new en("invalid_token","JWT aud claim must be a string or string array")}(l);const h=Math.floor(Date.now()/1e3);if(s&&"number"!=typeof l.exp)throw new en("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof l.exp&&h>l.exp+r)throw new en("token_expired","JWT has expired");if("number"==typeof l.nbf&&h+r<l.nbf)throw new en("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&l.iss!==n.issuer)throw new en("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 en("invalid_audience","JWT audience mismatch")}return l}function rn(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function sn(e){return Zt(He(JSON.stringify(e)))}function an(e,t,n){if(!t)throw new en("invalid_secret","Missing signing secret");const r=Math.floor(Date.now()/1e3),s={iat:r,exp:r+(n?.expiresInSec??3600),...e},i=`${sn({alg:"HS256",typ:"JWT"})}.${sn(s)}`;return`${i}.${Zt(Qe(He(t),He(i)))}`}function on(e){const t=rn(e.authorization);if(!t)throw new en("invalid_token","Missing Bearer token");return nn(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function cn(e){const t=rn(e.authorization);if(!t)throw new en("invalid_token","Missing Bearer token");return nn(t,e.clientSecret,{clockToleranceSec:e.clockToleranceSec})}function un(e){return{success:!0,token:e.token,message:e.message??"ok",..."number"==typeof e.expiresIn?{expiresIn:e.expiresIn}:{}}}function ln(e){return{success:!1,token:"",message:e}}async function dn(e){let t;try{t=on(e)}catch(e){return{status:401,body:ln(e instanceof en?e.code:"invalid_token")}}return{status:200,body:un(await e.mintToken(t))}}async function pn(e){let t;try{t=cn(e)}catch(e){return{status:401,body:{success:!1,message:e instanceof en?e.code:"invalid_token"}}}return await e.onRevoke(t),{status:200,body:{success:!0}}}function hn(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function fn(e){const t=[`Bearer resource_metadata="${hn(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${hn(e.error)}"`),e.errorDescription&&t.push(`error_description="${hn(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const gn=12,wn=16;function yn(){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 mn=new Map;function kn(e){let t=mn.get(e);return t||(t=(async()=>{const t=await yn().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return yn().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),mn.set(e,t)),t}function bn(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(t){const n=globalThis.crypto.getRandomValues(new Uint8Array(gn)),r=await kn(e),s=new Uint8Array(await yn().encrypt({name:"AES-GCM",iv:n},r,(new TextEncoder).encode(t))),i=s.subarray(s.length-wn),a=s.subarray(0,s.length-wn),o=new Uint8Array(28+a.length);return o.set(n,0),o.set(i,gn),o.set(a,28),Zt(o)},async decryptSessionRef(t){try{const n=Xt(t);if(n.length<=28)return null;const r=n.slice(0,gn),s=n.subarray(gn,28),i=n.subarray(28),a=new Uint8Array(i.length+wn);a.set(i,0),a.set(s,i.length);const o=await kn(e),c=await yn().decrypt({name:"AES-GCM",iv:r},o,a);return(new TextDecoder).decode(c)}catch{return null}}}}async function Sn(e){const{claims:t,secret:n}=e,r=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,i=t.sessionId?await bn(n).encryptSessionRef(t.sessionId):void 0;return{token:an({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...i?{sid:i}:{},...e.extraClaims},n,{expiresInSec:r}),expiresIn:r}}function vn(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 $n(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const n=bn(t),r=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&r.length)try{const e=new URL(r[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let i;try{i=nn(s,t,{...e.verify})}catch{return null}if(r.length){const t=i.aud?Array.isArray(i.aud)?i.aud:[i.aud]:[];if(!t.length&&e.requireAudience)return vn(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return vn(t,r,"aud does not include this resource"),null}const a="string"==typeof i.sid?await n.decryptSessionRef(i.sid):null,o=Array.isArray(i.scope)?i.scope.filter(e=>"string"==typeof e):"string"==typeof i.scope?i.scope.split(" ").filter(Boolean):void 0;return{sessionId:a??"",userId:"string"==typeof i.userId?i.userId:"string"==typeof i.sub?i.sub:void 0,workspaceId:"string"==typeof i.workspaceId?i.workspaceId:void 0,scopes:o,claims:i}}}}function Un(e){const{serverUrl:t,orgId:n,version:r="v1",getSessionId:s,timeout:i,maxRetries:a,debug:o,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!n)throw new Error("BuildBase: orgId is required");const d={...void 0!==i&&{timeout:i},...void 0!==a&&{maxRetries:a},...void 0!==o&&{debug:o},...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(),[i,a,o]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=o.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return De(r,{userId:n,workspaceRole:c?.role??null,workspace:i,settings:a})},resolve:async(t,n)=>{const r=await e(),[s,i,a]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),o=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===n);return je({userId:n,workspaceRole:o?.role??null,workspace:s,settings:i})}}}),g=f(async()=>p(await(async()=>{if(!s)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await s();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!s)return null;const e=await s();return e?{sessionId:e}:null},withSession:e=>{const t=p(e);return f(async()=>t)},client:{forSession:p},...g}}export{pt as AI_BOT_USER_AGENTS,$ as ApiVersion,en as AppBridgeError,w as AuthApi,ze as AuthStatus,A as BBAction,O as BBScreen,R as BBStatus,T as BB_PARAM,g as BaseApi,m as BetaForm,ge as BillingIntervals,Un as BuildBase,V as CURRENCY_DISPLAY,G as CURRENCY_FLAG,be as CreditBucketSource,Se as CreditBucketStatus,ve as CreditTransactionType,Me as DEFAULT_ROLE_PERMISSIONS,ke as DunningState,P as EventEmitter,ye as InvoiceStatuses,Y as PLAN_CURRENCY_CODES,Z as PLAN_CURRENCY_OPTIONS,qe as PUSH_SERVICE_WORKER_SCRIPT,Je as Permission,k as PushApi,U as SDKEvent,b as SettingsApi,me as SubscriptionItemType,we as SubscriptionStatus,S as UserApi,v as WorkspaceApi,ln as appTokenFailure,un as appTokenSuccess,fn as bearerChallenge,It as buildA2AAgentCard,St as buildAgentCard,Ut as buildAgentSkillsIndex,Ot as buildApiCatalog,Jt as buildAuthMd,Gt as buildDiscoveryLinkHeader,Rt as buildDnsAidRecords,_t as buildLlmsFullTxt,xt as buildLlmsTxt,Nt as buildMcpDiscoveryManifest,Ft as buildMcpServerCard,$t as buildProtectedResourceMetadata,jt as buildRobotsTxt,Ct as buildSecurityTxt,zt as buildSitemap,Et as buildSkillMd,Tt as buildWebBotAuthDirectory,$n as buildbaseAuth,Re as calculateBillableSeats,Oe as calculateSeatOverageCents,We as calculateTotalSubscriptionCents,L as cleanBBParams,bt as clearAgentReadinessCache,K as clearAuthIntent,z as consumeAuthIntent,W as createBBUrl,F as createCheckoutRedirectUrls,N as createCreditPurchaseRedirectUrls,bn as createSessionRefCrypto,Un as default,E as eventEmitter,rn as extractBearerToken,mt as fetchAgentReadiness,ae as formatCents,ie as formatMinorAmountIntl,ce as formatOverageRate,ue as formatOverageRateWithLabel,de as formatQuotaIncludedOverage,fe as formatQuotaWithPrice,xe as getAvailableCurrenciesFromPlans,Ue as getBasePriceCents,Ie as getBillingIntervalAndCurrencyFromPriceId,ne as getCurrencyDecimals,H as getCurrencyFlag,Q as getCurrencySymbol,Ce as getDisplayCurrency,Ae as getPerSeatPriceCents,$e as getPricingVariant,pe as getQuotaDisplayValue,_e as getQuotaDisplayWithVariant,Ee as getQuotaOverageCents,le as getQuotaUnitLabelFromName,Te as getSeatPricing,Pe as getStripePriceIdForInterval,pn as handleAppRevokeRequest,dn as handleAppTokenRequest,De as hasPermission,x as invalidateCreditBalance,_ as invalidateQuotaUsage,I as invalidateSubscription,re as isZeroDecimalCurrency,se as minorAmountToDisplay,Sn as mintAgentToken,Vt as negotiateMarkdown,et as parseWebhookEvent,Yt as provideWebMcpTools,J as readBBParams,Qt as resolveAgentPath,Fe as resolveMaxUsers,je as resolvePermissions,Ht as resolveWellKnown,B as safeRedirect,q as saveAuthIntent,gt as sha256Digest,an as signClientJwt,Ne as validateInvite,M as validateRedirectUrl,cn as verifyAppRevokeRequest,on as verifyAppTokenRequest,nn as verifyClientJwt,Xe as verifyWebhookSignature,Kt as wantsMarkdown};