@buildbase/sdk 0.0.60 → 0.0.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/README.md +95 -0
- package/dist/css/styles.css +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +84 -0
- package/dist/index.mjs +1 -1
- package/dist/mcp/index.cjs +1 -1
- package/dist/mcp/index.d.ts +23 -0
- package/dist/mcp/index.mjs +1 -1
- package/dist/react/chunks/SettingsDialog-CKwldz7y.mjs +2 -0
- package/dist/react/chunks/{SettingsDialog-DzcwBYsg.cjs → SettingsDialog-D4FCwpN7.cjs} +1 -1
- package/dist/react/chunks/SubscriptionDialog-DJmrU0r1.cjs +2 -0
- package/dist/react/chunks/SubscriptionDialog-DoWnS_JD.mjs +2 -0
- package/dist/react/chunks/react-Be1VMiVO.mjs +2 -0
- package/dist/react/chunks/react-ClieHJPH.cjs +2 -0
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.d.ts +186 -26
- package/dist/react/index.mjs +1 -1
- package/dist/tracking/index.cjs +2 -0
- package/dist/tracking/index.d.ts +657 -0
- package/dist/tracking/index.mjs +2 -0
- package/package.json +12 -2
- package/dist/react/chunks/SettingsDialog-4yk6t4tT.mjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-COw79gAi.cjs +0 -2
- package/dist/react/chunks/SubscriptionDialog-DLM_WA84.mjs +0 -2
- package/dist/react/chunks/react-D6q1fjoE.cjs +0 -2
- package/dist/react/chunks/react-DX2YGh4O.mjs +0 -2
- /package/dist/react/chunks/{ar-DHxjPtfZ.mjs → ar-CHTRXlXt.mjs} +0 -0
- /package/dist/react/chunks/{ar-D7uaSur2.cjs → ar-DPJVNHJV.cjs} +0 -0
- /package/dist/react/chunks/{de-D_xfGk1N.mjs → de-CdPeKWZ2.mjs} +0 -0
- /package/dist/react/chunks/{de-CBzx6NJq.cjs → de-DPd09yf-.cjs} +0 -0
- /package/dist/react/chunks/{es-D4-Dv2t5.mjs → es-BWGnjJKJ.mjs} +0 -0
- /package/dist/react/chunks/{es-WVRwuj-e.cjs → es-WdOYGt6G.cjs} +0 -0
- /package/dist/react/chunks/{fr-DurP7qkZ.mjs → fr-Big5DFPB.mjs} +0 -0
- /package/dist/react/chunks/{fr-CEpK52jT.cjs → fr-LIbCvYeh.cjs} +0 -0
- /package/dist/react/chunks/{hi-CVqVRSoy.cjs → hi-BoCY3pFe.cjs} +0 -0
- /package/dist/react/chunks/{hi-7roM83DB.mjs → hi-jArNRknR.mjs} +0 -0
- /package/dist/react/chunks/{ja-DT8x4SW1.mjs → ja-Cwdz0hCu.mjs} +0 -0
- /package/dist/react/chunks/{ja-BrDXec_v.cjs → ja-E0jqCiVq.cjs} +0 -0
- /package/dist/react/chunks/{zh-CH1Z55Je.mjs → zh-glRKcdia.mjs} +0 -0
- /package/dist/react/chunks/{zh-CdCzcD53.cjs → zh-tU-AqFYI.cjs} +0 -0
package/dist/mcp/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("zod");function t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function r(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4==0?"":"=".repeat(4-t.length%4),n=atob(t+r),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return s}const n=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]),s=(e,t)=>e>>>t|e<<32-t;function o(e){let t=1779033703,r=3144134277,o=1013904242,i=2773480762,a=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 m=8*p,f=Math.floor(m/4294967296),w=m>>>0;g[h-8]=f>>>24&255,g[h-7]=f>>>16&255,g[h-6]=f>>>8&255,g[h-5]=255&f,g[h-4]=w>>>24&255,g[h-3]=w>>>16&255,g[h-2]=w>>>8&255,g[h-1]=255&w;const y=new Uint32Array(64);for(let e=0;e<h;e+=64){for(let t=0;t<16;t++){const r=e+4*t;y[t]=g[r]<<24|g[r+1]<<16|g[r+2]<<8|g[r+3]}for(let e=16;e<64;e++){const t=s(y[e-15],7)^s(y[e-15],18)^y[e-15]>>>3,r=s(y[e-2],17)^s(y[e-2],19)^y[e-2]>>>10;y[e]=y[e-16]+t+y[e-7]+r>>>0}let p=t,d=r,h=o,m=i,f=a,w=c,b=u,k=l;for(let e=0;e<64;e++){const t=k+(s(f,6)^s(f,11)^s(f,25))+(f&w^~f&b)+n[e]+y[e]>>>0,r=p&d^p&h^d&h;k=b,b=w,w=f,f=m+t>>>0,m=h,h=d,d=p,p=t+((s(p,2)^s(p,13)^s(p,22))+r>>>0)>>>0}t=t+p>>>0,r=r+d>>>0,o=o+h>>>0,i=i+m>>>0,a=a+f>>>0,c=c+w>>>0,u=u+b>>>0,l=l+k>>>0}const b=new Uint8Array(32),k=[t,r,o,i,a,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 i(e){return(new TextEncoder).encode(e)}function a(e,t){let r=e;r.length>64&&(r=o(r));const n=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<r.length?r[e]:0;n[e]=54^t,s[e]=92^t}const i=o(c(n,t));return o(c(s,i))}function c(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}class u extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function l(e){const t=JSON.parse((new TextDecoder).decode(r(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function p(e,t,n={}){const s=n.clockToleranceSec??60,o=n.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,m;try{g=l(p),m=l(d)}catch{throw new u("invalid_token","Unreadable JWT segments")}if("HS256"!==g.alg)throw new u("invalid_algorithm",`Unexpected JWT alg: ${String(g.alg)}`);const f=a(i(t),i(`${p}.${d}`));let w;try{w=r(h)}catch{throw new u("invalid_signature","Unreadable JWT signature")}if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(f,w))throw new u("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 u("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const r=e[t];if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)))throw new u("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 u("invalid_token","JWT aud claim must be a string or string array")}(m);const y=Math.floor(Date.now()/1e3);if(o&&"number"!=typeof m.exp)throw new u("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof m.exp&&y>m.exp+s)throw new u("token_expired","JWT has expired");if("number"==typeof m.nbf&&y+s<m.nbf)throw new u("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&m.iss!==n.issuer)throw new u("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=m.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new u("invalid_audience","JWT audience mismatch")}return m}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(i(JSON.stringify(e)))}function g(e,r,n){if(!r)throw new u("invalid_secret","Missing signing secret");const s=Math.floor(Date.now()/1e3),o={iat:s,exp:s+(n?.expiresInSec??3600),...e},c=`${h({alg:"HS256",typ:"JWT"})}.${h(o)}`;return`${c}.${t(a(i(r),i(c)))}`}function m(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function f(e){const t=[`Bearer resource_metadata="${m(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${m(e.error)}"`),e.errorDescription&&t.push(`error_description="${m(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const w=e.z.string().optional().describe("Workspace id. Omit to use the workspace bound to your token.");function y(e,t){const r=e.workspaceId??t.workspaceId;if(!r)throw new Error("workspaceId is required — call list_workspaces to find one.");return r}const b={readOnlyHint:!0},k=[{name:"list_workspaces",description:"List the authenticated user's workspaces (id, name, roles).",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.workspace.list()},{name:"get_workspace",description:"Get one workspace: name, members, feature flags, quota snapshot.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.workspace.get(y(e,t))},{name:"get_user_profile",description:"Get the authenticated user's profile.",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.users.getProfile()},{name:"list_workspace_users",description:"List the members of a workspace with their roles.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.users.list(y(e,t))},{name:"get_subscription",description:"Get a workspace's subscription: plan, status, interval, seats.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.subscription.get(y(e,t))},{name:"get_plans",description:"Get the plan group available to a workspace (plans, prices, quotas).",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.plans.getGroup(y(e,t))},{name:"list_invoices",description:"List a workspace's invoices (newest first).",inputSchema:e.z.object({workspaceId:w,limit:e.z.number().int().min(1).max(100).optional().describe("Max invoices to return."),startingAfter:e.z.string().optional().describe("Invoice id to paginate after.")}),annotations:b,execute:(e,t)=>t.bb.invoices.list(y(e,t),e.limit,e.startingAfter)},{name:"get_quota_usage",description:"Get usage vs. limit for one quota in a workspace.",inputSchema:e.z.object({workspaceId:w,quotaSlug:e.z.string().describe('The quota slug, e.g. "api-calls".')}),annotations:b,execute:(e,t)=>t.bb.usage.getQuota(y(e,t),e.quotaSlug)},{name:"get_all_quota_usage",description:"Get usage vs. limit for every quota in a workspace.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.usage.getAll(y(e,t))},{name:"get_credit_balance",description:"Get a workspace's prepaid credit balance.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.credits.getBalance(y(e,t))},{name:"list_credit_transactions",description:"Get a workspace's credit transaction history (paginated).",inputSchema:e.z.object({workspaceId:w,limit:e.z.number().int().min(1).max(100).optional(),page:e.z.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getTransactions(y(e,t),{...void 0!==e.limit?{limit:e.limit}:{},...void 0!==e.page?{page:e.page}:{}})},{name:"check_feature_flag",description:"Check whether a feature flag is enabled for a workspace.",inputSchema:e.z.object({workspaceId:w,key:e.z.string().describe("The feature slug.")}),annotations:b,execute:async(e,t)=>{const r=y(e,t),n=await t.bb.workspace.get(r),s=n.features?.[e.key];if(void 0!==s)return{key:e.key,enabled:s,source:"workspace"};const o=(await t.bb.features.list()).find(t=>t.slug===e.key);if(!o)throw new Error(`Unknown feature flag: ${e.key}`);return{key:e.key,enabled:o.defaultValue,source:"default"}}},{name:"check_permission",description:"Check whether a user has permission(s) in a workspace.",inputSchema:e.z.object({workspaceId:w,permission:e.z.union([e.z.string(),e.z.array(e.z.string())]).describe("A permission (or list — all must hold), platform or app-defined."),userId:e.z.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const n=await t.bb.permissions.check(y(e,t),r,e.permission);return{userId:r,permission:e.permission,allowed:n}}},{name:"resolve_permissions",description:"List every permission a user holds in a workspace.",inputSchema:e.z.object({workspaceId:w,userId:e.z.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const n=await t.bb.permissions.resolve(y(e,t),r);return{userId:r,permissions:Array.from(n)}}},{name:"get_invoice",description:"Get one invoice by id.",inputSchema:e.z.object({workspaceId:w,invoiceId:e.z.string().describe("The invoice id.")}),annotations:b,execute:(e,t)=>t.bb.invoices.get(y(e,t),e.invoiceId)},{name:"get_plan_versions",description:"List the plan-group versions available to a workspace.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.plans.getVersions(y(e,t))},{name:"get_public_plans",description:"Get a public plan group by slug (no workspace / auth needed).",inputSchema:e.z.object({slug:e.z.string().describe("The plan-group slug.")}),annotations:b,execute:(e,t)=>t.bb.plans.getPublic(e.slug)},{name:"get_plan_version",description:"Get one public plan-group version by id (no auth needed).",inputSchema:e.z.object({groupVersionId:e.z.string().describe("The plan-group version id.")}),annotations:b,execute:(e,t)=>t.bb.plans.getVersion(e.groupVersionId)},{name:"get_usage_logs",description:"Get a workspace's usage log entries (paginated, filterable).",inputSchema:e.z.object({workspaceId:w,quotaSlug:e.z.string().optional(),from:e.z.string().optional().describe("ISO date lower bound."),to:e.z.string().optional().describe("ISO date upper bound."),source:e.z.string().optional(),page:e.z.number().int().min(1).optional(),limit:e.z.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.usage.getLogs(y(e,t),n)}},{name:"get_settings",description:"Get the organization settings.",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.settings.get()},{name:"get_credit_packages",description:"List the credit packages a workspace can purchase.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.credits.getPackages(y(e,t))},{name:"get_credit_buckets",description:"Get a workspace's credit buckets (paginated).",inputSchema:e.z.object({workspaceId:w,status:e.z.string().optional(),source:e.z.string().optional(),page:e.z.number().int().min(1).optional(),limit:e.z.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.credits.getBuckets(y(e,t),n)}},{name:"get_expiring_credits",description:"Get credits expiring within N days (default 7).",inputSchema:e.z.object({workspaceId:w,days:e.z.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getExpiring(y(e,t),e.days)},{name:"get_public_credit_packages",description:"List credit packages publicly (no workspace / auth needed).",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.credits.getPublicPackages()}],S=[{name:"record_usage",description:"Record quota usage for a workspace (metered billing).",inputSchema:e.z.object({workspaceId:w,quotaSlug:e.z.string().describe("The quota slug to record against."),quantity:e.z.number().positive().describe("Amount of usage to record."),idempotencyKey:e.z.string().optional().describe("Dedupe key for safe retries."),metadata:e.z.record(e.z.string(),e.z.unknown()).optional()}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},execute:(e,t)=>t.bb.usage.record(y(e,t),{quotaSlug:e.quotaSlug,quantity:e.quantity,source:"mcp",...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{},...e.metadata?{metadata:e.metadata}:{}})},{name:"consume_credits",description:"Consume prepaid credits from a workspace's balance.",inputSchema:e.z.object({workspaceId:w,amount:e.z.number().positive().describe("Credits to consume."),description:e.z.string().optional().describe("What the credits were spent on."),idempotencyKey:e.z.string().optional().describe("Dedupe key for safe retries.")}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.credits.consume(y(e,t),{amount:e.amount,...e.description?{description:e.description}:{},...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{}})},{name:"send_notification",description:"Send a notification event to a workspace user (or all members when userId is omitted).",inputSchema:e.z.object({workspaceId:w,event:e.z.string().describe('The event slug, e.g. "comment_added".'),userId:e.z.string().optional().describe("Recipient. Omit to notify all members."),message:e.z.string().optional().describe("Message body (used for push).")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.notification.send(y(e,t),e.event,e.userId,e.message?{message:e.message}:void 0)},{name:"record_usage_batch",description:"Record multiple usage entries in one call (max 100 items).",inputSchema:e.z.object({workspaceId:w,items:e.z.array(e.z.object({quotaSlug:e.z.string(),quantity:e.z.number().positive(),idempotencyKey:e.z.string().optional(),metadata:e.z.record(e.z.string(),e.z.unknown()).optional()})).min(1).max(100)}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.usage.recordBatch(y(e,t),{items:e.items.map(e=>({...e,source:"mcp"}))})},{name:"create_workspace",description:"Create a new workspace.",inputSchema:e.z.object({name:e.z.string().describe("Workspace name."),image:e.z.string().optional().describe("Image URL.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.workspace.create({name:e.name,...e.image?{image:e.image}:{}})},{name:"update_workspace",description:"Update a workspace's editable fields (name, image).",inputSchema:e.z.object({workspaceId:w,name:e.z.string().min(1).optional().describe("New workspace name."),image:e.z.string().optional().describe("New image URL.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};return void 0!==e.name&&(r.name=e.name),void 0!==e.image&&(r.image=e.image),t.bb.workspace.update(y(e,t),r)}},{name:"delete_workspace",description:"Delete a workspace. Irreversible.",inputSchema:e.z.object({workspaceId:w}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.workspace.delete(y(e,t))},{name:"invite_workspace_user",description:"Invite a user to a workspace with a role.",inputSchema:e.z.object({workspaceId:w,email:e.z.string().describe("Invitee email."),role:e.z.string().describe("Role to grant.")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.users.invite(y(e,t),e.email,e.role)},{name:"remove_workspace_user",description:"Remove a user from a workspace. Irreversible.",inputSchema:e.z.object({workspaceId:w,userId:e.z.string().describe("The user to remove.")}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.users.remove(y(e,t),e.userId)},{name:"update_workspace_user_role",description:"Change a workspace member's role.",inputSchema:e.z.object({workspaceId:w,userId:e.z.string(),role:e.z.string().describe("The new role.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.users.updateRole(y(e,t),e.userId,e.role)},{name:"update_user_profile",description:"Update the authenticated user's own profile (name, image, country, timezone, language, currency).",inputSchema:e.z.object({name:e.z.string().min(1).optional(),image:e.z.string().optional().describe("Profile image URL."),country:e.z.string().optional().describe("ISO country code."),timezone:e.z.string().optional().describe("IANA timezone."),language:e.z.string().optional().describe("Language code."),currency:e.z.string().optional().describe("Currency code.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};for(const t of["name","image","country","timezone","language","currency"]){const n=e[t];void 0!==n&&(r[t]=n)}return t.bb.users.updateProfile(r)}},{name:"update_feature_flag",description:"Set a feature flag on/off for a workspace.",inputSchema:e.z.object({workspaceId:w,key:e.z.string().describe("The feature slug."),value:e.z.boolean().describe("Enabled?")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.features.update(y(e,t),e.key,e.value)},{name:"create_subscription_checkout",description:"Create a Stripe checkout session to subscribe a workspace to a plan.",inputSchema:e.z.object({workspaceId:w,planVersionId:e.z.string(),billingInterval:e.z.string().optional(),currency:e.z.string().optional(),successUrl:e.z.string().optional(),cancelUrl:e.z.string().optional()}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.subscription.checkout(y(e,t),n)}},{name:"update_subscription",description:"Change a workspace's subscription plan.",inputSchema:e.z.object({workspaceId:w,planVersionId:e.z.string(),billingInterval:e.z.string().optional(),successUrl:e.z.string().optional(),cancelUrl:e.z.string().optional()}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.subscription.update(y(e,t),n)}},{name:"cancel_subscription",description:"Cancel a workspace's subscription.",inputSchema:e.z.object({workspaceId:w}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.subscription.cancel(y(e,t))},{name:"resume_subscription",description:"Resume a workspace's canceled subscription.",inputSchema:e.z.object({workspaceId:w}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.subscription.resume(y(e,t))},{name:"get_billing_portal_url",description:"Get a Stripe billing-portal URL for a workspace.",inputSchema:e.z.object({workspaceId:w,returnUrl:e.z.string().optional()}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.subscription.getBillingPortalUrl(y(e,t),e.returnUrl)},{name:"purchase_credits",description:"Create a Stripe checkout session to buy a credit package.",inputSchema:e.z.object({workspaceId:w,creditPackageId:e.z.string(),currency:e.z.string().optional(),successUrl:e.z.string().describe("Redirect URL on success."),cancelUrl:e.z.string().describe("Redirect URL on cancel.")}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.credits.purchase(y(e,t),n)}}],v=new Map([...k,...S].map(e=>[e.name,e]));function E(e){if(!1===e)return[];if("readonly"===e)return[...k];if("all"===e)return[...k,...S];const t=e.include?e.include.map(e=>{const t=v.get(e);if(!t)throw new Error(`Unknown built-in MCP tool: ${e}`);return t}):[...k],r=new Set(e.exclude??[]);return t.filter(e=>!r.has(e.name))}const x=e=>({type:"text",text:e}),I=e=>{if("object"!=typeof e||null===e)return!1;const t=e;switch(t.type){case"text":return"string"==typeof t.text;case"image":case"audio":return"string"==typeof t.data&&"string"==typeof t.mimeType;case"resource_link":return"string"==typeof t.uri&&"string"==typeof t.name;case"resource":{const e=t.resource;return"object"==typeof e&&null!==e&&"string"==typeof e.uri&&("string"==typeof e.text||"string"==typeof e.blob)}default:return!1}},T=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],_=T[0],P="application/json",U=/^[a-zA-Z0-9_-]{1,128}$/,$=-32002,C=-32700,A=-32600,z=-32601,O=-32602,R=-32603;function j(e,t){const r=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===r)return e[t]}function J(e,t){return{status:e,headers:{"Content-Type":P},body:JSON.stringify(t)}}function W(e,t){return J(200,{jsonrpc:"2.0",id:e??null,result:t})}function N(e,t,r,n=200,s){return J(n,{jsonrpc:"2.0",id:e??null,error:{code:t,message:r,...void 0!==s?{data:s}:{}}})}function F(e){return"object"==typeof e&&null!==e&&"function"==typeof e.safeParse}function M(e){return e instanceof Error?e.message:"string"==typeof e?e:JSON.stringify(e)}function q(t){const r=t.serverInfo??{name:"buildbase-mcp",version:"1.0.0"};t.auth&&!t.auth.resourceMetadataUrl&&console.warn("[buildbase/mcp] auth is enabled but `auth.resourceMetadataUrl` is unset — 401 responses will carry no WWW-Authenticate/resource_metadata pointer, so MCP clients cannot discover your authorization server. Set it to your /.well-known/oauth-protected-resource URL.");const n=e=>e.trim().toLowerCase().replace(/\/+$/,""),s=t.allowedOrigins?new Set(t.allowedOrigins.map(n)):null,o=e=>!!e&&!!s&&s.has(n(e)),i=t.builtinTools??(!!t.buildbase&&"readonly"),a=t.maxRequestBytes??1048576;if(!1!==i&&!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(i))c.set(e.name,e);const u=new Set;for(const e of t.tools??[]){if(!U.test(e.name))throw new Error(`Invalid MCP tool name: "${e.name}" (want ${String(U)})`);if(u.has(e.name))throw new Error(`Duplicate MCP tool name: "${e.name}"`);u.add(e.name),c.set(e.name,e)}if(t.builtinResources&&!t.buildbase)throw new Error("builtinResources requires a `buildbase` client — pass one to createMcpHandler.");const l=new Map,p=[];t.builtinResources&&(l.set("buildbase://profile",{uri:"buildbase://profile",name:"profile",title:"Your profile",description:"The authenticated user's BuildBase profile.",mimeType:"application/json",read:e=>e.bb.users.getProfile()}),l.set("buildbase://workspaces",{uri:"buildbase://workspaces",name:"workspaces",title:"Your workspaces",description:"The authenticated user's workspaces (id, name, roles).",mimeType:"application/json",read:e=>e.bb.workspace.list()}),p.push({uriTemplate:"buildbase://workspace/{workspaceId}",name:"workspace",title:"One workspace",description:"A single workspace: name, members, feature flags, quota snapshot.",mimeType:"application/json",read:(e,t,r)=>r.bb.workspace.get(e.workspaceId)}));for(const e of t.resources??[])l.set(e.uri,e);p.push(...t.resourceTemplates??[]);const h=new Map;for(const e of t.prompts??[]){if(!U.test(e.name))throw new Error(`Invalid MCP prompt name: "${e.name}" (want ${String(U)})`);if(h.has(e.name))throw new Error(`Duplicate MCP prompt name: "${e.name}"`);h.set(e.name,e)}const g=l.size>0||p.length>0,m=h.size>0,w=(e,t)=>{const r=new Set(t?.scopes??[]);return(e??[]).every(e=>r.has(e))};function y(e,r){const n=e?.sessionId??"";return{bb:t.buildbase?n?t.buildbase.withSession(n):v:S,auth:e??{sessionId:""},workspaceId:e?.workspaceId,custom:r}}function b(e,t){const r=[],n=e.replace(/[.*+?^$()|[\]\\]/g,e=>"\\"+e).replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>(r.push(t),"([^/]+)")),s=new RegExp(`^${n}$`).exec(t);if(!s)return null;const o={};return r.forEach((e,t)=>{try{o[e]=decodeURIComponent(s[t+1])}catch{o[e]=s[t+1]}}),o}function k(e,t,r){if("string"==typeof r)return{uri:e,mimeType:t??"text/plain",text:r};if(r&&"object"==typeof r){const n=r;if("string"==typeof n.text)return{uri:e,mimeType:"string"==typeof n.mimeType?n.mimeType:t??"text/plain",text:n.text};if("string"==typeof n.blob)return{uri:e,mimeType:"string"==typeof n.mimeType?n.mimeType:t??"application/octet-stream",blob:n.blob}}return{uri:e,mimeType:t??"application/json",text:JSON.stringify(r,null,2)}}const S=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.`)}}),v=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.`)}}),q=new Map;function B(t){const r=q.get(t.name);if(r)return r;let n;try{n=F(t.inputSchema)?e.z.toJSONSchema(t.inputSchema,{target:"draft-2020-12"}):t.inputSchema}catch(e){H(e,{method:"tools/list",tool:t.name}),n={type:"object",additionalProperties:!0}}return q.set(t.name,n),n}function L(e){const t=new Set(e?.scopes??[]);return Array.from(c.values()).filter(e=>(e.requiredScopes??[]).every(e=>t.has(e)))}function H(e,r){try{t.onError?.(e instanceof Error?e:new Error(M(e)),r)}catch{}}function D(){if(t.auth&&t.auth.resourceMetadataUrl){const e=f({resourceMetadataUrl:t.auth.resourceMetadataUrl});return{status:e.status,headers:e.headers,body:e.body}}return J(401,{error:"unauthorized"})}const G=Array.isArray(t.cors)?new Set(t.cors.map(n)):null;async function K(e){const i=function(e){if(!1===t.cors)return{};const r=j(e.headers,"origin");let i;return i=G?r&&G.has(n(r))?r:null:s?o(r)?r:null:"*",i?{"Access-Control-Allow-Origin":i,"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",..."*"!==i?{Vary:"Origin"}:{}}:{}}(e);if("OPTIONS"===e.method.toUpperCase())return{status:204,headers:i,body:""};const c=await async function(e){const n=e.method.toUpperCase();if(s){const t=j(e.headers,"origin");if(t&&!o(t))return J(403,{error:"origin_not_allowed"})}if("POST"!==n)return{status:405,headers:{"Content-Type":P,Allow:"POST, OPTIONS"},body:JSON.stringify({error:"method_not_allowed"})};if(a>0&&"string"==typeof e.body&&e.body.length>a)return J(413,{error:"payload_too_large"});let i=null;if(!1!==t.auth){const r=d(j(e.headers,"authorization"));if(!r)return D();try{i=await t.auth.verify(r,e)}catch(e){H(e,{method:"auth"}),i=null}if(!i)return D()}if(t.rateLimit){let r;try{r=await t.rateLimit(i,e)}catch(e){H(e,{method:"rateLimit"}),r=!1}if(!("boolean"==typeof r?r:r.ok)){const e="object"==typeof r?r.retryAfter:void 0;return{status:429,headers:{"Content-Type":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 N(null,C,"Invalid JSON",400)}if(Array.isArray(c))return N(null,A,"Batch requests are not supported",400);if("object"!=typeof c||null===c)return N(null,A,"Expected a JSON-RPC request object",400);const u=c,f=u.id,S="string"==typeof u.method?u.method:null;if(!S)return N(f,A,"Missing method",400);if(null==f)return{status:202,headers:{"Content-Type":P},body:""};const v=u.params??{};switch(S){case"initialize":{const e=v.protocolVersion;return W(f,{protocolVersion:"string"==typeof e&&T.includes(e)?e:_,capabilities:{tools:{listChanged:!1},...g?{resources:{}}:{},...m?{prompts:{}}:{}},serverInfo:r,...t.instructions?{instructions:t.instructions}:{}})}case"ping":return W(f,{});case"tools/list":return W(f,{tools:L(i).map(e=>({name:e.name,description:e.description,inputSchema:B(e),...e.annotations?{annotations:e.annotations}:{},...e.icons?{icons:e.icons}:{}}))});case"tools/call":{const r="string"==typeof v.name?v.name:"",n=L(i).find(e=>e.name===r);if(!n)return N(f,O,`Unknown tool: ${r||"(missing name)"}`);let s,o=v.arguments??{};if(F(n.inputSchema)){const e=n.inputSchema.safeParse(o);if(!e.success){const t=e.error.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ");return W(f,{content:[{type:"text",text:`Invalid arguments for ${r}: ${t}`}],isError:!0})}o=e.data}if(t.context)try{s=await t.context(i,e)}catch(e){return H(e,{method:S,tool:r}),N(f,R,"Context initialization failed")}const a=y(i,s);try{const e=await n.execute(o,a);if("object"==typeof(E=e)&&null!==E&&Array.isArray(E.content)&&E.content.length>0&&E.content.every(I))return W(f,{content:e.content,...void 0!==e.structuredContent?{structuredContent:e.structuredContent}:{},isError:e.isError??!1});const t="object"==typeof e&&null!==e&&!Array.isArray(e);return W(f,{content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e,null,2)}],...t?{structuredContent:e}:{},isError:!1})}catch(e){H(e,{method:S,tool:r});const n=e instanceof Error?e:new Error(M(e));return W(f,{content:[{type:"text",text:t.formatToolError?t.formatToolError(n,{tool:r}):n.message}],isError:!0})}}case"resources/list":if(!g)break;return W(f,{resources:Array.from(l.values()).filter(e=>w(e.requiredScopes,i)).map(e=>({uri:e.uri,name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.icons?{icons:e.icons}:{}}))});case"resources/templates/list":if(!g)break;return W(f,{resourceTemplates:p.filter(e=>w(e.requiredScopes,i)).map(e=>({uriTemplate:e.uriTemplate,name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.icons?{icons:e.icons}:{}}))});case"resources/read":{if(!g)break;if("string"!=typeof v.uri||""===v.uri)return N(f,O,"Missing required parameter: uri");const r=v.uri;let n,s=null;const o=l.get(r);if(o){if(!w(o.requiredScopes,i))return N(f,$,"Resource not found",200,{uri:r});n=o.mimeType,s=async e=>o.read(e)}else for(const e of p){if(!w(e.requiredScopes,i))continue;const t=b(e.uriTemplate,r);if(t){n=e.mimeType,s=async n=>e.read(t,r,n);break}}if(!s)return N(f,$,"Resource not found",200,{uri:r});let a;if(t.context)try{a=await t.context(i,e)}catch(e){return H(e,{method:S}),N(f,R,"Context initialization failed")}try{const e=await s(y(i,a));return W(f,{contents:[k(r,n,e)]})}catch(e){return H(e,{method:S}),N(f,R,"Resource read failed",200,{uri:r})}}case"prompts/list":if(!m)break;return W(f,{prompts:Array.from(h.values()).filter(e=>w(e.requiredScopes,i)).map(e=>({name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.arguments?{arguments:e.arguments}:{},...e.icons?{icons:e.icons}:{}}))});case"prompts/get":{if(!m)break;const r="string"==typeof v.name?v.name:"",n=h.get(r);if(!n||!w(n.requiredScopes,i))return N(f,O,`Unknown prompt: ${r||"(missing name)"}`);const s="object"==typeof v.arguments&&null!==v.arguments?v.arguments:{},o={};for(const[e,t]of Object.entries(s))"string"==typeof t&&(o[e]=t);const a=(n.arguments??[]).filter(e=>e.required&&!(e.name in o)).map(e=>e.name);if(a.length)return N(f,O,`Missing required arguments: ${a.join(", ")}`);let c;if(t.context)try{c=await t.context(i,e)}catch(e){return H(e,{method:S}),N(f,R,"Context initialization failed")}try{const e=await n.get(o,y(i,c)),t="string"==typeof e?{messages:[{role:"user",content:x(e)}]}:Array.isArray(e)?{messages:e}:e,r=t.description??n.description;return W(f,{...r?{description:r}:{},messages:t.messages})}catch(e){return H(e,{method:S}),N(f,R,"Prompt rendering failed")}}}var E;return N(f,z,`Method not found: ${S}`)}(e);return Object.keys(i).length?{...c,headers:{...c.headers,...i}}:c}return{handle:K,fetch:async function(e){const t={};if(e.headers.forEach((e,r)=>{t[r]=e}),a>0){const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>a)return new Response(JSON.stringify({error:"payload_too_large"}),{status:413,headers:{"Content-Type":P}})}const r="POST"===e.method.toUpperCase()?await e.text():void 0,n=await K({method:e.method,headers:t,body:r});return new Response(""===n.body?null:n.body,{status:n.status,headers:n.headers})},listTools:()=>Array.from(c.values()).map(e=>({name:e.name,description:e.description,...e.annotations?{annotations:e.annotations}:{}})),serverCard:e=>({name:r.name,version:r.version,endpoint:e.endpoint,transport:"streamable-http",capabilities:{tools:{listChanged:!1},...g?{resources:{}}:{},...m?{prompts:{}}:{}},...e.description?{description:e.description}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{}})}}const B=12,L=16;function H(){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 D=new Map;function G(e){let t=D.get(e);return t||(t=(async()=>{const t=await H().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return H().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),D.set(e,t)),t}function K(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(r){const n=globalThis.crypto.getRandomValues(new Uint8Array(B)),s=await G(e),o=new Uint8Array(await H().encrypt({name:"AES-GCM",iv:n},s,(new TextEncoder).encode(r))),i=o.subarray(o.length-L),a=o.subarray(0,o.length-L),c=new Uint8Array(28+a.length);return c.set(n,0),c.set(i,B),c.set(a,28),t(c)},async decryptSessionRef(t){try{const n=r(t);if(n.length<=28)return null;const s=n.slice(0,B),o=n.subarray(B,28),i=n.subarray(28),a=new Uint8Array(i.length+L);a.set(i,0),a.set(o,i.length);const c=await G(e),u=await H().decrypt({name:"AES-GCM",iv:s},c,a);return(new TextDecoder).decode(u)}catch{return null}}}}function V(e,t,r){const n=globalThis.process?.env;"1"===n?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${r}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function Q(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const r=K(t),n=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&n.length)try{const e=new URL(n[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let o;try{o=p(s,t,{...e.verify})}catch{return null}if(n.length){const t=o.aud?Array.isArray(o.aud)?o.aud:[o.aud]:[];if(!t.length&&e.requireAudience)return V(t,n,"token carries no aud claim"),null;if(t.length&&!t.some(e=>n.includes(e)))return V(t,n,"aud does not include this resource"),null}const i="string"==typeof o.sid?await r.decryptSessionRef(o.sid):null,a=Array.isArray(o.scope)?o.scope.filter(e=>"string"==typeof e):"string"==typeof o.scope?o.scope.split(" ").filter(Boolean):void 0;return{sessionId:i??"",userId:"string"==typeof o.userId?o.userId:"string"==typeof o.sub?o.sub:void 0,workspaceId:"string"==typeof o.workspaceId?o.workspaceId:void 0,scopes:a,claims:o}}}}const Y=300,Z="/.well-known/oauth-protected-resource",X="/.well-known/agent-skills",ee="/.well-known/api-catalog",te="/.well-known/mcp/server-card.json",re="/.well-known/agent-card.json",ne="application/json",se="application/linkset+json",oe="text/markdown; charset=utf-8",ie="text/plain; charset=utf-8",ae="application/xml; charset=utf-8",ce=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ue(e){return e.replace(/\/+$/,"")}function le(e){return`public, max-age=${e}, s-maxage=${e}`}function pe(e){return"sha256:"+function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(o(i(e)))}const de=new Map;async function he(e,t,r,n){if(!n||n<=0)return e(t,r);const s=new AbortController,o=setTimeout(()=>s.abort(),n);try{return await e(t,{...r,signal:s.signal})}finally{clearTimeout(o)}}async function ge(e){const t=e.cacheTtlSeconds??Y,r=`${ue(e.serverUrl)}::${e.orgId}`,n=de.get(r);if(n&&n.expiresAt>Date.now())return n.value;const s=e.fetch??fetch,o=`${ue(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const t=await he(s,o,{headers:{Accept:ne}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(i=e)}}catch{}return de.set(r,{value:i,expiresAt:Date.now()+1e3*t}),i}const me=new Map;function fe(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const r="/"===t?"":t.replace(/\/+$/,"");return Z+r}function we(e){return e.path??`${X}/${e.name}/SKILL.md`}function ye(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:ie,body:t.join("\n")+"\n",cacheControl:le(e.cacheTtlSeconds??Y)}}function be(e){return e.endsWith(".json")||e.includes(".well-known/")?ne:e.endsWith(".md")?oe:e.endsWith(".xml")?ae:ie}function ke(e){const t=e??{tools:!0},r={tools:!1,resources:!1,prompts:!1};for(const[e,n]of Object.entries(t))r[e]=!1!==n&&null!=n;return r}function Se(e,t){return{status:200,contentType:ne,body:JSON.stringify(e,null,2),cacheControl:le(t.cacheTtlSeconds??Y)}}function ve(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Ee(e,t){const r=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${ve(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&r.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])r.push(`Allow: ${ve(t)}`);for(const t of e.disallow??[])r.push(`Disallow: ${ve(t)}`);return void 0!==e.crawlDelay&&r.push(`Crawl-delay: ${ve(e.crawlDelay)}`),r.join("\n")}function xe(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Te(e){const t=ue(e.siteUrl),r=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&r.push(`<${t}${re}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const n=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;r.push(`<${n}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&r.push(`<${t}${ee}>; rel="api-catalog"; type="${se}"`),e.mcpServerCard&&r.push(`<${t}${te}>; rel="mcp-server"; type="application/json"`),r.join(", ")}async function _e(e,t){const r=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===r){return function(e,t){const r=ue(e.siteUrl),n={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:Z};return t.authorizationServer?.metadataUrl&&(n.oauth_authorization_server=t.authorizationServer.metadataUrl,n.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(n.auth="/auth.md"),e.skills?.length&&(n.agent_skills=`${X}/index.json`),e.apiCatalog?.length&&(n.api_catalog=ee),e.mcpServerCard&&(n.mcp_server_card=te),!1!==e.a2aCard&&(n.a2a_agent_card=re),e.llmsFullTxt&&(n.llms_full_txt="/llms-full.txt"),Se({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:r,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:r},capabilities:n,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}(t,await ge(t))}if(r===re)return function(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},r=ue(e.siteUrl),n=t.serviceUrl??r,s=t.transportProtocol??"http",o=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return Se({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:n,preferredTransport:s,supportedInterfaces:[{serviceUrl:n,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:r},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:o,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}(t);if("/.well-known/http-message-signatures-directory"===r)return function(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:le(e.cacheTtlSeconds??Y)}:null}(t);if("/.well-known/security.txt"===r)return ye(t);if(r===`${X}/index.json`)return function(e){const t=e.skills??[];if(!t.length)return null;const r=ue(e.siteUrl);return Se({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${r}${we(e)}`,digest:pe(e.content)}))},e)}(t);if(r.startsWith(`${X}/`)&&r.endsWith("SKILL.md"))return function(e,t){const r=(t.skills??[]).find(t=>we(t)===e);return r?{status:200,contentType:"text/markdown; charset=utf-8",body:r.content,cacheControl:le(t.cacheTtlSeconds??Y)}:null}(r,t);if("/.well-known/oauth-authorization-server"===r||"/.well-known/openid-configuration"===r){const e=(await ge(t)).authorizationServer;if(!e?.metadataUrl)return null;const r=await async function(e,t){const r=t.cacheTtlSeconds??Y,n=me.get(e);if(n&&n.expiresAt>Date.now())return n.value;const s=t.fetch??fetch;let o=null;try{const r=await he(s,e,{headers:{Accept:ne}},t.fetchTimeoutMs??5e3);if(r.ok){const e=await r.json();e&&"object"==typeof e&&(o=e)}}catch{}return me.set(e,{value:o,expiresAt:Date.now()+1e3*r}),o}(e.metadataUrl,t);return Se(r?r:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(r===ee)return function(e){const t=e.apiCatalog??[];if(!t.length)return null;const r=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:se,body:JSON.stringify({linkset:r},null,2),cacheControl:le(e.cacheTtlSeconds??Y)}}(t);if(r===te)return function(e){const t=e.mcpServerCard;return t?Se({$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:ke(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}(t);if("/.well-known/mcp.json"===r)return function(e){const t=e.mcpServerCard;if(!t)return null;const r=ue(e.siteUrl);let n;try{n={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${fe(t.endpoint)}`}}catch{}return Se({$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:ke(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${r}${te}`,...n?{authentication:n}:{}}]},e)}(t);if(r.startsWith(Z)){const e=await ge(t);return function(e,t,r){const n=t.protectedResources??[];if(!n.length)return null;const s=e.replace(/\/+$/,"")||Z,o=r??`${ue(t.serverUrl)}/org/${t.orgId}`,i=t.scopes?.map(e=>e.name),a=n.map(e=>{const r=e.resource??ue(t.siteUrl),n=e.scopes??i;return{path:fe(r),metadata:{resource:r,authorization_servers:[o],bearer_methods_supported:e.bearerMethods??["header"],...n?.length?{scopes_supported:n}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=a.find(e=>e.path===s);return c?Se(c.metadata,t):s===Z&&1===a.length?Se(a[0].metadata,t):null}(r,t,e.authorizationServer?.issuer)}return null}async function Pe(e,t){const r=e.replace(/\/+$/,"")||e,n=function(e,t){const r=t.extraPaths?.[e];if(void 0===r)return null;const n="string"==typeof r?{body:r}:r;return{status:n.status??200,contentType:n.contentType??be(e),body:n.body,cacheControl:n.cacheControl??le(t.cacheTtlSeconds??Y)}}(r,t);return n||("/robots.txt"===r?function(e){const t=e.robots??{},r=ue(e.siteUrl),n=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",o="allow"===s?[{userAgent:[...ce],allow:["/"]}]:"deny"===s?[{userAgent:[...ce],disallow:["/"]}]:s,i=t.sitemaps??(e.sitemap?[`${r}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${r}/llms.txt and ${r}/.well-known/agent.json`,...n.map((e,r)=>Ee(e,0===r?t.contentSignals:void 0)),...o.map(e=>Ee(e)),...i.length?[i.map(e=>`Sitemap: ${ve(e)}`).join("\n")]:[]];return{status:200,contentType:ie,body:a.join("\n\n")+"\n",cacheControl:le(e.cacheTtlSeconds??Y)}}(t):"/llms-full.txt"===r?function(e){return e.llmsFullTxt?{status:200,contentType:ie,body:e.llmsFullTxt,cacheControl:le(e.cacheTtlSeconds??Y)}:null}(t):"/sitemap.xml"===r?function(e){const t=e.sitemap?.urls;if(!t?.length)return null;const r=ue(e.siteUrl),n='<?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:`${r}${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>${xe(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:ae,body:n,cacheControl:le(e.cacheTtlSeconds??Y)}}(t):"/llms.txt"===r?function(e){return e.llmsTxt?{status:200,contentType:ie,body:e.llmsTxt,cacheControl:le(e.cacheTtlSeconds??Y)}:null}(t):"/auth.md"===r?function(e,t){const r=le(e.cacheTtlSeconds??Y);if(e.authMd)return{status:200,contentType:oe,body:e.authMd,cacheControl:r};const n=t.authorizationServer;if(!n)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: \`${n.issuer}\`\n- Metadata (RFC 8414): ${n.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:oe,body:s,cacheControl:r}}(t,await ge(t)):"/security.txt"===r?ye(t):r.startsWith("/.well-known")?_e(r,t):null)}let Ue=!0;function $e(e,...t){Ue&&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 Ce(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 Ae(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await Ce(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await Ce(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class ze extends Error{constructor(e,t,r,n){super(e),this.code=t,this.context=r,this.originalError=n,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,ze)}}const Oe=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&&(Ue=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new ze("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),n=r instanceof ze?r:new ze(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&$e(`[SDK Error] ${t.component||"Unknown"}:`,{message:n.message,code:n.code,context:n.context,originalError:n.originalError,stack:n.stack}),this.config.onError)try{this.config.onError(n,t)}catch(e){!function(e,...t){console.error(e,...t)}("[SDK Error Handler] Error in custom error callback:",e)}this.config.showUserNotifications&&this.notifyUser(n,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function Re(e,t={}){Oe.handleError(e,t)}function je(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return Re(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}const Je="saas-session-id",We="saas-device-id";function Ne(){return function(){if("undefined"==typeof window)return null;try{return je(Je)}catch(e){return Re(e,{component:"auth-utils",action:"getSessionId",metadata:{key:Je}}),null}}()}function Fe(){const e=Ne(),t={};e&&(t["x-session-id"]=e);const r=function(){if("undefined"==typeof window)return null;try{return je(We)??null}catch(e){return Re(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:We}}),null}}();return r&&(t["x-device-id"]=r),t}const Me=new WeakSet,qe=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Be="SDK is not ready (missing serverUrl, version, or orgId)";class Le{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(Be);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(Be)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:Fe()}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){Me.has(e)||(Me.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((r,n)=>{const s=()=>{clearTimeout(o),n(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const o=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,r){const n=(t.method??"GET").toUpperCase(),s=r??e,o=this.buildHeaders(t),i={...t,headers:o},a=qe.has(n);let c,u;if(this._timeout>0){u=new AbortController;const e=u;c=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const n=new AbortController,s=e=>{n.signal.aborted||n.abort(e.reason)};for(const r of[e,t]){if(r.aborted){s(r);break}r.addEventListener("abort",()=>s(r),{once:!0})}return n.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: ${n} ${s}`);return this.reportError(e,{method:n,path:s}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const r=this._fetch.bind(globalThis),s=await r(e,i);if(this._debug&&console.log(`[BuildBase] ${n} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await Le.delay(e,i.signal),p(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await Le.delay(e,i.signal)}catch(e){throw l(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:n,path:s}),e}};try{return await p(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await Ae(n,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},r="Request failed"){const n=await this.fetchResponse(e,t);return n.ok||await this.throwResponseError(n,r),this.unwrapResponse(n,r)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw new Error(r)}apiPath(e,...t){return e.reduce((e,r,n)=>e+r+(n<t.length?encodeURIComponent(String(t[n])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class He extends Le{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,r){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}class De extends Le{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 Ge extends Le{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class Ke extends Le{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class Ve extends Le{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class Qe extends Le{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,r){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:r},"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,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to invite member")}async removeUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:r},"Failed to remove user")}async updateUser(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r),signal:n},"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,r){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:r},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}}),signal:n},"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,r){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:r},"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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create checkout session")}async selectFreePlan(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:r},"Failed to select free plan")}async updateSubscription(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:r},"Failed to update subscription")}async createBillingPortalSession(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:r})}async listInvoices(e,t=10,r,n){const s=new URLSearchParams;return s.append("limit",t.toString()),r&&s.append("starting_after",r),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:n},"Failed to fetch invoices")}async getInvoice(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:r},"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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record usage")}async recordUsageBatch(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:r},"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,r){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(),o=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch usage logs")}async sendNotification(e,t,r,n,s){const o={event:t};return r&&(o.userId=r),n&&(o.data=n),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(o),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,r){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:r},"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,r){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:r});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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const r=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t,r){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(),o=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,r){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(),o=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,r){const n=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+n,{signal:r},"Failed to fetch expiring credits")}}const Ye={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"},Ze=Object.values(Ye),Xe={admin:Ze.filter(e=>e!==Ye.WORKSPACE_DELETE),member:[Ye.WORKSPACE_SETTINGS_VIEW,Ye.WORKSPACE_MEMBERS_VIEW,Ye.WORKSPACE_FEATURES_VIEW,Ye.WORKSPACE_BILLING_VIEW,Ye.WORKSPACE_USAGE_VIEW],viewer:[Ye.WORKSPACE_SETTINGS_VIEW,Ye.WORKSPACE_MEMBERS_VIEW]};function et(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function tt(e){const{userId:t,workspace:r,settings:n,appPermissions:s}=e;if(!r||!t)return new Set;if(function(e,t){if(!t)return!1;const r=(n=e.createdBy)?"string"==typeof n?n:"object"==typeof n&&"_id"in n&&"string"==typeof n._id?n._id:null:null;var n;return null!==r&&r===t}(r,t)){const e=new Set(Ze);if(s)for(const t of et(s))e.add(t);if(r.permissions)for(const t of et(r.permissions))e.add(t);if(n?.workspace?.permissions)for(const t of et(n.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}(r,t);if(!o)return new Set;const i=r.permissions,a=n?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!i&&o in i,p=!!a&&o in a,d=o in Xe;let h;if(l)h=c(i[o]);else if(p)h=c(a[o]);else if(d)h=Xe[o];else{const e=n?.workspace?.defaultRole;h=e&&e in Xe?Xe[e]:[]}const g=new Set(h),m=l?u(i[o]):[],f=s?.[o]?u(s[o]):[],w=l?m:f;for(const e of w)g.add(e);return function(e,t,r){if(!r?.workspace)return;const{canInviteMembers:n}=r.workspace;(!1===n||"admin-only"===n&&"admin"!==t)&&e.delete(Ye.WORKSPACE_MEMBERS_INVITE)}(g,o,n),g}function rt(e){const{serverUrl:t,orgId:r,version:n="v1",getSessionId:s,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!r)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},d=e=>{const s={serverUrl:t,version:n,orgId:r,sessionId:e,...p};return{workspace:new Qe(s),user:new Ve(s),settings:new Ke(s),push:new De(s),devices:new He(s),sessions:new Ge(s)}},h=new Qe({serverUrl:t,version:n,orgId:r,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,r)=>(await e()).workspace.updateWorkspace(t,r),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,r,n)=>(await e()).workspace.addUser(t,{email:r,role:n}),remove:async(t,r)=>(await e()).workspace.removeUser(t,r),updateRole:async(t,r,n)=>(await e()).workspace.updateUser(t,r,{role:n}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,r)=>(await e()).workspace.createCheckoutSession(t,r),update:async(t,r)=>(await e()).workspace.updateSubscription(t,r),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,r)=>(await e()).workspace.createBillingPortalSession(t,r)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,r,n)=>(await e()).workspace.listInvoices(t,r,n),get:async(t,r)=>(await e()).workspace.getInvoice(t,r)},usage:{record:async(t,r)=>(await e()).workspace.recordUsage(t,r),recordBatch:async(t,r)=>(await e()).workspace.recordUsageBatch(t,r),getQuota:async(t,r)=>(await e()).workspace.getQuotaUsageStatus(t,r),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,r)=>(await e()).workspace.getUsageLogs(t,r)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,r,n)=>(await e()).workspace.updateFeature(t,r,n)},notification:{send:async(t,r,n,s)=>(await e()).workspace.sendNotification(t,r,n,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,r)=>(await e()).workspace.consumeCredits(t,r),purchase:async(t,r)=>(await e()).workspace.purchaseCredits(t,r),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,r)=>(await e()).workspace.getCreditTransactions(t,r),getBuckets:async(t,r)=>(await e()).workspace.getCreditBuckets(t,r),getExpiring:async(t,r)=>(await e()).workspace.getExpiringCredits(t,r),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,r,n)=>{const s=await e(),[o,i,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return function(e,t){const r=tt(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}(n,{userId:r,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,r)=>{const n=await e(),[s,o,i]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return tt({userId:r,workspaceRole:a?.role??null,workspace:s,settings:o})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,r)=>(await e()).devices.rename(t,r),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),m=g(async()=>d(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=d(e);return g(async()=>t)},client:{forSession:d},...m}}exports.AppBridgeError=u,exports.bearerChallenge=f,exports.buildbaseAuth=Q,exports.builtinMcpTools=v,exports.createAgentStack=function(e){const t=ue(e.siteUrl),r=e.mcp?.path??"/api/mcp",n=`${t}${r.startsWith("/")?r:`/${r}`}`,s=e.mcp?.serverInfo??{name:e.site.name,version:"1.0.0"},o=`${t}/mcp`,i=Array.from(new Set([o,n])),a=e.mcp?.auth??(e.secret?Q({secret:e.secret,resource:i,resourceMetadataUrl:`${t}/.well-known/oauth-protected-resource/mcp`,requireAudience:!0}):void 0);if(void 0===a)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=q({buildbase:e.mcp?.buildbase??rt({serverUrl:e.serverUrl,orgId:e.orgId}),serverInfo:s,auth:a,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:n,...e.site.description?{description:e.site.description}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}),...e.scopes?{scopes:e.scopes}:{},protectedResources:i.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:n,title:`${e.site.name} MCP server`,serviceDesc:`${t}/.well-known/mcp/server-card.json`}],...e.discovery},l={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, OPTIONS"},p=e=>c.fetch(e);return{mcp:c,mcpEndpoint:n,config:u,linkHeader:Te(u),resolvePath:e=>Pe(e,u),serveAgentPath:async function(e){if("OPTIONS"===e.method.toUpperCase())return new Response(null,{status:204,headers:l});const t=await Pe(new URL(e.url).pathname,u);return t?new Response(t.body,{status:t.status,headers:{"Content-Type":t.contentType,"Cache-Control":t.cacheControl,...t.vary?{Vary:t.vary}:{},...l}}):new Response(JSON.stringify({error:"not_found"}),{status:404,headers:{"Content-Type":"application/json",...l}})},routes:{GET:p,POST:p,DELETE:p,OPTIONS:p}}},exports.createMcpHandler=q,exports.createSessionRefCrypto=K,exports.defineMcpPrompt=e=>e,exports.defineMcpResource=e=>e,exports.defineMcpResourceTemplate=e=>e,exports.defineMcpTool=function(e){return e},exports.extractBearerToken=d,exports.mcpAudio=(e,t)=>({type:"audio",data:e,mimeType:t}),exports.mcpEmbeddedResource=e=>({type:"resource",resource:e}),exports.mcpImage=(e,t)=>({type:"image",data:e,mimeType:t}),exports.mcpResourceLink=(e,t,r)=>({type:"resource_link",uri:e,name:t,...r}),exports.mcpText=x,exports.mintAgentToken=async function(e){const{claims:t,secret:r}=e,n=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,o=t.sessionId?await K(r).encryptSessionRef(t.sessionId):void 0;return{token:g({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...o?{sid:o}:{},...e.extraClaims},r,{expiresInSec:n}),expiresIn:n}},exports.selectBuiltinTools=E,exports.signClientJwt=g,exports.verifyClientJwt=p;
|
|
1
|
+
"use strict";var e=require("zod");function t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function r(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t.length%4==0?"":"=".repeat(4-t.length%4),n=atob(t+r),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return s}const n=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]),s=(e,t)=>e>>>t|e<<32-t;function o(e){let t=1779033703,r=3144134277,o=1013904242,i=2773480762,a=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 m=8*p,f=Math.floor(m/4294967296),w=m>>>0;g[h-8]=f>>>24&255,g[h-7]=f>>>16&255,g[h-6]=f>>>8&255,g[h-5]=255&f,g[h-4]=w>>>24&255,g[h-3]=w>>>16&255,g[h-2]=w>>>8&255,g[h-1]=255&w;const y=new Uint32Array(64);for(let e=0;e<h;e+=64){for(let t=0;t<16;t++){const r=e+4*t;y[t]=g[r]<<24|g[r+1]<<16|g[r+2]<<8|g[r+3]}for(let e=16;e<64;e++){const t=s(y[e-15],7)^s(y[e-15],18)^y[e-15]>>>3,r=s(y[e-2],17)^s(y[e-2],19)^y[e-2]>>>10;y[e]=y[e-16]+t+y[e-7]+r>>>0}let p=t,d=r,h=o,m=i,f=a,w=c,b=u,k=l;for(let e=0;e<64;e++){const t=k+(s(f,6)^s(f,11)^s(f,25))+(f&w^~f&b)+n[e]+y[e]>>>0,r=p&d^p&h^d&h;k=b,b=w,w=f,f=m+t>>>0,m=h,h=d,d=p,p=t+((s(p,2)^s(p,13)^s(p,22))+r>>>0)>>>0}t=t+p>>>0,r=r+d>>>0,o=o+h>>>0,i=i+m>>>0,a=a+f>>>0,c=c+w>>>0,u=u+b>>>0,l=l+k>>>0}const b=new Uint8Array(32),k=[t,r,o,i,a,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 i(e){return(new TextEncoder).encode(e)}function a(e,t){let r=e;r.length>64&&(r=o(r));const n=new Uint8Array(64),s=new Uint8Array(64);for(let e=0;e<64;e++){const t=e<r.length?r[e]:0;n[e]=54^t,s[e]=92^t}const i=o(c(n,t));return o(c(s,i))}function c(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}class u extends Error{constructor(e,t){super(t),this.name="AppBridgeError",this.code=e}}function l(e){const t=JSON.parse((new TextDecoder).decode(r(e)));if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("JWT segment is not a JSON object");return t}function p(e,t,n={}){const s=n.clockToleranceSec??60,o=n.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,m;try{g=l(p),m=l(d)}catch{throw new u("invalid_token","Unreadable JWT segments")}if("HS256"!==g.alg)throw new u("invalid_algorithm",`Unexpected JWT alg: ${String(g.alg)}`);const f=a(i(t),i(`${p}.${d}`));let w;try{w=r(h)}catch{throw new u("invalid_signature","Unreadable JWT signature")}if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(f,w))throw new u("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 u("invalid_token",`JWT ${t} claim must be a string`);for(const t of["exp","nbf","iat"]){const r=e[t];if(void 0!==r&&("number"!=typeof r||!Number.isFinite(r)))throw new u("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 u("invalid_token","JWT aud claim must be a string or string array")}(m);const y=Math.floor(Date.now()/1e3);if(o&&"number"!=typeof m.exp)throw new u("invalid_token","JWT is missing a numeric exp claim");if("number"==typeof m.exp&&y>m.exp+s)throw new u("token_expired","JWT has expired");if("number"==typeof m.nbf&&y+s<m.nbf)throw new u("token_not_yet_valid","JWT is not yet valid");if(void 0!==n.issuer&&m.iss!==n.issuer)throw new u("invalid_issuer","JWT issuer mismatch");if(void 0!==n.audience){const e=m.aud;if(!(Array.isArray(e)?e.includes(n.audience):e===n.audience))throw new u("invalid_audience","JWT audience mismatch")}return m}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(i(JSON.stringify(e)))}function g(e,r,n){if(!r)throw new u("invalid_secret","Missing signing secret");const s=Math.floor(Date.now()/1e3),o={iat:s,exp:s+(n?.expiresInSec??3600),...e},c=`${h({alg:"HS256",typ:"JWT"})}.${h(o)}`;return`${c}.${t(a(i(r),i(c)))}`}function m(e){return e.replace(/[\x00-\x1f\x7f]/g,"").replace(/([\\"])/g,"\\$1")}function f(e){const t=[`Bearer resource_metadata="${m(e.resourceMetadataUrl)}"`];return e.error&&t.push(`error="${m(e.error)}"`),e.errorDescription&&t.push(`error_description="${m(e.errorDescription)}"`),{status:401,headers:{"WWW-Authenticate":t.join(", "),"Content-Type":"application/json"},body:JSON.stringify({error:e.error??"invalid_token"})}}const w=e.z.string().optional().describe("Workspace id. Omit to use the workspace bound to your token.");function y(e,t){const r=e.workspaceId??t.workspaceId;if(!r)throw new Error("workspaceId is required — call list_workspaces to find one.");return r}const b={readOnlyHint:!0},k=[{name:"list_workspaces",description:"List the authenticated user's workspaces (id, name, roles).",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.workspace.list()},{name:"get_workspace",description:"Get one workspace: name, members, feature flags, quota snapshot.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.workspace.get(y(e,t))},{name:"get_user_profile",description:"Get the authenticated user's profile.",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.users.getProfile()},{name:"list_workspace_users",description:"List the members of a workspace with their roles.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.users.list(y(e,t))},{name:"get_subscription",description:"Get a workspace's subscription: plan, status, interval, seats.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.subscription.get(y(e,t))},{name:"get_plans",description:"Get the plan group available to a workspace (plans, prices, quotas).",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.plans.getGroup(y(e,t))},{name:"list_invoices",description:"List a workspace's invoices (newest first).",inputSchema:e.z.object({workspaceId:w,limit:e.z.number().int().min(1).max(100).optional().describe("Max invoices to return."),startingAfter:e.z.string().optional().describe("Invoice id to paginate after.")}),annotations:b,execute:(e,t)=>t.bb.invoices.list(y(e,t),e.limit,e.startingAfter)},{name:"get_quota_usage",description:"Get usage vs. limit for one quota in a workspace.",inputSchema:e.z.object({workspaceId:w,quotaSlug:e.z.string().describe('The quota slug, e.g. "api-calls".')}),annotations:b,execute:(e,t)=>t.bb.usage.getQuota(y(e,t),e.quotaSlug)},{name:"get_all_quota_usage",description:"Get usage vs. limit for every quota in a workspace.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.usage.getAll(y(e,t))},{name:"get_credit_balance",description:"Get a workspace's prepaid credit balance.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.credits.getBalance(y(e,t))},{name:"list_credit_transactions",description:"Get a workspace's credit transaction history (paginated).",inputSchema:e.z.object({workspaceId:w,limit:e.z.number().int().min(1).max(100).optional(),page:e.z.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getTransactions(y(e,t),{...void 0!==e.limit?{limit:e.limit}:{},...void 0!==e.page?{page:e.page}:{}})},{name:"check_feature_flag",description:"Check whether a feature flag is enabled for a workspace.",inputSchema:e.z.object({workspaceId:w,key:e.z.string().describe("The feature slug.")}),annotations:b,execute:async(e,t)=>{const r=y(e,t),n=await t.bb.workspace.get(r),s=n.features?.[e.key];if(void 0!==s)return{key:e.key,enabled:s,source:"workspace"};const o=(await t.bb.features.list()).find(t=>t.slug===e.key);if(!o)throw new Error(`Unknown feature flag: ${e.key}`);return{key:e.key,enabled:o.defaultValue,source:"default"}}},{name:"check_permission",description:"Check whether a user has permission(s) in a workspace.",inputSchema:e.z.object({workspaceId:w,permission:e.z.union([e.z.string(),e.z.array(e.z.string())]).describe("A permission (or list — all must hold), platform or app-defined."),userId:e.z.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const n=await t.bb.permissions.check(y(e,t),r,e.permission);return{userId:r,permission:e.permission,allowed:n}}},{name:"resolve_permissions",description:"List every permission a user holds in a workspace.",inputSchema:e.z.object({workspaceId:w,userId:e.z.string().optional().describe("Defaults to the authenticated user.")}),annotations:b,execute:async(e,t)=>{const r=e.userId??t.auth.userId;if(!r)throw new Error("userId is required — the token carries no user identity.");const n=await t.bb.permissions.resolve(y(e,t),r);return{userId:r,permissions:Array.from(n)}}},{name:"get_invoice",description:"Get one invoice by id.",inputSchema:e.z.object({workspaceId:w,invoiceId:e.z.string().describe("The invoice id.")}),annotations:b,execute:(e,t)=>t.bb.invoices.get(y(e,t),e.invoiceId)},{name:"get_plan_versions",description:"List the plan-group versions available to a workspace.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.plans.getVersions(y(e,t))},{name:"get_public_plans",description:"Get a public plan group by slug (no workspace / auth needed).",inputSchema:e.z.object({slug:e.z.string().describe("The plan-group slug.")}),annotations:b,execute:(e,t)=>t.bb.plans.getPublic(e.slug)},{name:"get_plan_version",description:"Get one public plan-group version by id (no auth needed).",inputSchema:e.z.object({groupVersionId:e.z.string().describe("The plan-group version id.")}),annotations:b,execute:(e,t)=>t.bb.plans.getVersion(e.groupVersionId)},{name:"get_usage_logs",description:"Get a workspace's usage log entries (paginated, filterable).",inputSchema:e.z.object({workspaceId:w,quotaSlug:e.z.string().optional(),from:e.z.string().optional().describe("ISO date lower bound."),to:e.z.string().optional().describe("ISO date upper bound."),source:e.z.string().optional(),page:e.z.number().int().min(1).optional(),limit:e.z.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.usage.getLogs(y(e,t),n)}},{name:"get_settings",description:"Get the organization settings.",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.settings.get()},{name:"get_credit_packages",description:"List the credit packages a workspace can purchase.",inputSchema:e.z.object({workspaceId:w}),annotations:b,execute:(e,t)=>t.bb.credits.getPackages(y(e,t))},{name:"get_credit_buckets",description:"Get a workspace's credit buckets (paginated).",inputSchema:e.z.object({workspaceId:w,status:e.z.string().optional(),source:e.z.string().optional(),page:e.z.number().int().min(1).optional(),limit:e.z.number().int().min(1).max(100).optional()}).strict(),annotations:b,execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.credits.getBuckets(y(e,t),n)}},{name:"get_expiring_credits",description:"Get credits expiring within N days (default 7).",inputSchema:e.z.object({workspaceId:w,days:e.z.number().int().min(1).optional()}),annotations:b,execute:(e,t)=>t.bb.credits.getExpiring(y(e,t),e.days)},{name:"get_public_credit_packages",description:"List credit packages publicly (no workspace / auth needed).",inputSchema:e.z.object({}),annotations:b,execute:(e,t)=>t.bb.credits.getPublicPackages()}],S=[{name:"record_usage",description:"Record quota usage for a workspace (metered billing).",inputSchema:e.z.object({workspaceId:w,quotaSlug:e.z.string().describe("The quota slug to record against."),quantity:e.z.number().positive().describe("Amount of usage to record."),idempotencyKey:e.z.string().optional().describe("Dedupe key for safe retries."),metadata:e.z.record(e.z.string(),e.z.unknown()).optional()}),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},execute:(e,t)=>t.bb.usage.record(y(e,t),{quotaSlug:e.quotaSlug,quantity:e.quantity,source:"mcp",...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{},...e.metadata?{metadata:e.metadata}:{}})},{name:"consume_credits",description:"Consume prepaid credits from a workspace's balance.",inputSchema:e.z.object({workspaceId:w,amount:e.z.number().positive().describe("Credits to consume."),description:e.z.string().optional().describe("What the credits were spent on."),idempotencyKey:e.z.string().optional().describe("Dedupe key for safe retries.")}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.credits.consume(y(e,t),{amount:e.amount,...e.description?{description:e.description}:{},...e.idempotencyKey?{idempotencyKey:e.idempotencyKey}:{}})},{name:"send_notification",description:"Send a notification event to a workspace user (or all members when userId is omitted).",inputSchema:e.z.object({workspaceId:w,event:e.z.string().describe('The event slug, e.g. "comment_added".'),userId:e.z.string().optional().describe("Recipient. Omit to notify all members."),message:e.z.string().optional().describe("Message body (used for push).")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.notification.send(y(e,t),e.event,e.userId,e.message?{message:e.message}:void 0)},{name:"record_usage_batch",description:"Record multiple usage entries in one call (max 100 items).",inputSchema:e.z.object({workspaceId:w,items:e.z.array(e.z.object({quotaSlug:e.z.string(),quantity:e.z.number().positive(),idempotencyKey:e.z.string().optional(),metadata:e.z.record(e.z.string(),e.z.unknown()).optional()})).min(1).max(100)}),annotations:{readOnlyHint:!1,destructiveHint:!1},execute:(e,t)=>t.bb.usage.recordBatch(y(e,t),{items:e.items.map(e=>({...e,source:"mcp"}))})},{name:"create_workspace",description:"Create a new workspace.",inputSchema:e.z.object({name:e.z.string().describe("Workspace name."),image:e.z.string().optional().describe("Image URL.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.workspace.create({name:e.name,...e.image?{image:e.image}:{}})},{name:"update_workspace",description:"Update a workspace's editable fields (name, image).",inputSchema:e.z.object({workspaceId:w,name:e.z.string().min(1).optional().describe("New workspace name."),image:e.z.string().optional().describe("New image URL.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};return void 0!==e.name&&(r.name=e.name),void 0!==e.image&&(r.image=e.image),t.bb.workspace.update(y(e,t),r)}},{name:"delete_workspace",description:"Delete a workspace. Irreversible.",inputSchema:e.z.object({workspaceId:w}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.workspace.delete(y(e,t))},{name:"invite_workspace_user",description:"Invite a user to a workspace with a role.",inputSchema:e.z.object({workspaceId:w,email:e.z.string().describe("Invitee email."),role:e.z.string().describe("Role to grant.")}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.users.invite(y(e,t),e.email,e.role)},{name:"remove_workspace_user",description:"Remove a user from a workspace. Irreversible.",inputSchema:e.z.object({workspaceId:w,userId:e.z.string().describe("The user to remove.")}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.users.remove(y(e,t),e.userId)},{name:"update_workspace_user_role",description:"Change a workspace member's role.",inputSchema:e.z.object({workspaceId:w,userId:e.z.string(),role:e.z.string().describe("The new role.")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.users.updateRole(y(e,t),e.userId,e.role)},{name:"update_user_profile",description:"Update the authenticated user's own profile (name, image, country, timezone, language, currency).",inputSchema:e.z.object({name:e.z.string().min(1).optional(),image:e.z.string().optional().describe("Profile image URL."),country:e.z.string().optional().describe("ISO country code."),timezone:e.z.string().optional().describe("IANA timezone."),language:e.z.string().optional().describe("Language code."),currency:e.z.string().optional().describe("Currency code.")}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const r={};for(const t of["name","image","country","timezone","language","currency"]){const n=e[t];void 0!==n&&(r[t]=n)}return t.bb.users.updateProfile(r)}},{name:"update_feature_flag",description:"Set a feature flag on/off for a workspace.",inputSchema:e.z.object({workspaceId:w,key:e.z.string().describe("The feature slug."),value:e.z.boolean().describe("Enabled?")}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.features.update(y(e,t),e.key,e.value)},{name:"create_subscription_checkout",description:"Create a Stripe checkout session to subscribe a workspace to a plan.",inputSchema:e.z.object({workspaceId:w,planVersionId:e.z.string(),billingInterval:e.z.string().optional(),currency:e.z.string().optional(),successUrl:e.z.string().optional(),cancelUrl:e.z.string().optional()}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.subscription.checkout(y(e,t),n)}},{name:"update_subscription",description:"Change a workspace's subscription plan.",inputSchema:e.z.object({workspaceId:w,planVersionId:e.z.string(),billingInterval:e.z.string().optional(),successUrl:e.z.string().optional(),cancelUrl:e.z.string().optional()}).strict(),annotations:{readOnlyHint:!1},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.subscription.update(y(e,t),n)}},{name:"cancel_subscription",description:"Cancel a workspace's subscription.",inputSchema:e.z.object({workspaceId:w}),annotations:{readOnlyHint:!1,destructiveHint:!0},execute:(e,t)=>t.bb.subscription.cancel(y(e,t))},{name:"resume_subscription",description:"Resume a workspace's canceled subscription.",inputSchema:e.z.object({workspaceId:w}),annotations:{readOnlyHint:!1},execute:(e,t)=>t.bb.subscription.resume(y(e,t))},{name:"get_billing_portal_url",description:"Get a Stripe billing-portal URL for a workspace.",inputSchema:e.z.object({workspaceId:w,returnUrl:e.z.string().optional()}),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>t.bb.subscription.getBillingPortalUrl(y(e,t),e.returnUrl)},{name:"purchase_credits",description:"Create a Stripe checkout session to buy a credit package.",inputSchema:e.z.object({workspaceId:w,creditPackageId:e.z.string(),currency:e.z.string().optional(),successUrl:e.z.string().describe("Redirect URL on success."),cancelUrl:e.z.string().describe("Redirect URL on cancel.")}).strict(),annotations:{readOnlyHint:!1,openWorldHint:!0},execute:(e,t)=>{const{workspaceId:r,...n}=e;return t.bb.credits.purchase(y(e,t),n)}}],v=new Map([...k,...S].map(e=>[e.name,e]));function E(e){if(!1===e)return[];if("readonly"===e)return[...k];if("all"===e)return[...k,...S];const t=e.include?e.include.map(e=>{const t=v.get(e);if(!t)throw new Error(`Unknown built-in MCP tool: ${e}`);return t}):[...k],r=new Set(e.exclude??[]);return t.filter(e=>!r.has(e.name))}const x=e=>({type:"text",text:e}),I=e=>{if("object"!=typeof e||null===e)return!1;const t=e;switch(t.type){case"text":return"string"==typeof t.text;case"image":case"audio":return"string"==typeof t.data&&"string"==typeof t.mimeType;case"resource_link":return"string"==typeof t.uri&&"string"==typeof t.name;case"resource":{const e=t.resource;return"object"==typeof e&&null!==e&&"string"==typeof e.uri&&("string"==typeof e.text||"string"==typeof e.blob)}default:return!1}},T=["2025-11-25","2025-06-18","2025-03-26","2024-11-05"],_=T[0],P="application/json",U=/^[a-zA-Z0-9_-]{1,128}$/,$=-32002,C=-32700,A=-32600,z=-32601,O=-32602,R=-32603;function j(e,t){const r=t.toLowerCase();for(const t of Object.keys(e))if(t.toLowerCase()===r)return e[t]}function J(e,t){return{status:e,headers:{"Content-Type":P},body:JSON.stringify(t)}}function W(e,t){return J(200,{jsonrpc:"2.0",id:e??null,result:t})}function N(e,t,r,n=200,s){return J(n,{jsonrpc:"2.0",id:e??null,error:{code:t,message:r,...void 0!==s?{data:s}:{}}})}function F(e){return"object"==typeof e&&null!==e&&"function"==typeof e.safeParse}function M(e){return e instanceof Error?e.message:"string"==typeof e?e:JSON.stringify(e)}function q(t){const r=t.serverInfo??{name:"buildbase-mcp",version:"1.0.0"};t.auth&&!t.auth.resourceMetadataUrl&&console.warn("[buildbase/mcp] auth is enabled but `auth.resourceMetadataUrl` is unset — 401 responses will carry no WWW-Authenticate/resource_metadata pointer, so MCP clients cannot discover your authorization server. Set it to your /.well-known/oauth-protected-resource URL.");const n=e=>e.trim().toLowerCase().replace(/\/+$/,""),s=t.allowedOrigins?new Set(t.allowedOrigins.map(n)):null,o=e=>!!e&&!!s&&s.has(n(e)),i=t.builtinTools??(!!t.buildbase&&"readonly"),a=t.maxRequestBytes??1048576;if(!1!==i&&!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(i))c.set(e.name,e);const u=new Set;for(const e of t.tools??[]){if(!U.test(e.name))throw new Error(`Invalid MCP tool name: "${e.name}" (want ${String(U)})`);if(u.has(e.name))throw new Error(`Duplicate MCP tool name: "${e.name}"`);u.add(e.name),c.set(e.name,e)}if(t.builtinResources&&!t.buildbase)throw new Error("builtinResources requires a `buildbase` client — pass one to createMcpHandler.");const l=new Map,p=[];t.builtinResources&&(l.set("buildbase://profile",{uri:"buildbase://profile",name:"profile",title:"Your profile",description:"The authenticated user's BuildBase profile.",mimeType:"application/json",read:e=>e.bb.users.getProfile()}),l.set("buildbase://workspaces",{uri:"buildbase://workspaces",name:"workspaces",title:"Your workspaces",description:"The authenticated user's workspaces (id, name, roles).",mimeType:"application/json",read:e=>e.bb.workspace.list()}),p.push({uriTemplate:"buildbase://workspace/{workspaceId}",name:"workspace",title:"One workspace",description:"A single workspace: name, members, feature flags, quota snapshot.",mimeType:"application/json",read:(e,t,r)=>r.bb.workspace.get(e.workspaceId)}));for(const e of t.resources??[])l.set(e.uri,e);p.push(...t.resourceTemplates??[]);const h=new Map;for(const e of t.prompts??[]){if(!U.test(e.name))throw new Error(`Invalid MCP prompt name: "${e.name}" (want ${String(U)})`);if(h.has(e.name))throw new Error(`Duplicate MCP prompt name: "${e.name}"`);h.set(e.name,e)}const g=l.size>0||p.length>0,m=h.size>0,w=(e,t)=>{const r=new Set(t?.scopes??[]);return(e??[]).every(e=>r.has(e))};function y(e,r){const n=e?.sessionId??"";return{bb:t.buildbase?n?t.buildbase.withSession(n):v:S,auth:e??{sessionId:""},workspaceId:e?.workspaceId,custom:r}}function b(e,t){const r=[],n=e.replace(/[.*+?^$()|[\]\\]/g,e=>"\\"+e).replace(/\{([a-zA-Z0-9_]+)\}/g,(e,t)=>(r.push(t),"([^/]+)")),s=new RegExp(`^${n}$`).exec(t);if(!s)return null;const o={};return r.forEach((e,t)=>{try{o[e]=decodeURIComponent(s[t+1])}catch{o[e]=s[t+1]}}),o}function k(e,t,r){if("string"==typeof r)return{uri:e,mimeType:t??"text/plain",text:r};if(r&&"object"==typeof r){const n=r;if("string"==typeof n.text)return{uri:e,mimeType:"string"==typeof n.mimeType?n.mimeType:t??"text/plain",text:n.text};if("string"==typeof n.blob)return{uri:e,mimeType:"string"==typeof n.mimeType?n.mimeType:t??"application/octet-stream",blob:n.blob}}return{uri:e,mimeType:t??"application/json",text:JSON.stringify(r,null,2)}}const S=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.`)}}),v=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.`)}}),q=new Map;function B(t){const r=q.get(t.name);if(r)return r;let n;try{n=F(t.inputSchema)?e.z.toJSONSchema(t.inputSchema,{target:"draft-2020-12"}):t.inputSchema}catch(e){H(e,{method:"tools/list",tool:t.name}),n={type:"object",additionalProperties:!0}}return q.set(t.name,n),n}function L(e){const t=new Set(e?.scopes??[]);return Array.from(c.values()).filter(e=>(e.requiredScopes??[]).every(e=>t.has(e)))}function H(e,r){try{t.onError?.(e instanceof Error?e:new Error(M(e)),r)}catch{}}function D(){if(t.auth&&t.auth.resourceMetadataUrl){const e=f({resourceMetadataUrl:t.auth.resourceMetadataUrl});return{status:e.status,headers:e.headers,body:e.body}}return J(401,{error:"unauthorized"})}const G=Array.isArray(t.cors)?new Set(t.cors.map(n)):null;async function K(e){const i=function(e){if(!1===t.cors)return{};const r=j(e.headers,"origin");let i;return i=G?r&&G.has(n(r))?r:null:s?o(r)?r:null:"*",i?{"Access-Control-Allow-Origin":i,"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",..."*"!==i?{Vary:"Origin"}:{}}:{}}(e);if("OPTIONS"===e.method.toUpperCase())return{status:204,headers:i,body:""};const c=await async function(e){const n=e.method.toUpperCase();if(s){const t=j(e.headers,"origin");if(t&&!o(t))return J(403,{error:"origin_not_allowed"})}if("POST"!==n)return{status:405,headers:{"Content-Type":P,Allow:"POST, OPTIONS"},body:JSON.stringify({error:"method_not_allowed"})};if(a>0&&"string"==typeof e.body&&e.body.length>a)return J(413,{error:"payload_too_large"});let i=null;if(!1!==t.auth){const r=d(j(e.headers,"authorization"));if(!r)return D();try{i=await t.auth.verify(r,e)}catch(e){H(e,{method:"auth"}),i=null}if(!i)return D()}if(t.rateLimit){let r;try{r=await t.rateLimit(i,e)}catch(e){H(e,{method:"rateLimit"}),r=!1}if(!("boolean"==typeof r?r:r.ok)){const e="object"==typeof r?r.retryAfter:void 0;return{status:429,headers:{"Content-Type":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 N(null,C,"Invalid JSON",400)}if(Array.isArray(c))return N(null,A,"Batch requests are not supported",400);if("object"!=typeof c||null===c)return N(null,A,"Expected a JSON-RPC request object",400);const u=c,f=u.id,S="string"==typeof u.method?u.method:null;if(!S)return N(f,A,"Missing method",400);if(null==f)return{status:202,headers:{"Content-Type":P},body:""};const v=u.params??{};switch(S){case"initialize":{const e=v.protocolVersion;return W(f,{protocolVersion:"string"==typeof e&&T.includes(e)?e:_,capabilities:{tools:{listChanged:!1},...g?{resources:{}}:{},...m?{prompts:{}}:{}},serverInfo:r,...t.instructions?{instructions:t.instructions}:{}})}case"ping":return W(f,{});case"tools/list":return W(f,{tools:L(i).map(e=>({name:e.name,description:e.description,inputSchema:B(e),...e.annotations?{annotations:e.annotations}:{},...e.icons?{icons:e.icons}:{}}))});case"tools/call":{const r="string"==typeof v.name?v.name:"",n=L(i).find(e=>e.name===r);if(!n)return N(f,O,`Unknown tool: ${r||"(missing name)"}`);let s,o=v.arguments??{};if(F(n.inputSchema)){const e=n.inputSchema.safeParse(o);if(!e.success){const t=e.error.issues.map(e=>`${e.path.join(".")||"(root)"}: ${e.message}`).join("; ");return W(f,{content:[{type:"text",text:`Invalid arguments for ${r}: ${t}`}],isError:!0})}o=e.data}if(t.context)try{s=await t.context(i,e)}catch(e){return H(e,{method:S,tool:r}),N(f,R,"Context initialization failed")}const a=y(i,s);try{const e=await n.execute(o,a);if("object"==typeof(E=e)&&null!==E&&Array.isArray(E.content)&&E.content.length>0&&E.content.every(I))return W(f,{content:e.content,...void 0!==e.structuredContent?{structuredContent:e.structuredContent}:{},isError:e.isError??!1});const t="object"==typeof e&&null!==e&&!Array.isArray(e);return W(f,{content:[{type:"text",text:"string"==typeof e?e:JSON.stringify(e,null,2)}],...t?{structuredContent:e}:{},isError:!1})}catch(e){H(e,{method:S,tool:r});const n=e instanceof Error?e:new Error(M(e));return W(f,{content:[{type:"text",text:t.formatToolError?t.formatToolError(n,{tool:r}):n.message}],isError:!0})}}case"resources/list":if(!g)break;return W(f,{resources:Array.from(l.values()).filter(e=>w(e.requiredScopes,i)).map(e=>({uri:e.uri,name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.icons?{icons:e.icons}:{}}))});case"resources/templates/list":if(!g)break;return W(f,{resourceTemplates:p.filter(e=>w(e.requiredScopes,i)).map(e=>({uriTemplate:e.uriTemplate,name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.mimeType?{mimeType:e.mimeType}:{},...e.icons?{icons:e.icons}:{}}))});case"resources/read":{if(!g)break;if("string"!=typeof v.uri||""===v.uri)return N(f,O,"Missing required parameter: uri");const r=v.uri;let n,s=null;const o=l.get(r);if(o){if(!w(o.requiredScopes,i))return N(f,$,"Resource not found",200,{uri:r});n=o.mimeType,s=async e=>o.read(e)}else for(const e of p){if(!w(e.requiredScopes,i))continue;const t=b(e.uriTemplate,r);if(t){n=e.mimeType,s=async n=>e.read(t,r,n);break}}if(!s)return N(f,$,"Resource not found",200,{uri:r});let a;if(t.context)try{a=await t.context(i,e)}catch(e){return H(e,{method:S}),N(f,R,"Context initialization failed")}try{const e=await s(y(i,a));return W(f,{contents:[k(r,n,e)]})}catch(e){return H(e,{method:S}),N(f,R,"Resource read failed",200,{uri:r})}}case"prompts/list":if(!m)break;return W(f,{prompts:Array.from(h.values()).filter(e=>w(e.requiredScopes,i)).map(e=>({name:e.name,...e.title?{title:e.title}:{},...e.description?{description:e.description}:{},...e.arguments?{arguments:e.arguments}:{},...e.icons?{icons:e.icons}:{}}))});case"prompts/get":{if(!m)break;const r="string"==typeof v.name?v.name:"",n=h.get(r);if(!n||!w(n.requiredScopes,i))return N(f,O,`Unknown prompt: ${r||"(missing name)"}`);const s="object"==typeof v.arguments&&null!==v.arguments?v.arguments:{},o={};for(const[e,t]of Object.entries(s))"string"==typeof t&&(o[e]=t);const a=(n.arguments??[]).filter(e=>e.required&&!(e.name in o)).map(e=>e.name);if(a.length)return N(f,O,`Missing required arguments: ${a.join(", ")}`);let c;if(t.context)try{c=await t.context(i,e)}catch(e){return H(e,{method:S}),N(f,R,"Context initialization failed")}try{const e=await n.get(o,y(i,c)),t="string"==typeof e?{messages:[{role:"user",content:x(e)}]}:Array.isArray(e)?{messages:e}:e,r=t.description??n.description;return W(f,{...r?{description:r}:{},messages:t.messages})}catch(e){return H(e,{method:S}),N(f,R,"Prompt rendering failed")}}}var E;return N(f,z,`Method not found: ${S}`)}(e);return Object.keys(i).length?{...c,headers:{...c.headers,...i}}:c}return{handle:K,fetch:async function(e){const t={};if(e.headers.forEach((e,r)=>{t[r]=e}),a>0){const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>a)return new Response(JSON.stringify({error:"payload_too_large"}),{status:413,headers:{"Content-Type":P}})}const r="POST"===e.method.toUpperCase()?await e.text():void 0,n=await K({method:e.method,headers:t,body:r});return new Response(""===n.body?null:n.body,{status:n.status,headers:n.headers})},listTools:()=>Array.from(c.values()).map(e=>({name:e.name,description:e.description,...e.annotations?{annotations:e.annotations}:{}})),serverCard:e=>({name:r.name,version:r.version,endpoint:e.endpoint,transport:"streamable-http",capabilities:{tools:{listChanged:!1},...g?{resources:{}}:{},...m?{prompts:{}}:{}},...e.description?{description:e.description}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{}})}}const B=12,L=16;function H(){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 D=new Map;function G(e){let t=D.get(e);return t||(t=(async()=>{const t=await H().digest("SHA-256",(new TextEncoder).encode(`${e}:bb-session`));return H().importKey("raw",t,{name:"AES-GCM"},!1,["encrypt","decrypt"])})(),D.set(e,t)),t}function K(e){if(!e)throw new Error("createSessionRefCrypto: missing secret");return{async encryptSessionRef(r){const n=globalThis.crypto.getRandomValues(new Uint8Array(B)),s=await G(e),o=new Uint8Array(await H().encrypt({name:"AES-GCM",iv:n},s,(new TextEncoder).encode(r))),i=o.subarray(o.length-L),a=o.subarray(0,o.length-L),c=new Uint8Array(28+a.length);return c.set(n,0),c.set(i,B),c.set(a,28),t(c)},async decryptSessionRef(t){try{const n=r(t);if(n.length<=28)return null;const s=n.slice(0,B),o=n.subarray(B,28),i=n.subarray(28),a=new Uint8Array(i.length+L);a.set(i,0),a.set(o,i.length);const c=await G(e),u=await H().decrypt({name:"AES-GCM",iv:s},c,a);return(new TextDecoder).decode(u)}catch{return null}}}}function V(e,t,r){const n=globalThis.process?.env;"1"===n?.MCP_AUTH_DEBUG&&console.warn(`[buildbase/mcp-auth] audience rejected (${r}): received aud=${JSON.stringify(e)} expected one of ${JSON.stringify(t)}`)}function Q(e){const{secret:t}=e;if(!t)throw new Error("buildbaseAuth: missing secret");const r=K(t),n=e.resource?Array.isArray(e.resource)?e.resource:[e.resource]:[];let s=e.resourceMetadataUrl;if(!s&&n.length)try{const e=new URL(n[0]),t="/"===e.pathname?"":e.pathname.replace(/\/+$/,"");s=`${e.origin}/.well-known/oauth-protected-resource${t}`}catch{}return{resourceMetadataUrl:s,verify:async s=>{let o;try{o=p(s,t,{...e.verify})}catch{return null}if(n.length){const t=o.aud?Array.isArray(o.aud)?o.aud:[o.aud]:[];if(!t.length&&e.requireAudience)return V(t,n,"token carries no aud claim"),null;if(t.length&&!t.some(e=>n.includes(e)))return V(t,n,"aud does not include this resource"),null}const i="string"==typeof o.sid?await r.decryptSessionRef(o.sid):null,a=Array.isArray(o.scope)?o.scope.filter(e=>"string"==typeof e):"string"==typeof o.scope?o.scope.split(" ").filter(Boolean):void 0;return{sessionId:i??"",userId:"string"==typeof o.userId?o.userId:"string"==typeof o.sub?o.sub:void 0,workspaceId:"string"==typeof o.workspaceId?o.workspaceId:void 0,scopes:a,claims:o}}}}const Y=300,Z="/.well-known/oauth-protected-resource",X="/.well-known/agent-skills",ee="/.well-known/api-catalog",te="/.well-known/mcp/server-card.json",re="/.well-known/agent-card.json",ne="application/json",se="application/linkset+json",oe="text/markdown; charset=utf-8",ie="text/plain; charset=utf-8",ae="application/xml; charset=utf-8",ce=["GPTBot","OAI-SearchBot","ChatGPT-User","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","CCBot","Bytespider","meta-externalagent","Amazonbot"];function ue(e){return e.replace(/\/+$/,"")}function le(e){return`public, max-age=${e}, s-maxage=${e}`}function pe(e){return"sha256:"+function(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}(o(i(e)))}const de=new Map;async function he(e,t,r,n){if(!n||n<=0)return e(t,r);const s=new AbortController,o=setTimeout(()=>s.abort(),n);try{return await e(t,{...r,signal:s.signal})}finally{clearTimeout(o)}}async function ge(e){const t=e.cacheTtlSeconds??Y,r=`${ue(e.serverUrl)}::${e.orgId}`,n=de.get(r);if(n&&n.expiresAt>Date.now())return n.value;const s=e.fetch??fetch,o=`${ue(e.serverUrl)}/api/v1/public/${e.orgId}/agent-readiness`;let i={enabled:!1};try{const t=await he(s,o,{headers:{Accept:ne}},e.fetchTimeoutMs??5e3);if(t.ok){const e=await t.json();e&&"object"==typeof e&&(i=e)}}catch{}return de.set(r,{value:i,expiresAt:Date.now()+1e3*t}),i}const me=new Map;function fe(e){let t="/";try{t=new URL(e).pathname}catch{t=e.startsWith("/")?e:`/${e}`}const r="/"===t?"":t.replace(/\/+$/,"");return Z+r}function we(e){return e.path??`${X}/${e.name}/SKILL.md`}function ye(e){if(!e.security)return null;const t=(Array.isArray(e.security.contact)?e.security.contact:[e.security.contact]).map(e=>`Contact: ${e}`);return e.security.expires&&t.push(`Expires: ${e.security.expires}`),e.security.policy&&t.push(`Policy: ${e.security.policy}`),{status:200,contentType:ie,body:t.join("\n")+"\n",cacheControl:le(e.cacheTtlSeconds??Y)}}function be(e){return e.endsWith(".json")||e.includes(".well-known/")?ne:e.endsWith(".md")?oe:e.endsWith(".xml")?ae:ie}function ke(e){const t=e??{tools:!0},r={tools:!1,resources:!1,prompts:!1};for(const[e,n]of Object.entries(t))r[e]=!1!==n&&null!=n;return r}function Se(e,t){return{status:200,contentType:ne,body:JSON.stringify(e,null,2),cacheControl:le(t.cacheTtlSeconds??Y)}}function ve(e){return String(e).replace(/[\x00-\x1f\x7f]/g,"")}function Ee(e,t){const r=(Array.isArray(e.userAgent)?e.userAgent:[e.userAgent]).map(e=>`User-agent: ${ve(e)}`);if(t){const e=[...void 0!==t.search?["search="+(t.search?"yes":"no")]:[],...void 0!==t.aiInput?["ai-input="+(t.aiInput?"yes":"no")]:[],...void 0!==t.aiTrain?["ai-train="+(t.aiTrain?"yes":"no")]:[]];e.length&&r.push(`Content-Signal: ${e.join(", ")}`)}for(const t of e.allow??[])r.push(`Allow: ${ve(t)}`);for(const t of e.disallow??[])r.push(`Disallow: ${ve(t)}`);return void 0!==e.crawlDelay&&r.push(`Crawl-delay: ${ve(e.crawlDelay)}`),r.join("\n")}function xe(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Te(e){const t=ue(e.siteUrl),r=[`<${t}/llms.txt>; rel="describedby"; type="text/plain"`,`<${t}/.well-known/agent.json>; rel="describedby"; type="application/json"`];if(!1!==e.a2aCard&&r.push(`<${t}${re}>; rel="describedby"; type="application/json"`),e.sitemap||e.robots?.sitemaps?.length){const n=e.robots?.sitemaps?.[0]??`${t}/sitemap.xml`;r.push(`<${n}>; rel="sitemap"; type="application/xml"`)}return e.apiCatalog?.length&&r.push(`<${t}${ee}>; rel="api-catalog"; type="${se}"`),e.mcpServerCard&&r.push(`<${t}${te}>; rel="mcp-server"; type="application/json"`),r.join(", ")}async function _e(e,t){const r=e.replace(/\/+$/,"")||e;if("/.well-known/agent.json"===r){return function(e,t){const r=ue(e.siteUrl),n={llms_txt:"/llms.txt",sitemap:"/sitemap.xml",robots:"/robots.txt",oauth_protected_resource:Z};return t.authorizationServer?.metadataUrl&&(n.oauth_authorization_server=t.authorizationServer.metadataUrl,n.openid_configuration="/.well-known/openid-configuration"),(t.authorizationServer||e.authMd)&&(n.auth="/auth.md"),e.skills?.length&&(n.agent_skills=`${X}/index.json`),e.apiCatalog?.length&&(n.api_catalog=ee),e.mcpServerCard&&(n.mcp_server_card=te),!1!==e.a2aCard&&(n.a2a_agent_card=re),e.llmsFullTxt&&(n.llms_full_txt="/llms-full.txt"),Se({schema_version:"1.0",name:e.site.name,...e.site.description?{description:e.site.description}:{},url:r,...e.site.documentationUrl?{documentation_url:e.site.documentationUrl}:{},provider:e.site.provider??{name:e.site.name,url:r},capabilities:n,...e.site.contactEmail?{contact:{email:e.site.contactEmail}}:{}},e)}(t,await ge(t))}if(r===re)return function(e){if(!1===e.a2aCard)return null;const t=e.a2aCard??{},r=ue(e.siteUrl),n=t.serviceUrl??r,s=t.transportProtocol??"http",o=t.skills??((e.skills??[]).length?(e.skills??[]).map(e=>({id:e.name,name:e.name,description:e.description,tags:["discovery"]})):[{id:"site-content",name:"Site content",description:`Read ${e.site.name}'s public content and machine-readable discovery documents (llms.txt, sitemap, API catalog).`,tags:["content"]}]);return Se({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:n,preferredTransport:s,supportedInterfaces:[{serviceUrl:n,transportProtocol:s}],provider:e.site.provider?{organization:e.site.provider.name,url:e.site.provider.url}:{organization:e.site.name,url:r},capabilities:t.capabilities??{streaming:!1,pushNotifications:!1},defaultInputModes:["text/plain","application/json"],defaultOutputModes:["text/plain","application/json"],skills:o,...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}},e)}(t);if("/.well-known/http-message-signatures-directory"===r)return function(e){const t=e.webBotAuth?.keys;return t?.length?{status:200,contentType:"application/http-message-signatures-directory+json",body:JSON.stringify({keys:t},null,2),cacheControl:le(e.cacheTtlSeconds??Y)}:null}(t);if("/.well-known/security.txt"===r)return ye(t);if(r===`${X}/index.json`)return function(e){const t=e.skills??[];if(!t.length)return null;const r=ue(e.siteUrl);return Se({$schema:"https://schemas.agentskills.io/discovery/0.2.0/schema.json",skills:t.map(e=>({name:e.name,type:e.type??"skill-md",description:e.description,url:`${r}${we(e)}`,digest:pe(e.content)}))},e)}(t);if(r.startsWith(`${X}/`)&&r.endsWith("SKILL.md"))return function(e,t){const r=(t.skills??[]).find(t=>we(t)===e);return r?{status:200,contentType:"text/markdown; charset=utf-8",body:r.content,cacheControl:le(t.cacheTtlSeconds??Y)}:null}(r,t);if("/.well-known/oauth-authorization-server"===r||"/.well-known/openid-configuration"===r){const e=(await ge(t)).authorizationServer;if(!e?.metadataUrl)return null;const r=await async function(e,t){const r=t.cacheTtlSeconds??Y,n=me.get(e);if(n&&n.expiresAt>Date.now())return n.value;const s=t.fetch??fetch;let o=null;try{const r=await he(s,e,{headers:{Accept:ne}},t.fetchTimeoutMs??5e3);if(r.ok){const e=await r.json();e&&"object"==typeof e&&(o=e)}}catch{}return me.set(e,{value:o,expiresAt:Date.now()+1e3*r}),o}(e.metadataUrl,t);return Se(r?r:{...e.issuer?{issuer:e.issuer}:{},oauth_authorization_server_metadata:e.metadataUrl},t)}if(r===ee)return function(e){const t=e.apiCatalog??[];if(!t.length)return null;const r=t.map(e=>({anchor:e.anchor,...e.title?{title:e.title}:{},...e.serviceDesc?{"service-desc":[{href:e.serviceDesc}]}:{},...e.serviceDoc?{"service-doc":[{href:e.serviceDoc}]}:{},...e.status?{status:[{href:e.status}]}:{}}));return{status:200,contentType:se,body:JSON.stringify({linkset:r},null,2),cacheControl:le(e.cacheTtlSeconds??Y)}}(t);if(r===te)return function(e){const t=e.mcpServerCard;return t?Se({$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:ke(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{}},e):null}(t);if("/.well-known/mcp.json"===r)return function(e){const t=e.mcpServerCard;if(!t)return null;const r=ue(e.siteUrl);let n;try{n={type:"oauth2",protected_resource_metadata:`${new URL(t.endpoint).origin}${fe(t.endpoint)}`}}catch{}return Se({$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:ke(t.capabilities),...t.documentationUrl?{documentation_url:t.documentationUrl}:{},server_card:`${r}${te}`,...n?{authentication:n}:{}}]},e)}(t);if(r.startsWith(Z)){const e=await ge(t);return function(e,t,r){const n=t.protectedResources??[];if(!n.length)return null;const s=e.replace(/\/+$/,"")||Z,o=r??`${ue(t.serverUrl)}/org/${t.orgId}`,i=t.scopes?.map(e=>e.name),a=n.map(e=>{const r=e.resource??ue(t.siteUrl),n=e.scopes??i;return{path:fe(r),metadata:{resource:r,authorization_servers:[o],bearer_methods_supported:e.bearerMethods??["header"],...n?.length?{scopes_supported:n}:{},...e.documentationUrl?{resource_documentation:e.documentationUrl}:{}}}}),c=a.find(e=>e.path===s);return c?Se(c.metadata,t):s===Z&&1===a.length?Se(a[0].metadata,t):null}(r,t,e.authorizationServer?.issuer)}return null}async function Pe(e,t){const r=e.replace(/\/+$/,"")||e,n=function(e,t){const r=t.extraPaths?.[e];if(void 0===r)return null;const n="string"==typeof r?{body:r}:r;return{status:n.status??200,contentType:n.contentType??be(e),body:n.body,cacheControl:n.cacheControl??le(t.cacheTtlSeconds??Y)}}(r,t);return n||("/robots.txt"===r?function(e){const t=e.robots??{},r=ue(e.siteUrl),n=t.policies??[{userAgent:"*",allow:["/"]}],s=t.aiBots??"allow",o="allow"===s?[{userAgent:[...ce],allow:["/"]}]:"deny"===s?[{userAgent:[...ce],disallow:["/"]}]:s,i=t.sitemaps??(e.sitemap?[`${r}/sitemap.xml`]:[]),a=[`# robots.txt — agent-ready. See ${r}/llms.txt and ${r}/.well-known/agent.json`,...n.map((e,r)=>Ee(e,0===r?t.contentSignals:void 0)),...o.map(e=>Ee(e)),...i.length?[i.map(e=>`Sitemap: ${ve(e)}`).join("\n")]:[]];return{status:200,contentType:ie,body:a.join("\n\n")+"\n",cacheControl:le(e.cacheTtlSeconds??Y)}}(t):"/llms-full.txt"===r?function(e){return e.llmsFullTxt?{status:200,contentType:ie,body:e.llmsFullTxt,cacheControl:le(e.cacheTtlSeconds??Y)}:null}(t):"/sitemap.xml"===r?function(e){const t=e.sitemap?.urls;if(!t?.length)return null;const r=ue(e.siteUrl),n='<?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:`${r}${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>${xe(t.priority)}</priority>`]:[]].join("\n")}\n </url>`}).join("\n")+"\n</urlset>\n";return{status:200,contentType:ae,body:n,cacheControl:le(e.cacheTtlSeconds??Y)}}(t):"/llms.txt"===r?function(e){return e.llmsTxt?{status:200,contentType:ie,body:e.llmsTxt,cacheControl:le(e.cacheTtlSeconds??Y)}:null}(t):"/auth.md"===r?function(e,t){const r=le(e.cacheTtlSeconds??Y);if(e.authMd)return{status:200,contentType:oe,body:e.authMd,cacheControl:r};const n=t.authorizationServer;if(!n)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: \`${n.issuer}\`\n- Metadata (RFC 8414): ${n.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:oe,body:s,cacheControl:r}}(t,await ge(t)):"/security.txt"===r?ye(t):r.startsWith("/.well-known")?_e(r,t):null)}let Ue=!0;function $e(e,...t){Ue&&function(){try{const e="undefined"!=typeof globalThis?globalThis:null;return"development"===e?.process?.env?.NODE_ENV}catch{return!1}}()&&console.error(e,...t)}function Ce(e,...t){console.error(e,...t)}async function Ae(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 ze(e,t="Request failed"){if(!e.ok){let r=t;try{const t=await Ae(e);r=t.message||t.error||r}catch{r=function(e,t){const r={400:"Bad Request",401:"Unauthorized - Please check your session",403:"Forbidden - You do not have permission",404:"Resource not found",500:"Internal server error",502:"Bad Gateway",503:"Service unavailable"}[e.status]||e.statusText||t;return new Error(`${t} (${e.status}: ${r})`)}(e,t).message}throw new Error(r)}try{return await Ae(e)}catch(e){if(e instanceof Error&&e.message.includes("Invalid JSON"))throw e;throw new Error("Failed to parse response as JSON")}}class Oe extends Error{constructor(e,t,r,n){super(e),this.code=t,this.context=r,this.originalError=n,this.name="SDKError","undefined"!=typeof Error&&"captureStackTrace"in Error&&Error.captureStackTrace(this,Oe)}}const Re=new class{constructor(){this.config={enableConsoleLogging:!0,showUserNotifications:!1},this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}configure(e){this.config={...this.config,...e},void 0!==e.enableConsoleLogging&&function(e){void 0!==e.enableLogging&&(Ue=e.enableLogging)}({enableLogging:e.enableConsoleLogging})}handleError(e,t={}){if(function(e){return e instanceof Error&&("AbortError"===e.name||"ERR_CANCELED"===e.code)}(e))return;const r=e instanceof Error?e:new Oe("string"==typeof e?e:"An unknown error occurred","UNKNOWN_ERROR",t),n=r instanceof Oe?r:new Oe(r.message,"SDK_ERROR",t,r);if(this.config.enableConsoleLogging&&$e(`[SDK Error] ${t.component||"Unknown"}:`,{message:n.message,code:n.code,context:n.context,originalError:n.originalError,stack:n.stack}),this.config.onError)try{this.config.onError(n,t)}catch(e){Ce("[SDK Error Handler] Error in custom error callback:",e)}for(const e of this.listeners)try{e(n,t)}catch(e){Ce("[SDK Error Handler] Error in error listener:",e)}this.config.showUserNotifications&&this.notifyUser(n,t)}notifyUser(e,t){"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("sdk-error",{detail:{error:e,context:t}}))}wrapAsync(e,t){return(...r)=>e(...r).catch(e=>{throw this.handleError(e,t),e})}wrapSync(e,t){return(...r)=>{try{return e(...r)}catch(e){throw this.handleError(e,t),e}}}};function je(e,t={}){Re.handleError(e,t)}function Je(e){if("undefined"==typeof window)return null;try{return localStorage.getItem(e)}catch(t){return je(t,{component:"storage",action:"getStorageItem",metadata:{key:e}}),null}}const We="saas-session-id",Ne="saas-device-id";function Fe(){return function(){if("undefined"==typeof window)return null;try{return Je(We)}catch(e){return je(e,{component:"auth-utils",action:"getSessionId",metadata:{key:We}}),null}}()}function Me(){const e=Fe(),t={};e&&(t["x-session-id"]=e);const r=function(){if("undefined"==typeof window)return null;try{return Je(Ne)??null}catch(e){return je(e,{component:"auth-utils",action:"getOrCreateDeviceId",metadata:{key:Ne}}),null}}();return r&&(t["x-device-id"]=r),t}const qe=new WeakSet,Be=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]),Le="SDK is not ready (missing serverUrl, version, or orgId)";class He{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(Le);if(this.requireOrgId&&!this.orgId?.trim())throw new Error(Le)}get baseUrl(){return this.ensureReady(),`${this.serverUrl}/api/${this.version}/${this.basePath}`}getAuthHeaders(){return this._sessionId?{"x-session-id":this._sessionId}:Me()}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){qe.has(e)||(qe.add(e),this._onError?.(e,t))}async executeFetch(e,t){return this.executeFetchUrl(this.url(e),t,e)}static delay(e,t){return new Promise((r,n)=>{const s=()=>{clearTimeout(o),n(new DOMException("The operation was aborted.","AbortError"))};if(t?.aborted)return s();const o=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e);t?.addEventListener("abort",s,{once:!0})})}async executeFetchUrl(e,t,r){const n=(t.method??"GET").toUpperCase(),s=r??e,o=this.buildHeaders(t),i={...t,headers:o},a=Be.has(n);let c,u;if(this._timeout>0){u=new AbortController;const e=u;c=setTimeout(()=>e.abort(),this._timeout),i.signal=t.signal?function(e,t){const r=AbortSignal.any;if("function"==typeof r)return r([e,t]);const n=new AbortController,s=e=>{n.signal.aborted||n.abort(e.reason)};for(const r of[e,t]){if(r.aborted){s(r);break}r.addEventListener("abort",()=>s(r),{once:!0})}return n.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: ${n} ${s}`);return this.reportError(e,{method:n,path:s}),e}return e},p=async t=>{try{if("function"!=typeof this._fetch)throw new Error("No fetch implementation available. Global fetch requires Node 18+; on older runtimes pass a `fetch` in the SDK config (e.g. from `undici` or `node-fetch`).");const r=this._fetch.bind(globalThis),s=await r(e,i);if(this._debug&&console.log(`[BuildBase] ${n} ${e} → ${s.status}`),401===s.status&&this._onUnauthorized&&this._onUnauthorized(),s.status>=500&&a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);return this._debug&&console.log(`[BuildBase] Retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`),await He.delay(e,i.signal),p(t+1)}return s}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw l(e);if(a&&t<this._maxRetries){const e=Math.min(1e3*Math.pow(2,t),1e4);this._debug&&console.log(`[BuildBase] Network error, retrying in ${e}ms (attempt ${t+1}/${this._maxRetries})`);try{await He.delay(e,i.signal)}catch(e){throw l(e)}return p(t+1)}throw e instanceof Error&&this.reportError(e,{method:n,path:s}),e}};try{return await p(0)}finally{void 0!==c&&clearTimeout(c)}}async fetchJson(e,t={},r="Request failed"){this.ensureReady();try{const n=await this.executeFetch(e,t);return await ze(n,r)}catch(r){throw r instanceof Error&&this.reportError(r,{method:(t.method??"GET").toUpperCase(),path:e}),r}}async fetchResponse(e,t={}){return this.ensureReady(),this.executeFetch(e,t)}async fetchUnwrapped(e,t={},r="Request failed"){const n=await this.fetchResponse(e,t);return n.ok||await this.throwResponseError(n,r),this.unwrapResponse(n,r)}async fetchAbsoluteUrl(e,t={}){return this.ensureReady(),this.executeFetchUrl(e,t)}async throwResponseError(e,t){let r=t;try{r=(await e.json()).message||r}catch{r=`${t} (${e.status}: ${e.statusText})`}throw Object.assign(new Error(r),{status:e.status})}apiPath(e,...t){return e.reduce((e,r,n)=>e+r+(n<t.length?encodeURIComponent(String(t[n])):""),"")}async unwrapResponse(e,t){const r=await e.json();if(void 0!==r.success){if(!r.success)throw new Error(r.message||t);return void 0!==r.data?r.data:r}return r}}class De extends He{constructor(e){super(e)}async list(e){const t=await this.fetchJson("devices",{signal:e},"Failed to load devices");return t?.devices??[]}async rename(e,t,r){await this.fetchJson(this.apiPath`devices/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"Failed to rename device")}async signOut(e,t){return this.fetchJson(this.apiPath`devices/${e}`,{method:"DELETE",signal:t},"Failed to sign out device")}async forget(e,t){return this.fetchJson(`${this.apiPath`devices/${e}`}?forget=true`,{method:"DELETE",signal:t},"Failed to forget device")}}class Ge extends He{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 Ke extends He{constructor(e){super(e)}async list(e){const t=await this.fetchJson("sessions",{signal:e},"Failed to load sessions");return t?.sessions??[]}async revoke(e,t){await this.fetchJson(this.apiPath`sessions/${e}`,{method:"DELETE",signal:t},"Failed to sign out session")}}class Ve extends He{constructor(e){super({...e,requireOrgId:!0})}async getSettings(e){return this.fetchJson(`${this.orgId}/settings`,{signal:e},"Failed to fetch settings")}}class Qe extends He{constructor(e){super(e)}async getAttributes(e){const t=await this.fetchResponse("users/attributes",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user attributes");const r=await this.unwrapResponse(t,"Failed to fetch user attributes");return r&&"object"==typeof r&&!Array.isArray(r)?r:{}}async updateAttributes(e){return this.fetchJson("users/attributes",{method:"PATCH",body:JSON.stringify({attributes:e})},"Failed to update user attributes")}async updateAttribute(e,t){return this.fetchJson(this.apiPath`users/attributes/${e}`,{method:"PATCH",body:JSON.stringify({value:t})},"Failed to update user attribute")}async getFeatures(e){const t=await this.fetchResponse("users/features",{signal:e});t.ok||await this.throwResponseError(t,"Failed to fetch user features");const r=await this.unwrapResponse(t,"Failed to fetch user features");return"object"==typeof r&&null!==r?r:{}}}class Ye extends He{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,r){return this.fetchJson(this.apiPath`workspaces/${e}`,{method:"PUT",body:JSON.stringify(t),signal:r},"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,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/add`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to invite member")}async removeUser(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"DELETE",signal:r},"Failed to remove user")}async updateUser(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/users/${t}`,{method:"PATCH",body:JSON.stringify(r),signal:n},"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,r){return this.fetchJson(this.apiPath`workspaces/${e}/permissions`,{method:"PATCH",body:JSON.stringify({permissions:t}),signal:r},"Failed to update workspace permissions")}async getFeatures(e){return this.fetchJson("workspaces/features",{signal:e},"Failed to fetch features")}async updateFeature(e,t,r,n){return this.fetchJson(this.apiPath`workspaces/${e}/features`,{method:"PATCH",body:JSON.stringify({features:{[t]:r}}),signal:n},"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,r){await this.fetchJson(this.apiPath`passkeys/${e}`,{method:"PATCH",body:JSON.stringify({name:t}),signal:r},"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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/plan-group`+`?groupVersionId=${encodeURIComponent(t)}`,{signal:r},"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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/checkout`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create checkout session")}async selectFreePlan(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/select-free-plan`,{method:"POST",body:JSON.stringify({planVersionId:t}),signal:r},"Failed to select free plan")}async updateSubscription(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription`,{method:"PATCH",body:JSON.stringify(t),signal:r},"Failed to update subscription")}async createBillingPortalSession(e,t,r){return this.fetchJson(this.apiPath`workspaces/${e}/subscription/billing-portal`,{method:"POST",body:JSON.stringify(t?{returnUrl:t}:{}),signal:r})}async listInvoices(e,t=10,r,n){const s=new URLSearchParams;return s.append("limit",t.toString()),r&&s.append("starting_after",r),this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices`+`?${s.toString()}`,{signal:n},"Failed to fetch invoices")}async getInvoice(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/invoices/${t}`,{signal:r},"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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record usage")}async recordUsageBatch(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/batch`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to record batch usage")}async getQuotaUsageStatus(e,t,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/subscription/usage/status`+`?quotaSlug=${encodeURIComponent(t)}`,{signal:r},"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,r){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(),o=this.apiPath`workspaces/${e}/subscription/usage/logs`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch usage logs")}async sendNotification(e,t,r,n,s){const o={event:t};return r&&(o.userId=r),n&&(o.data=n),this.fetchJson(this.apiPath`workspaces/${e}/notifications/send`,{method:"POST",body:JSON.stringify(o),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,r){return(await this.fetchJson(this.apiPath`workspaces/${e}/notification-preferences`,{method:"PATCH",body:JSON.stringify({notificationPreferences:t}),signal:r},"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,r){const n=await this.fetchResponse(this.apiPath`workspaces/${e}/credits/consume`,{method:"POST",body:JSON.stringify(t),signal:r});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,r){return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/purchase`,{method:"POST",body:JSON.stringify(t),signal:r},"Failed to create credit purchase checkout")}async getCreditPackages(e,t){const r=await this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/packages`,{signal:t},"Failed to fetch credit packages");return r.docs??r}async getCreditTransactions(e,t,r){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(),o=this.apiPath`workspaces/${e}/credits/transactions`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch credit transactions")}async getCreditBuckets(e,t,r){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(),o=this.apiPath`workspaces/${e}/credits/buckets`+(s?`?${s}`:"");return this.fetchUnwrapped(o,{signal:r},"Failed to fetch credit buckets")}async getExpiringCredits(e,t,r){const n=t?`?days=${t}`:"";return this.fetchUnwrapped(this.apiPath`workspaces/${e}/credits/expiring`+n,{signal:r},"Failed to fetch expiring credits")}}const Ze={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(Ze),et={admin:Xe.filter(e=>e!==Ze.WORKSPACE_DELETE),member:[Ze.WORKSPACE_SETTINGS_VIEW,Ze.WORKSPACE_MEMBERS_VIEW,Ze.WORKSPACE_FEATURES_VIEW,Ze.WORKSPACE_BILLING_VIEW,Ze.WORKSPACE_USAGE_VIEW],viewer:[Ze.WORKSPACE_SETTINGS_VIEW,Ze.WORKSPACE_MEMBERS_VIEW]};function tt(e){const t=new Set;for(const r of Object.values(e))for(const e of r)t.add(e);return Array.from(t)}function rt(e){const{userId:t,workspace:r,settings:n,appPermissions:s}=e;if(!r||!t)return new Set;if(function(e,t){if(!t)return!1;const r=(n=e.createdBy)?"string"==typeof n?n:"object"==typeof n&&"_id"in n&&"string"==typeof n._id?n._id:null:null;var n;return null!==r&&r===t}(r,t)){const e=new Set(Xe);if(s)for(const t of tt(s))e.add(t);if(r.permissions)for(const t of tt(r.permissions))e.add(t);if(n?.workspace?.permissions)for(const t of tt(n.workspace.permissions))e.add(t);return e}const o=e.workspaceRole??function(e,t){if(!t||!e.users||!Array.isArray(e.users))return null;const r=e.users.find(e=>"string"==typeof e?e===t:"object"==typeof e&&null!==e&&"_id"in e&&e._id===t);return r&&"object"==typeof r&&"role"in r&&"string"==typeof r.role?r.role:null}(r,t);if(!o)return new Set;const i=r.permissions,a=n?.workspace?.permissions,c=e=>e.filter(e=>e.startsWith("workspace:")),u=e=>e.filter(e=>!e.startsWith("workspace:")),l=!!i&&o in i,p=!!a&&o in a,d=o in et;let h;if(l)h=c(i[o]);else if(p)h=c(a[o]);else if(d)h=et[o];else{const e=n?.workspace?.defaultRole;h=e&&e in et?et[e]:[]}const g=new Set(h),m=l?u(i[o]):[],f=s?.[o]?u(s[o]):[],w=l?m:f;for(const e of w)g.add(e);return function(e,t,r){if(!r?.workspace)return;const{canInviteMembers:n}=r.workspace;(!1===n||"admin-only"===n&&"admin"!==t)&&e.delete(Ze.WORKSPACE_MEMBERS_INVITE)}(g,o,n),g}function nt(e){const{serverUrl:t,orgId:r,version:n="v1",getSessionId:s,timeout:o,maxRetries:i,debug:a,headers:c,onError:u,fetch:l}=e;if(!t)throw new Error("BuildBase: serverUrl is required");if(!r)throw new Error("BuildBase: orgId is required");const p={...void 0!==o&&{timeout:o},...void 0!==i&&{maxRetries:i},...void 0!==a&&{debug:a},...c&&{headers:c},...u&&{onError:u},...l&&{fetch:l}},d=e=>{const s={serverUrl:t,version:n,orgId:r,sessionId:e,...p};return{workspace:new Ye(s),user:new Qe(s),settings:new Ve(s),push:new Ge(s),devices:new De(s),sessions:new Ke(s)}},h=new Ye({serverUrl:t,version:n,orgId:r,...p}),g=e=>({workspace:{list:async()=>(await e()).workspace.getWorkspaces(),get:async t=>(await e()).workspace.getWorkspace(t),create:async t=>(await e()).workspace.createWorkspace(t),update:async(t,r)=>(await e()).workspace.updateWorkspace(t,r),delete:async t=>(await e()).workspace.deleteWorkspace(t)},users:{list:async t=>(await e()).workspace.getWorkspaceUsers(t),invite:async(t,r,n)=>(await e()).workspace.addUser(t,{email:r,role:n}),remove:async(t,r)=>(await e()).workspace.removeUser(t,r),updateRole:async(t,r,n)=>(await e()).workspace.updateUser(t,r,{role:n}),getProfile:async()=>(await e()).workspace.getProfile(),updateProfile:async t=>(await e()).workspace.updateUserProfile(t)},subscription:{get:async t=>(await e()).workspace.getCurrentSubscription(t),checkout:async(t,r)=>(await e()).workspace.createCheckoutSession(t,r),update:async(t,r)=>(await e()).workspace.updateSubscription(t,r),cancel:async t=>(await e()).workspace.cancelSubscriptionAtPeriodEnd(t),resume:async t=>(await e()).workspace.resumeSubscription(t),getBillingPortalUrl:async(t,r)=>(await e()).workspace.createBillingPortalSession(t,r)},plans:{getGroup:async t=>(await e()).workspace.getPlanGroup(t),getVersions:async t=>(await e()).workspace.getPlanGroupVersions(t),getPublic:e=>h.getPublicPlans(e),getVersion:e=>h.getPlanGroupVersion(e)},invoices:{list:async(t,r,n)=>(await e()).workspace.listInvoices(t,r,n),get:async(t,r)=>(await e()).workspace.getInvoice(t,r)},usage:{record:async(t,r)=>(await e()).workspace.recordUsage(t,r),recordBatch:async(t,r)=>(await e()).workspace.recordUsageBatch(t,r),getQuota:async(t,r)=>(await e()).workspace.getQuotaUsageStatus(t,r),getAll:async t=>(await e()).workspace.getAllQuotaUsage(t),getLogs:async(t,r)=>(await e()).workspace.getUsageLogs(t,r)},settings:{get:async()=>(await e()).settings.getSettings()},features:{list:async()=>(await e()).workspace.getFeatures(),update:async(t,r,n)=>(await e()).workspace.updateFeature(t,r,n)},notification:{send:async(t,r,n,s)=>(await e()).workspace.sendNotification(t,r,n,s)},credits:{getBalance:async t=>(await e()).workspace.getCreditBalance(t),consume:async(t,r)=>(await e()).workspace.consumeCredits(t,r),purchase:async(t,r)=>(await e()).workspace.purchaseCredits(t,r),getPackages:async t=>(await e()).workspace.getCreditPackages(t),getTransactions:async(t,r)=>(await e()).workspace.getCreditTransactions(t,r),getBuckets:async(t,r)=>(await e()).workspace.getCreditBuckets(t,r),getExpiring:async(t,r)=>(await e()).workspace.getExpiringCredits(t,r),getPublicPackages:()=>h.getPublicCreditPackages()},permissions:{check:async(t,r,n)=>{const s=await e(),[o,i,a]=await Promise.all([s.workspace.getWorkspace(t),s.settings.getSettings(),s.workspace.getWorkspaceUsers(t)]),c=a.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return function(e,t){const r=rt(t);return Array.isArray(e)?e.every(e=>r.has(e)):r.has(e)}(n,{userId:r,workspaceRole:c?.role??null,workspace:o,settings:i})},resolve:async(t,r)=>{const n=await e(),[s,o,i]=await Promise.all([n.workspace.getWorkspace(t),n.settings.getSettings(),n.workspace.getWorkspaceUsers(t)]),a=i.find(e=>("string"==typeof e.user?e.user:e.user._id)===r);return rt({userId:r,workspaceRole:a?.role??null,workspace:s,settings:o})}},devices:{list:async()=>(await e()).devices.list(),rename:async(t,r)=>(await e()).devices.rename(t,r),signOut:async t=>(await e()).devices.signOut(t),forget:async t=>(await e()).devices.forget(t)},sessions:{list:async()=>(await e()).sessions.list(),revoke:async t=>(await e()).sessions.revoke(t)}}),m=g(async()=>d(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=d(e);return g(async()=>t)},client:{forSession:d},...m}}exports.AppBridgeError=u,exports.bearerChallenge=f,exports.buildbaseAuth=Q,exports.builtinMcpTools=v,exports.createAgentStack=function(e){const t=ue(e.siteUrl),r=e.mcp?.path??"/api/mcp",n=`${t}${r.startsWith("/")?r:`/${r}`}`,s=e.mcp?.serverInfo??{name:e.site.name,version:"1.0.0"},o=`${t}/mcp`,i=Array.from(new Set([o,n])),a=e.mcp?.auth??(e.secret?Q({secret:e.secret,resource:i,resourceMetadataUrl:`${t}/.well-known/oauth-protected-resource/mcp`,requireAudience:!0}):void 0);if(void 0===a)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=q({buildbase:e.mcp?.buildbase??nt({serverUrl:e.serverUrl,orgId:e.orgId}),serverInfo:s,auth:a,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:n,...e.site.description?{description:e.site.description}:{},...e.site.documentationUrl?{documentationUrl:e.site.documentationUrl}:{}}),...e.scopes?{scopes:e.scopes}:{},protectedResources:i.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:n,title:`${e.site.name} MCP server`,serviceDesc:`${t}/.well-known/mcp/server-card.json`}],...e.discovery},l={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, OPTIONS"},p=e=>c.fetch(e);return{mcp:c,mcpEndpoint:n,config:u,linkHeader:Te(u),resolvePath:e=>Pe(e,u),serveAgentPath:async function(e){if("OPTIONS"===e.method.toUpperCase())return new Response(null,{status:204,headers:l});const t=await Pe(new URL(e.url).pathname,u);return t?new Response(t.body,{status:t.status,headers:{"Content-Type":t.contentType,"Cache-Control":t.cacheControl,...t.vary?{Vary:t.vary}:{},...l}}):new Response(JSON.stringify({error:"not_found"}),{status:404,headers:{"Content-Type":"application/json",...l}})},routes:{GET:p,POST:p,DELETE:p,OPTIONS:p}}},exports.createMcpHandler=q,exports.createSessionRefCrypto=K,exports.defineMcpPrompt=e=>e,exports.defineMcpResource=e=>e,exports.defineMcpResourceTemplate=e=>e,exports.defineMcpTool=function(e){return e},exports.extractBearerToken=d,exports.mcpAudio=(e,t)=>({type:"audio",data:e,mimeType:t}),exports.mcpEmbeddedResource=e=>({type:"resource",resource:e}),exports.mcpImage=(e,t)=>({type:"image",data:e,mimeType:t}),exports.mcpResourceLink=(e,t,r)=>({type:"resource_link",uri:e,name:t,...r}),exports.mcpText=x,exports.mintAgentToken=async function(e){const{claims:t,secret:r}=e,n=e.expiresInSec??3600,s=t.resource&&t.resource.length?1===t.resource.length?t.resource[0]:t.resource:void 0,o=t.sessionId?await K(r).encryptSessionRef(t.sessionId):void 0;return{token:g({sub:t.id,userId:t.id,email:t.email,...t.name?{name:t.name}:{},...t.scope?{scope:t.scope}:{},...s?{aud:s}:{},...o?{sid:o}:{},...e.extraClaims},r,{expiresInSec:n}),expiresIn:n}},exports.selectBuiltinTools=E,exports.signClientJwt=g,exports.verifyClientJwt=p;
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -659,6 +659,11 @@ interface ICheckoutSessionResponse {
|
|
|
659
659
|
success: boolean;
|
|
660
660
|
checkoutUrl: string;
|
|
661
661
|
sessionId: string;
|
|
662
|
+
/** What Stripe charges today, in the currency's minor unit. Absent on older servers. */
|
|
663
|
+
amountTotal?: number | null;
|
|
664
|
+
currency?: string;
|
|
665
|
+
/** True when this checkout starts a trial rather than a paid period. */
|
|
666
|
+
trial?: boolean;
|
|
662
667
|
message: string;
|
|
663
668
|
planVersion?: {
|
|
664
669
|
_id: string;
|
|
@@ -705,6 +710,19 @@ interface ISubscriptionUpdateRequest {
|
|
|
705
710
|
cancelUrl?: string;
|
|
706
711
|
}
|
|
707
712
|
interface ISubscriptionUpdateResponse {
|
|
713
|
+
/**
|
|
714
|
+
* Set when the change was applied in place and prorated, rather than sent
|
|
715
|
+
* out to a Stripe checkout. The two paths report differently: a checkout
|
|
716
|
+
* comes back through `purchase`, a proration is reported here and the money
|
|
717
|
+
* lands later on an invoice.
|
|
718
|
+
*/
|
|
719
|
+
prorated?: boolean;
|
|
720
|
+
/** Present when the proration needs paying now. Minor units. */
|
|
721
|
+
invoice?: {
|
|
722
|
+
id?: string;
|
|
723
|
+
amount_due?: number;
|
|
724
|
+
status?: string | null;
|
|
725
|
+
} | null;
|
|
708
726
|
_id: string;
|
|
709
727
|
subscriptionStatus: string;
|
|
710
728
|
workspace: string;
|
|
@@ -954,11 +972,16 @@ interface ICreditPurchaseRequest {
|
|
|
954
972
|
currency?: string;
|
|
955
973
|
successUrl: string;
|
|
956
974
|
cancelUrl: string;
|
|
975
|
+
/** Written onto the Stripe session. The SDK adds its `bb_` tracking keys here. */
|
|
976
|
+
metadata?: Record<string, string>;
|
|
957
977
|
}
|
|
958
978
|
/** Response from POST .../credits/purchase */
|
|
959
979
|
interface ICreditPurchaseResponse {
|
|
960
980
|
sessionId: string;
|
|
961
981
|
url: string;
|
|
982
|
+
/** What Stripe charges, in the currency's minor unit. Absent on older servers. */
|
|
983
|
+
amountTotal?: number | null;
|
|
984
|
+
currency?: string;
|
|
962
985
|
}
|
|
963
986
|
/** Query params for GET .../credits/transactions */
|
|
964
987
|
interface ICreditTransactionsQuery {
|