@buildbase/sdk 0.0.51 → 0.0.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/AGENTS.md +24 -8
  2. package/CHANGELOG.md +102 -0
  3. package/README.md +283 -33
  4. package/dist/css/styles.css +1 -1
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.ts +1248 -76
  7. package/dist/index.mjs +1 -1
  8. package/dist/mcp/index.cjs +1 -0
  9. package/dist/mcp/index.d.ts +1956 -0
  10. package/dist/mcp/index.mjs +1 -0
  11. package/dist/react/chunks/{SettingsDialog-DitAiAqr.cjs → SettingsDialog-B28WJsAr.cjs} +1 -1
  12. package/dist/react/chunks/{SettingsDialog-uVKFxlal.mjs → SettingsDialog-blhppbNm.mjs} +1 -1
  13. package/dist/react/chunks/{SubscriptionDialog-P0GlXEyn.mjs → SubscriptionDialog-BTWVX3cH.mjs} +1 -1
  14. package/dist/react/chunks/{SubscriptionDialog-Cg-qYVKr.cjs → SubscriptionDialog-QKmwvJU1.cjs} +1 -1
  15. package/dist/react/chunks/ar-1Z1MOGAP.mjs +2 -0
  16. package/dist/react/chunks/ar-VGzBv3AZ.cjs +2 -0
  17. package/dist/react/chunks/de-BjdDg60Y.cjs +2 -0
  18. package/dist/react/chunks/de-CXUItplO.mjs +2 -0
  19. package/dist/react/chunks/es-BBPsSZUp.cjs +2 -0
  20. package/dist/react/chunks/es-BTbzVutz.mjs +2 -0
  21. package/dist/react/chunks/fr-Cax48X_S.cjs +2 -0
  22. package/dist/react/chunks/fr-DPMeOQu3.mjs +2 -0
  23. package/dist/react/chunks/hi-BJqvpG6d.cjs +2 -0
  24. package/dist/react/chunks/hi-JfJx-LV7.mjs +2 -0
  25. package/dist/react/chunks/ja-CDGtLzTk.mjs +2 -0
  26. package/dist/react/chunks/ja-DvVyj5xX.cjs +2 -0
  27. package/dist/react/chunks/react-6QJCOE-D.cjs +2 -0
  28. package/dist/react/chunks/react-CC6T7Zky.mjs +2 -0
  29. package/dist/react/chunks/zh-BAcqxkxk.cjs +2 -0
  30. package/dist/react/chunks/zh-BNZ2Ooe8.mjs +2 -0
  31. package/dist/react/index.cjs +1 -1
  32. package/dist/react/index.d.ts +98 -43
  33. package/dist/react/index.mjs +1 -1
  34. package/package.json +20 -5
  35. package/dist/react/chunks/ar-SrPOJXdL.mjs +0 -2
  36. package/dist/react/chunks/ar-a3aRbPCs.cjs +0 -2
  37. package/dist/react/chunks/de-DE3_z7r0.cjs +0 -2
  38. package/dist/react/chunks/de-xnPl61SS.mjs +0 -2
  39. package/dist/react/chunks/es-C_xcyGtp.cjs +0 -2
  40. package/dist/react/chunks/es-CyuBtosP.mjs +0 -2
  41. package/dist/react/chunks/fr-BMu7Bk4k.cjs +0 -2
  42. package/dist/react/chunks/fr-CxuDLZ27.mjs +0 -2
  43. package/dist/react/chunks/hi-CQ215yc9.cjs +0 -2
  44. package/dist/react/chunks/hi-CpuvyorS.mjs +0 -2
  45. package/dist/react/chunks/ja-DIJ_xCIi.mjs +0 -2
  46. package/dist/react/chunks/ja-DK6Buuws.cjs +0 -2
  47. package/dist/react/chunks/react-C2ikFWBG.cjs +0 -2
  48. package/dist/react/chunks/react-CCukNQ4q.mjs +0 -2
  49. package/dist/react/chunks/zh-CYQwZiBL.mjs +0 -2
  50. package/dist/react/chunks/zh-Dt-apS2s.cjs +0 -2
