palbase 0.11.2 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +11 -11
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{PF3S7VGN.js → 22JG5QKQ.js} +1 -1
  8. package/dist/chunks/{W6LUHPMU.js → 2DBSGJ7Z.js} +2 -2
  9. package/dist/chunks/{MWKPDZHT.js → 53ZQBGJV.js} +2 -2
  10. package/dist/chunks/66QSZDXV.js +2 -0
  11. package/dist/chunks/{5FJNJOWL.js → 7ZSVOQFN.js} +2 -2
  12. package/dist/chunks/{XOPSQEWX.js → ABRUIWQ3.js} +1 -1
  13. package/dist/chunks/B33QXIR5.js +2 -0
  14. package/dist/chunks/{NZRVCF6B.js → B5XYZZDJ.js} +1 -1
  15. package/dist/chunks/{NT7K4S2X.js → DLQT5KPC.js} +1 -1
  16. package/dist/chunks/IYUDOOD7.js +2 -0
  17. package/dist/chunks/JEI4RW55.js +6 -0
  18. package/dist/chunks/{XQUWS373.js → JWLK6SLN.js} +2 -2
  19. package/dist/chunks/{E765DY7Q.js → LDZ7OKNS.js} +2 -2
  20. package/dist/chunks/{BPFIGT6G.js → MWTLLONV.js} +2 -2
  21. package/dist/chunks/{6FV2T52H.js → NRWY25JZ.js} +1 -1
  22. package/dist/chunks/{W7UOMPUA.js → QCZJK4GZ.js} +2 -2
  23. package/dist/chunks/UMCUTNWL.js +2 -0
  24. package/dist/chunks/{4NC6D3AY.js → WAMYRYDY.js} +2 -2
  25. package/dist/chunks/{4OASGT7Q.js → WUYO4O77.js} +7 -7
  26. package/dist/chunks/{SI2TXLYT.js → X2BWW2WC.js} +1 -1
  27. package/dist/chunks/YWEI45Q6.js +21 -0
  28. package/dist/chunks/{FIWWCA6S.js → ZOF56QTG.js} +2 -2
  29. package/dist/chunks/ZT4AKS6D.js +13 -0
  30. package/dist/cli.js +132 -131
  31. package/dist/refuse/ai.js +1 -1
  32. package/dist/refuse/backend.js +1 -1
  33. package/dist/refuse/server.js +1 -1
  34. package/dist/server/index.js +2 -2
  35. package/dist/server/testing.js +2 -2
  36. package/dist/web/index.js +2 -2
  37. package/dist/web/message.js +2 -2
  38. package/dist/web/palbe.js +2 -2
  39. package/dist/web/paywall.js +2 -2
  40. package/dist/web/push-sw.js +1 -1
  41. package/dist/web/ssr.js +2 -2
  42. package/dist/web/vite.js +2 -2
  43. package/package.json +2 -2
  44. package/types/ai/src/chats.d.ts +7 -0
  45. package/types/backend/src/index.d.ts +1 -0
  46. package/types/backend/src/transit.d.ts +39 -0
  47. package/types/internal/src/modules/ai.d.ts +8 -0
  48. package/types/internal/src/modules/purchases.d.ts +95 -11
  49. package/types/internal/src/modules/secrets.d.ts +148 -1
  50. package/types/internal/src/transit-marks.d.ts +51 -0
  51. package/types/internal/src/transit.d.ts +108 -0
  52. package/types/server/src/index.d.ts +1 -0
  53. package/types/server/src/server.d.ts +8 -0
  54. package/types/server/src/transit.d.ts +91 -0
  55. package/types/web/src/backend-transit.d.ts +23 -0
  56. package/types/web/src/backends.d.ts +8 -1
  57. package/types/web/src/index.d.ts +1 -0
  58. package/dist/chunks/6S6MUPJA.js +0 -2
  59. package/dist/chunks/D5A6USBN.js +0 -6
  60. package/dist/chunks/QNJK2UIR.js +0 -20
  61. package/dist/chunks/VPFDS7G7.js +0 -2
  62. package/dist/chunks/WUPBDP6G.js +0 -13