@@ -0,0 +1 @@
1
+ import{z as e}from"zod";function t(e){let t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function s(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),s=t.length%4==0?"":"=".repeat(4-t.length%4),r=atob(t+s),n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r.charCodeAt(e);return n}const r=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),n=(e,t)=>e>>>t|e<<32-t;function o(e){let t=1779033703,s=3144134277,o=1013904242,a=2773480762,i=1359893119,c=2600822924,u=528734635,l=1541459225;const p=e.length,d=p+1,h=d+(56-d%64+64)%64+8,g=new Uint8Array(h);g.set(e,0),g[p]=128;const w=8*p,m=Math.floor(w/4294967296),f=w>>>0;g[h-8]=m>>>24&255,g[h-7]=m>>>16&255,g[h-6]=m>>>8&255,g[h-5]=255&m,g[h-4]=f>>>24&255,g[h-3]=f>>>16&255,g[h-2]=f>>>8&255,g[h-1]=255&f;const y=new Uint32Array(64);for(let e=0;e<h;e+=64){for(let t=0;t<16;t++){const s=e+4*t;y[t]=g[s]<<24|g[s+1]<<16|g[s+2]<<8|g[s+3]}for(let e=16;e<64;e++){const t=n(y[e-15],7)^n(y[e-15],18)^y[e-15]>>>3,s=n(y[e-2],17)^n(y[e-2],19)^y[e-2]>>>10;y[e]=y[e-16]+t+y[e-7]+s>>>0}let p=t,d=s,h=o,w=a,m=i,f=c,b=u,k=l;for(let e=0;e<64;e++){const t=k+(n(m,6)^n(m,11)^n(m,25))+(m&f^~m&b)+r[e]+y[e]>>>0,s=p&d^p&h^d&h;k=b,b=f,f=m,m=w+t>>>0,w=h,h=d,d=p,p=t+((n(p,2)^n(p,13)^n(p,22))+s>>>0)>>>0}t=t+p>>>0,s=s+d>>>0,o=o+h>>>0,a=a+w>>>0,i=i+m>>>0,c=c+f>>>0,u=u+b>>>0,l=l+k>>>0}const b=new Uint8Array(32),k=[t,s,o,a,i,c,u,l];for(let e=0;e<8;e++)b[4*e]=k[e]>>>24&255,b[4*e+1]=k[e]>>>16&255,b[4*e+2]=k[e]>>>8&255,b[4*e+3]=255&k[e];return b}function a(e){return(new TextEncoder).encode(e)}function i(e,t){let s=e;s.length>64&&(s=o(s));const r=new Uint8Array(64),n=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<s.length?s[e]:0;r[e]=54^t,n[e]=92^t}const a=o(c(r,t));return o(c(n,a))}function c(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e,0),s.set(t,e.length),s}class u extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function l(e){return JSON.parse((new TextDecoder).decode(s(e)))}function p(e,t,r={}){const n=r.clockToleranceSec??60,o=r.requireExp??!0;if(!e||!t)throw new u("invalid_token","Missing token or client secret");const c=e.split(".");if(3!==c.length)throw new u("invalid_token","Malformed JWT");const[p,d,h]=c;let g,w;try{g=l(p),w=l(d)}catch{throw new u("invalid_token","Unreadable JWT segments")}if("HS256"!==g.alg)throw new u("invalid_algorithm",`Unexpected JWT alg: ${String(g.alg)}`);const m=i(a(t),a(`${p}.${d}`));let f;try{f=s(h)}catch{throw new u("invalid_signature","Unreadable JWT signature")}if(!function(e,t){if(e.length!==t.length)return!1;let s=0;for(let r=0;r<e.length;r++)s|=e[r]^t[r];return 0===s}(m,f))throw new u("invalid_signature","JWT signature verification failed");const y=Math.floor(Date.now()/1e3);if(o&&"number"!=typeof w.exp)throw new u("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof w.exp&&y>w.exp+n)throw new u("token_expired","JWT has expired");if("number"==typeof w.nbf&&y+n<w.nbf)throw new u("token_not_yet_valid","JWT is not yet valid");if(void 0!==r.issuer&&w.iss!==r.issuer)throw new u("invalid_issuer","JWT issuer mismatch");if(void 0!==r.audience){const e=w.aud;if(!(Array.isArray(e)?e.includes(r.audience):e===r.audience))throw new u("invalid_audience","JWT audience mismatch")}return w}function d(e){if(!e)return null;const t=/^Bearer\s+(.+)$/i.exec(e.trim());return t?t[1].trim():null}function h(e){return t(a(JSON.stringify(e)))}function g(e,s,r){if(!s)throw new u("invalid_secret","Missing signing secret");const n=Math.floor(Date.now()/1e3),o={iat:n,exp:n+(r?.expiresInSec??3600),...e},c=`${h({alg:"HS256",typ:"JWT"})}.${h(o)}`;return`${c}.${t(i(a(s),a(c)))}`}function w(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function m(e){const t=[`Bearer resource_metadata="${w(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${w(e.error)}"`),e.errorDescription&&t.push(`error_description="${w(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const f=e.string().optional().describe("Workspace id. Omit to use the workspace bound to your token.");function y(e,t){const s=e.workspaceId??t.workspaceId;if(!s)throw new Error("workspaceId is required — call list_workspaces to find one.");return s}const b={readOnlyHint:!0},k=[{name:"list_workspaces",description:"List the authenticated user's workspaces (id, name, roles).",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.workspace.list()},{name:"get_workspace",description:"Get one workspace: name, members, feature flags, quota snapshot.",inputSchema:e.object({workspaceId:f}),annotations:b,execute:(e,t)=>t.bb.workspace.get(y(e,t))},{name:"get_user_profile",description:"Get the authenticated user's profile.",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.users.getProfile()},{name:"list_workspace_users",description:"List the members of a workspace with their roles.",inputSchema:e.object({workspaceId:f}),annotations:b,execute:(e,t)=>t.bb.users.list(y(e,t))},{name:"get_subscription",description:"Get a workspace's subscription: plan, status, interval, seats.",inputSchema:e.object({workspaceId:f}),annotations:b,execute:(e,t)=>t.bb.subscription.get(y(e,t))},{name:"get_plans",description:"Get the plan group available to a workspace (plans, prices, quotas).",inputSchema:e.object({workspaceId:f}),annotations:b,execute:(e,t)=>t.bb.plans.getGroup(y(e,t))},{name:"list_invoices",description:"List a workspace's invoices (newest first).",inputSchema:e.object({workspaceId:f,limit:e.number().int().min(1).max(100).optional().describe("Max invoices to return."),startingAfter:e.string().optional().describe("Invoice id to paginate after.")}),annotations:b,execute:(e,t)=>t.bb.invoices.list(y(e,t),e.limit,e.startingAfter)},{name:"get_quota_usage",description:"Get usage vs. limit for one quota in a workspace.",inputSchema:e.object({workspaceId:f,quotaSlug:e.string().describe('The quota slug, e.g. "api-calls".')}),annotations:b,execute:(e,t)=>t.bb.usage.getQuota(y(e,t),e.quotaSlug)},{name:"get_all_quota_usage",description:"Get usage vs. limit for every quota in a workspace.",inputSchema:e.object({workspaceId:f}),annotations:b,execute:(e,t)=>t.bb.usage.getAll(y(e,t))},{name:"get_credit_balance",description:"Get a workspace's prepaid credit balance.",inputSchema:e.object({workspaceId:f}),annotations:b,execute:(e,t)=>t.bb.credits.getBalance(y(e,t))},{name:"list_credit_transactions",description:"Get a workspace's credit transaction history (paginated).",inputSchema:e.object({workspaceId:f,limit:e.number().int().min(1).max(100).optional(),page:e.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getTransactions(y(e,t),{...void 0!==e.limit?{limit:e.limit}:{},...void 0!==e.page?{page:e.page}:{}})},{name:"check_feature_flag",description:"Check whether a feature flag is enabled for a workspace.",inputSchema:e.object({workspaceId:f,key:e.string().describe("The feature slug.")}),annotations:b,execute:async(e,t)=>{const s=y(e,t),r=await t.bb.workspace.get(s),n=r.features?.[e.key];if(void 0!==n)return{key:e.key,enabled:n,source:"workspace"};const o=(await t.bb.features.list()).find(t=>t.slug===e.key);if(!o)throw new Error(`Unknown feature flag: ${e.key}`);return{key:e.key,enabled:o.defaultValue,source:"default"}}},{name:"check_permission",description:"Check whether a user has permission(s) in a workspace.",inputSchema:e.object({workspaceId:f,permission:e.union([e.string(),e.array(e.string())]).describe("A permission (or list — all must hold), platform or app-defined."),userId:e.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const s=e.userId??t.auth.userId;if(!s)throw new Error("userId is required — the token carries no user identity.");const r=await t.bb.permissions.check(y(e,t),s,e.permission);return{userId:s,permission:e.permission,allowed:r}}},{name:"resolve_permissions",description:"List every permission a user holds in a workspace.",inputSchema:e.object({workspaceId:f,userId:e.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const s=e.userId??t.auth.userId;if(!s)throw new Error("userId is required — the token carries no user identity.");const r=await t.bb.permissions.resolve(y(e,t),s);return{userId:s,permissions:Array.from(r)}}},{name:"get_invoice",description:"Get one invoice by id.",inputSchema:e.object({workspaceId:f,invoiceId:e.string().describe("The invoice id.")}),annotations:b,execute:(e,t)=>t.bb.invoices.get(y(e,t),e.invoiceId)},{name:"get_plan_versions",description:"List the plan-group versions available to a workspace.",inputSchema:e.object({workspaceId:f}),annotations:b,execute:(e,t)=>t.bb.plans.getVersions(y(e,t))},{name:"get_public_plans",description:"Get a public plan group by slug (no workspace / auth needed).",inputSchema:e.object({slug:e.string().describe("The plan-group slug.")}),annotations:b,execute:(e,t)=>t.bb.plans.getPublic(e.slug)},{name:"get_plan_version",description:"Get one public plan-group version by id (no auth needed).",inputSchema:e.object({groupVersionId:e.string().describe("The plan-group version id.")}),annotations:b,execute:(e,t)=>t.bb.plans.getVersion(e.groupVersionId)},{name:"get_usage_logs",description:"Get a workspace's usage log entries (paginated, filterable).",inputSchema:e.object({workspaceId:f,quotaSlug:e.string().optional(),from:e.string().optional().describe("ISO date lower bound."),to:e.string().optional().describe("ISO date upper bound."),source:e.string().optional(),page:e.number().int().min(1).optional(),limit:e.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:s,...r}=e;return t.bb.usage.getLogs(y(e,t),r)}},{name:"get_settings",description:"Get the organization settings.",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.settings.get()},{name:"get_credit_packages",description:"List the credit packages a workspace can purchase.",inputSchema:e.object({workspaceId:f}),annotations:b,execute:(e,t)=>t.bb.credits.getPackages(y(e,t))},{name:"get_credit_buckets",description:"Get a workspace's credit buckets (paginated).",inputSchema:e.object({workspaceId:f,status:e.string().optional(),source:e.string().optional(),page:e.number().int().min(1).optional(),limit:e.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:s,...r}=e;return t.bb.credits.getBuckets(y(e,t),r)}},{name:"get_expiring_credits",description:"Get credits expiring within N days (default 7).",inputSchema:e.object({workspaceId:f,days:e.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getExpiring(y(e,t),e.days)},{name:"get_public_credit_packages",description:"List credit packages publicly (no workspace / auth needed).",inputSchema:e.object({}),annotations:b,execute:(e,t)=>t.bb.credits.getPublicPackages()}],S=[{name:"record_usage",description:"Record quota usage for a workspace (metered billing).",inputSchema:e.object({workspaceId:f,quotaSlug:e.string().describe("The quota slug to record against."),quantity:e.number().positive().describe("Amount of usage to record."),idempotencyKey:e.string().optional().describe("Dedupe key for safe retries."),metadata:e.record(e.string(),e.unknown()).optional()}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},execute:(e,t)=>t.bb.usage.record(y(e,t),{quotaSlug:e.quotaSlug,quantity:e.quantity,source:"mcp",...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{},...e.metadata?{metadata:e.metadata}:{}})},{name:"consume_credits",description:"Consume prepaid credits from a workspace's balance.",inputSchema:e.object({workspaceId:f,amount:e.number().positive().describe("Credits to consume."),description:e.string().optional().describe("What the credits were spent on."),idempotencyKey:e.string().optional().describe("Dedupe key for safe retries.")}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.credits.consume(y(e,t),{amount:e.amount,...e.description?{description:e.description}:{},...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{}})},{name:"send_notification",description:"Send a notification event to a workspace user (or all members when userId is omitted).",inputSchema:e.object({workspaceId:f,event:e.string().describe('The event slug, e.g. "comment_added".'),userId:e.string().optional().describe("Recipient. Omit to notify all members."),message:e.string().optional().describe("Message body (used for push).")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.notification.send(y(e,t),e.event,e.userId,e.message?{message:e.message}:void 0)},{name:"record_usage_batch",description:"Record multiple usage entries in one call (max 100 items).",inputSchema:e.object({workspaceId:f,items:e.array(e.object({quotaSlug:e.string(),quantity:e.number().positive(),idempotencyKey:e.string().optional(),metadata:e.record(e.string(),e.unknown()).optional()})).min(1).max(100)}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.usage.recordBatch(y(e,t),{items:e.items.map(e=>({...e,source:"mcp"}))})},{name:"create_workspace",description:"Create a new workspace.",inputSchema:e.object({name:e.string().describe("Workspace name."),image:e.string().optional().describe("Image URL.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.workspace.create({name:e.name,...e.image?{image:e.image}:{}})},{name:"update_workspace",description:"Update a workspace's editable fields (name, image).",inputSchema:e.object({workspaceId:f,name:e.string().min(1).optional().describe("New workspace name."),image:e.string().optional().describe("New image URL.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const s={};return void 0!==e.name&&(s.name=e.name),void 0!==e.image&&(s.image=e.image),t.bb.workspace.update(y(e,t),s)}},{name:"delete_workspace",description:"Delete a workspace. Irreversible.",inputSchema:e.object({workspaceId:f}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.workspace.delete(y(e,t))},{name:"invite_workspace_user",description:"Invite a user to a workspace with a role.",inputSchema:e.object({workspaceId:f,email:e.string().describe("Invitee email."),role:e.string().describe("Role to grant.")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.users.invite(y(e,t),e.email,e.role)},{name:"remove_workspace_user",description:"Remove a user from a workspace. Irreversible.",inputSchema:e.object({workspaceId:f,userId:e.string().describe("The user to remove.")}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.users.remove(y(e,t),e.userId)},{name:"update_workspace_user_role",description:"Change a workspace member's role.",inputSchema:e.object({workspaceId:f,userId:e.string(),role:e.string().describe("The new role.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.users.updateRole(y(e,t),e.userId,e.role)},{name:"update_user_profile",description:"Update the authenticated user's own profile (name, image, country, timezone, language, currency).",inputSchema:e.object({name:e.string().min(1).optional(),image:e.string().optional().describe("Profile image URL."),country:e.string().optional().describe("ISO country code."),timezone:e.string().optional().describe("IANA timezone."),language:e.string().optional().describe("Language code."),currency:e.string().optional().describe("Currency code.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const s={};for(const t of["name","image","country","timezone","language","currency"]){const r=e[t];void 0!==r&&(s[t]=r)}return t.bb.users.updateProfile(s)}},{name:"update_feature_flag",description:"Set a feature flag on/off for a workspace.",inputSchema:e.object({workspaceId:f,key:e.string().describe("The feature slug."),value:e.boolean().describe("Enabled?")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.features.update(y(e,t),e.key,e.value)},{name:"create_subscription_checkout",description:"Create a Stripe checkout session to subscribe a workspace to a plan.",inputSchema:e.object({workspaceId:f,planVersionId:e.string(),billingInterval:e.string().optional(),currency:e.string().optional(),successUrl:e.string().optional(),cancelUrl:e.string().optional()}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:s,...r}=e;return t.bb.subscription.checkout(y(e,t),r)}},{name:"update_subscription",description:"Change a workspace's subscription plan.",inputSchema:e.object({workspaceId:f,planVersionId:e.string(),billingInterval:e.string().optional(),successUrl:e.string().optional(),cancelUrl:e.string().optional()}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const{workspaceId:s,...r}=e;return t.bb.subscription.update(y(e,t),r)}},{name:"cancel_subscription",description:"Cancel a workspace's subscription.",inputSchema:e.object({workspaceId:f}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.subscription.cancel(y(e,t))},{name:"resume_subscription",description:"Resume a workspace's canceled subscription.",inputSchema:e.object({workspaceId:f}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.subscription.resume(y(e,t))},{name:"get_billing_portal_url",description:"Get a Stripe billing-portal URL for a workspace.",inputSchema:e.object({workspaceId:f,returnUrl:e.string().optional()}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.subscription.getBillingPortalUrl(y(e,t),e.returnUrl)},{name:"purchase_credits",description:"Create a Stripe checkout session to buy a credit package.",inputSchema:e.object({workspaceId:f,creditPackageId:e.string(),currency:e.string().optional(),successUrl:e.string().describe("Redirect URL on success."),cancelUrl:e.string().describe("Redirect URL on cancel.")}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:s,...r}=e;return t.bb.credits.purchase(y(e,t),r)}}],v=new Map([...k,...S].map(e=>[e.name,e]));function E(e){if(!1===e)return[];if("readonly"===e)return[...k];if("all"===e)return[...k,...S];const t=e.include?e.include.map(e=>{const t=v.get(e);if(!t)throw new Error(`Unknown built-in MCP tool: ${e}`);return t}):[...k],s=new Set(e.exclude??[]);return t.filter(e=>!s.has(e.name))}const I=["2025-06-18","2025-03-26","2024-11-05"],_=I[0],P="application/json",R=/^[a-zA-Z0-9_-]{1,128}$/,x=-32700,$=-32600,U=-32601,T=-32602,C=-32603;function A(e,t){const s=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===s)return e[t]}function O(e,t){return{status:e,headers:{"Content-Type":P},body:JSON.stringify(t)}}function F(e,t){return O(200,{jsonrpc:"2.0",id:e??null,result:t})}function j(e,t,s,r=200,n){return O(r,{jsonrpc:"2.0",id:e??null,error:{code:t,message:s,...void 0!==n?{data:n}:{}}})}function W(e){return"object"==typeof e&&null!==e&&"function"==typeof e.safeParse}function N(e){return e instanceof Error?e.message:"string"==typeof e?e:JSON.stringify(e)}function J(t){const s=t.serverInfo??{name:"buildbase-mcp",version:"1.0.0"};t.auth&&!t.auth.resourceMetadataUrl&&console.warn("[buildbase/mcp] auth is enabled but `auth.resourceMetadataUrl` is unset — 401 responses will carry no WWW-Authenticate/resource_metadata pointer, so MCP clients cannot discover your authorization server. Set it to your /.well-known/oauth-protected-resource URL.");const r=e=>e.trim().toLowerCase().replace(/\/+$/,""),n=t.allowedOrigins?new Set(t.allowedOrigins.map(r)):null,o=e=>!!e&&!!n&&n.has(r(e)),a=t.builtinTools??(!!t.buildbase&&"readonly"),i=t.maxRequestBytes??1048576;if(!1!==a&&!t.buildbase)throw new Error("builtinTools require a `buildbase` client — pass one to createMcpHandler, or set builtinTools: false.");const c=new Map;for(const e of E(a))c.set(e.name,e);const u=new Set;for(const e of t.tools??[]){if(!R.test(e.name))throw new Error(`Invalid MCP tool name: "${e.name}" (want ${String(R)})`);if(u.has(e.name))throw new Error(`Duplicate MCP tool name: "${e.name}"`);u.add(e.name),c.set(e.name,e)}const l=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`No \`buildbase\` client configured — pass one to createMcpHandler to use bb.${t} in tools.`)}}),p=new Proxy({},{get(e,t){if("string"==typeof t)throw new Error(`This tool needs an authenticated BuildBase session, but the token carried none (bb.${t}). Re-authenticate.`)}}),h=new Map;function g(t){const s=h.get(t.name);if(s)return s;let r;try{r=W(t.inputSchema)?e.toJSONSchema(t.inputSchema,{target:"draft-2020-12"}):t.inputSchema}catch(e){f(e,{method:"tools/list",tool:t.name}),r={type:"object",additionalProperties:!0}}return h.set(t.name,r),r}function w(e){const t=new Set(e?.scopes??[]);return Array.from(c.values()).filter(e=>(e.requiredScopes??[]).every(e=>t.has(e)))}function f(e,s){try{t.onError?.(e instanceof Error?e:new Error(N(e)),s)}catch{}}function y(){if(t.auth&&t.auth.resourceMetadataUrl){const e=m({resourceMetadataUrl:t.auth.resourceMetadataUrl});return{status:e.status,headers:e.headers,body:e.body}}return O(401,{error:"unauthorized"})}const b=Array.isArray(t.cors)?new Set(t.cors.map(r)):null;async function k(e){const a=function(e){if(!1===t.cors)return{};const s=A(e.headers,"origin");let a;return a=b?s&&b.has(r(s))?s:null:n?o(s)?s:null:"*",a?{"Access-Control-Allow-Origin":a,"Access-Control-Allow-Methods":"POST, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, MCP-Protocol-Version, Mcp-Session-Id, Last-Event-ID","Access-Control-Expose-Headers":"MCP-Protocol-Version, Mcp-Session-Id, WWW-Authenticate","Access-Control-Max-Age":"86400",..."*"!==a?{Vary:"Origin"}:{}}:{}}(e);if("OPTIONS"===e.method.toUpperCase())return{status:204,headers:a,body:""};const c=await async function(e){const r=e.method.toUpperCase();if(n){const t=A(e.headers,"origin");if(t&&!o(t))return O(403,{error:"origin_not_allowed"})}if("POST"!==r)return{status:405,headers:{"Content-Type":P,Allow:"POST, OPTIONS"},body:JSON.stringify({error:"method_not_allowed"})};if(i>0&&"string"==typeof e.body&&e.body.length>i)return O(413,{error:"payload_too_large"});let a=null;if(!1!==t.auth){const s=d(A(e.headers,"authorization"));if(!s)return y();try{a=await t.auth.verify(s,e)}catch(e){f(e,{method:"auth"}),a=null}if(!a)return y()}if(t.rateLimit){let s;try{s=await t.rateLimit(a,e)}catch(e){f(e,{method:"rateLimit"}),s=!1}if(!("boolean"==typeof s?s:s.ok)){const e="object"==typeof s?s.retryAfter:void 0;return{status:429,headers:{"Content-Type":P,...void 0!==e?{"Retry-After":String(e)}:{}},body:JSON.stringify({error:"rate_limited"})}}}let c=e.body;if("string"==typeof e.body)try{c=JSON.parse(e.body)}catch{return j(null,x,"Invalid JSON",400)}if(Array.isArray(c))return j(null,$,"Batch requests are not supported",400);if("object"!=typeof c||null===c)return j(null,$,"Expected a JSON-RPC request object",400);const u=c,h=u.id,m="string"==typeof u.method?u.method:null;if(!m)return j(h,$,"Missing method",400);if(null==h)return{status:202,headers:{"Content-Type":P},body:""};const b=u.params??{};switch(m){case"initialize":{const e=b.protocolVersion;return F(h,{protocolVersion:"string"==typeof e&&I.includes(e)?e:_,capabilities:{tools:{listChanged:!1}},serverInfo:s,...t.instructions?{instructions:t.instructions}:{}})}case"ping":return F(h,{});case"tools/list":return F(h,{tools:w(a).map(e=>({name:e.name,description:e.description,inputSchema:g(e),...e.annotations?{annotations:e.annotations}:{}}))});case"tools/call":{const s="string"==typeof b.name?b.name:"",r=w(a).find(e=>e.name===s);if(!r)return j(h,T,`Unknown tool: ${s||"(missing name)"}`);let n,o=b.arguments??{};if(W(r.inputSchema)){const e=r.inputSchema.safeParse(o);if(!e.success)return j(h,T,`Invalid arguments for ${s}`,200,{issues:e.error.issues});o=e.data}if(t.context)try{n=await t.context(a,e)}catch(e){return f(e,{method:m,tool:s}),j(h,C,"Context initialization failed")}const i=a?.sessionId??"",c={bb:t.buildbase?i?t.buildbase.withSession(i):p:l,auth:a??{sessionId:""},workspaceId:a?.workspaceId,custom:n};try{const e=await r.execute(o,c),t="object"==typeof e&&null!==e&&!Array.isArray(e);return F(h,{content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e,null,2)}],...t?{structuredContent:e}:{},isError:!1})}catch(e){f(e,{method:m,tool:s});const r=e instanceof Error?e:new Error(N(e));return F(h,{content:[{type:"text",text:t.formatToolError?t.formatToolError(r,{tool:s}):r.message}],isError:!0})}}default:return j(h,U,`Method not found: ${m}`)}}(e);return Object.keys(a).length?{...c,headers:{...c.headers,...a}}:c}return{handle:k,fetch:async function(e){const t={};if(e.headers.forEach((e,s)=>{t[s]=e}),i>0){const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>i)return new Response(JSON.stringify({error:"payload_too_large"}),{status:413,headers:{"Content-Type":P}})}const s="POST"===e.method.toUpperCase()?await e.text():void 0,r=await k({method:e.method,headers:t,body:s});return new Response(""===r.body?null:r.body,{status:r.status,headers:r.headers})},listTools:()=>Array.from(c.values()).map(e=>({name:e.name,description:e.description,...e.annotations?{annotations:e.annotations}:{}})),serverCard:e=>({name:s.name,version:s.version,endpoint:e.endpoint,transport:"streamable-http",capabilities:{tools:{listChanged:!1}},...e.description?{description:e.description}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{}})}}function M(e){return e}const B=12,q=16;function L(){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 H=new Map;function D(e){let t=H.get(e);return t||(t=(async()=>{const t=await L().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return L().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),H.set(e,t)),t}function G(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(s){const r=globalThis.crypto.getRandomValues(new Uint8Array(B)),n=await D(e),o=new Uint8Array(await L().encrypt({name:"AES-GCM",iv:r},n,(new TextEncoder).encode(s))),a=o.subarray(o.length-q),i=o.subarray(0,o.length-q),c=new Uint8Array(28+i.length);return c.set(r,0),c.set(a,B),c.set(i,28),t(c)},async decryptSessionRef(t){try{const r=s(t);if(r.length<=28)return null;const n=r.slice(0,B),o=r.subarray(B,28),a=r.subarray(28),i=new Uint8Array(a.length+q);i.set(a,0),i.set(o,a.length);const c=await D(e),u=await L().decrypt({name:"AES-GCM",iv:n},c,i);return(new TextDecoder).decode(u)}catch{return null}}}}async function K(e){const{claims:t,secret:s}=e,r=e.expiresInSec??3600,n=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,o=t.sessionId?await G(s).encryptSessionRef(t.sessionId):void 0;return{token:g({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...n?{aud:n}:{},...o?{sid:o}:{},...e.extraClaims},s,{expiresInSec:r}),expiresIn:r}}function V(e,t,s){const r=globalThis.process?.env;"1"===r?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${s}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function z(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const s=G(t),r=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let n=e.resourceMetadataUrl;if(!n&&r.length)try{const e=new URL(r[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");n=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:n,verify:async n=>{let o;try{o=p(n,t,{...e.verify})}catch{return null}if(r.length){const t=o.aud?Array.isArray(o.aud)?o.aud:[o.aud]:[];if(!t.length&&e.requireAudience)return V(t,r,"token carries no aud claim"),null;if(t.length&&!t.some(e=>r.includes(e)))return V(t,r,"aud does not include this resource"),null}const a="string"==typeof o.sid?await s.decryptSessionRef(o.sid):null,i=Array.isArray(o.scope)?o.scope:"string"==typeof o.scope?o.scope.split(" ").filter(Boolean):void 0;return{sessionId:a??"",userId:"string"==typeof o.userId?o.userId:"string"==typeof o.sub?o.sub:void 0,workspaceId:"string"==typeof o.workspaceId?o.workspaceId:void 0,scopes:i,claims:o}}}}const Q=300,Y="/.well-known/oauth-protected-resource",Z="/.well-known/agent-skills",X="/.well-known/api-catalog",ee="/.well-known/mcp/server-card.json",te="/.well-known/agent-card.json",se="application/json",re="application/linkset+json",ne="text/markdown; charset=utf-8",oe="text/plain; charset=utf-8",ae="application/xml; charset=utf-8",ie=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ce(e){return e.replace(/\/+$/,"")}function ue(e){return`public, max-age=${e}, s-maxage=${e}`}function le(e){return"sha256:"+function(e){let t="";for(let s=0;s<e.length;s++)t+=e[s].toString(16).padStart(2,"0");return t}(o(a(e)))}const pe=new Map;async function de(e,t,s,r){if(!r||r<=0)return e(t,s);const n=new AbortController,o=setTimeout(()=>n.abort(),r);try{return await e(t,{...s,signal:n.signal})}finally{clearTimeout(o)}}async function he(e){const t=e.cacheTtlSeconds??Q,s=`${ce(e.serverUrl)}::${e.orgId}`,r=pe.get(s);if(r&&r.expiresAt>Date.now())return r.value;const n=e.fetch??fetch,o=`${ce(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let a={enabled:!1};try{const t=await de(n,o,{headers:{Accept:se}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(a=e)}}catch{}return pe.set(s,{value:a,expiresAt:Date.now()+1e3*t}),a}const ge=new Map;function we(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const s="/"===t?"":t.replace(/\/+$/,"");return Y+s}function me(e){return e.path??`${Z}/${e.name}/SKILL.md`}function fe(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:oe,body:t.join("\n")+"\n",cacheControl:ue(e.cacheTtlSeconds??Q)}}function ye(e){return e.endsWith(".json")||e.includes(".well-known/")?se:e.endsWith(".md")?ne:e.endsWith(".xml")?ae:oe}function be(e){const t=e??{tools:!0},s={tools:!1,resources:!1,prompts:!1};for(const[e,r]of Object.entries(t))s[e]=!1!==r&&null!=r;return s}function ke(e,t){return{status:200,contentType:se,body:JSON.stringify(e,null,2),cacheControl:ue(t.cacheTtlSeconds??Q)}}function Se(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function ve(e,t){const s=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${Se(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&&s.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])s.push(`Allow: ${Se(t)}`);for(const t of e.disallow??[])s.push(`Disallow: ${Se(t)}`);return void 0!==e.crawlDelay&&s.push(`Crawl-delay: ${Se(e.crawlDelay)}`),s.join("\n")}function Ee(e){const t="number"==typeof e&&Number.isFinite(e)?e:.5;return String(Math.min(1,Math.max(0,t)))}function Ie(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function _e(e){const t=ce(e.siteUrl),s=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&s.push(`<${t}${te}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const r=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;s.push(`<${r}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&s.push(`<${t}${X}>; rel="api-catalog"; type="${re}"`),e.mcpServerCard&&s.push(`<${t}${ee}>; rel="mcp-server"; type="application/json"`),s.join(", ")}async function Pe(e,t){const s=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===s){return function(e,t){const s=ce(e.siteUrl),r={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:Y};return 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=`${Z}/index.json`),e.apiCatalog?.length&&(r.api_catalog=X),e.mcpServerCard&&(r.mcp_server_card=ee),!1!==e.a2aCard&&(r.a2a_agent_card=te),e.llmsFullTxt&&(r.llms_full_txt="/llms-full.txt"),ke({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:s,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:s},capabilities:r,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}(t,await he(t))}if(s===te)return function(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},s=ce(e.siteUrl),r=t.serviceUrl??s,n=t.transportProtocol??"http",o=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return ke({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:n,supportedInterfaces:[{serviceUrl:r,transportProtocol:n}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:s},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:o,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}(t);if("/.well-known/http-message-signatures-directory"===s)return function(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:ue(e.cacheTtlSeconds??Q)}:null}(t);if("/.well-known/security.txt"===s)return fe(t);if(s===`${Z}/index.json`)return function(e){const t=e.skills??[];if(!t.length)return null;const s=ce(e.siteUrl);return ke({$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:`${s}${me(e)}`,digest:le(e.content)}))},e)}(t);if(s.startsWith(`${Z}/`)&&s.endsWith("SKILL.md"))return function(e,t){const s=(t.skills??[]).find(t=>me(t)===e);return s?{status:200,contentType:"text/markdown; charset=utf-8",body:s.content,cacheControl:ue(t.cacheTtlSeconds??Q)}:null}(s,t);if("/.well-known/oauth-authorization-server"===s||"/.well-known/openid-configuration"===s){const e=(await he(t)).authorizationServer;if(!e?.metadataUrl)return null;const s=await async function(e,t){const s=t.cacheTtlSeconds??Q,r=ge.get(e);if(r&&r.expiresAt>Date.now())return r.value;const n=t.fetch??fetch;let o=null;try{const s=await de(n,e,{headers:{Accept:se}},t.fetchTimeoutMs??5e3);if(s.ok){const e=await s.json();e&&"object"==typeof e&&(o=e)}}catch{}return ge.set(e,{value:o,expiresAt:Date.now()+1e3*s}),o}(e.metadataUrl,t);return ke(s?s:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(s===X)return function(e){const t=e.apiCatalog??[];if(!t.length)return null;const s=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:re,body:JSON.stringify({linkset:s},null,2),cacheControl:ue(e.cacheTtlSeconds??Q)}}(t);if(s===ee)return function(e){const t=e.mcpServerCard;return t?ke({$schema:"https://modelcontextprotocol.io/schemas/server-card/v1.0",version:"1.0",protocolVersion:t.protocolVersion??"2025-06-18",serverInfo:{name:t.name,version:t.version},...t.description?{description:t.description}:{},transport:{type:t.transport??"streamable-http",url:t.endpoint},capabilities:be(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}(t);if("/.well-known/mcp.json"===s)return function(e){const t=e.mcpServerCard;if(!t)return null;const s=ce(e.siteUrl);let r;try{r={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${we(t.endpoint)}`}}catch{}return ke({$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:be(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${s}${ee}`,...r?{authentication:r}:{}}]},e)}(t);if(s.startsWith(Y)){const e=await he(t);return function(e,t,s){const r=t.protectedResources??[];if(!r.length)return null;const n=e.replace(/\/+$/,"")||Y,o=s??`${ce(t.serverUrl)}/org/${t.orgId}`,a=t.scopes?.map(e=>e.name),i=r.map(e=>{const s=e.resource??ce(t.siteUrl),r=e.scopes??a;return{path:we(s),metadata:{resource:s,authorization_servers:[o],bearer_methods_supported:e.bearerMethods??["header"],...r?.length?{scopes_supported:r}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=i.find(e=>e.path===n);return c?ke(c.metadata,t):n===Y&&1===i.length?ke(i[0].metadata,t):null}(s,t,e.authorizationServer?.issuer)}return null}async function Re(e,t){const s=e.replace(/\/+$/,"")||e,r=function(e,t){const s=t.extraPaths?.[e];if(void 0===s)return null;const r="string"==typeof s?{body:s}:s;return{status:r.status??200,contentType:r.contentType??ye(e),body:r.body,cacheControl:r.cacheControl??ue(t.cacheTtlSeconds??Q)}}(s,t);return r||("/robots.txt"===s?function(e){const t=e.robots??{},s=ce(e.siteUrl),r=t.policies??[{userAgent:"*",allow:["/"]}],n=t.aiBots??"allow",o="allow"===n?[{userAgent:[...ie],allow:["/"]}]:"deny"===n?[{userAgent:[...ie],disallow:["/"]}]:n,a=t.sitemaps??(e.sitemap?[`${s}/sitemap.xml`]:[]),i=[`# robots.txt — agent-ready. See ${s}/llms.txt and ${s}/.well-known/agent.json`,...r.map((e,s)=>ve(e,0===s?t.contentSignals:void 0)),...o.map(e=>ve(e)),...a.length?[a.map(e=>`Sitemap: ${Se(e)}`).join("\n")]:[]];return{status:200,contentType:oe,body:i.join("\n\n")+"\n",cacheControl:ue(e.cacheTtlSeconds??Q)}}(t):"/llms-full.txt"===s?function(e){return e.llmsFullTxt?{status:200,contentType:oe,body:e.llmsFullTxt,cacheControl:ue(e.cacheTtlSeconds??Q)}:null}(t):"/sitemap.xml"===s?function(e){const t=e.sitemap?.urls;if(!t?.length)return null;const s=ce(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>${Ie(/^https?:\/\//.test(t.loc)?t.loc:`${s}${t.loc.startsWith("/")?"":"/"}${t.loc}`)}</loc>`,...t.lastmod?[` <lastmod>${Ie(t.lastmod)}</lastmod>`]:[],...t.changefreq?[` <changefreq>${Ie(String(t.changefreq))}</changefreq>`]:[],...void 0!==t.priority?[` <priority>${Ee(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:ae,body:r,cacheControl:ue(e.cacheTtlSeconds??Q)}}(t):"/llms.txt"===s?function(e){return e.llmsTxt?{status:200,contentType:oe,body:e.llmsTxt,cacheControl:ue(e.cacheTtlSeconds??Q)}:null}(t):"/auth.md"===s?function(e,t){const s=ue(e.cacheTtlSeconds??Q);if(e.authMd)return{status:200,contentType:ne,body:e.authMd,cacheControl:s};const r=t.authorizationServer;if(!r)return null;const n=`# Agent Authentication\n\n${e.site.name} supports AI-agent access via OAuth 2.0 (authorization code + PKCE).\n\n## Authorization server\n- Issuer: \`${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:ne,body:n,cacheControl:s}}(t,await he(t)):"/security.txt"===s?fe(t):s.startsWith("/.well-known")?Pe(s,t):null)}let xe=!0;function $e(e,...t){xe&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}async function Ue(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 Te(e,t="Request failed"){if(!e.ok){let s=t;try{const t=await Ue(e);s=t.message||t.error||s}catch{s=function(e,t){const s={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}: ${s})`)}(e,t).message}throw new Error(s)}try{return await Ue(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Ce extends Error{constructor(e,t,s,r){super(e),this.code=t,this.context=s,this.originalError=r,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,Ce)}}const Ae=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(xe=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const s=e instanceof Error?e:new Ce("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),r=s instanceof Ce?s:new Ce(s.message,"SDK_ERROR",t,s);if(this.config.enableConsoleLogging&&$e(`[SDK Error] ${t.component||"Unknown"}:`,{message:r.message,code:r.code,context:r.context,originalError:r.originalError,stack:r.stack}),this.config.onError)try{this.config.onError(r,t)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(r,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...s)=>e(...s).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...s)=>{try{return e(...s)}catch(e){throw this.handleError(e,t),e}}}};function Oe(e,t={}){Ae.handleError(e,t)}const Fe="saas-session-id";function je(){if("undefined"==typeof window)return null;try{return function(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return Oe(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}(Fe)}catch(e){return Oe(e,{component:"auth-utils",action:"getSessionId",metadata:{key:Fe}}),null}}function We(){const e=je(),t={};return e&&(t["x-session-id"]=e),t}const Ne=new WeakSet,Je=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Me="SDK is not ready (missing serverUrl, version, or orgId)";class Be{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(Me);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(Me)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:We()}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){Ne.has(e)||(Ne.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((s,r)=>{const n=()=>{clearTimeout(o),r(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return n();const o=setTimeout(()=>{t?.removeEventListener("abort",n),s()},e);t?.addEventListener("abort",n,{once:!0})})}async executeFetchUrl(e,t,s){const r=(t.method??"GET").toUpperCase(),n=s??e,o=this.buildHeaders(t),a={...t,headers:o},i=Je.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 s=AbortSignal.any;if("function"==typeof s)return s([e,t]);const r=new AbortController,n=e=>{r.signal.aborted||r.abort(e.reason)};for(const s of[e,t]){if(s.aborted){n(s);break}s.addEventListener("abort",()=>n(s),{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} ${n}`);return this.reportError(e,{method:r,path:n}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const s=this._fetch.bind(globalThis),n=await s(e,a);if(this._debug&&console.log(`[BuildBase] ${r} ${e} → ${n.status}`),401===n.status&&this._onUnauthorized&&this._onUnauthorized(),n.status>=500&&i&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await Be.delay(e,a.signal),p(t+1)}return n}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(i&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await Be.delay(e,a.signal)}catch(e){throw l(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:r,path:n}),e}};try{return await p(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},s="Request failed"){this.ensureReady();try{const r=await this.executeFetch(e,t);return await Te(r,s)}catch(s){throw s instanceof Error&&this.reportError(s,{method:(t.method??"GET").toUpperCase(),path:e}),s}}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 s=t;try{s=(await e.json()).message||s}catch{s=`${t} (${e.status}: ${e.statusText})`}throw new Error(s)}apiPath(e,...t){return e.reduce((e,s,r)=>e+s+(r<t.length?encodeURIComponent(String(t[r])):""),"")}async unwrapResponse(e,t){const s=await e.json();if(void 0!==s.success){if(!s.success)throw new Error(s.message||t);return void 0!==s.data?s.data:s}return s}}class qe extends Be{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 Le extends Be{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class He extends Be{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 s=await this.unwrapResponse(t,"Failed to fetch user attributes");return s&&"object"==typeof s&&!Array.isArray(s)?s:{}}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 s=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof s&&null!==s?s:{}}}class De extends Be{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,s){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(s)},"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,s){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:s}})},"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 s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch plan group version"),this.unwrapResponse(s,"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 s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to create checkout session"),this.unwrapResponse(s,"Failed to create checkout session")}async selectFreePlan(e,t){const s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t})});return s.ok||await this.throwResponseError(s,"Failed to select free plan"),s.json()}async updateSubscription(e,t){const s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to update subscription"),this.unwrapResponse(s,"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,s){const r=new URLSearchParams;r.append("limit",t.toString()),s&&r.append("starting_after",s);const n=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices`+`?${r.toString()}`);return n.ok||await this.throwResponseError(n,"Failed to fetch invoices"),this.unwrapResponse(n,"Failed to fetch invoices")}async getInvoice(e,t){const s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/invoices/${t}`);return s.ok||await this.throwResponseError(s,"Failed to fetch invoice"),this.unwrapResponse(s,"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 s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to record usage"),this.unwrapResponse(s,"Failed to record usage")}async recordUsageBatch(e,t){const s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to record batch usage"),this.unwrapResponse(s,"Failed to record batch usage")}async getQuotaUsageStatus(e,t){const s=await this.fetchResponse(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`);return s.ok||await this.throwResponseError(s,"Failed to fetch quota usage status"),this.unwrapResponse(s,"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 s=new URLSearchParams;t?.quotaSlug&&s.append("quotaSlug",t.quotaSlug),t?.from&&s.append("from",t.from),t?.to&&s.append("to",t.to),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=this.apiPath`workspaces/${e}/subscription/usage/logs`+(r?`?${r}`:""),o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch usage logs"),this.unwrapResponse(o,"Failed to fetch usage logs")}async sendNotification(e,t,s,r){const n={event:t};return s&&(n.userId=s),r&&(n.data=r),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(n)},"Failed to send notification")}async getNotificationEvents(e){return this.fetchJson(this.apiPath`workspaces/${e}/notification-events`,{},"Failed to fetch notification events")}async getNotificationPreferences(e){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{},"Failed to fetch notification preferences")).notificationPreferences??{}}async updateNotificationPreferences(e,t){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t})},"Failed to update notification preferences")).notificationPreferences??{}}async getCreditBalance(e){const t=await this.fetchResponse(this.apiPath`workspaces/${e}/credits`);return t.ok||await this.throwResponseError(t,"Failed to fetch credit balance"),this.unwrapResponse(t,"Failed to fetch credit balance")}async consumeCredits(e,t){const s=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t)});if(!s.ok){if(402===s.status){const e=await s.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(s,"Failed to consume credits")}return this.unwrapResponse(s,"Failed to consume credits")}async purchaseCredits(e,t){const s=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t)});return s.ok||await this.throwResponseError(s,"Failed to create credit purchase checkout"),this.unwrapResponse(s,"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 s=await this.unwrapResponse(t,"Failed to fetch credit packages");return s.docs??s}async getCreditTransactions(e,t){const s=new URLSearchParams;t?.type&&s.append("type",t.type),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=this.apiPath`workspaces/${e}/credits/transactions`+(r?`?${r}`:""),o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch credit transactions"),this.unwrapResponse(o,"Failed to fetch credit transactions")}async getCreditBuckets(e,t){const s=new URLSearchParams;t?.status&&s.append("status",t.status),t?.source&&s.append("source",t.source),t?.page&&s.append("page",t.page.toString()),t?.limit&&s.append("limit",t.limit.toString());const r=s.toString(),n=this.apiPath`workspaces/${e}/credits/buckets`+(r?`?${r}`:""),o=await this.fetchResponse(n);return o.ok||await this.throwResponseError(o,"Failed to fetch credit buckets"),this.unwrapResponse(o,"Failed to fetch credit buckets")}async getExpiringCredits(e,t){const s=t?`?days=${t}`:"",r=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/expiring`+s);return r.ok||await this.throwResponseError(r,"Failed to fetch expiring credits"),this.unwrapResponse(r,"Failed to fetch expiring credits")}}const Ge={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"},Ke=Object.values(Ge),Ve={admin:Ke.filter(e=>e!==Ge.WORKSPACE_DELETE),member:[Ge.WORKSPACE_SETTINGS_VIEW,Ge.WORKSPACE_MEMBERS_VIEW,Ge.WORKSPACE_FEATURES_VIEW,Ge.WORKSPACE_BILLING_VIEW,Ge.WORKSPACE_USAGE_VIEW],viewer:[Ge.WORKSPACE_SETTINGS_VIEW,Ge.WORKSPACE_MEMBERS_VIEW]};function ze(e){const t=new Set;for(const s of Object.values(e))for(const e of s)t.add(e);return Array.from(t)}function Qe(e){const{userId:t,workspace:s,settings:r,appPermissions:n}=e;if(!s||!t)return new Set;if(function(e,t){if(!t)return!1;const s=(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!==s&&s===t}(s,t)){const e=new Set(Ke);if(n)for(const t of ze(n))e.add(t);if(s.permissions)for(const t of ze(s.permissions))e.add(t);if(r?.workspace?.permissions)for(const t of ze(r.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const s=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return s&&"object"==typeof s&&"role"in s&&"string"==typeof s.role?s.role:null}(s,t);if(!o)return new Set;const a=s.permissions,i=r?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!a&&o in a,p=!!i&&o in i,d=o in Ve;let h;if(l)h=c(a[o]);else if(p)h=c(i[o]);else if(d)h=Ve[o];else{const e=r?.workspace?.defaultRole;h=e&&e in Ve?Ve[e]:[]}const g=new Set(h),w=l?u(a[o]):[],m=n?.[o]?u(n[o]):[],f=l?w:m;for(const e of f)g.add(e);return function(e,t,s){if(!s?.workspace)return;const{canInviteMembers:r}=s.workspace;(!1===r||"admin-only"===r&&"admin"!==t)&&e.delete(Ge.WORKSPACE_MEMBERS_INVITE)}(g,o,r),g}function Ye(e){const{serverUrl:t,orgId:s,version:r="v1",getSessionId:n,timeout:o,maxRetries:a,debug:i,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!s)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==a&&{maxRetries:a},...void 0!==i&&{debug:i},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},d=e=>{const n={serverUrl:t,version:r,orgId:s,sessionId:e,...p};return{workspace:new De(n),user:new He(n),settings:new Le(n),push:new qe(n)}},h=new De({serverUrl:t,version:r,orgId:s,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,s)=>(await e()).workspace.updateWorkspace(t,s),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,s,r)=>(await e()).workspace.addUser(t,{email:s,role:r}),remove:async(t,s)=>(await e()).workspace.removeUser(t,s),updateRole:async(t,s,r)=>(await e()).workspace.updateUser(t,s,{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,s)=>(await e()).workspace.createCheckoutSession(t,s),update:async(t,s)=>(await e()).workspace.updateSubscription(t,s),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,s)=>(await e()).workspace.createBillingPortalSession(t,s)},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,s,r)=>(await e()).workspace.listInvoices(t,s,r),get:async(t,s)=>(await e()).workspace.getInvoice(t,s)},usage:{record:async(t,s)=>(await e()).workspace.recordUsage(t,s),recordBatch:async(t,s)=>(await e()).workspace.recordUsageBatch(t,s),getQuota:async(t,s)=>(await e()).workspace.getQuotaUsageStatus(t,s),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,s)=>(await e()).workspace.getUsageLogs(t,s)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,s,r)=>(await e()).workspace.updateFeature(t,s,r)},notification:{send:async(t,s,r,n)=>(await e()).workspace.sendNotification(t,s,r,n)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,s)=>(await e()).workspace.consumeCredits(t,s),purchase:async(t,s)=>(await e()).workspace.purchaseCredits(t,s),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,s)=>(await e()).workspace.getCreditTransactions(t,s),getBuckets:async(t,s)=>(await e()).workspace.getCreditBuckets(t,s),getExpiring:async(t,s)=>(await e()).workspace.getExpiringCredits(t,s),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,s,r)=>{const n=await e(),[o,a,i]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),c=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return function(e,t){const s=Qe(t);return Array.isArray(e)?e.every(e=>s.has(e)):s.has(e)}(r,{userId:s,workspaceRole:c?.role??null,workspace:o,settings:a})},resolve:async(t,s)=>{const r=await e(),[n,o,a]=await Promise.all([r.workspace.getWorkspace(t),r.settings.getSettings(),r.workspace.getWorkspaceUsers(t)]),i=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===s);return Qe({userId:s,workspaceRole:i?.role??null,workspace:n,settings:o})}}}),w=g(async()=>d(await(async()=>{if(!n)throw new Error("BuildBase: getSessionId callback is required for authenticated calls. Pass it in BuildBase({ getSessionId: ... }) or use withSession(id) / client.forSession(id).");const e=await n();if(!e)throw new Error("BuildBase: Not authenticated (getSessionId returned null)");return e})()));return{auth:async()=>{if(!n)return null;const e=await n();return e?{sessionId:e}:null},withSession:e=>{const t=d(e);return g(async()=>t)},client:{forSession:d},...w}}function Ze(e){const t=e.siteUrl.replace(/\/+$/,"");const s=e.mcp?.path??"/api/mcp",r=`${t}${s.startsWith("/")?s:`/${s}`}`,n=e.mcp?.serverInfo??{name:e.site.name,version:"1.0.0"},o=`${t}/mcp`,a=Array.from(new Set([o,r])),i=e.mcp?.auth??(e.secret?z({secret:e.secret,resource:a,resourceMetadataUrl:`${t}/.well-known/oauth-protected-resource/mcp`,requireAudience:!0}):void 0);if(void 0===i)throw new Error("createAgentStack: pass `secret` (the app token-signing secret) to derive auth, or set `mcp.auth` yourself (`false` disables auth — local development only).");const c=J({buildbase:e.mcp?.buildbase??Ye({serverUrl:e.serverUrl,orgId:e.orgId}),serverInfo:n,auth:i,tools:e.mcp?.tools,builtinTools:e.mcp?.builtinTools??"readonly",...e.mcp?.handler}),u={serverUrl:e.serverUrl,orgId:e.orgId,siteUrl:e.siteUrl,site:e.site,mcpServerCard:c.serverCard({endpoint:r,...e.site.description?{description:e.site.description}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}),...e.scopes?{scopes:e.scopes}:{},protectedResources:a.map(t=>({resource:t,...e.mcp?.scopes?.length?{scopes:e.mcp.scopes}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}})).concat([{resource:t,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}]),apiCatalog:[{anchor:r,title:`${e.site.name} MCP server`,serviceDesc:`${t}/.well-known/mcp/server-card.json`}],...e.discovery},l={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, OPTIONS"};const p=e=>c.fetch(e);return{mcp:c,mcpEndpoint:r,config:u,linkHeader:_e(u),resolvePath:e=>Re(e,u),serveAgentPath:async function(e){if("OPTIONS"===e.method.toUpperCase())return new Response(null,{status:204,headers:l});const t=await Re(new URL(e.url).pathname,u);return t?new Response(t.body,{status:t.status,headers:{"Content-Type":t.contentType,"Cache-Control":t.cacheControl,...t.vary?{Vary:t.vary}:{},...l}}):new Response(JSON.stringify({error:"not_found"}),{status:404,headers:{"Content-Type":"application/json",...l}})},routes:{GET:p,POST:p,DELETE:p,OPTIONS:p}}}export{u as AppBridgeError,m as bearerChallenge,z as buildbaseAuth,v as builtinMcpTools,Ze as createAgentStack,J as createMcpHandler,G as createSessionRefCrypto,M as defineMcpTool,d as extractBearerToken,K as mintAgentToken,E as selectBuiltinTools,g as signClientJwt,p as verifyClientJwt};