@@ -0,0 +1,21 @@
1
+ /*! palbase 0.13.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as $t,c as re,d as tr,e as nr,f as we,h as E,i as ir}from"./MWTLLONV.js";import{c as rr,d as sr,e as Jt,f as ar,g as or}from"./IYUDOOD7.js";import{a as Zn,e as st,g as kt,h as Yn,i as Qn,j as vt,k as Tt,n as Xn,t as er}from"./UMCUTNWL.js";import{a as bt,b as Wn,n as Vn}from"./B33QXIR5.js";import{b as ce}from"./7ZSVOQFN.js";import"reflect-metadata";var Wt=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],dr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Et=/^\d+$/;function ra(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Et.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let l=t,m=n;if(o!=="*")if(o.includes("-")){let y=o.indexOf("-"),v=o.slice(0,y),S=o.slice(y+1);if(!Et.test(v)||!Et.test(S)||Number(v)<t||Number(S)>n||Number(v)>Number(S))return;l=Number(v),m=Number(S)}else{if(!Et.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),m=a===-1?l:n}for(let y=l;y<=m;y+=d)r.add(y)}return r}function cr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${dr}; "${e}" is not`;let n=[];for(let m=0;m<5;m++){let y=ra(t[m],Wt[m].lo,Wt[m].hi);if(!y)return`${dr}; its ${Wt[m].name} "${t[m]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let m=0;m<366*8+2;m++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let y=r.has(l.getUTCDate()),v=a.has(l.getUTCDay());if(o||d?y&&v:y||v)return}return`"${e}" is never due: no date has that day in that month`}var Le=Symbol.for("palbase.backend.controller"),Ie=Symbol.for("palbase.backend.routes"),Zt=Symbol.for("palbase.backend.params"),Yt=Symbol.for("palbase.backend.injectable"),Qt=Symbol.for("palbase.backend.module"),Re=Symbol.for("palbase.backend.events"),ze=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ue(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Vt=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[Vt]instanceof Set||(e[Vt]=new Set),e[Vt]}var qe=new Set(["webhooks","_palbase"]);function Gi(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&qe.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ue(n,Le,()=>({basePath:e,options:t})),se().add(n)}}function He(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ue(r.constructor,Ie,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Ki=He("GET"),Fi=He("POST"),Bi=He("PUT"),Ji=He("PATCH"),Wi=He("DELETE"),Vi=He("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ue(n.constructor,Zt,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function Xt(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Zi=e=>pe("body",{schema:Xt("Body",e)}),Yi=e=>pe("query",{schema:Xt("QueryParams",e)}),Qi=e=>pe("headers",e===void 0?{}:{schema:Xt("Headers",e)}),Xi=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},ed=()=>pe("user"),td=()=>pe("optionalUser"),nd=()=>pe("req"),rd=()=>pe("requestId"),sd=()=>pe("requestId"),ad=()=>pe("client");function od(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function id(){return e=>{ue(e,Yt,()=>!0),se().add(e)}}function dd(e){return t=>{ue(t,Qt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var fr=/^[a-z]+(\.[a-z_]+)+$/,sa=/^[a-z][a-z0-9-]{1,62}$/,en=e=>e.startsWith("file.");function cd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!sa.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!en(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ue(r.constructor,Re,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var tn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,aa=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function ur(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!aa.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function ud(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!tn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=cr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||ur(t.timeZone)!==void 0))throw new TypeError(`${n}: ${ur(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var lr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],oa=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function ld(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!oa.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!lr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${lr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&ia(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Re)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ue(t,ze,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function ia(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function fd(){return[...se()].filter(e=>D(e,Le)!==void 0)}function pd(e){return(D(e,Ie)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var St=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function wd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!tn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var sn;function mr(e){sn=e}function nn(){if(!sn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return sn}var da=720*3600;function ca(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>da))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function ua(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var bd=$t("Tasks",{async enqueue(e,t,n={}){return ca(n),nn().enqueue(ua(e),t===void 0?null:t,n)},async cancel(e,t={}){return nn().cancel(e,t.machine)},async get(e,t={}){return nn().get(e,t.machine)}}),rn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function hr(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await we.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return rn(a.data,a.status===200)},async cancel(n,r){return rn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return rn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var la=1e4,fa=36e5,pr=24*36e5,_t=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ce({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ce({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ce({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<pr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ce({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ce({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(la*2**Math.min(t.attempt-1,16),fa),E.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=pr&&this.tasks.delete(s);n==="failed"&&E.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var xt="/_palbase/test-user-templates",pa=/^[a-z][a-z0-9_-]{0,63}$/;function $d(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!pa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function gr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function yr(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ce&&n.status===404)return!1;throw n}}var ma="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function wr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,ma),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var an="/_palbase/storage/upload/authorize",br="/_palbase/storage/upload/complete",on="/_palbase/realtime/rooms";var ha=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ge(e){if(!ha(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function kr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function vr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Rt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var ga=/^[a-z][a-z0-9-]{1,62}$/,Tr=1024,ya=new Set(["userId","uploadId","filename"]);function Rd(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!ga.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=wa(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,l)=>{if(typeof d!="string"||l===void 0||typeof l.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ue(o.constructor,Ie,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function Od(){return pe("uploadedObject")}function wa(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ya.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!$r(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function $r(e){if(e===""||new TextEncoder().encode(e).byteLength>Tr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function ba(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ka(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ka(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function Er(e,t){let n=ba(e,t);return $r(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Tr} bytes)`}}function Sr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var dn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function _r(e,t){if(!dn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Ge(t.user);if(!o)return"user is { id?, session?, role }";let d=kr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=va(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function va(e){if(!dn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:m,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||m!==void 0&&typeof m!="string")&&!(!dn(y)||!Object.values(y).every(v=>typeof v=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...m!==void 0?{thumbhash:m}:{},variants:{...y}}}import{markData as Ta}from"palgres";var Oe=Symbol.for("palbase.backend.gateway"),Be=Symbol.for("palbase.backend.gatewayHooks"),xr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},$a={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(xr),output:()=>structuredClone(xr)}}},Mr=Symbol.for("palbase.backend.gatewayRefusal"),Rr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Mr,{value:!0})}},Ea=e=>typeof e=="object"&&e!==null&&e[Mr]===!0&&typeof e.reason=="string",Ke=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Sa=6e4,_a=86400,Or=604800,Ar=65536,$e=255,xa=["roles:","flags:","messaging:","debug:"],Ra=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Fe=e=>new TextEncoder().encode(e).byteLength,cn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",fn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Oa(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Fe(e)>$e)return`a channel is ${$e} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=xa.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Dr(e){if(typeof e!="string"||e==="")return"is a name";if(Fe(e)>$e)return`is ${$e} bytes at most`}function Dd(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Oa(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&fn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Aa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||Ra.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,v]of Object.entries(d)){let S=Dr(y);if(S)throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" ${S}`);if(!cn(v))throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=ue(a,Be,pn),m={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:$a}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Sa,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(m.access===void 0&&m.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(m.access!==void 0&&m.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${m.access}' and @Authorize both say who may join \u2014 keep one`);if(m.publish&&Ke(m))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(m.publish&&m.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(m.chat&&!Ke(m))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ue(a,Oe,()=>m),se().add(a)}}function Aa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return _a;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Or)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Or} (a week)`);return n}var pn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Pa={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function at(e){let t=Pa[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ue(n.constructor,Be,pn),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var Nd=at("authorize"),Ud=at("first"),Ld=at("connect"),Id=at("disconnect"),zd=at("empty");function qd(e,t,n={}){let r=Dr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!cn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!cn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=ue(s.constructor,Be,pn),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ca(e){return D(e,Oe)}function ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Nr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Fe(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Ma(e,t,n){let r=fn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Nr(e,t):Da(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Da(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Na=1e4,Ua=1e3,La=100,mn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Pr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Cr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Ur(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:w,instance:_}of e){let b=Ca(w),x=a.get(b.name);if(x!==void 0&&x!==w)throw new TypeError(`@Gateway("${b.pattern}"): two gateways are named ${b.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(b.name,w);let C=s.get(Cr(b.pattern));if(C!==void 0)throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: ${n.get(C)?.cls.name}'s "${C}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Cr(b.pattern),b.pattern);for(let[F,B]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([q,I])=>[`message ${q}`,I.fn])])if(typeof _[B]!="function")throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: its ${F} is ${B}, which is no method of it`);let N={cls:w,instance:_,g:b};n.set(b.pattern,N),r.set(w,N)}let o=new Map,d=new Set,l=new Set,m=new ln(t.broadcast),y=w=>{let _=o.get(w);return _||(_=new AbortController,o.set(w,_)),_},v=(w,_)=>{_?.abort(),o.get(w)===_&&o.delete(w)},S=(w,_,b,x,C,N)=>{if(!Object.hasOwn(w.g.events,b)){E.warn(`[palbase] ${C}: emit("${b}") is not sent \u2014 ${w.cls.name} declares no event "${b}" (static events)`);return}if(w.g.chat&&b==="chat"){E.warn(`[palbase] ${C}: emit("chat") is not sent \u2014 ${w.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}m.send({topic:_,event:b,payload:x??{},...N!==void 0?{conn_id:N}:{}},C)},G=async(w,_,b)=>{if(typeof w!="object"||w===null||typeof w.pipe!="function")throw new TypeError(`${b}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await w.pipe(_)};function U(w,_,b,x,C,N,F){let B=x?.signal??AbortSignal.abort(),q=`${w.cls.name} (${_})`;return{channel:_,params:Object.freeze({...b}),signal:B,count:C,user:N,emit:(I,V)=>S(w,_,I,V,q,F),pipe:I=>G(I,_,q),owner:{hold(I){re.exit(async()=>{try{await I(B)}catch(V){B.aborted||E.error(`[palbase] ${q}: a task owner.hold ran failed`,{error:V})}}).catch(()=>{})},release:()=>v(_,x)}}}function L(w){let{room:_,channel:b}=w;if(typeof _!="string"||typeof b!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let x=n.get(_);return!x||!Ke(x.g)?he(404,"not_found",`This app serves no gateway "${_}"`):{entry:x,channel:b,params:ja(_,b)}}let Q=(w,_)=>he(400,"bad_request",`"${_}" is not a channel of the gateway "${w}"`);async function ee(w,_){let b=L(w);if("status"in b)return b;let{entry:x,channel:C,params:N}=b,F={status:200,body:{subscribe:!1,publish:!1}};if(!N)return E.warn(`[palbase] ${x.cls.name}: realtime asked about "${C}", which is not a channel of the gateway "${x.g.pattern}"; the join is refused`),F;let B=Ge(w.user),q=B?.id;if(!q)return F;if(x.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}};if(x.g.access==="owner")return N[fn(x.g.pattern)[0].slice(1,-1)]===q?{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}}:F;let I=x.g.hooks.authorize;if(!I)return F;let V,W;try{V=await t.run(B,`${x.cls.name}.${I}`,_,async()=>x.instance[I]({user:{id:q},params:Object.freeze({...N})})),W=Ia(V)}catch(ie){if(t.isOutage(ie)||_?.aborted)throw ie;return E.error(`[palbase] ${x.cls.name}.${I} (@Authorize of ${C}) failed; the join is refused`,{error:ie}),F}return W==="malformed"?(E.warn(`[palbase] ${x.cls.name}.${I} (@Authorize of ${C}) answered ${za(V)}, which is no grant (true, { read, write } or null); the join is refused`),F):{status:200,body:W}}async function ae(w,_){let b=L(w);if("status"in b)return b;if(!b.params)return Q(b.entry.g.pattern,b.channel);let x=Ge(w.user);if(!x?.id||typeof w.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let C=Object.hasOwn(b.entry.g.messages,w.event)?b.entry.g.messages[w.event]:void 0;if(!C)return{status:200,body:{ok:!1,reason:un(`gateway "${b.channel}" takes no message "${w.event}"`,Ot)}};let N=await C.schema["~standard"].validate(Ta(w.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:jr(N.issues)}};let F=y(b.channel),B={...U(b.entry,b.channel,b.params,F,0,{id:x.id}),payload:N.value},q=`${b.entry.cls.name}.${C.fn} (@Subscribe "${w.event}" of ${b.channel})`,I;try{I=await t.run(x,`${b.entry.cls.name}.${C.fn}`,_,async()=>b.entry.instance[C.fn](B))}catch(W){if(t.isOutage(W))throw W;return Ea(W)?{status:200,body:{ok:!1,reason:un(W.reason,Ot)}}:(_?.aborted||E.error(`[palbase] ${q} failed`,{error:W}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(C.reply){let W=await C.reply["~standard"].validate(I);if(W.issues)return E.error(`[palbase] ${q} returned an ack its reply schema refuses (${jr(W.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=W.value}let V;try{V=JSON.stringify(I)}catch(W){return E.error(`[palbase] ${q} returned an ack that is not JSON; the member is told it failed`,{error:W}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return V===void 0?{status:200,body:{ok:!0}}:Fe(V)>Ar?(E.error(`[palbase] ${q} returned an ack of ${Fe(V)} bytes, past ${Ar}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(V)}}}async function k(w,_){let b=L(w);if("status"in b)return b;if(!b.params)return Q(b.entry.g.pattern,b.channel);let x=w.event;if(typeof x!="string"||!Object.hasOwn(Pr,x))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let C=typeof w.count=="number"&&Number.isInteger(w.count)&&w.count>=0?w.count:void 0;if(C===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let N=x==="join"||x==="leave",F=N?Ge(w.user):void 0,B=N?w.connId:void 0;if(N&&(!F?.id||typeof B!="string"||B===""))return he(400,"bad_request",`A ${x} names its member: user and connId`);let q=`${x}\0${b.channel}\0${typeof B=="string"?B:""}`;if(N&&d.has(q))return{status:204};if(l.has(q))return he(503,"in_progress","This moment of the gateway is being handled",5);l.add(q);try{let I=b.entry.g.hooks[Pr[x]],V;if(x==="empty"?(V=o.get(b.channel),v(b.channel,V)):V=x==="leave"?o.get(b.channel):y(b.channel),I){let W=U(b.entry,b.channel,b.params,V,C,{id:F?.id??""},x==="join"?B:void 0);try{await t.run(F,`${b.entry.cls.name}.${I}`,_,async()=>b.entry.instance[I](W))}catch(ie){if(t.isOutage(ie))throw ie;return _?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${I} (${x} of ${b.channel}) failed; realtime tells it again`,{error:ie}),he(500,"handler_failed",`The gateway's ${x} could not be handled`)}}return N&&(d.add(q),d.size>Na&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(q)}}function X(w,_){let b=r.get(w),x=`Palbase.gateways.to(${w?.name??String(w)})`;if(!b)throw new TypeError(`${x}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let C=Nr(b.g.pattern,_??{});if(typeof C!="string")throw new TypeError(`${x}: ${C.problem}`);return{entry:b,channel:C,where:x}}return{declarations:[...n.values()].map(w=>w.g),async serve(w,_,b){return mn(_)?w==="authorize"?ee(_,b):w==="message"?ae(_,b):w==="lifecycle"?k(_,b):he(404,"not_found",`No gateway call ${JSON.stringify(w)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(w,_,b,x){let{entry:C,channel:N,where:F}=X(w,_);S(C,N,b,x,F)},async pipe(w,_,b){let{channel:x,where:C}=X(w,_);await G(b,x,C)},async revalidate(w,_,b={}){let x=r.get(w),C=`Palbase.gateways.to(${w?.name??String(w)}).revalidate`;if(!x)throw new TypeError(`${C}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=Ma(x.g.pattern,_??{},b);if("problem"in N)throw new TypeError(`${C}: ${N.problem}`);await t.revalidate(N)},close(){for(let w of o.values())w.abort();o.clear()}}}function Ia(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!mn(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function za(e){return Array.isArray(e)?"an array":mn(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var qa=20,Ot=256;function jr(e){let t="";for(let n of e.slice(0,qa)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ot)break}return un(t,Ot)}function un(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var ln=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Fe(t.event)>$e){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){E.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ua?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),re.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,La);try{await this.broadcast(s)}catch(o){E.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),E.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as hn,createHmac as Ha,createPublicKey as qr,timingSafeEqual as Ga,verify as Hr}from"node:crypto";function Fd(e){let t=D(e,ze);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function Gr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,ze),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let m=`@Webhook "${d.name}" (${o.name})`,y=n[d.secret.env],v;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${m} reads its signing secret from ${d.secret.env}, which is not set`);else try{v=Ka(d,y)}catch(U){a.push(`${m}: ${d.secret.env} ${U.message}`)}let S=t(o),G=new Map(d.events.map(({event:U,fn:L})=>[U,{name:`${o.name}.${L}`,call:(Q,ee)=>S[L](Q,ee)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:v,events:G})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
+ - ${a.join(`
4
+ - `)}`);return s}function Kr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Je=1024,Lr=1024*Je;function Ka(e,t){if(e.signature)return Ae(void 0,e.signature.header,1/0,to(e.signature,t));switch(e.provider){case"stripe":return Ae("stripe","stripe-signature",512*Je,Ja(t));case"github":return Ae("github","x-hub-signature-256",25*Lr,Wa(t));case"slack":return Ae("slack","x-slack-signature",64*Je,Va(t));case"discord":return Ae("discord","x-signature-ed25519",64*Je,Za(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Je),check:Qa(t)};case"sendgrid":return Ae("sendgrid","x-twilio-email-event-webhook-signature",Lr,Xa(t));case"livekit":return Ae("livekit","authorization",512*Je,eo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function Ae(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??Fr(e,s)}}function Fr(e,t){let n=gn(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:Br(e,t.headers,r),event:r,...Fa(e,t,r)}}function Br(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Pe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Vr(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return Pe(n,"EventType");case"livekit":return Pe(n,"event");default:return Pe(n,"type")}}function Fa(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Pe(n,"id"));case"slack":return r(Pe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${Jr(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Pe(s,"sg_event_id")||void 0)}:{};default:return{}}}var Ba=300;function Ja(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let l of r.split(",")){let m=l.indexOf("=");if(m<=0)continue;let y=l.slice(0,m).trim(),v=l.slice(m+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=v}else if(y==="v1"){let S=me(v,"hex");if(!S)return"malformed_signature";a.push(S)}}let o=ot(s);if(o===void 0||a.length===0)return"malformed_signature";if(it(o,n))return"stale_timestamp";let d=We("sha256",e,`${s}.`,t.body);return a.some(l=>Ee(l,d))?void 0:"signature_mismatch"}}function Wa(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?Ee(r,We("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function Va(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ot(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":it(a,n)?"stale_timestamp":Ee(o,We("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function Za(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=qr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ot(o),l=me(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":it(d,s)?"stale_timestamp":Hr(null,Wr(o,r.body),n,l)?void 0:"signature_mismatch"}}var Ya=1e3;function Qa(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!Ee(Buffer.from(a.toLowerCase()),Buffer.from(hn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let G=1;for(let Q of t.body)if(Q===38&&++G>Ya)return"malformed_signature";let U=new Map;for(let[Q,ee]of new URLSearchParams(gn(t.body))){let ae=U.get(Q);ae||U.set(Q,ae=new Set),ae.add(ee)}let L=[];for(let Q of[...U.keys()].sort()){let ee=[...U.get(Q)].sort();for(let ae of ee)o+=Q+ae;L.push([Q,ee.length===1?ee[0]:ee])}d=Object.fromEntries(L)}let l=s.protocol==="https:"?"443":"80",m=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![m,y].some(G=>Ee(r,We("sha1",e,G,o))))return"signature_mismatch";let v=t.headers.get("i-twilio-idempotency-token"),S=v?{id:`${v}:${Jr(`${m}
5
+ ${o}`)}`}:{};return d?{type:Br("twilio",t.headers,d),event:d,...S}:{...Fr("twilio",t),...S}}}function Xa(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=qr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=ot(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":it(o,r)?"stale_timestamp":Hr("sha256",Wr(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Ir=60;function eo(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=zr(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Ee(o,We("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=zr(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Ir||typeof d.nbf=="number"&&n<d.nbf-Ir)return"stale_timestamp";let l=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return l&&Ee(l,hn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function to(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let m=ot(d);if(m===void 0)return"malformed_signature";if(it(m,a))return"stale_timestamp"}let l=me(o.trim(),e.encoding);return l?Ee(l,We(r,t,...n.map(m=>m==="{body}"?s.body:m==="{ts}"?d:m)))?void 0:"signature_mismatch":"malformed_signature"}}var no=new TextEncoder;function We(e,t,...n){let r=Ha(e,t);for(let s of n)r.update(s);return r.digest()}function Jr(e){return hn("sha256").update(e).digest("hex")}function Wr(e,t){return Buffer.concat([no.encode(e),t])}function Ee(e,t){return e.byteLength===t.byteLength&&Ga(e,t)}var ro={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return ro[t].test(e)?Buffer.from(e,t):void 0}function ot(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function it(e,t){return Math.abs(t-e)>Ba}function gn(e){return new TextDecoder().decode(e)}function zr(e){if(e)try{return JSON.parse(gn(e))}catch{return}}function Vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e,t){let n=Vr(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var J=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
6
+ Kind: ${t}
7
+ Path: ${n.join(" -> ")}
8
+ At: ${r}
9
+ ${s}
10
+
11
+ Potential solutions:
12
+ ${a.map(o=>` - ${o}`).join(`
13
+ `)}`),this.name="DiError",this.kind=t,this.path=n}},so=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],ao=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),At=class{owner=new Map;defs=new Map;instances=new Map;providers=new Set;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];templateProviders=[];gateways=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let a=D(r,Qt);if(!a)throw new J("unknown import",[...s,r.name],r.name,`${r.name} is not a @Module`,["decorate it with @Module({ \u2026 })","or list the module itself, not one of its classes"]);this.defs.set(r,a);for(let o of a.imports){if(o===r)throw new J("unknown import",[r.name],r.name,`${r.name} imports itself`,["remove it from its own imports"]);n(o,[...s,r.name])}};for(let r of t)n(r,[]);for(let[r,s]of this.defs){for(let a of[...s.controllers,...s.providers]){let o=this.owner.get(a);if(o&&o!==r)throw new J("duplicate ownership",[o.name,a.name,r.name],a.name,`${a.name} is listed by ${o.name} and by ${r.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(a,r)}for(let a of s.providers)this.providers.add(a);for(let a of s.controllers){if(!D(a,Le))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is in ${r.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(D(a,Te))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Cron: a cron is a provider's`,["give the cron a class of its own \u2014 @Cron({ name, schedule }) with run(meta) \u2014 listed in the module's providers"]);if(D(a,be))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Task: a task is a provider's`,["give the task a class of its own \u2014 @Task({ name }) with run(payload, meta) \u2014 listed in the module's providers"]);if(D(a,ke))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @TestUserTemplate: a template is a provider's`,["give the template a class of its own \u2014 @TestUserTemplate({ name }) with seed(user, meta) \u2014 listed in the module's providers"]);if(D(a,Oe)||D(a,Be))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Gateway: a gateway is a provider's`,["give the gateway a class of its own, listed in the module's providers"]);this.controllers.push({cls:a,module:r})}}}validate(){for(let t of se())if(!this.owner.has(t))throw new J("unowned class",[t.name],t.name,`${t.name} is declared but no module lists it: it would never be built`,["list it in a module's controllers or providers","or delete it"]);for(let[t,n]of this.defs){for(let r of n.exports)if(this.owner.get(r)!==t)throw new J("unknown export",[t.name,r.name],t.name,`${t.name} exports ${r.name}, which it does not own`,[`list ${r.name} in ${t.name}'s providers`,"or export it from the module that owns it"]);for(let r of n.providers){if(D(r,Be)&&!D(r,Oe))throw new J("undeclared provider",[t.name,r.name],r.name,`${r.name} has a gateway's methods (@Authorize, @OnFirst, @Subscribe\u2026) but is no @Gateway`,["decorate it with @Gateway(pattern, options)"]);if(!D(r,Yt)&&!D(r,Re)&&!D(r,Oe)&&!D(r,Te)&&!D(r,be)&&!D(r,ke)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new J("metadata missing",[t.name,r.name],r.name,`${r.name} has constructor parameters but no emitted types`,["decorate it with @Injectable()","enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json"]):new J("undeclared provider",[t.name,r.name],r.name,`${r.name} is in ${t.name}'s providers but is not @Injectable() (nor an @On handler, a @Gateway, a @Cron, a @Task or a @TestUserTemplate)`,["decorate it with @Injectable()"])}D(r,Oe)&&this.gateways.push(r),D(r,ze)?this.webhooks.push(r):D(r,Re)&&this.eventProviders.push(r),D(r,Te)&&this.cronProviders.push(r),D(r,be)&&this.taskProviders.push(r),D(r,ke)&&this.templateProviders.push(r)}}for(let t of this.owner.keys())for(let n of so)if(typeof t.prototype[n]=="function")throw new J("nest lifecycle name",[t.name],`${t.name}.${n}`,`${n} is NestJS's; it is never called here`,["use onStart() and onShutdown()"]);for(let t of this.owner.keys())this.resolve(t,[])}get(t){let n=this.instances.get(t);if(!n)throw new Error(`${t.name} is not built by this app`);return n}resolve(t,n){let r=this.instances.get(t);if(r)return r;if(n.includes(t.name))throw new J("dependency cycle",[...n,t.name],t.name,`${[...n,t.name].join(" -> ")} goes round`,["move the shared part into a third class both depend on"]);let s=[...n,t.name],a=t.length,o=Reflect.getMetadata("design:paramtypes",t)??[];if(a>0&&o.length===0)throw new J("metadata missing",s,t.name,`${t.name} takes ${a} constructor parameter(s) but no types were emitted`,["enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json","build with tsc, Bun or SWC (esbuild does not emit them)"]);let d=[];o.slice(0,a).forEach((m,y)=>{if(ao.has(m)||typeof m!="function")throw new J("unresolvable dependency",s,`${t.name} constructor parameter ${y}`,`parameter ${y} of ${t.name} is typed as ${m===void 0?"something with no runtime class":m.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);d.push(this.resolve(this.reachable(t,m,s),s))});let l=new t(...d);return this.instances.set(t,l),this.order.push(l),l}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}provider(t,n){if(typeof t!="function")throw new TypeError(`${n}: inject takes a provider's class \u2014 it was given ${t===null?"null":typeof t}`);let r=t;if(!this.owner.has(r)&&![...this.owner.keys()].some(a=>a.prototype instanceof r))throw new J("unowned class",[n,r.name],r.name,`${n} asks for ${r.name}, which no module provides: the app built none`,[`list ${r.name} in a module's providers`]);let s=this.target(r,[n]);if(!this.providers.has(s))throw new J("undeclared provider",[n,s.name],s.name,`${s.name} is a controller: only a module's providers are given`,[`move what ${n} needs into a provider, listed in a module's providers`]);return this.get(s)}reachable(t,n,r){let s=this.owner.get(t),a=this.target(n,r),o=this.owner.get(a);if(o!==s){if(!this.defs.get(s).imports.includes(o))throw new J("missing import",[...r,a.name],`${s.name}`,`${t.name} (in ${s.name}) needs ${a.name}, owned by ${o.name}, which ${s.name} does not import`,[`add ${o.name} to ${s.name}'s imports (imports are not transitive)`]);if(!this.defs.get(o).exports.includes(a))throw new J("private dependency",[...r,a.name],`${o.name}`,`${a.name} is ${o.name}'s own: it is not in its exports`,[`add ${a.name} to ${o.name}'s exports`])}return a}target(t,n){if(this.owner.has(t))return t;let r=[...this.owner.keys()].filter(s=>s.prototype instanceof t);if(r.length===1)return r[0];throw r.length>1?new J("duplicate ownership",[...n,t.name],t.name,`${t.name} has ${r.length} owned subclasses (${r.map(s=>s.name).join(", ")}): which one is meant cannot be told`,["ask for the subclass itself"]):new J("unowned class",[...n,t.name],t.name,`${t.name} is needed but no module lists it`,[`list ${t.name} in a module's providers (and export it if another module needs it)`])}async start(){let t=[];for(let n of this.order){let r=n.onStart;if(typeof r=="function")try{await r.call(n)}catch(s){throw await this.shutdown(t),new Error(`[palbase] ${n.constructor.name}.onStart() failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}t.push(n)}}async shutdown(t=this.order){for(let n of[...t].reverse()){let r=n.onShutdown;if(typeof r=="function")try{await r.call(n)}catch(s){console.error(`[palbase] ${n.constructor.name}.onShutdown() failed`,s)}}}};import{HTTP_ERROR_BRAND as oo,HttpError as dt}from"palgres";import{z as Se}from"zod";import{BadRequest as nc,Conflict as rc,DeadlockDetected as sc,HttpError as ac,NotFound as oc,SerializationFailure as ic,TooManyRequests as dc,UniqueViolation as cc}from"palgres";function ct(e){if(typeof e!="object"||e===null||e[oo]!==!0)return!1;let t=e;return Number.isInteger(t.status)&&t.status>=400&&t.status<=599&&typeof t.error=="string"&&typeof t.errorDescription=="string"}var Zr=class extends dt{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},Yr=class extends dt{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},Qr=class extends dt{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function es(e,t){let n={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(n.data=e.data),n}var io=Symbol.for("palbase.backend.errorRegistry"),co={bad_request:Se.object({fields:Se.array(Se.object({field:Se.string(),message:Se.string()})),more:Se.number().int().optional()}),too_many_requests:Se.object({retryAfter:Se.number().int()})},uo=new Set(["auth_unavailable","check_failed","client_closed_request","database_unavailable","duplicate_upload","email_not_verified","handler_failed","idempotency_key_in_use","idempotency_key_reused","in_progress","internal_error","invalid_idempotency_key","invalid_signature","invalid_token","job_failed","job_not_found","method_not_allowed","missing_signature","payload_too_large","service_unavailable","signature_mismatch","temporarily_unavailable","unknown_token","upload_required","webhook_secret_missing"]);function lo(){let e=new Map;for(let[t,n,r]of[["bad_request",400,"BadRequest"],["unauthorized",401,"Unauthorized"],["forbidden",403,"Forbidden"],["not_found",404,"NotFound"],["conflict",409,"Conflict"],["unique_violation",409,"UniqueViolation"],["too_many_requests",429,"TooManyRequests"]]){let s=co[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function fo(){let e=globalThis;return e[io]??=lo()}var po=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function Xd(e,t,n){if(typeof e!="string"||e.length>100||!po.test(e))throw new TypeError(`defineError(code, status): code is a wire code like room_locked or invite.notFound \u2014 a letter, then letters and digits in parts joined by . _ or - \u2014 not ${JSON.stringify(e)}`);if(!Number.isInteger(t)||t<400||t>599)throw new TypeError(`defineError("${e}", status): status is a 4xx or 5xx integer, not ${String(t)} \u2014 an error is never a success`);if(n!==void 0&&typeof n?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if(uo.has(e))throw new TypeError(`defineError("${e}", ${t}): "${e}" is the framework's own answer \u2014 a client would read the framework's refusal as the project's error; give the project's its own code`);let r=fo(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&Xr(s.data)!==Xr(n)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${s.builtin?`the built-in ${s.className}`:`defined with status ${s.status}${s.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let a=e.split(/[._-]/).flatMap(S=>S.split(/(?=[A-Z])/)),o=a.map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(""),d=a.map(S=>S.toLowerCase()).join(" "),l=d.charAt(0).toUpperCase()+d.slice(1),v=n?(S=>class extends dt{static code=e;static status=t;constructor(G,U){let L=mo(e,S,G);super(t,e,U??(typeof L=="string"?L:l),L),this.name=o}})(n):class extends dt{static code=e;static status=t;constructor(S){super(t,e,S??l),this.name=o}};return Object.defineProperty(v,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),v}function mo(e,t,n){let r=t["~standard"].validate(n);if(r instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(r.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${r.issues.map(s=>s.message).join("; ")}`);return r.value}function Xr(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as ho}from"palgres";var ts="/_palbase/ai/tools",ns="/_palbase/ai/agents",rs="/_palbase/ai/repos",Ze=4<<20,go=Symbol.for("palbase.ai.tool_error");function ss(e){return e instanceof Error&&e[go]===!0}var yo=Symbol.for("palbase.ai.declared");function as(){let e=globalThis[yo];if(!e)return{tools:new Map,agents:new Map,repos:new Map,repoTokens:void 0};if(e.twice.size>0){let t=[...e.twice].map(n=>n.replace(":"," "));throw new TypeError(`[palbase] ${t.join(", ")}: declared twice with different values \u2014 an ai.tool's and an ai.agent's name is its own, and ai.repoTokens is given once; make each once, at a module's top level`)}return{tools:new Map(e.tools),agents:new Map(e.agents),repos:new Map(e.repos??[]),repoTokens:e.repoTokens}}var Ve=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function os(e){let t={};if(e==null)return t;if(Ve(e)){for(let[n,r]of Object.entries(e)){if(typeof r!="string")return;Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0})}return t}}function is(e){if(!Ve(e))return"context is {chat_id, agent, user, metadata}";if(typeof e.chat_id!="string")return"context.chat_id is the chat (empty for a one-shot answer's call)";if(typeof e.agent!="string")return"context.agent is the agent's name";let t=null;if(e.user!==null&&e.user!==void 0){if(!Ve(e.user)||typeof e.user.id!="string"||e.user.id===""||e.user.name!==void 0&&typeof e.user.name!="string")return"context.user is {id, name}, or null";t={id:e.user.id,name:typeof e.user.name=="string"?e.user.name:""}}let n=os(e.metadata);return n===void 0?"context.metadata is an object of strings":{chatId:e.chat_id,agent:e.agent,user:t,metadata:n}}function ds(e){let t=is(e);if(typeof t=="string")return t;let n=e;return typeof n.turn_id!="string"||typeof n.run_id!="string"?"context.turn_id and context.run_id are the turn the call is made in and the run that made it":n.subagent!==null&&typeof n.subagent!="string"?"context.subagent is the subagent that made the call, or null":{...t,turnId:n.turn_id,runId:n.run_id,subagent:n.subagent}}function cs(e){let t=is(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=Ve(a)?os(a.metadata):void 0;if(!Ve(a)||typeof a.id!="string"||typeof a.client_id!="string"||a.author!==null&&typeof a.author!="string"||typeof a.author_name!="string"||typeof a.text!="string"||typeof a.delivery!="string"||o===void 0)return"message is {id, client_id, author, author_name, text, delivery, metadata}, or null";r={id:a.id,clientId:a.client_id,author:a.author,authorName:a.author_name,text:a.text,delivery:a.delivery,metadata:ho(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!Ve(n.goal)||typeof n.goal.objective!="string"||typeof n.goal.rubric!="string")return"goal is {objective, rubric}";s={objective:n.goal.objective,rubric:n.goal.rubric}}return{...t,message:r,goal:s}}var wo=1e4,bo=10*6e4,Pt=class{constructor(t=Date.now){this.now=t}now;seen=new Map;take(t){let n=this.now();for(let[r,s]of this.seen){if(n-s<=bo&&this.seen.size<=wo)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},ko=1e3,vo=256*1024,Ct=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,n){this.running.delete(t),!(n===void 0||n.answer.length>vo)&&(this.answers.set(t,n),this.answers.size>ko&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as Ls,isEngineRaised as Cn,markData as fe}from"palgres";import{createHash as Is}from"node:crypto";import{createHash as To,randomInt as $o}from"node:crypto";import{ago as yn,isRetryable as Eo,now as us}from"palgres";import{defineSchema as So,defineTable as _o,index as xo,integer as Ro,jsonb as Oo,raw as Ao,text as wn,timestamp as ls}from"palgres/dsl";var ws=new Set(["POST","PUT","PATCH","DELETE"]),fs=255,ps=35,ms=24,Po=65536,hs=1e3,Co=64,kn={description:"Makes the write safe to send again (at most 255 characters). A retry with the same key and the same request gets the first answer back, marked `Idempotent-Replayed: true`, and changes nothing; the same key with a different request is refused with 422, and while the first request still runs a retry gets 409 with Retry-After. Answers are kept for 24 hours.",in:"header",name:"Idempotency-Key",required:!1,schema:{maxLength:255,type:"string"}},jo=_o("idempotency_keys",{columns:{key:wn().primaryKey(),fingerprint:wn(),started_at:ls().defaultNow(),completed_at:ls().nullable(),status_code:Ro().nullable(),response_headers:Oo().nullable(),response_body:wn().nullable()},indexes:e=>[xo("idempotency_keys_started").on(e.col("started_at"))]}),wc=So("palbase",{tables:[jo],raw:[Ao("idempotency_answer",`CREATE OR REPLACE FUNCTION palbase.idempotency_answer(record_key text, claimed_at timestamptz, answer_status integer, answer_headers jsonb, answer_body text) RETURNS boolean
14
+ LANGUAGE sql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp
15
+ AS $answer$
16
+ UPDATE palbase.idempotency_keys
17
+ SET completed_at = now(), status_code = answer_status, response_headers = answer_headers, response_body = answer_body
18
+ WHERE key = record_key AND started_at = claimed_at AND completed_at IS NULL
19
+ RETURNING true
20
+ $answer$`,{drop:"DROP FUNCTION IF EXISTS palbase.idempotency_answer(text, timestamptz, integer, jsonb, text)"})]}),Mo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Do={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},No={status:409,code:"idempotency_key_in_use",message:"This request's Idempotency-Key was taken over by a retry; what it did is not kept",retryAfter:1},gs={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},Mt=class extends Error{};function ut(e){return ws.has(e.method)&&e.meta.upload===void 0}function bs(e,t){if(!ws.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Uo(e,t){return ks([e.role,e.uid,t]).digest("hex")}function Lo(e){return ks([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function ks(e){let t=To("sha256");for(let n of e)t.update(n).update("\0");return t}function Io(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function bn(e){return e<500&&e!==429&&e!==499}function zo(e,t){return t&&bn(e)}function vs(e){let t=e["~standard"].jsonSchema?.input,n;try{n=t?.({target:"draft-2020-12"})}catch{return!1}let r=n?.properties;return typeof r=="object"&&r!==null&&Object.keys(r).some(s=>s.toLowerCase()==="idempotency-key")}var qo={role:"service",claims:{}},Ho={seal:e=>e,open:async e=>e},Dt=class{db;answers;constructor(t,n=Ho){this.db=t,this.answers=n}async serve(t,n,r){if(t.key.length>fs)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${fs} characters`});let s;try{s=await this.begin(Uo(t.caller,t.key),Lo(t))}catch(d){return E.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:d}),r.refusal(gs)}if("kept"in s){let d;try{d=s.kept.body===null?null:await this.answers.open(s.kept.body)}catch(l){return E.warn("[palbase] the answer kept against an Idempotency-Key could not be opened; the write is not run again",{error:l}),r.refusal(gs)}return Go({...s.kept,body:d},r.requestId)}if("refused"in s)return r.refusal(s.refused==="reused"?Mo:Do);let a=s.claim,o;try{o=await n(d=>this.record(a,d))}catch(d){if(d instanceof Mt)return r.refusal(No);let l=r.failure(d);return zo(l.status,r.ran())&&!Eo(d)?this.keep(a,l):(await this.release(a),l)}return bn(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:yn({hours:ms})}}}))}async begin(t,n){return $o(Co)===0&&await this.sweep().catch(r=>E.warn("[palbase] the expired Idempotency-Keys could not be taken away; the next sweep tries again",{error:r})),this.asService(async r=>{for(let s=0;s<3;s++){let[a]=await r.insertMany([{key:t,fingerprint:n}],{onConflict:["key"],action:"ignore"});if(a)return{claim:{key:t,started:a.started_at}};if(await r.deleteMany({where:{key:t,started_at:{lt:yn({hours:ms})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let d=Io(o,n);if(d==="reused")return{refused:"reused"};if(d==="replay")return{kept:{status:o.status_code,headers:o.response_headers??[],body:o.response_body}};let[l]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:yn({seconds:ps})}},set:{started_at:us()}});return l?{claim:{key:t,started:l.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!bn(n.status))return n;let{response:r,kept:s}=await ys(n),a=re.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let o=s.body===null?null:this.answers.seal(s.body),[d]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),o]);if(d?.answered!==!0)throw new Mt;return r}async keep(t,n){let{response:r,kept:s}=await ys(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:us(),status_code:s.status,response_headers:s.headers,response_body:s.body===null?null:this.answers.seal(s.body)}}))}catch(a){E.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:a})}return r}async release(t){if(await this.releaseOnce(t))return;let n=Date.now()+ps*1e3,r=()=>{Date.now()+hs>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},hs).unref()};r()}async releaseOnce(t){try{return await this.asService(n=>n.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let n=this.db.request(qo),r;try{r=await t(n.database.palbase.idempotency_keys)}catch(s){throw await n.rollback(s).catch(()=>{}),s}try{await n.commit()}catch(s){throw await n.rollback(s).catch(()=>{}),s}return r}};function Go(e,t){let n=new Headers(e.headers);return n.set("x-request-id",t),n.set("idempotent-replayed","true"),new Response(e.body===null?null:Buffer.from(e.body,"base64"),{status:e.status,headers:n})}var jt=Symbol("waits");function Ko(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(jt));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function ys(e){let t=[];e.headers.forEach((d,l)=>{l!=="x-request-id"&&t.push([l,d])});let n=d=>new Response(d,{status:e.status,statusText:e.statusText,headers:e.headers});if(e.body===null)return{response:n(null),kept:{status:e.status,headers:t,body:null}};let r=e.body.getReader(),s=[],a=0;for(;;){let d=r.read(),l=await Ko(d);if(l!==jt&&l.done)break;if(l!==jt&&(s.push(l.value),a+=l.value.byteLength,a<=Po))continue;let m=l===jt?d:void 0,y=new ReadableStream({start(v){for(let S of s)v.enqueue(S)},async pull(v){let S=await(m??r.read());m=void 0,S.done?v.close():v.enqueue(S.value)},cancel:v=>r.cancel(v)});return{response:n(y),kept:{status:e.status,headers:t.filter(([v])=>v!=="content-length"&&v!=="content-encoding"),body:null}}}let o=Buffer.concat(s);return{response:n(o),kept:{status:e.status,headers:t,body:o.byteLength===0?null:o.toString("base64")}}}import{createHash as Fo}from"node:crypto";var vn="/webhooks/palbase",xs="PalbaseErrorEnvelope",Ts="PalbaseBearer",Bo={$ref:`#/components/schemas/${xs}`},Jo={type:"object",description:"Every refusal: the framework's, a handler's HttpError, the database's.",properties:{error:{type:"string",description:"A stable code, like bad_request"},error_description:{type:"string",description:"What went wrong, for a person"},status:{type:"integer",description:"The HTTP status"},request_id:{type:"string",description:"The request's id, as the app's log has it"},data:{description:"Details, when the refusal has them: a validation's fields, a token's reason, a limit's retryAfter"}},required:["error","error_description","status","request_id"]},$s={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Ye={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Rs(e,t,n){let r={[xs]:Jo},s={},a=[],o=[],d=new Set,l=new Map;for(let k of e){let X=o.find(Y=>Zo(Y,k));if(X){a.push({route:k.id,handler:Es(k),answeredBy:X.id});continue}o.push(k);let w=k.segments.map(Y=>typeof Y=="string"?Y:"{}").join("/");l.has(w)||l.set(w,Qo(k.segments.flatMap(Y=>typeof Y=="string"?[]:[Y.param])));let _=l.get(w),b=0,x=`/${k.segments.map(Y=>typeof Y=="string"?Y:`{${_[b++]}}`).join("/")}`,C=t(k),N=Nt(Yo(k),d),F=k.method!=="GET"&&k.method!=="HEAD",B=Y=>{let Ce=k.params.filter(je=>je.kind===Y&&je.schema).map((je,Me)=>It(je.schema,`${N}.${Y}${Me===0?"":`.${Me+1}`}`,r));return Ce.length===0?void 0:Ce.length===1?Ce[0]:{allOf:Ce}},q=_.map(Y=>({name:Y,in:"path",required:!0,schema:{type:"string"}})),I=B("query");I&&q.push(..._s(I,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:I}]);let V=B("headers");V&&q.push(..._s(V,"header")??[]);let W=n.idempotency===!0&&ut(k);W&&q.push({...kn,schema:{...kn.schema}});let ie=F?B("body"):void 0,de={operationId:N};k.controller.name!==""&&(de.tags=[k.controller.name]),q.length>0&&(de.parameters=q),ie&&(de.requestBody={required:!ri(ie),content:{"application/json":{schema:ie}}});let ge=k.params.some(Y=>Y.schema!==void 0),ve=n.routes?.(k),_e=ai(N,ve?.throws??[],n.errors);de.responses={...si(ve,N,r),...di(C,{validates:ge,hasPathParams:_.length>0,readsBody:F,keyed:W}),...ii(_e,N,r)},_e.length>0&&(de["x-palbase-errors"]=oi(N,_e)),C.auth.required&&(de.security=[{[Ts]:[]}]),de["x-palbase-handler"]=Es(k);let Kt=k.params.some(Y=>Y.kind==="optionalUser")||n.databaseSeesCaller;de["x-palbase-auth"]=C.auth.required?"required":Kt?"optional":"public",de["x-palbase-verified-email"]=C.auth.verifiedEmail,de["x-palbase-rate-limit"]=C.limit===!1?!1:{max:C.limit.max,window:C.limit.window},k.meta.upload&&(de["x-palbase-upload"]={bucket:k.meta.upload.bucket,pathTemplate:k.meta.upload.pathTemplate}),(s[x]??={})[k.method.toLowerCase()]=de}for(let k of n.webhooks??[]){let X={operationId:Nt(`webhooks.${k.name}`,d)};k.cls!==""&&(X.tags=[k.cls]),X.description=k.provider?`${$s[k.provider]??k.provider}'s deliveries: verified with ${$s[k.provider]??k.provider}'s signature scheme under the secret in ${k.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${k.signatureHeader} header: verified under the secret in ${k.secretEnv}, then handed to the @On of their event type.`,X.responses={200:{description:"Taken: { ok: true, handled } \u2014 handled is false when no @On takes the event's type, and duplicate is true for a delivery already run; or the handler's answer: a Response as it is, text as text, anything else as JSON",content:{"application/json":{},[k.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:te("invalid_signature: the delivery is not signed with the secret \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:te("in_progress: the same delivery is being handled; the sender delivers it again",Ye),413:te("payload_too_large: the body is over what this sender sends"),500:te("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:te("service_unavailable, auth_unavailable or database_unavailable: what the handler needs of the platform did not answer \u2014 the sender delivers it again after Retry-After",Ye)},X["x-palbase-webhook"]=k.provider?{provider:k.provider,secretEnv:k.secretEnv,events:k.events}:{signatureHeader:k.signatureHeader,secretEnv:k.secretEnv,events:k.events},s[`/webhooks/${k.name}`]={post:X}}let m=[...new Set(n.platformEvents??[])].sort();if(m.length>0){let k={operationId:Nt("webhooks.palbase",d)};k.description="The project's events, delivered by the platform to the app's machine: verified under the secret in PALBASE_WEBHOOK_SECRET, then handed to the @On of their type \u2014 user.deleted first to forgetting the rows the app keeps of that user.",k.responses={204:{description:"Taken: handled, or a delivery already run"},401:te("invalid_signature: the delivery is not the platform's \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:te("in_progress: the same event is being handled; the platform delivers it again",Ye),500:te("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:te("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let X=[...new Set(n.platformEventBuckets??[])].sort();k["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:m,...X.length>0?{buckets:X}:{}},s[vn]={post:k}}let y=n.gateways??[],v=Wo(y,r),S=y.length>0,G=Object.fromEntries(y.filter(Ke).map(k=>[k.pattern,{events:v[k.name].events,messages:Object.fromEntries(Object.entries(v[k.name].messages).map(([X,w])=>[X,w.payload])),graceMs:k.graceMs,...k.logKeepSeconds>0?{logKeepSeconds:k.logKeepSeconds}:{}}])),U=Object.keys(G).length>0,L=y.filter(k=>!Ke(k)).map(k=>({pattern:k.pattern,kind:k.access,publish:k.publish,state_read:!1,state_write:!1,...k.logKeepSeconds>0?{log_keep_seconds:k.logKeepSeconds}:{}})),Q=L.length>0,ee={schemas:r,securitySchemes:{[Ts]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},ae={openapi:"3.2.0",info:{title:"Palbase backend",version:Fo("sha256").update(JSON.stringify({paths:s,components:ee,unreachable:a,...S?{gateways:v}:{},...U?{rooms:G}:{},...Q?{channels:L}:{}})).digest("hex").slice(0,12),description:"The routes this app serves, as its decorators declare them, and \u2014 when its source was read as the contract was written \u2014 what each answers and the errors it throws (x-palbase-errors). Every refusal is the PalbaseErrorEnvelope; a declared error's carries its code and its data."},paths:s,components:ee};return a.length>0&&(ae["x-palbase-unreachable"]=a),S&&(ae["x-palbase-gateways"]=v),U&&(ae["x-palbase-room"]=G),Q&&(ae["x-palbase-channels"]=L),ae}function Wo(e,t){let n=[];for(let r of e){let s=(d,l,m,y)=>{let v=Lt(`${r.name}_${d}_${l}`),S={},G=It(m,v,S,y);G.$ref===void 0&&(S[v]=G),Vo(r.pattern,d,l,S[v]);for(let[U,L]of Object.entries(S)){if(Object.hasOwn(t,U)&&JSON.stringify(t[U])!==JSON.stringify(L))throw new Error(`@Gateway("${r.pattern}") ${d} "${l}": its schema is the component ${U}, which another gateway's names with another schema \u2014 rename one of them`);t[U]=L}return{$ref:`#/components/schemas/${v}`}},a=Object.fromEntries(Object.entries(r.events).map(([d,l])=>[d,s("event",d,l,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([d,l])=>[d,{payload:s("message",d,l.schema,"sent"),...l.reply?{reply:s("reply",d,l.reply,"answered")}:{}}]));n.push([r.name,{pattern:r.pattern,...r.access?{access:r.access}:{},...r.logKeepSeconds>0?{durable:r.logKeepSeconds}:{},...r.chat?{chat:!0}:{},events:a,messages:o}])}return Object.fromEntries(n)}function Vo(e,t,n,r){if(!(!oe(r)||!oe(r.properties))){for(let[s,a]of Object.entries(r.properties))if(a===!0||oe(a)&&Object.keys(a).length===0)throw new Error(t==="message"?`@Gateway("${e}") message "${n}" has an untyped field "${s}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`:`@Gateway("${e}") ${t} "${n}" has an untyped field "${s}". An untyped payload makes every generated client opaque \u2014 declare its shape.`)}}function Zo(e,t){return e.method===t.method&&e.segments.length===t.segments.length&&e.segments.every((n,r)=>typeof n!="string"||n===t.segments[r])}function Es(e){return`${e.controller.name}.${e.fn}`}function Yo(e){let t=e.controller.name;if(t.endsWith("Controller")&&(t=t.slice(0,-10)),t!=="")return`${t[0].toLowerCase()}${t.slice(1)}.${e.fn}`;let n=r=>r.charAt(0).toUpperCase()+r.slice(1);return e.method.toLowerCase()+e.segments.map(r=>typeof r=="string"?n(r):`By${n(r.param)}`).join("")}function Nt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function Qo(e){let t=new Set;return e.map(n=>Nt(n,t))}function It(e,t,n,r="sent"){let s=e["~standard"],a=s.jsonSchema?.input;if(typeof a!="function")return{};let o;try{o=a({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...s.vendor==="zod"?{override:Xo}:{}}})}catch{return{}}let d=Lt(t);for(;Object.keys(n).some(l=>l===d||l.startsWith(`${d}.`));)d=`${d}_`;return ei(o,d,n,r)}function Xo(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function ei(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=m=>m==="#"?(a=!0,`#/components/schemas/${t}`):m.startsWith("#/$defs/")?`#/components/schemas/${t}.${Lt(ni(m.slice(8)))}`:m,d="all";if(r==="sent"){let m=new Set;for(let y of[e,...Object.values(s)])Ut(y,m);d=m}for(let[m,y]of Object.entries(s))n[`${t}.${Lt(m)}`]=ft(lt(y,o,d));let l=ft(lt(e,o,d));return a?(n[t]=l,{$ref:`#/components/schemas/${t}`}):l}var ti=new Set(["type","enum","required","dependentRequired","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","contentEncoding","contentMediaType","minItems","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties","readOnly","writeOnly","deprecated",Wn]),Tn=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),$n=new Set(["anyOf","oneOf","allOf","prefixItems"]),En=new Set(["properties","patternProperties","dependentSchemas"]),oe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function lt(e,t,n){if(!oe(e))return typeof e=="boolean"?e:{};let r={};for(let[s,a]of Object.entries(e))s==="$ref"&&typeof a=="string"?r.$ref=t(a):s==="const"?(n==="all"||n.has(e))&&(r.const=a):ti.has(s)?r[s]=a:Tn.has(s)?r[s]=lt(a,t,n):$n.has(s)&&Array.isArray(a)?r[s]=a.map(o=>lt(o,t,n)):En.has(s)&&oe(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,d])=>[o,lt(d,t,n)])));return r}var Ss=Number.MAX_SAFE_INTEGER;function ft(e){if(!oe(e))return e;let t={};for(let[r,s]of Object.entries(e))Tn.has(r)?t[r]=ft(s):$n.has(r)&&Array.isArray(s)?t[r]=s.map(ft):En.has(r)&&oe(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,ft(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Ss&&delete t.minimum,t.maximum===Ss&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,oe(t.propertyNames)&&Object.keys(t.propertyNames).length===1&&t.propertyNames.type==="string"&&delete t.propertyNames,Array.isArray(t.type)&&t.type.filter(r=>r!=="null").length>1&&Object.keys(t).length===1)return{anyOf:t.type.map(r=>({type:r}))};let n=t.anyOf;if(Array.isArray(n)&&n.length===2&&Object.keys(t).length===1){let r=n.findIndex(a=>oe(a)&&Object.keys(a).length===1&&a.type==="null"),s=n[1-r];if(r!==-1&&oe(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function Ut(e,t){if(oe(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(oe))continue;if(r.every(a=>"const"in a||Array.isArray(a.enum)))for(let a of r)t.add(a);let s=r.map(a=>oe(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(o=>oe(o[a])&&"const"in o[a]))for(let o of s)t.add(o[a])}for(let[n,r]of Object.entries(e))if(Tn.has(n))Ut(r,t);else if($n.has(n)&&Array.isArray(r))for(let s of r)Ut(s,t);else if(En.has(n)&&oe(r))for(let s of Object.values(r))Ut(s,t)}}function ni(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Lt(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function _s(e,t){if(e.type!=="object"||typeof e.properties!="object"||e.properties===null)return;let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([r,s])=>({name:r,in:t,required:n.has(r),schema:s}))}function ri(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function te(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:Bo}}}}function si(e,t,n){if(!e)return{200:{description:"The handler's answer, as JSON",content:{"application/json":{}}},204:{description:"The handler answered nothing (undefined or null)"}};if(e.returns.kind==="void")return{204:{description:"No Content"}};if(e.returns.kind==="raw")return{default:{description:"The handler's own Response, as it built it"}};let r=It(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function ai(e,t,n){let r=new Set,s=[];for(let a of t){if(r.has(a.code))continue;r.add(a.code);let o=n?.get(a.code);if(o&&a.status!==o.status)throw new Error(`${e} throws "${a.code}" with status ${a.status}, but the code is defined with status ${o.status} \u2014 a client matches an error by its code, so one code carries one status`);s.push({...a,...o?.data?{data:o.data}:{}})}return s}function oi(e,t){let n=Object.create(null);for(let r of t){let s=r.name.charAt(0).toLowerCase()+r.name.slice(1),a=Object.hasOwn(n,s)?n[s]:void 0;if(a)throw new Error(`${e} throws "${a.code}" and "${r.code}" under one name, "${r.name}" \u2014 every client names an error case after it; give one of them its own defineError`);n[s]={status:r.status,code:r.code,hasData:r.data!==void 0,description:""}}return n}function ii(e,t,n){let r=new Map;for(let a of e)r.set(a.status,[...r.get(a.status)??[],a]);let s={};for(let a of[...r.keys()].sort((o,d)=>o-d)){let o=r.get(a),d=o.map(l=>{let m={error:{type:"string",const:l.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},y=["error","error_description","status","request_id"];return l.data&&(m.data=It(l.data,`${t}.${l.code}.data`,n,"answered"),y.push("data")),{type:"object",properties:m,required:y}});s[String(a)]={description:o.map(l=>l.code).join(" | "),content:{"application/json":{schema:d.length===1?d[0]:{oneOf:d}}}}}return s}function di(e,t){let n={},r=[t.validates&&"a parameter failed its schema (data.fields names each field, data.more how many more)",t.hasPathParams&&"the path is not valid percent-encoding"].filter(Boolean),s=[r.length>0&&`bad_request: ${r.join("; or ")}`,t.keyed&&"invalid_idempotency_key: the Idempotency-Key is over 255 characters"].filter(Boolean);return s.length>0&&(n[400]=te(s.join("; "))),e.auth.required&&(n[401]=te("unauthorized: no access token was sent; invalid_token: the token is not valid (data.reason says why), or the Authorization header is not a Bearer token")),e.auth.verifiedEmail&&(n[403]=te("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=te("idempotency_key_in_use: a request with this Idempotency-Key is still running",Ye)),t.readsBody&&(n[413]=te("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=te("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=te("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Ye)),n[500]=te("internal_error: the handler failed; the app's log has it under the request id"),n[503]=te(`${e.auth.required?"auth_unavailable: sign-ins cannot be checked right now; ":""}service_unavailable: a platform service the request needs did not answer${t.keyed?"; temporarily_unavailable: the Idempotency-Key could not be recorded":""}`,Ye),n}var zt=class{windows=new Map;now;maxKeys;constructor(t=Date.now,n=1e5){this.now=t,this.maxKeys=n}take(t,n){let r=this.now(),s=this.windows.get(t);if((!s||r>=s.resetAt)&&(s={count:0,resetAt:r+n.window*1e3}),this.windows.delete(t),this.windows.set(t,s),this.windows.size>this.maxKeys&&this.windows.delete(this.windows.keys().next().value),s.count++,s.count>n.max)return Math.max(1,Math.ceil((s.resetAt-r)/1e3))}reserve(t,n){let r=this.take(t,n);return r!==void 0?{wait:r}:{window:this.windows.get(t).resetAt}}give(t,n){let r=this.windows.get(t);r&&r.resetAt===n&&r.count>0&&r.count--}};function qt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return ci(r??t??"unknown")}function ci(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(n)return n[1];let[r,s=""]=t.split("::"),a=r?r.split(":"):[],o=s?s.split(":"):[],d=t.includes("::")?[...a,...Array(8-a.length-o.length).fill("0"),...o]:a;return d.length!==8||d.some(l=>!/^[0-9a-f]{1,4}$/i.test(l))?t:`${d.slice(0,4).map(l=>parseInt(l,16).toString(16)).join(":")}::/64`}function Os(e){let t=[];for(let n of e){let r=D(n,Le),s=D(n,Ie)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=D(n,Zt)??new Map;for(let o of s){let d=`${r.basePath}${o.subpath}`||"/",l=d.split("/").filter(Boolean).map(y=>{let v=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(y)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(y);return v?{param:v[1]}:y});if(typeof l[0]=="string"&&qe.has(l[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${d} \u2014 /${l[0]} is the platform's; a route is served elsewhere`);let m=[...a.get(o.fn)??[]].sort((y,v)=>y.index-v.index);for(let y of m)if(y.kind==="param"&&!l.some(v=>typeof v!="string"&&v.param===y.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${y.name}") names no {${y.name}} in ${o.method} ${d}`);t.push({id:`${o.method} ${d}`,method:o.method,segments:l,controller:n,fn:o.fn,params:m,meta:o,controllerAuth:r.options.auth})}}return Sr(t),t}function Sn(e,t,n){let r=n.split("/").filter(Boolean);for(let s of e){if(s.method!==t||s.segments.length!==r.length)continue;let a={},o=!0;for(let d=0;d<r.length&&o;d++){let l=s.segments[d];if(typeof l=="string")o=l===r[d];else try{a[l.param]=decodeURIComponent(r[d])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function Rn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Qe(e,t,n,r,s){return nt(e,e?Rn(e.requests,t):void 0,n,r,s)}var pt={role:"service",claims:{}};async function nt(e,t,n,r,s){if(!e||!t)return s();let a=m=>E.warn(`[palbase] ${r}: a transaction of the request could not be given back \u2014 it wrote, locked, is an $atomic or an $attempt, ran SQL of its own, or the database keeps one snapshot for it \u2014 and sat ${m} ms with no statement running: the handler waited on something else, and a database connection waited with it. Make the outside call before the first write, or outside $atomic.`,{waitedMs:m}),o=e.app.request(t,{signal:n,heldIdle:a}),d=re.getStore();d&&(d.database=o.database);let l;try{l=await s()}catch(m){throw await o.rollback(m).catch(y=>E.error("[palbase] the request's transaction could not be rolled back",{error:y})),m}try{await o.commit()}catch(m){throw await o.rollback(m).catch(y=>E.error("[palbase] the request's transaction could not be rolled back",{error:y})),m}return l}var li=1024*1024,fi=20,pi={max:300,window:60},Xe="/_palbase/crons",et="/_palbase/tasks",As=50,Ps=50,mi=4096,hi=69632,Cs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,tt=1e4,gi=6e4;function yi(e,t){let n=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof n=="boolean")return{required:n,verifiedEmail:!1};if((n.role??"").trim()!==""||(n.permission??"").trim()!=="")throw new TypeError(`${e.id}: auth { role, permission } is not checked by Palbase \u2014 check the role in the service`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0}}var ne=class extends Error{constructor(n,r,s,a,o,d){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=o;this.challenge=d}status;code;data;retryAfter;challenge};function wi(e){if(e==="proof")return'DPoP error="invalid_dpop_proof", algs="ES256"';if(e==="bound"||e==="not_bound")return'DPoP error="invalid_token", algs="ES256"'}var bi=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function ki(e,t){let n=new Headers(e.headers);for(let r of bi)n.delete(r);return e.url!==""&&(n.delete("content-encoding"),n.delete("content-length")),n.set("x-request-id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function js(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Ht(e.headers,"Accept-Language")),e}function Ht(e,t){let n=(e.get("vary")??"").split(",").map(r=>r.trim()).filter(Boolean);n.includes("*")||n.some(r=>r.toLowerCase()===t.toLowerCase())||e.set("vary",[...n,t].join(", "))}function le(e,t,n,r={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}})}function T(e,t){let n={error:e.code,error_description:e.message,status:e.status,request_id:t};e.data!==void 0&&(n.data=e.data);let r={};return e.retryAfter!==void 0&&(r["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(r["www-authenticate"]=e.challenge),le(e.status,n,t,r)}var zs=new Set([0,429,502,503,504]);function Ms(e,t,n,r){if(r?.aborted)return E.info(`[palbase] ${n}: the client left before its answer`),T({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof ne)return T({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(ct(e)){let a=e;return a.status>=500&&E.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),le(a.status,es(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Gt(e,n);return s?T(s,t):(e instanceof ce?E.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):E.error(`[palbase] unhandled error in ${n}`,{error:e}),T({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Gt(e,t){if(e instanceof Tt)return E.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ce&&zs.has(e.status))return E.warn(`[palbase] ${t}: a platform service did not answer (${e.op}: ${e.status} ${e.code})`,{error:e}),{status:503,code:"service_unavailable",message:"A service this request needs did not answer; try again shortly",retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))};let n=Ls(e);if(n!==void 0)return E.warn(`[palbase] ${t}: the database connection ${n==="lost"?"was lost":"could not be opened"}`,{error:e}),{status:503,code:"database_unavailable",message:"The database is temporarily unavailable",data:{retrySafe:n==="never"},retryAfter:1}}function vi(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return ss(e)?t(e.message):ct(e)&&!Cn(e)&&!On(e)?t(e.errorDescription):On(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function On(e){return e instanceof Tt||e instanceof ce&&zs.has(e.status)||Ls(e)!==void 0||ct(e)&&e.status===503&&Cn(e)}async function _n(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,fi).map(o=>({field:(o.path??[]).map(d=>String(typeof d=="object"&&d!==null&&"key"in d?d.key:d)).join("."),message:o.message})),a=r.issues.length-s.length;throw new ne(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function mt(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new ne(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let r=e.body.getReader(),s=[],a=0;for(;;){let{done:l,value:m}=await r.read();if(l)break;if(a+=m.byteLength,a>t)throw await r.cancel().catch(()=>{}),new ne(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(m)}let o=new Uint8Array(a),d=0;for(let l of s)o.set(l,d),d+=l.byteLength;return o}function Ti(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return fe(t)}function $i(e){let t=e.claims.custom_claims;return{id:e.id,email:e.email,role:e.role,emailVerified:e.emailVerified,metadata:typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},sessionId:e.sessionId,test:e.claims.test===!0}}function Ei(e){return e.id?{id:e.id,email:e.email??null,role:e.role,emailVerified:e.emailVerified??!1,metadata:{},sessionId:e.session??null,test:!1}:null}var Si=/^[A-Za-z0-9._:-]{8,128}$/,_i=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,xi={max:20,window:60},Ri=10*6e4,Oi=1e4,ht=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},An=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=Is("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,d;if(!a){let m=this.limiter.reserve(o,xi);if("wait"in m)throw new ht(m.wait);d=m}let l=await r();if(!l)throw this.known.delete(s),new vt("unknown_token","The token is not one of the app's");return d&&this.limiter.give(o,d.window),this.known.delete(s),this.known.set(s,this.now()+Ri),this.known.size>Oi&&this.known.delete(this.known.keys().next().value),l}};function Qc(e){let t=new At(e.modules),n=Os(t.controllers.map(i=>i.cls)),r=new Map(n.map(i=>[i,yi(i,e.auth)])),s=new Map;for(let i of n){let c={body:[],query:[]};for(let f of i.params){if(!f.schema)continue;let u=ar(f.schema);if(f.kind==="body")c.body.push(...Jt(u,"/body",i.id));else if(f.kind==="query"){let h=Jt(u,"/query",i.id),p=h.find(g=>g.split("/").length!==3);if(p)throw new TypeError(`${i.id}: ${p} \u2014 an encrypted query field is one of the query's own names`);c.query.push(...h)}else if(or(u))throw new TypeError(`${i.id}: its ${f.kind} carry no encrypted field \u2014 its body's or its query's do`)}if(c.body.length+c.query.length!==0){if(i.meta.upload)throw new TypeError(`${i.id}: an upload's body comes through storage, which seals nothing \u2014 it carries no encrypted field`);s.set(i,c)}}async function a(i,c,f,u){let h=e.server.transit;try{return h.loaded||await h.load(),await h.request({header:f,method:u,path:ji(i),params:i.segments.flatMap(p=>typeof p=="string"?[]:[c[p.param]??""])})}catch(p){throw Ns(p)}}for(let[i,c]of r){if(!c.required&&i.params.some(f=>f.kind==="user"))throw new TypeError(`${i.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(i.meta.upload&&c.verifiedEmail)throw new TypeError(`${i.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`)}let o=new Map;for(let i of n)for(let c of i.params)c.kind==="resolve"&&o.set(c,t.dependencyOf(i.controller,c.resolver,`${i.id} @Resolve(${c.resolver?.name})`));let d=new Map;for(let i of t.cronProviders){let c=t.get(i),f=D(i,Te),u=d.get(f.name);if(u)throw new TypeError(`@Cron "${f.name}" is ${u.owner} and ${i.name}: a cron's name is its own \u2014 name one of them`);d.set(f.name,{declaration:f,owner:i.name,run:h=>c.run(h)})}let l=new Map;for(let i of t.taskProviders){let c=t.get(i),f=D(i,be),u=l.get(f.name);if(u)throw new TypeError(`@Task "${f.name}" is ${u.owner} and ${i.name}: a task type's name is its own \u2014 name one of them`);l.set(f.name,{declaration:f,owner:i.name,run:(h,p)=>c.run(h,p)})}let m=new Map;for(let i of t.templateProviders){let c=t.get(i),f=D(i,ke),u=m.get(f.name);if(u)throw new TypeError(`@TestUserTemplate "${f.name}" is ${u.owner} and ${i.name}: a template's name is its own \u2014 name one of them`);m.set(f.name,{owner:i.name,seed:(h,p)=>c.seed(h,p),...typeof c.undo=="function"?{undo:(h,p)=>c.undo(h,p)}:{}})}m.size>0&&!e.platform&&E.info(`[palbase] ${m.size} @TestUserTemplate(s): the platform calls a machine for its test users; nothing does here`);let y=new Map,v=new Set,S=new Set,G=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(d.size>As)throw new TypeError(`${d.size} @Cron classes: a machine runs ${As} crons at most`);if(l.size>Ps)throw new TypeError(`${l.size} @Task classes: a machine runs ${Ps} task types at most`);d.size>0&&!e.platform&&E.info(`[palbase] ${d.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let U=Ur(t.gateways.map(i=>({cls:i,instance:t.get(i)})),{run:(i,c,f,u)=>re.run({requestId:re.getStore()?.requestId??"",...i?.id?{userId:i.id}:{}},()=>nt(e.database,e.database?i?.id?Rn(e.database.requests,Rt(i)):pt:void 0,f,c,async()=>{let h=await u();if(f?.aborted)throw new Error(`realtime gave up on ${c} before it ended`);return h})),broadcast:i=>e.server.realtime.broadcast({body:{messages:i}}),revalidate:i=>e.server.realtime.revalidate({body:i}),isOutage:On});U.declarations.length>0&&!e.platform&&E.info(`[palbase] ${U.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let L=as();(L.tools.size>0||L.agents.size>0)&&!e.platform&&E.info(`[palbase] ${L.tools.size} ai.tool(s) and ${L.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let Q=i=>c=>t.provider(c,`${i} ctx.inject(${typeof c=="function"?c.name:String(c)})`),ee=new Ct,ae=new Pt(e.now??Date.now),k=new Set,X=e.database!==void 0||e.contractOnly?.database===!0;if(X){for(let i of n)if(ut(i)&&i.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&vs(c.schema)))throw new TypeError(`${i.id}: its @Headers schema declares Idempotency-Key \u2014 the framework takes that header on every write of an app with a database and answers a retry from it; a handler reads it with @Headers() (no schema)`)}let w=e.database?new Dt(e.database.app,e.database.keptAnswers):void 0,_=Ii(e.cors),b=e.now??Date.now,x=new zt(e.now),C=new An(x,e.now??Date.now),N=e.maxBodyBytes??li,F=i=>{let c=i.meta.options.rateLimit??e.rateLimit??pi;return c!==!1&&c.max>0&&c.window>0?c:!1},B=e.env??process.env,q=Gr(t.webhooks,i=>t.get(i),B,{secrets:e.contractOnly===void 0}),I=q.size===0&&d.size===0&&l.size===0&&m.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(B).filter(i=>typeof i[1]=="string"&&!er(i[0])))),V=new Map([...q.keys()].map(i=>[i,{seen:new Set,inflight:new Set}])),W=new Map([...q.keys()].map(i=>[i,{counts:new Map,at:void 0}])),ie,de=()=>ie??=Rs(n,i=>({auth:r.get(i),limit:F(i)}),{databaseSeesCaller:X,idempotency:X,webhooks:[...q.values()].map(i=>({name:i.name,cls:i.cls.name,provider:i.provider,signatureHeader:i.signatureHeader,secretEnv:i.secretEnv,events:[...i.events.keys()]})),platformEvents:[...ge.keys()],gateways:U.declarations,platformEventBuckets:Pi(ge),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),ge=new Map;for(let[i,c]of Object.entries(e.events??{}))ge.set(i,c.map(f=>({name:`palbase(${i})`,call:u=>f(u)})));for(let i of t.eventProviders){let c=t.get(i);for(let{event:f,fn:u,bucket:h}of D(i,Re)??[]){if(!fr.test(f))throw new TypeError(`@On("${f}") on ${i.name}.${u}: a platform event's type is dotted lowercase words, like user.deleted \u2014 a third party's event is taken by an @On in its @Webhook class`);ge.has(f)||ge.set(f,[]),ge.get(f).push({name:`${i.name}.${u}`,bucket:h,call:async(p,g)=>c[u](p,g)})}}let ve=new Set,_e=new Set;tr(e.server),nr({to:(i,c)=>({emit:(f,u)=>U.emit(i,c,f,u),pipe:f=>U.pipe(i,c,f),revalidate:f=>U.revalidate(i,c,f)})}),mr(e.platform?hr(B.PALBASE_MACHINE):new _t(new Map([...l].map(([i,c])=>[i,c.declaration])),(i,c)=>Un(i,c),e.now));async function Kt(i,c){let f;try{f=await Qn(i,e.webhookSecret,{now:e.now})}catch(u){if(u instanceof st)return T({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${u.code}`},c);throw u}if(fe(f.data),ve.has(f.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(_e.has(f.id))return T({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);_e.add(f.id);try{let u;try{await Qe(e.database,null,void 0,`event ${f.type}`,async()=>{for(let h of ge.get(f.type)??[])if(!(h.bucket!==void 0&&Ai(f)!==h.bucket))try{await h.call(f,{requestId:c})}catch(p){throw u=h.name,p}})}catch(h){return E.error(`[palbase] ${u??"the delivery"} failed on ${f.type} ${f.id}; the platform delivers it again`,{error:h}),T({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return ve.add(f.id),ve.size>tt&&ve.delete(ve.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{_e.delete(f.id)}}async function Y(i,c={}){let f=i.headers.get("origin");if(_&&f!==null){let u=_.allows(f);if(i.method==="OPTIONS"&&i.headers.has("access-control-request-method"))return u?new Response(null,{status:204,headers:_.preflight(f,i.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let h=await qn(i,c);if(u)for(let[p,g]of Object.entries(_.headers(f)))p==="vary"?Ht(h.headers,g):h.headers.set(p,g);else Ht(h.headers,"Origin");return h}return qn(i,c)}async function Ce(i,c,f,u){if(!i.headers.get(f.scheme.header))return Me(f,"missing_signature",u);let h={headers:i.headers,body:await mt(i,f.scheme.maxBytes(N)),url:Kr(i,c)},p;try{p=f.scheme.check(h,b()/1e3)}catch{return Me(f,"signature_mismatch",u,"check_failed")}if(typeof p=="string")return Me(f,p,u);let g=f.events.get(p.type);if(!g)return E.info(`[palbase] webhook ${f.name}: no @On takes "${p.type}"; acknowledged`),le(200,{ok:!0,handled:!1},u);let $=V.get(f.name),R=p.event,j=[];if(p.id!==void 0){if($.seen.has(p.id))return le(200,{ok:!0,handled:!1,duplicate:!0},u);j=[p.id]}else if(p.ids&&Array.isArray(R)){let A=p.ids,O=R.map((M,Z)=>[M,A[Z]]).filter(([,M])=>M===void 0||!$.seen.has(M));if(O.length===0)return le(200,{ok:!0,handled:!1,duplicate:!0},u);R=O.map(([M])=>M),j=O.flatMap(([,M])=>M===void 0?[]:[M])}if(j.some(A=>$.inflight.has(A)))return T({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},u);fe(R);for(let A of j)$.inflight.add(A);let P;try{P=await Qe(e.database,null,void 0,`webhook ${f.name}`,()=>g.call(R,{env:I,requestId:u,environmentId:e.projectId??""}))}catch(A){let O=Gt(A,`webhook ${f.name}`)??Mi(A,f.name);return O?T(O,u):(E.error(`[palbase] ${g.name} failed on ${f.name} "${p.type}"; the sender delivers it again`,{error:A}),T({status:500,code:"handler_failed",message:"The event could not be handled"},u))}finally{for(let A of j)$.inflight.delete(A)}for(let A of j)$.seen.add(A),$.seen.size>tt&&$.seen.delete($.seen.values().next().value);return je(P,f,u)}function je(i,c,f){if(i instanceof Response)return i;if(typeof i=="string"){let u=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(i,{status:200,headers:{"content-type":u,"x-request-id":f}})}return le(200,i??{ok:!0,handled:!0},f)}function Me(i,c,f,u=c){let h=W.get(i.name);h.counts.set(u,(h.counts.get(u)??0)+1);let p=b();return(h.at===void 0||p-h.at>=gi)&&(Nn(i.name),h.at=p),T({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},f)}function Nn(i){let c=W.get(i).counts;if(c.size===0)return;let f=[...c.values()].reduce((u,h)=>u+h,0);E.warn(`[palbase] webhook ${i}: ${f} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function Gs(i){let c=i.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?q.get(c[1]):void 0}async function Ks(i,c,f,u){let h=c.pathname===Xe;if(i.method!==(h?"GET":"POST"))return T({status:405,code:"method_not_allowed",message:h?"The crons are listed with GET":"A cron is run with POST"},u);let p=h?new Uint8Array(0):await mt(i,mi);try{await kt({secret:f,signature:i.headers.get("palbase-signature"),body:p,now:e.now})}catch(H){if(H instanceof st)return T({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${H.code}`},u);throw H}if(h){let H=[...d.values()].map(({declaration:K})=>({name:K.name,schedule:K.schedule,time_zone:K.timeZone,timeout:K.timeout,retry:K.retries}));return le(200,{crons:H},u,{"cache-control":"no-store"})}let g=c.pathname.slice(Xe.length+1),$=d.get(g);if(!$)return T({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(g)}`},u);let R;try{R=JSON.parse(new TextDecoder().decode(p))}catch{return T({status:400,code:"bad_request",message:"A run is the JSON {cron, run_id, scheduled_at, attempt}"},u)}let{cron:j,run_id:P,scheduled_at:A,attempt:O}=R??{};if(j!==g||typeof P!="string"||P===""||typeof A!="string"||!Cs.test(A)||Number.isNaN(Date.parse(A))||!Number.isInteger(O)||O<1)return T({status:400,code:"bad_request",message:`A run of ${g} is the JSON {cron: "${g}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},u);let M=`${P}#${String(O)}`;if(S.has(M))return new Response(null,{status:204,headers:{"x-request-id":u}});if(G.has(M))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);G.add(M);let Z={env:I,environmentId:e.projectId??"",cron:g,runId:P,scheduledAt:new Date(A),attempt:O};try{await nt(e.database,e.database?pt:void 0,i.signal,`cron ${g}`,async()=>{if(await $.run(Z),i.signal.aborted)throw new Error(`the platform gave up on this attempt of ${g} before it ended`)})}catch(H){return i.signal.aborted||E.error(`[palbase] cron ${g} failed (run ${P}, attempt ${String(O)})`,{error:H}),T({status:500,code:"cron_failed",message:`The cron ${g} failed; the platform tries it again`},u)}finally{G.delete(M)}return S.add(M),S.size>tt&&S.delete(S.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}let Un=async({task:i,id:c,attempt:f,payload:u,createdAt:h},p)=>{let g=l.get(i);if(!g)return{status:404,message:`this version has no task ${JSON.stringify(i)}`};let $=fe(u??null),R=g.declaration.payload;if(R){let P=await R["~standard"].validate($);if(P.issues){let A=P.issues.slice(0,5).map(O=>`${(O.path??[]).map(M=>String(typeof M=="object"&&M!==null&&"key"in M?M.key:M)).join(".")||"(payload)"}: ${O.message}`).join("; ");return E.error(`[palbase] task ${i} ${c}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${A}`),{status:422,message:`what it carries is not what @Task "${i}" takes: ${A}`}}$=P.value}let j={env:I,environmentId:e.projectId??"",task:i,id:c,attempt:f,createdAt:h};try{await nt(e.database,e.database?pt:void 0,p,`task ${i}`,async()=>{if(await g.run($,j),p.aborted)throw new Error(`the platform gave up on this attempt of ${i} before it ended`)})}catch(P){return P instanceof St?(E.error(`[palbase] task ${i} ${c} can never be done: ${P.message}`),{status:422,message:P.message}):(p.aborted||E.error(`[palbase] task ${i} failed (task ${c}, attempt ${String(f)})`,{error:P}),{status:500,message:`the task ${i} failed; it is tried again`})}return{status:204}};async function Fs(i,c,f,u){let h=c.pathname===et;if(i.method!==(h?"GET":"POST"))return T({status:405,code:"method_not_allowed",message:h?"The task types are listed with GET":"A task is run with POST"},u);let p=h?new Uint8Array(0):await mt(i,hi);try{await kt({secret:f,signature:i.headers.get("palbase-signature"),body:p,now:e.now})}catch(H){if(H instanceof st)return T({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${H.code}`},u);throw H}if(h){let H=[...l.values()].map(({declaration:K})=>({name:K.name,timeout:K.timeout,retry:K.retries,concurrency:K.concurrency}));return le(200,{tasks:H},u,{"cache-control":"no-store"})}let g=c.pathname.slice(et.length+1),$;try{$=JSON.parse(new TextDecoder().decode(p))}catch{return T({status:400,code:"bad_request",message:"A task is the JSON {task, id, attempt, payload, created_at}"},u)}let{task:R,id:j,attempt:P,payload:A,created_at:O}=$??{};if(R!==g||typeof j!="string"||j===""||typeof O!="string"||!Cs.test(O)||Number.isNaN(Date.parse(O))||!Number.isInteger(P)||P<1)return T({status:400,code:"bad_request",message:`A task of ${g} is the JSON {task: "${g}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},u);let M=`task:${j}#${String(P)}`;if(S.has(M))return new Response(null,{status:204,headers:{"x-request-id":u}});if(G.has(M))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);G.add(M);let Z;try{Z=await Un({task:g,id:j,attempt:P,payload:A,createdAt:new Date(O)},i.signal)}finally{G.delete(M)}return Z.status===404?T({status:404,code:"task_not_found",message:Z.message??""},u):Z.status===422?T({status:422,code:"task_failure",message:Z.message??""},u):Z.status>=300?T({status:Z.status,code:"task_failed",message:Z.message??""},u):(S.add(M),S.size>tt&&S.delete(S.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}}))}async function De(i,c,f,u){if(i.method!=="POST")return T({status:405,code:"method_not_allowed",message:`${u} is POSTed`},f);let h;try{Yn({signature:i.headers.get("palbase-signature"),now:e.now}),h=await mt(i,1048576),await kt({secret:c,signature:i.headers.get("palbase-signature"),body:h,now:e.now})}catch(g){if(g instanceof st)return T({status:401,code:"invalid_signature",message:`${u} is the platform's to call: ${g.code}`},f);throw g}let p;try{p=JSON.parse(new TextDecoder().decode(h))}catch{return T({status:400,code:"bad_request",message:`${u} is JSON`},f)}return typeof p!="object"||p===null||!Object.hasOwn(p,"call")||p.call!==new URL(i.url).pathname?T({status:401,code:"invalid_signature",message:`${u} is the platform's to call: signed_for_another_call`},f):{body:p}}async function Bs(i,c,f,u,h){let p=await De(c,f,u,`An upload's ${i}`);if(p instanceof Response)return p;let g=_r(i,p.body);if(typeof g=="string")return T({status:400,code:"bad_request",message:`An upload's ${i}: ${g}`},u);if(i==="complete"){if(k.has(g.uploadId))return T({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},u);k.add(g.uploadId),k.size>tt&&k.delete(k.values().next().value)}let $=Sn(n,g.method,g.route);if(!$||"malformed"in $||!$.route.meta.upload)return T({status:404,code:"not_found",message:`No upload route for ${g.method} ${g.route}`},u);let{route:R,params:j}=$,P=$.route.meta.upload,A=Ei(g.user);if(A&&Hn(h,A.id),r.get(R).required&&!A)throw new ne(401,"unauthorized","This route needs a signed-in user");if(i==="authorize"){let Z=F(R);if(Z!==!1){let K=x.take(`${R.id}\0${vr(g.user,g.client)}`,Z);if(K!==void 0)throw new ne(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:K},K)}let H=Er(P.pathTemplate,{userId:A?.id??null,uploadId:g.uploadId,filename:g.filename});if("problem"in H)throw new ne(400,"bad_request",H.problem);return await Qe(e.database,Rt(g.user),c.signal,R.id,async()=>{let K={request:c,query:new URLSearchParams(g.query),params:j,user:A,body:g.body===void 0||g.body===null?{}:fe(g.body),requestId:u};await zn(R,K);for(let Ne of R.params)(Ne.kind==="query"||Ne.kind==="body"&&g.body!==void 0)&&await Us(Ne,K)}),le(200,{bucket:P.bucket,path:H.path},u)}h.endpoint=R.id.slice(R.id.indexOf(" ")+1);let O=new URLSearchParams(g.query),M=g.body===null||g.body===void 0?{}:fe(g.body);return xn(await Ft(R,{request:c,query:O,params:j,user:A,body:M,requestId:u,uploadedObject:fe(g.uploadedObject)},Rt(g.user)),void 0,u)}async function Js(i,c,f,u){let h=c.pathname.slice(xt.length+1),p=h.endsWith("/undo"),g=p?h.slice(0,-5):h,$=await De(i,f,u,"A test user template");if($ instanceof Response)return $;let R=m.get(g);if(!R||p&&!R.undo)return T({status:404,code:"template_not_found",message:R?`@TestUserTemplate "${g}" has no undo: the user's deletion cleans up after it`:`This version has no test user template ${JSON.stringify(g)}`},u);let j=gr(g,$.body);if(typeof j=="string")return T({status:400,code:"bad_request",message:`A test user template's call: ${j}`},u);let P=fe(j.user),A;try{A=await yr(e.server,P.id)}catch(H){return E.error(`[palbase] test user template ${g}: auth could not say whether ${P.id} is a test user; nothing was written`,{error:H}),T({status:503,code:"auth_unavailable",message:"Auth could not say whether the user is a test user: the template did not run",retryAfter:5},u)}if(!A)return E.warn(`[palbase] test user template ${g}${p?" undo":""}: auth does not say ${P.id} is a test user \u2014 nothing was run`),T({status:403,code:"not_a_test_user",message:"Auth does not say this user is a test user: a template writes for test users alone"},u);let O=`${P.id}\0${g}`;if(v.has(O))return T({status:409,code:"in_progress",message:`The template ${g} is being written for this user`,retryAfter:5},u);if(!p&&y.has(O))return le(200,{rows:y.get(O)},u);v.add(O);let M={env:I,environmentId:e.projectId??"",template:g},Z=`test user template ${g}${p?" undo":""}`;try{let H={};return await nt(e.database,e.database?pt:void 0,i.signal,Z,async()=>{if(p?await R.undo(P,M):(await R.seed(P,M),H=await wr(re.getStore()?.database)),i.signal.aborted)throw new Error(`the platform gave up on ${Z} before it ended`)}),p?(y.delete(O),new Response(null,{status:204,headers:{"x-request-id":u}})):(y.set(O,H),y.size>tt&&y.delete(y.keys().next().value),le(200,{rows:H},u))}catch(H){i.signal.aborted||E.error(`[palbase] ${Z} failed for ${P.id}: nothing of it was kept`,{error:H});let K=H instanceof Error&&H.message!==""?`: ${H.message.replace(/\s+/g," ").slice(0,300)}`:"";return T({status:500,code:p?"undo_failed":"template_failed",message:`${p?"The undo of":"The template"} ${g} failed${K}; nothing of it was kept`},u)}finally{v.delete(O)}}function Ln(i,c,f,u){let h=i?{sub:i.id,role:"authenticated"}:null;return re.run({requestId:re.getStore()?.requestId??"",...i?{userId:i.id}:{}},()=>Qe(e.database,h,f,c,async()=>{let p=await u();if(f.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return p}))}let In=(i,c)=>new Response(i,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function Ws(i,c,f){let u=await De(i,c,f,"A tool call");if(u instanceof Response)return u;let h=u.body,p=h.tool;if(typeof p!="string"||p==="")return T({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},f);let g=L.tools.get(p);if(!g)return T({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(p.slice(0,64))}`},f);let $=h.call_id,R=ds(h.context);if(typeof $!="string"||$===""||$.length>256||typeof R=="string")return T({status:400,code:"bad_request",message:`A call of ${p} is {tool, call_id, input, context}${typeof R=="string"?`: ${R}`:""}`},f);let j=Is("sha256").update(JSON.stringify(h)).digest("hex"),P=ee.answered($);if(P!==void 0)return P.digest!==j?T({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},f):In(P.answer,f);if(ee.isRunning($))return T({status:409,code:"in_progress",message:"This call is running",retryAfter:2},f);ee.start($);let A;try{let O=await Ln(R.user,`ai.tool ${p}`,i.signal,()=>g.call(fe(h.input??{}),{...R,callId:$,signal:i.signal,inject:Q(`ai.tool ${p}`)}));A="deferred"in O?JSON.stringify({deferred:!0,...O.expires_in_seconds!==void 0?{expires_in_seconds:O.expires_in_seconds}:{}}):JSON.stringify({output:O.output,is_error:O.is_error});let M=new TextEncoder().encode(A).byteLength;M>Ze&&(E.error(`[palbase] ai.tool ${p} answered ${M} bytes (call ${$}): a machine's answer is ${Ze} at most; the agent is told it failed`),A=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${Ze/(1<<20)} MiB it may be`}],is_error:!0}))}catch(O){if(i.signal.aborted)return ee.end($,void 0),T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);E.error(`[palbase] ai.tool ${p} failed (call ${$}, chat ${R.chatId}); the agent is told`,{error:O}),A=JSON.stringify({output:[{type:"text",text:vi(O)}],is_error:!0})}return ee.end($,{digest:j,answer:A}),In(A,f)}async function Vs(i,c,f){let u=await De(i,c,f,"An agent's turn");if(u instanceof Response)return u;let h=cs(u.body);if(typeof h=="string"||h.agent==="")return T({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata, message}${typeof h=="string"?`: ${h}`:": agent names it"}`},f);let p=h.agent,g=L.agents.get(p);if(!g)return T({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(p.slice(0,64))}`},f);let $;try{$=await Ln(h.user,`ai.agent ${p}`,i.signal,()=>g.resolve({...h,signal:i.signal,inject:Q(`ai.agent ${p}`)}))}catch(P){if(i.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let A=Gt(P,`ai.agent ${p}`);return A?T(A,f):(E.error(`[palbase] ai.agent ${p} failed for chat ${h.chatId}; the turn is not started`,{error:P}),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},f))}let R=$.tools.find(P=>L.tools.get(P.name)!==P);if(R)return E.error(`[palbase] ai.agent ${p} handed out ai.tool ${JSON.stringify(R.name)}, which this app did not declare when it was made \u2014 make each ai.tool once, at a module's top level, and hand that one out`),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},f);let j=JSON.stringify($.definition);return new TextEncoder().encode(j).byteLength>Ze?(E.error(`[palbase] ai.agent ${p}'s definition is larger than the ${Ze} bytes a machine's answer may be`),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},f)):new Response(j,{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function Zs(i,c,f){let u=await De(i,c,f,"A repository's token");if(u instanceof Response)return u;let h=u.body;if(typeof h.repo!="string"||h.repo===""||typeof h.repository!="string"||typeof h.call_id!="string"||h.call_id===""||h.call_id.length>256)return T({status:400,code:"bad_request",message:"A repository's token is asked as {call_id, repo, repository}"},f);if(!ae.take(h.call_id))return T({status:409,code:"call_id_reused",message:"This token ask was answered already"},f);let p=L.repos.get(h.repo),g=p?R=>p.token(R):L.repoTokens;if(!g)return T({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(h.repo.slice(0,64))}, and no ai.repoTokens`},f);let $;try{$=await nt(e.database,e.database?pt:void 0,i.signal,`ai.repo ${h.repo}`,async()=>g({repo:h.repo,repository:h.repository,signal:i.signal,inject:Q(p?`ai.repo ${h.repo}`:`ai.repoTokens for ${h.repo}`)}))}catch(R){if(i.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let j=Gt(R,`ai.repo ${h.repo}`);return j?T(j,f):(E.error(`[palbase] ai.repo ${h.repo} gave no token; the workspace's clone or push is refused`,{error:R}),T({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},f))}return!p&&$==null?T({status:404,code:"repo_not_found",message:`ai.repoTokens gives no token for ${JSON.stringify(h.repo.slice(0,64))}`},f):typeof $!="string"||$.trim()===""?(E.error(`[palbase] ai.repo ${h.repo}'s token function answered no token`),T({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},f)):new Response(JSON.stringify({token:$}),{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function Ys(i,c,f,u){let h=await De(c,f,u,`A gateway's ${i}`);if(h instanceof Response)return h;let p=await U.serve(i,h.body,c.signal);return"code"in p?T({status:p.status,code:p.code,message:p.message,retryAfter:p.retryAfter},u):"body"in p?le(200,p.body,u):new Response(null,{status:204,headers:{"x-request-id":u}})}async function zn(i,c){let f=[],u={params:Object.freeze({...c.params}),user:fe(c.user),headers:i.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let h of i.params)h.kind==="resolve"&&(f[h.index]=await o.get(h).resolve(u,h.options));return f}async function Ft(i,c,f,u){let h=t.get(i.controller),p=await Qe(e.database,f,c.request.signal,i.id,async()=>{let g=await zn(i,c);for(let R of i.params)R.kind!=="resolve"&&(g[R.index]=await Us(R,c));u?.ran();let $=await h[i.fn](...g);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${i.id}'s upload before it was answered`);return u?u.record(js(Ds($,c.requestId),re.getStore()?.usedLocales)):$});return u?p:js(Ds(p,c.requestId),re.getStore()?.usedLocales)}async function qn(i,c){let f=i.headers.get("x-request-id")??"",u=Si.test(f)?f:`req_${crypto.randomUUID()}`,h=performance.now(),p=new URL(i.url).pathname,g={endpoint:p},$=await Qs(i,c,u,g);return e.telemetry?.record({requestId:u,method:i.method,endpoint:g.endpoint,path:p,status:$.status,durationMs:performance.now()-h,userId:g.userId}),$}function Hn(i,c){i.userId=c;let f=re.getStore();f&&(f.userId=c)}async function Qs(i,c,f,u){let h=e.strings,p=h?{requestId:f,strings:h,locales:ir(i.headers.get("accept-language"),h.source),usedLocales:[]}:{requestId:f},g=await Xs(p,i,c,f,u);return h&&Ht(g.headers,"Accept-Language"),g}async function Xs(i,c,f,u,h){return re.run(i,async()=>{let p=new URL(c.url),g=`${c.method} ${p.pathname}`;try{if(p.pathname===vn&&ge.size>0)return c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):e.webhookSecret?await Kt(c,u):T({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},u);let $=Gs(p.pathname);if($)return g=`webhook ${$.name}`,c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):await Ce(c,p,$,u);if(e.platform&&(p.pathname===Xe||p.pathname.startsWith(`${Xe}/`)))return g=p.pathname===Xe?"crons":`cron ${p.pathname.slice(Xe.length+1)}`,await Ks(c,p,e.platform.secret,u);if(e.platform&&(p.pathname===et||p.pathname.startsWith(`${et}/`)))return g=p.pathname===et?"tasks":`task ${p.pathname.slice(et.length+1)}`,await Fs(c,p,e.platform.secret,u);if(e.platform&&(p.pathname===an||p.pathname===br)){let z=p.pathname===an?"authorize":"complete";return g=`upload ${z}`,await Bs(z,c,e.platform.secret,u,h)}if(e.platform&&p.pathname.startsWith(`${on}/`)){let z=p.pathname.slice(on.length+1);return g=`gateway ${z}`,await Ys(z,c,e.platform.secret,u)}if(e.platform&&p.pathname===ts)return g="ai tool call",await Ws(c,e.platform.secret,u);if(e.platform&&p.pathname===ns)return g="ai agent's turn",await Vs(c,e.platform.secret,u);if(e.platform&&p.pathname===rs)return g="ai repository's token",await Zs(c,e.platform.secret,u);if(e.platform&&p.pathname.startsWith(`${xt}/`))return g=`test user template ${p.pathname.slice(xt.length+1)}`,await Js(c,p,e.platform.secret,u);if(Di(p.pathname))return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},u);let R=Sn(n,c.method,p.pathname);if(R&&"malformed"in R)return T({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},u);if(!R)return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},u);let{route:j,params:P}=R;if(g=j.id,h.endpoint=j.id.slice(j.id.indexOf(" ")+1),j.meta.upload)throw new ne(400,"upload_required",`${j.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let A=r.get(j),O=null,M=null,Z=c.headers.get("authorization")??"",H=/^(bearer|dpop)\s+(\S+)$/i.exec(Z),K=H?.[2],Ne=H?.[1].toLowerCase()==="dpop";if(K)try{let z=!Ne&&e.tokens&&!_i.test(K)&&e.tokens.accepts(K)?e.tokens:void 0,ye=z?await C.ask(K,qt(c.headers,f.remoteAddress),()=>Qe(e.database,null,c.signal,"token",()=>z.resolve(K))):await e.verifier.verify(K,Ne?{proof:c.headers.get("dpop"),method:c.method,url:Xn(c.headers,p)}:void 0);O=$i(ye),M=ye.claims}catch(z){if(!A.required&&(z instanceof vt||z instanceof Tt||z instanceof ht))O=null;else throw z instanceof ht?new ne(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:z.wait},z.wait):z instanceof vt?new ne(401,"invalid_token","The access token is not valid",{reason:z.reason},void 0,wi(z.reason)):z}else if(Z!==""&&A.required)throw new ne(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(O&&Hn(h,O.id),A.required&&!O)throw new ne(401,"unauthorized","This route needs a signed-in user");if(A.verifiedEmail&&!O?.emailVerified)throw new ne(403,"email_not_verified","This route needs a verified email address");let Gn=F(j);if(Gn!==!1){let z=O?`u:${O.id}`:`a:${qt(c.headers,f.remoteAddress)}`,ye=x.take(`${j.id}\0${z}`,Gn);if(ye!==void 0)throw new ne(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:ye},ye)}let Ue=c.method==="GET"||c.method==="HEAD"?void 0:await mt(c,N),gt=Ue===void 0?void 0:Ti(Ue),Bt=p.searchParams,xe=s.get(j),yt=c.headers.get(bt),rt=xe!==void 0||yt!==null?await a(j,P,yt,c.method):void 0;if(rt&&xe)try{if(xe.body.length>0&&gt!==void 0&&(gt=await rt.open(gt,"/body",xe.body)),xe.query.length>0){let z=await rt.open(Object.fromEntries(p.searchParams),"/query",xe.query);Bt=new URLSearchParams(p.searchParams);for(let ye of xe.query){let Jn=Vn(ye.slice(7)),wt=z[Jn];wt!==void 0&&Bt.set(Jn,typeof wt=="string"?wt:JSON.stringify(wt))}}}catch(z){throw Ns(z)}let Kn={request:c,query:Bt,params:P,user:O,body:gt,raw:Ue,requestId:u},Fn=w&&Ue!==void 0&&ut(j)?bs(c.method,c.headers):void 0;if(!w||Fn===void 0)return await xn(await Ft(j,Kn,M),rt,u);let ea={role:Rn(e.database.requests,M).role,uid:O?.id??`a:${qt(c.headers,f.remoteAddress)}`},Bn=!1,ta=yt!==null?{uri:`${p.pathname}${p.search}`,body:Ci(new TextEncoder().encode(`${yt}
21
+ `),Ue)}:{uri:`${p.pathname}${p.search}`,body:Ue},na=z=>async ye=>z(await xn(ye,rt,u));return await w.serve({key:Fn,caller:ea,method:c.method,...ta},z=>Ft(j,Kn,M,{record:na(z),ran:()=>{Bn=!0}}),{requestId:u,refusal:z=>T(z,u),failure:z=>Ms(z,u,g,c.signal),ran:()=>Bn})}catch($){return Ms($,u,g,c.signal)}})}return{handle:Y,routes:n.map(i=>i.id),contract:de,start:()=>t.start(),stop:async()=>{U.close();for(let i of W.keys())Nn(i);await t.shutdown(),await e.telemetry?.flush()}}}function Ai(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Pi(e){let t=new Set;for(let[n,r]of e)if(en(n))for(let s of r){if(s.bucket===void 0)return;t.add(s.bucket)}return t.size===0?void 0:[...t].sort()}function Ds(e,t){if(e instanceof Response)return ki(e,t);if(e==null)return new Response(null,{status:204,headers:{"x-request-id":t}});if(rr()===0)return le(200,e,t);let{value:n,pointers:r}=sr(e);return le(200,n,t,r.length>0?{[Pn]:JSON.stringify(r)}:{})}var Pn="x-palbase-answer-encrypted";async function xn(e,t,n){let r=e.headers.get(Pn);if(r===null)return e;if(!t)return await e.body?.cancel(),T({status:400,code:"encryption_required",message:`This route answers encrypted fields: the request names its key in ${bt}`,data:{field:bt}},n);let s=new Headers(e.headers);s.delete(Pn),s.delete("content-length");let a=await t.seal(await e.json(),JSON.parse(r));return new Response(JSON.stringify(a),{status:e.status,statusText:e.statusText,headers:s})}function Ci(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Ns(e){return e instanceof Zn?new ne(e.status,e.code,e.message,e.data):e}function ji(e){return`/${e.segments.map(t=>typeof t=="string"?t:"{}").join("/")}`}function Mi(e,t){if(!(!ct(e)||e.status!==503||!Cn(e)))return E.warn(`[palbase] webhook ${t}: the database did not answer (${e.error})`,{error:e}),{status:503,code:e.error,message:e.errorDescription,data:e.data,retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))}}function Di(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return qe.has(decodeURIComponent(t))}catch{return qe.has(t)}}var Ni="GET, POST, PUT, PATCH, DELETE, QUERY",Ui=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function Li(e){return Ui.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function Ii(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!Li(r))throw new TypeError(`cors origin ${JSON.stringify(r)} is https://host[:port] (http only for localhost), with no path`)}let t=e.origins==="*"?null:new Set(e.origins),n=String(e.maxAge??600);return{allows:r=>t===null||t.has(r),headers:r=>({"access-control-allow-origin":t===null?"*":r,"access-control-expose-headers":"idempotent-replayed, retry-after, x-request-id",vary:"Origin"}),preflight:(r,s)=>({"access-control-allow-origin":t===null?"*":r,"access-control-allow-methods":Ni,"access-control-allow-headers":s&&/^[A-Za-z0-9-]+(\s*,\s*[A-Za-z0-9-]+)*$/.test(s)?s:"authorization, content-type","access-control-max-age":n,vary:"Origin"})}}async function Us(e,t){switch(e.kind){case"body":return _n(e.schema,t.body??{},"Request body");case"query":return _n(e.schema,fe(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),fe(n),e.schema?_n(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return fe(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"client":{let n=t.request.headers;return fe({sdkVersion:n.get("x-palbase-sdk-version"),appVersion:n.get("x-palbase-client-version"),platform:n.get("x-platform"),osVersion:n.get("x-os-version")})}}}var Mn=720*3600;function jn(e){return e instanceof ce&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function qs(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),Mn)}function Hs(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Dn=class{filling=new Map;async get(t){try{let n=await we.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!jn(n))throw n;return E.warn("cache: a read could not reach the cache; it is a miss",{key:t,status:n.status}),null}}async set(t,n,r){try{await we.cache.putCacheEntry({query:{key:t},body:{value:Hs(n),ttl:qs(r)}})}catch(s){if(!jn(s))throw s;E.warn("cache: a write could not reach the cache; it is let go",{key:t,status:s.status})}}async del(t){await we.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await we.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,n,r){let s=this.filling.get(t);if(s)return s;let a=(async()=>{try{let o;try{o=(await we.cache.getCacheEntry({query:{key:t}})).data}catch(l){if(!jn(l))throw l;E.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:l.status})}if(o?.found)return o.value??null;let d=await r();return await this.set(t,d,n),d}finally{this.filling.delete(t)}})();return this.filling.set(t,a),a}},nu=$t("Cache",new Dn);function ru(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=m=>{let y=r.get(m);if(y&&y.expiresAt<=n()){r.delete(m);return}return y},o=()=>{let m=n();for(let[v,S]of r)S.expiresAt<=m&&r.delete(v);if(r.size<t)return;let y=[...r.entries()].sort((v,S)=>v[1].expiresAt-S[1].expiresAt);for(let[v]of y.slice(0,Math.ceil(y.length/4)))r.delete(v)},d=async(m,y,v)=>{r.size>=t&&!r.has(m)&&o(),r.set(m,{value:Hs(y),expiresAt:n()+(qs(v)??Mn)*1e3})};return{get:async m=>{let y=a(m);return y?structuredClone(y.value):null},set:d,async del(m){r.delete(m)},async incr(m){let y=a(m),v=(typeof y?.value=="number"&&Number.isInteger(y.value)?y.value:0)+1;return r.set(m,{value:v,expiresAt:y?.expiresAt??n()+Mn*1e3}),v},getOrSet(m,y,v){let S=a(m);if(S)return Promise.resolve(structuredClone(S.value));let G=s.get(m);if(G)return G;let U=(async()=>{try{let L=await v();return await d(m,L,y),L}finally{s.delete(m)}})();return s.set(m,U),U}}}export{Qt as a,Re as b,ze as c,Gi as d,Ki as e,Fi as f,Bi as g,Ji as h,Wi as i,Vi as j,Zi as k,Yi as l,Qi as m,Xi as n,ed as o,td as p,nd as q,rd as r,sd as s,ad as t,od as u,id as v,dd as w,cd as x,ud as y,ld as z,D as A,fd as B,pd as C,St as D,wd as E,bd as F,$d as G,Rd as H,Od as I,$a as J,Rr as K,Dd as L,Nd as M,Ud as N,Ld as O,Id as P,zd as Q,qd as R,Fd as S,J as T,Zr as U,Yr as V,Qr as W,fo as X,Xd as Y,nc as Z,rc as _,sc as $,ac as aa,oc as ba,ic as ca,dc as da,cc as ea,wc as fa,li as ga,Qc as ha,Li as ia,Mn as ja,nu as ka,ru as la};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./5FJNJOWL.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
1
+ /*! palbase 0.13.2 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./7ZSVOQFN.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
@@ -0,0 +1,13 @@
1
+ /*! palbase 0.13.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as z,f as Q,g as Y,j as Z,k as X,l as ee,o as G,p as te,q as ne}from"./B33QXIR5.js";import{b as M,c as N,d as T}from"./2DBSGJ7Z.js";import{d as A}from"./ZOF56QTG.js";import{a as b,b as V,c as _,e as j}from"./7ZSVOQFN.js";var l=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function oe(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??qe(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:Ne(e)??t.retryAfter});let s=Me(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function R(t){return t instanceof V||t instanceof Error&&t.name==="PalbaseError"}function se(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Me(t){let e=E(E(t,"data"),"fields");if(se(e))return e;let n=E(t,"fields");return se(n)?n:void 0}function Ne(t){return re(t,"retry_after")??re(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function re(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function qe(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var De=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ke=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Be=new Set(Ke),Le=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Le.has(t)}function ae(t){return t==="call"||t==="join"||P(t)}function ie(t){return typeof t=="string"&&De.test(t)&&!Be.has(t)&&!P(t)}function de(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function le(t){j(t)}function ce(t){return j(t).origin}var I=class{me;reader;messages=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let a=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(a,s)}if(this.ended)return!1;let o=(r?.parts??[]).map(a=>M(a)).filter(a=>a!==void 0);return this.older=[...o,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(a=>e=a)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=M(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:N(n.text),thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:N(n.text),thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset));break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Fe(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?ue(e.attachments):s?.attachments??[]}),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n}),this.changed()}place(e,n){let s=e.response_id??null,o=s!==null&&![...this.messages.entries()].some(([a,i])=>a!==n&&i.responseId===s)?this.order.findIndex(a=>a.type==="response"&&a.key===s):-1;o>=0?this.order.splice(o,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=d=>e!==void 0&&d.startedBy===e,s=new Map;for(let d of this.responses.values()){let u=d.parentId!==null?this.responses.get(d.parentId)??d:d;s.set(d.id,We(d,u.startedBy??null,n(u),d.goal??u.goal))}let r=new Map([...this.messages].map(([d,u])=>[d,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([d],[u])=>d-u).flatMap(([d,u])=>u.map((f,m)=>He(f,`${d}:${m}`,e))),a=[...o];for(let d of this.order)d.type==="goal"?a.push({type:"goal",goal:d.event}):d.type==="voice"?a.push({type:"voice",voice:d.event}):d.type==="message"?a.push({type:"message",message:r.get(d.key)}):this.responses.get(d.key).parentId===null&&a.push({type:"response",response:s.get(d.key)});let i=o.flatMap(d=>d.type==="message"?[d.message]:[]),c=o.flatMap(d=>d.type==="response"?[d.response]:[]),p=[...this.calls.values()].filter(d=>s.get(d.response_id)?.mine===!0);return{items:a,messages:[...i,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:p.filter(d=>d.status==="awaiting_approval"),outputs:p.filter(d=>d.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Je(this.voice,e):null}}};function Je(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function ue(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Fe(t){return`${t.author??""}\0${t.client_id}`}function We(t,e,n,s){let r=[...t.marks.values()].map((c,p)=>({m:c,i:p,at:T(t.text,Math.max(0,Number(c.text_offset)||0))}));r.sort((c,p)=>c.at-p.at||c.i-p.i);let o=[],a=[],i=0;for(let{m:c,at:p}of r)p>i&&o.push({type:"text",text:t.text.slice(i,p)}),i=Math.max(i,p),c.type==="thinking"?(o.push({type:"thinking",thinking:c.thinking}),a.push(c.thinking)):o.push(c.type==="tool"?{type:"tool",tool:c}:{type:"agent",agent:c});return i<t.text.length&&o.push({type:"text",text:t.text.slice(i)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:a,goal:s,history:!1,truncated:!1}}function He(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:ue(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function pe(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var $=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},he=new WeakMap;async function fe(t,e,n,s={},r=()=>{},o){let{pattern:a,events:i,messages:c,durable:p,chat:d}=Ue(e),u=Ve(a,n),f=he.get(t);f||he.set(t,f=new Map);let m=f,g=m.get(u)??{count:0};m.set(u,g),g.count++;let y=t.channel(u,p&&s.history!==!1?{after:0}:{});if(d&&!g.chat){let h=n.chatId,k=new I(r,o,typeof h=="string"&&h!==""?h:void 0);g.chat=k,g.unchat=y.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let x=()=>{--g.count>0||(m.delete(u),g.unchat?.(),g.chat?.end(),y.leave())};try{await y.join()}catch{let h=y.state==="refused"?ge(y.refusal,"unavailable"):"socket closed";throw x(),new $(`gateway ${JSON.stringify(u)} was not joined: ${h}`,h)}let C=!1,S=new Set,W=()=>{if(!C){C=!0,Ge();for(let h of[...S])h();x()}},Ge=y.onClosed(W),H=h=>{if(C)return()=>{};let k=y.on("broadcast",v=>{typeof v.event=="string"&&i.has(v.event)&&h(v.event,b(v.payload))}),w=()=>{S.delete(w),k()};return S.add(w),w},U={topic:u,get seq(){return y.logSeq},on(h,k){if(typeof h=="function")return H((w,v)=>h({event:w,payload:v}));if(!i.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(h))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===h&&k(v)})},off(h){S.has(h)&&h()},async send(h,k){if(!c.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(h))}`);let w=C?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:h,payload:k});if(w.status==="ok")return b(w.response.reply);let v=ge(w.response,"unavailable");throw new $(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(h)}: ${v}`,v)},leave:W};return d&&Object.defineProperty(U,"chat",{value:g.chat,enumerable:!0}),U}function Ue(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function Ve(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ge(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ze=3600*1e3,O=new Map;function Qe(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=O.get(s);if(!n&&r&&Date.now()-r.at<ze)return r.list;let o=(async()=>{let a=te(),i;try{i=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new l("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await ne(i,e.signer,e.projectId,a)}catch(c){throw new l("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:c})}})();return O.set(s,{list:o,at:Date.now()}),o.catch(()=>{O.get(s)?.list===o&&O.delete(s)}),o}async function ye(t,e,n,s,r,o){let i=(await Qe(t,e,o)).keys[0];return Y(i.kid,i.key,Q(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>Z(t.key,r,o))}function me(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!X(o))throw new l("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ee(t.key,r,o)}catch(a){throw new l("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function we(t){return t instanceof l&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
+ `);let n=[],s=this.pending.indexOf(`
4
+ `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
5
+ `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let a=o.slice(5);this.dataLines.push(a.startsWith(" ")?a.slice(1):a)}else if(o.startsWith("event:")){let a=o.slice(6);this.eventName=a.startsWith(" ")?a.slice(1):a}}s=this.pending.indexOf(`
6
+ `)}return n}};async function*ve(t,e){let n=t.getReader(),s=new TextDecoder,r=new B;try{for(;;){let{done:o,value:a}=await n.read();if(o)break;for(let i of r.consume(s.decode(a,{stream:!0}))){if(i.event==="error")throw new l("network",{code:"stream_failed",message:`stream failed: ${i.payload}`});let c;try{c=JSON.parse(i.payload)}catch{throw new l("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${i.payload.slice(0,120)}`})}yield b(c)}}}finally{e.abort();try{await n.cancel()}catch{}}}var Ye={},be=new WeakMap;function Nt(t,e,n,s,r,o=()=>{}){be.set(t,{project:e,machine:n,storage:s,socket:r,me:o})}var _e=new Map,ke=new WeakMap;function qt(t,e,n,s,r,o){if(!ie(e))throw new l("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let a=ce(t);if(!de(n))throw new TypeError(`${JSON.stringify(String(n))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);le(s),Ce(r);for(let i of Object.keys(r))if(ae(i))throw Ee(i);if(o!==void 0)nt(o);else if(xe(r))throw new l("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(_e.get(e)??Ze(e)).set(a,{machine:n,url:s,tree:r,...o?{transit:{...o}}:{}})}function Ze(t){let e=new Map;return _e.set(t,e),Object.defineProperty(Ye,t,{configurable:!0,get(){return Xe(this,t,e)}}),e}function Xe(t,e,n){let s=be.get(t);if(!s)return;let r=n.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...n.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=ke.get(t);o||ke.set(t,o=new Map);let a=o.get(e);if(a?.registration===r)return a.ns;let i={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},c=Object.assign({call:(p,d,u)=>dt(i.machine,p,d,u),join:(p,d,u)=>fe(s.socket,p,d,u,s.me,pe(s.storage))},Se(r.tree,i));return o.set(e,{registration:r,ns:c}),c}function Ee(t){return new l("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(t)}: the name is reserved.`})}function L(t){return typeof t.path=="string"&&typeof t.method=="string"}function et(t,e){if(t.pathParams!==void 0){if(!Array.isArray(t.pathParams)||!t.pathParams.every(n=>typeof n=="string"))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let n of t.pathParams)if(!t.path.includes(`{${n}}`))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${n}' has no '{${n}}' placeholder in the path.`})}if(t.sse!==void 0&&typeof t.sse!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(t.idempotent!==void 0&&typeof t.idempotent!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(t.upload!==void 0&&typeof t.upload!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(t.upload===!0&&(t.method!=="POST"||t.sse===!0))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(t.sse===!0&&t.input==="query")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(t.input!==void 0&&t.input!=="body"&&t.input!=="query"&&t.input!=="none")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(t.encryption!==void 0&&tt(t,e),t.errors!==void 0){for(let[n,s]of Object.entries(t.errors))if(typeof s!="function")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${n}'] must be a function.`})}}function tt(t,e){let n=t.encryption,s=r=>new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof n!="object"||n===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let a=n[r];if(a!==void 0&&(!Array.isArray(a)||!a.every(i=>typeof i=="string"&&o.some(c=>i===c||i.startsWith(c.endsWith("/")?c:`${c}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(t.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(t.sse===!0&&(n.response?.length??0)>0)throw s("of a streamed answer is none")}function xe(t){return L(t)?t.encryption!==void 0:Object.values(t).some(e=>xe(e))}function nt(t){if(typeof t!="object"||t===null||typeof t.projectId!="string"||!/^[0-9a-f-]{36}$/.test(t.projectId)||typeof t.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(t.signer))throw new l("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Ce(t){if(typeof t!="object"||t===null)throw new l("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)throw new l("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[n,s]of Object.entries(t)){if(P(n))throw Ee(n);typeof s=="object"&&s!==null&&L(s)?(s.method=s.method.toUpperCase(),et(s,s.path)):Ce(s)}}function Se(t,e){if(L(t))return t.upload===!0?async(...s)=>at(e,t,s):async(...s)=>Pe(e.machine(),t,s,e.transit);let n={};for(let[s,r]of Object.entries(t))n[s]=Se(r,e);return n}function J(t){if(t==null)return"";let e=Object.entries(t).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new l("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function Te(t,e,n){try{return _(t.path,e,n)}catch(s){if(!R(s)||s.code!=="invalid_path_parameter")throw s;let r=String(n);throw new l("validation",{code:"invalid_path_parameter",message:`${t.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function Re(t,e){let n=t.pathParams??[],s=t.path;for(let r=0;r<n.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new l("validation",{code:"missing_path_param",message:`${t.path}: path parameter '${n[r]}' must be a string or number`});s=s.replace(`{${n[r]}}`,Te(t,`path parameter '${n[r]}'`,o))}return s}var st=new Set(["POST","PUT","PATCH","DELETE"]);async function Pe(t,e,n,s){let r=e.pathParams??[],o=Re(e,n),a=o;if(e.input==="none"&&n.length>r.length+1)throw new l("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let i=e.input==="none"?void 0:n[r.length],c=e.input==="none"?r.length:r.length+1,p=n[c],d;if(e.input==="query")a+=J(i);else if(e.input!=="none")if(e.method==="GET"){if(i!==void 0)throw new l("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else d=i;let u={...p?.headers};if(st.has(e.method)&&!Object.keys(u).some(f=>f.toLowerCase()==="idempotency-key")&&(u["Idempotency-Key"]=A()),e.encryption!==void 0){if(!s)throw new l("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return rt(t,e,o,i,d,u,p?.signal,r.map((f,m)=>String(n[m])),s)}try{return e.sse===!0?await Ae(t,e,a,d,u,p?.signal):await Oe(t,e,a,d,u,p?.signal)}catch(f){throw F(e,f)}}async function rt(t,e,n,s,r,o,a,i,c){let p=e.encryption;for(let d=0;;d++){let u=await ye(c.project,c.config,e.method,e.path,i,d>0);try{let f=e.input==="query"?n+J(await K(u,s,"/query",p.request)):n,m=await K(u,r,"/body",p.request),g={...o,[z]:u.header};return e.sse===!0?await Ae(t,e,f,m,g,a):b(await me(u,await Oe(t,e,f,m,g,a),p.response,`${e.method} ${e.path}`))}catch(f){if(d===0&&we(f))continue;throw F(e,f)}}}function F(t,e){return t.errors&&oe(e)&&Object.hasOwn(t.errors,e.code)?t.errors[e.code](e):e}var ot=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function at(t,e,n){let s=e.pathParams??[],r=Re(e,n),o=e.input==="none"?s.length:s.length+1;if(n.length>o+2)throw new l("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let a=e.input==="none"?void 0:n[s.length],i=n[o],c=n[o+1];if(!(i instanceof Blob))throw new l("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let p=`/storage/upload/${t.name}/${Te(e,"the route",r.slice(1))}`;e.input==="query"&&(p+=J(a));let d=it(e.input==="query"?void 0:a,i),u=d.body.size,f=0,m=g=>{f=g;try{c?.onProgress?.({loaded:g,total:u})}catch{}};c?.onProgress&&m(0);try{let g;try{let y={op:`Upload ${e.path}`,method:"POST",path:p,auth:ot,answers:Ie,body:{kind:"raw",contentType:d.type,value:d.body},signal:c?.signal,...c?.onProgress?{onUploadProgress:x=>m(x)}:{}};g=(await t.storage.send(y)).data}catch(y){throw R(y)?q(y):y}return c?.onProgress&&f<u&&m(u),await je(e,g,c?.signal)}catch(g){throw F(e,g)}}function it(t,e){let n=`Palbase-${A()}`,s=i=>i.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(i,c)=>`--${n}\r
7
+ Content-Disposition: form-data; ${i}\r
8
+ Content-Type: ${c}\r
9
+ \r
10
+ `,a=[];return t!==void 0&&a.push(o('name="body"',"application/json"),JSON.stringify(t),`\r
11
+ `),a.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
12
+ --${n}--\r
13
+ `),{body:new Blob(a),type:`multipart/form-data; boundary=${n}`}}async function dt(t,e,n,s){if(typeof e!="string"||e===""||e==="/")throw new l("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Pe(t(),{method:"POST",path:r},[n,s])}var Ie=Object.fromEntries(Array.from({length:100},(t,e)=>[200+e,"raw"])),lt=[["userJWT"],[]];async function $e(t,e,n,s,r,o){let a={op:`${e.method} ${e.path}`,method:e.method,path:n,auth:lt,answers:Ie,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await t.send(a)).data}catch(i){throw R(i)?q(i):i}}async function Oe(t,e,n,s,r,o){return je(e,await $e(t,e,n,s,r,o),o)}async function je(t,e,n){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw n?.aborted?o:new l("network",{code:"network_error",message:`${t.method} ${t.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return b(JSON.parse(r))}catch(o){throw new l("decode",{code:"invalid_json",message:`${t.method} ${t.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function Ae(t,e,n,s,r,o){let a=new AbortController;o&&(o.aborted?a.abort():o.addEventListener("abort",()=>a.abort(),{once:!0}));let i=await $e(t,e,n,s,{accept:"text/event-stream",...r},a.signal);if(!i.body)throw new l("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:i.status});return ve(i.body,a)}export{l as a,oe as b,Ke as c,ie as d,pe as e,$ as f,Ye as g,Nt as h,qt as i};