palbase 0.10.2 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +11 -11
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/26UTOC32.js +2 -0
- package/dist/chunks/{IW34A4TV.js → 3453XVQL.js} +2 -2
- package/dist/chunks/{7PBQ3LI2.js → 3VY3ZZCI.js} +1 -1
- package/dist/chunks/{MAPLN2FY.js → 43VM626B.js} +1 -1
- package/dist/chunks/{BMCC423W.js → 7WIMZTYB.js} +2 -2
- package/dist/chunks/{ZOAWYN6L.js → AFFE3Q5O.js} +2 -2
- package/dist/chunks/{RYWIWH4U.js → BUAGC2PT.js} +1 -1
- package/dist/chunks/{5TVS7F23.js → BUYFMLTF.js} +2 -2
- package/dist/chunks/{O5CJJFEU.js → EEWP43KI.js} +1 -1
- package/dist/chunks/EWBRYA7P.js +2 -0
- package/dist/chunks/{S4F256W2.js → FVLHT7UQ.js} +2 -2
- package/dist/chunks/{SCXHU5B7.js → KNPQNBC2.js} +2 -2
- package/dist/chunks/{D2UQQWJC.js → KW6ODEYS.js} +1 -1
- package/dist/chunks/{5NZGW67E.js → LYEEW4UG.js} +2 -2
- package/dist/chunks/{SBVBCENU.js → NGE3D2K4.js} +2 -2
- package/dist/chunks/Q3S76MYJ.js +2 -0
- package/dist/chunks/{QTAPRS4Q.js → R3EIGCWV.js} +2 -2
- package/dist/chunks/{XJEZB4MI.js → S2KRJF6J.js} +2 -2
- package/dist/chunks/{6JUQZ4D4.js → V2FEPVVD.js} +2 -2
- package/dist/chunks/WLAO2QSR.js +20 -0
- package/dist/chunks/{L4SCG6HT.js → ZZG7ICDG.js} +2 -2
- package/dist/cli.js +124 -122
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/backend/src/database.d.ts +8 -1
- package/types/backend/src/engine-db.d.ts +3 -1
- package/types/backend/src/engine.d.ts +2 -0
- package/types/backend/src/idempotency.d.ts +136 -0
- package/types/internal/src/modules/auth.d.ts +25 -8
- package/types/internal/src/modules/purchases.d.ts +39 -3
- package/types/internal/src/modules/secrets.d.ts +138 -3
- package/types/internal/src/modules/stores.d.ts +30 -1
- package/types/server/src/fields.d.ts +62 -0
- package/types/server/src/index.d.ts +1 -0
- package/types/server/src/server.d.ts +8 -0
- package/types/server/src/testing.d.ts +8 -0
- package/dist/chunks/I2TY2GLY.js +0 -2
- package/dist/chunks/PKBCMWTM.js +0 -2
- package/dist/chunks/QCKQXIQV.js +0 -20
package/dist/chunks/QCKQXIQV.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.10.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as yt,c as ae,d as zn,e as Hn,f as ge,h as E,i as Gn}from"./XJEZB4MI.js";import{b as et,d as mt,e as Nn,f as Un,g as ht,h as gt,k as Ln,q as In}from"./PKBCMWTM.js";import{b as ce}from"./SCXHU5B7.js";import"reflect-metadata";var zt=[{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}],Fn="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)",wt=/^\d+$/;function Ms(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 g=s.slice(a+1);if(!wt.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let u=t,m=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),S=o.slice(g+1);if(!wt.test(k)||!wt.test(S)||Number(k)<t||Number(S)>n||Number(k)>Number(S))return;u=Number(k),m=Number(S)}else{if(!wt.test(o)||Number(o)<t||Number(o)>n)return;u=Number(o),m=a===-1?u:n}for(let g=u;g<=m;g+=d)r.add(g)}return r}function Bn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${Fn}; "${e}" is not`;let n=[];for(let m=0;m<5;m++){let g=Ms(t[m],zt[m].lo,zt[m].hi);if(!g)return`${Fn}; its ${zt[m].name} "${t[m]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),u=new Date(Date.UTC(2e3,0,1));for(let m=0;m<366*8+2;m++,u.setUTCDate(u.getUTCDate()+1)){if(!s.has(u.getUTCMonth()+1))continue;let g=r.has(u.getUTCDate()),k=a.has(u.getUTCDay());if(o||d?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Ce=Symbol.for("palbase.backend.controller"),je=Symbol.for("palbase.backend.routes"),Gt=Symbol.for("palbase.backend.params"),Ft=Symbol.for("palbase.backend.injectable"),Bt=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),Me=Symbol.for("palbase.backend.webhook"),ke=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks"),we=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 Ht=Symbol.for("palbase.backend.declared");function oe(){let e=globalThis;return e[Ht]instanceof Set||(e[Ht]=new Set),e[Ht]}var De=new Set(["webhooks","_palbase"]);function wi(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&&De.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ue(n,Ce,()=>({basePath:e,options:t})),oe().add(n)}}function Ne(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,je,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var bi=Ne("GET"),ki=Ne("POST"),vi=Ne("PUT"),Ti=Ne("PATCH"),$i=Ne("DELETE"),Ei=Ne("QUERY");function fe(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,Gt,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function Kt(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 Si=e=>fe("body",{schema:Kt("Body",e)}),_i=e=>fe("query",{schema:Kt("QueryParams",e)}),xi=e=>fe("headers",e===void 0?{}:{schema:Kt("Headers",e)}),Oi=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return fe("param",{name:e})},Ri=()=>fe("user"),Ai=()=>fe("optionalUser"),Pi=()=>fe("req"),Ci=()=>fe("requestId"),ji=()=>fe("requestId"),Mi=()=>fe("client");function Di(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 fe("resolve",{resolver:e,options:t[0]})}function Ni(){return e=>{ue(e,Ft,()=>!0),oe().add(e)}}function Ui(e){return t=>{ue(t,Bt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Jn=/^[a-z]+(\.[a-z_]+)+$/,Ds=/^[a-z][a-z0-9-]{1,62}$/,qt=e=>e.startsWith("file.");function Li(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"||!Ds.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(!qt(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,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),oe().add(r.constructor)}}var Jt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ns=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Kn(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(!Ns.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 Ii(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Jt.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=Bn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Kn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Kn(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,ke))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,ke,{value:s,enumerable:!1}),oe().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Us=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function zi(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(!Us.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&&!qn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${qn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Ls(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,Se)??[];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,Me,()=>({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}))})),oe().add(t)}}function Ls(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 Hi(){return[...oe()].filter(e=>D(e,Ce)!==void 0)}function Gi(e){return(D(e,je)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var bt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Ji(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Jt.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,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),oe().add(s)}}var Zt;function Vn(e){Zt=e}function Wt(){if(!Zt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Zt}var Is=720*3600;function zs(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Is))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 Hs(e){if(typeof e=="string")return e;let t=e[ye];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Wi=yt("Tasks",{async enqueue(e,t,n={}){return zs(n),Wt().enqueue(Hs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Wt().cancel(e,t.machine)},async get(e,t={}){return Wt().get(e,t.machine)}}),Vt=(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 Zn(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 ge.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 Vt(a.data,a.status===200)},async cancel(n,r){return Vt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Vt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Gs=1e4,Fs=36e5,Wn=24*36e5,kt=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 u of this.tasks.values())if(u.task===t&&u.key===r.key&&(u.finishedAt===void 0||this.now()-u.finishedAt<Wn))return this.view(u,!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(Gs*2**Math.min(t.attempt-1,16),Fs),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>=Wn&&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 vt="/_palbase/test-user-templates",Bs=/^[a-z][a-z0-9_-]{0,63}$/;function Yi(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bs.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,we))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,we,{value:r,enumerable:!1}),oe().add(s)}}function Qn(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 Yn(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 Ks="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 Xn(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Ks),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var Qt="/_palbase/storage/upload/authorize",er="/_palbase/storage/upload/complete",Yt="/_palbase/realtime/rooms";var qs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ue(e){if(!qs(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 tr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function nr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Tt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Js=/^[a-z][a-z0-9-]{1,62}$/,rr=1024,Ws=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(!Js.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=Vs(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,u)=>{if(typeof d!="string"||u===void 0||typeof u.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ue(o.constructor,je,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function sd(){return fe("uploadedObject")}function Vs(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Ws.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(!sr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function sr(e){if(e===""||new TextEncoder().encode(e).byteLength>rr)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 Zs(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Qs(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Qs(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 ar(e,t){let n=Zs(e,t);return sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${rr} bytes)`}}function or(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 Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ir(e,t){if(!Xt(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=Ue(t.user);if(!o)return"user is { id?, session?, role }";let d=tr(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 u=Ys(t.uploadedObject);return u?u.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:u,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Ys(e){if(!Xt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:u,thumbhash:m,variants:g}=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"||u!==void 0&&typeof u!="number"||m!==void 0&&typeof m!="string")&&!(!Xt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...u!==void 0?{height:u}:{},...m!==void 0?{thumbhash:m}:{},variants:{...g}}}import{markData as Xs}from"palgres";var _e=Symbol.for("palbase.backend.gateway"),ze=Symbol.for("palbase.backend.gatewayHooks"),dr={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"]},ea={"~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(dr),output:()=>structuredClone(dr)}}},hr=Symbol.for("palbase.backend.gatewayRefusal"),cr=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,hr,{value:!0})}},ta=e=>typeof e=="object"&&e!==null&&e[hr]===!0&&typeof e.reason=="string",Le=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,na=6e4,ra=86400,ur=604800,lr=65536,ve=255,sa=["roles:","flags:","messaging:","debug:"],aa=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(" ")),Ie=e=>new TextEncoder().encode(e).byteLength,en=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",rn=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(Ie(e)>ve)return`a channel is ${ve} 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=sa.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 gr(e){if(typeof e!="string"||e==="")return"is a name";if(Ie(e)>ve)return`is ${ve} bytes at most`}function ud(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"&&rn(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=ia(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)||aa.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[g,k]of Object.entries(d)){let S=gr(g);if(S)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${S}`);if(!en(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let u=ue(a,ze,sn),m={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:ea}:{...d},chat:r.chat===!0,graceMs:r.graceMs??na,hooks:{...u.hooks},messages:Object.assign(Object.create(null),u.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&&Le(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&&!Le(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,_e,()=>m),oe().add(a)}}function ia(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return ra;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>ur)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${ur} (a week)`);return n}var sn=()=>({hooks:Object.create(null),messages:Object.create(null)}),da={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function tt(e){let t=da[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,ze,sn),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,oe().add(n.constructor)}}var ld=tt("authorize"),fd=tt("first"),pd=tt("connect"),md=tt("disconnect"),hd=tt("empty");function gd(e,t,n={}){let r=gr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!en(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!en(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,ze,sn),u=d.messages[e];if(u!==void 0&&u.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${u.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},oe().add(s.constructor)}}function ca(e){return D(e,_e)}function ua(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 yr(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 Ie(r)>ve?{problem:`a channel is ${ve} bytes at most`}:r}function la(e,t,n){let r=rn(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))?yr(e,t):fa(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 fa(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 pa=1e4,ma=1e3,ha=100,an=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}:{}}),fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},pr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function wr(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 P=s.get(pr(b.pattern));if(P!==void 0)throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: ${n.get(P)?.cls.name}'s "${P}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(pr(b.pattern),b.pattern);for(let[F,K]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([G,U])=>[`message ${G}`,U.fn])])if(typeof _[K]!="function")throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: its ${F} is ${K}, 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,u=new Set,m=new nn(t.broadcast),g=w=>{let _=o.get(w);return _||(_=new AbortController,o.set(w,_)),_},k=(w,_)=>{_?.abort(),o.get(w)===_&&o.delete(w)},S=(w,_,b,x,P,N)=>{if(!Object.hasOwn(w.g.events,b)){E.warn(`[palbase] ${P}: 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] ${P}: 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}:{}},P)},I=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 H(w,_,b,x,P,N,F){let K=x?.signal??AbortSignal.abort(),G=`${w.cls.name} (${_})`;return{channel:_,params:Object.freeze({...b}),signal:K,count:P,user:N,emit:(U,W)=>S(w,_,U,W,G,F),pipe:U=>I(U,_,G),owner:{hold(U){ae.exit(async()=>{try{await U(K)}catch(W){K.aborted||E.error(`[palbase] ${G}: a task owner.hold ran failed`,{error:W})}}).catch(()=>{})},release:()=>k(_,x)}}}function z(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||!Le(x.g)?he(404,"not_found",`This app serves no gateway "${_}"`):{entry:x,channel:b,params:ua(_,b)}}let te=(w,_)=>he(400,"bad_request",`"${_}" is not a channel of the gateway "${w}"`);async function ee(w,_){let b=z(w);if("status"in b)return b;let{entry:x,channel:P,params:N}=b,F={status:200,body:{subscribe:!1,publish:!1}};if(!N)return E.warn(`[palbase] ${x.cls.name}: realtime asked about "${P}", which is not a channel of the gateway "${x.g.pattern}"; the join is refused`),F;let K=Ue(w.user),G=K?.id;if(!G)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[rn(x.g.pattern)[0].slice(1,-1)]===G?{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}}:F;let U=x.g.hooks.authorize;if(!U)return F;let W,V;try{W=await t.run(K,`${x.cls.name}.${U}`,_,async()=>x.instance[U]({user:{id:G},params:Object.freeze({...N})})),V=ga(W)}catch(Y){if(t.isOutage(Y)||_?.aborted)throw Y;return E.error(`[palbase] ${x.cls.name}.${U} (@Authorize of ${P}) failed; the join is refused`,{error:Y}),F}return V==="malformed"?(E.warn(`[palbase] ${x.cls.name}.${U} (@Authorize of ${P}) answered ${ya(W)}, which is no grant (true, { read, write } or null); the join is refused`),F):{status:200,body:V}}async function se(w,_){let b=z(w);if("status"in b)return b;if(!b.params)return te(b.entry.g.pattern,b.channel);let x=Ue(w.user);if(!x?.id||typeof w.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let P=Object.hasOwn(b.entry.g.messages,w.event)?b.entry.g.messages[w.event]:void 0;if(!P)return{status:200,body:{ok:!1,reason:tn(`gateway "${b.channel}" takes no message "${w.event}"`,$t)}};let N=await P.schema["~standard"].validate(Xs(w.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:mr(N.issues)}};let F=g(b.channel),K={...H(b.entry,b.channel,b.params,F,0,{id:x.id}),payload:N.value},G=`${b.entry.cls.name}.${P.fn} (@Subscribe "${w.event}" of ${b.channel})`,U;try{U=await t.run(x,`${b.entry.cls.name}.${P.fn}`,_,async()=>b.entry.instance[P.fn](K))}catch(V){if(t.isOutage(V))throw V;return ta(V)?{status:200,body:{ok:!1,reason:tn(V.reason,$t)}}:(_?.aborted||E.error(`[palbase] ${G} failed`,{error:V}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(U===void 0)return{status:200,body:{ok:!0}};if(P.reply){let V=await P.reply["~standard"].validate(U);if(V.issues)return E.error(`[palbase] ${G} returned an ack its reply schema refuses (${mr(V.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};U=V.value}let W;try{W=JSON.stringify(U)}catch(V){return E.error(`[palbase] ${G} returned an ack that is not JSON; the member is told it failed`,{error:V}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return W===void 0?{status:200,body:{ok:!0}}:Ie(W)>lr?(E.error(`[palbase] ${G} returned an ack of ${Ie(W)} bytes, past ${lr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(W)}}}async function v(w,_){let b=z(w);if("status"in b)return b;if(!b.params)return te(b.entry.g.pattern,b.channel);let x=w.event;if(typeof x!="string"||!Object.hasOwn(fr,x))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let P=typeof w.count=="number"&&Number.isInteger(w.count)&&w.count>=0?w.count:void 0;if(P===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let N=x==="join"||x==="leave",F=N?Ue(w.user):void 0,K=N?w.connId:void 0;if(N&&(!F?.id||typeof K!="string"||K===""))return he(400,"bad_request",`A ${x} names its member: user and connId`);let G=`${x}\0${b.channel}\0${typeof K=="string"?K:""}`;if(N&&d.has(G))return{status:204};if(u.has(G))return he(503,"in_progress","This moment of the gateway is being handled",5);u.add(G);try{let U=b.entry.g.hooks[fr[x]],W;if(x==="empty"?(W=o.get(b.channel),k(b.channel,W)):W=x==="leave"?o.get(b.channel):g(b.channel),U){let V=H(b.entry,b.channel,b.params,W,P,{id:F?.id??""},x==="join"?K:void 0);try{await t.run(F,`${b.entry.cls.name}.${U}`,_,async()=>b.entry.instance[U](V))}catch(Y){if(t.isOutage(Y))throw Y;return _?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${U} (${x} of ${b.channel}) failed; realtime tells it again`,{error:Y}),he(500,"handler_failed",`The gateway's ${x} could not be handled`)}}return N&&(d.add(G),d.size>pa&&d.delete(d.values().next().value)),{status:204}}finally{u.delete(G)}}function Q(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 P=yr(b.g.pattern,_??{});if(typeof P!="string")throw new TypeError(`${x}: ${P.problem}`);return{entry:b,channel:P,where:x}}return{declarations:[...n.values()].map(w=>w.g),async serve(w,_,b){return an(_)?w==="authorize"?ee(_,b):w==="message"?se(_,b):w==="lifecycle"?v(_,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:P,channel:N,where:F}=Q(w,_);S(P,N,b,x,F)},async pipe(w,_,b){let{channel:x,where:P}=Q(w,_);await I(b,x,P)},async revalidate(w,_,b={}){let x=r.get(w),P=`Palbase.gateways.to(${w?.name??String(w)}).revalidate`;if(!x)throw new TypeError(`${P}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=la(x.g.pattern,_??{},b);if("problem"in N)throw new TypeError(`${P}: ${N.problem}`);await t.revalidate(N)},close(){for(let w of o.values())w.abort();o.clear()}}}function ga(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!an(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 ya(e){return Array.isArray(e)?"an array":an(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 wa=20,$t=256;function mr(e){let t="";for(let n of e.slice(0,wa)){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)>=$t)break}return tn(t,$t)}function tn(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 nn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ie(t.event)>ve){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${ve} 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>=ma?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),ae.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,ha);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 on,createHmac as ba,createPublicKey as Tr,timingSafeEqual as ka,verify as $r}from"node:crypto";function kd(e){let t=D(e,Me);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 Er(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Me),u=s.get(d.name);if(u)throw new TypeError(`@Webhook "${d.name}" is declared by ${u.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let m=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${m} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=va(d,g)}catch(H){a.push(`${m}: ${d.secret.env} ${H.message}`)}let S=t(o),I=new Map(d.events.map(({event:H,fn:z})=>[H,{name:`${o.name}.${z}`,call:(te,ee)=>S[z](te,ee)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:I})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
|
-
- ${a.join(`
|
|
4
|
-
- `)}`);return s}function Sr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var He=1024,br=1024*He;function va(e,t){if(e.signature)return xe(void 0,e.signature.header,1/0,Ca(e.signature,t));switch(e.provider){case"stripe":return xe("stripe","stripe-signature",512*He,Ea(t));case"github":return xe("github","x-hub-signature-256",25*br,Sa(t));case"slack":return xe("slack","x-slack-signature",64*He,_a(t));case"discord":return xe("discord","x-signature-ed25519",64*He,xa(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*He),check:Ra(t)};case"sendgrid":return xe("sendgrid","x-twilio-email-event-webhook-signature",br,Aa(t));case"livekit":return xe("livekit","authorization",512*He,Pa(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function xe(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??_r(e,s)}}function _r(e,t){let n=dn(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:xr(e,t.headers,r),event:r,...Ta(e,t,r)}}function xr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Oe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Ar(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 Oe(n,"EventType");case"livekit":return Oe(n,"event");default:return Oe(n,"type")}}function Ta(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Oe(n,"id"));case"slack":return r(Oe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${Or(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Oe(s,"sg_event_id")||void 0)}:{};default:return{}}}var $a=300;function Ea(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let u of r.split(",")){let m=u.indexOf("=");if(m<=0)continue;let g=u.slice(0,m).trim(),k=u.slice(m+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(g==="v1"){let S=pe(k,"hex");if(!S)return"malformed_signature";a.push(S)}}let o=nt(s);if(o===void 0||a.length===0)return"malformed_signature";if(rt(o,n))return"stale_timestamp";let d=Ge("sha256",e,`${s}.`,t.body);return a.some(u=>Te(u,d))?void 0:"signature_mismatch"}}function Sa(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?pe(n.slice(7),"hex"):void 0;return r?Te(r,Ge("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function _a(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=nt(s),o=r.startsWith("v0=")?pe(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":rt(a,n)?"stale_timestamp":Te(o,Ge("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function xa(e){let t=pe(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=Tr({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=nt(o),u=pe(a,"hex");return d===void 0||!u||u.byteLength!==64?"malformed_signature":rt(d,s)?"stale_timestamp":$r(null,Rr(o,r.body),n,u)?void 0:"signature_mismatch"}}var Oa=1e3;function Ra(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=pe(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(!Te(Buffer.from(a.toLowerCase()),Buffer.from(on("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let I=1;for(let te of t.body)if(te===38&&++I>Oa)return"malformed_signature";let H=new Map;for(let[te,ee]of new URLSearchParams(dn(t.body))){let se=H.get(te);se||H.set(te,se=new Set),se.add(ee)}let z=[];for(let te of[...H.keys()].sort()){let ee=[...H.get(te)].sort();for(let se of ee)o+=te+se;z.push([te,ee.length===1?ee[0]:ee])}d=Object.fromEntries(z)}let u=s.protocol==="https:"?"443":"80",m=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||u}${s.pathname}${s.search}`;if(![m,g].some(I=>Te(r,Ge("sha1",e,I,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),S=k?{id:`${k}:${Or(`${m}
|
|
5
|
-
${o}`)}`}:{};return d?{type:xr("twilio",t.headers,d),event:d,...S}:{..._r("twilio",t),...S}}}function Aa(e){let t;try{let n=pe(e,"base64");if(!n)throw new Error;t=Tr({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=nt(a),d=pe(s.trim(),"base64");return o===void 0||!d?"malformed_signature":rt(o,r)?"stale_timestamp":$r("sha256",Rr(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var kr=60;function Pa(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=vr(pe(s[0],"base64url")),o=pe(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Te(o,Ge("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=vr(pe(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+kr||typeof d.nbf=="number"&&n<d.nbf-kr)return"stale_timestamp";let u=typeof d.sha256=="string"?pe(d.sha256,"base64"):void 0;return u&&Te(u,on("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function Ca(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=nt(d);if(m===void 0)return"malformed_signature";if(rt(m,a))return"stale_timestamp"}let u=pe(o.trim(),e.encoding);return u?Te(u,Ge(r,t,...n.map(m=>m==="{body}"?s.body:m==="{ts}"?d:m)))?void 0:"signature_mismatch":"malformed_signature"}}var ja=new TextEncoder;function Ge(e,t,...n){let r=ba(e,t);for(let s of n)r.update(s);return r.digest()}function Or(e){return on("sha256").update(e).digest("hex")}function Rr(e,t){return Buffer.concat([ja.encode(e),t])}function Te(e,t){return e.byteLength===t.byteLength&&ka(e,t)}var Ma={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 pe(e,t){return Ma[t].test(e)?Buffer.from(e,t):void 0}function nt(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function rt(e,t){return Math.abs(t-e)>$a}function dn(e){return new TextDecoder().decode(e)}function vr(e){if(e)try{return JSON.parse(dn(e))}catch{return}}function Ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oe(e,t){let n=Ar(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}},Da=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],Na=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),Et=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,Bt);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,Ce))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,ke))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,ye))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,we))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,_e)||D(a,ze))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 oe())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,ze)&&!D(r,_e))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,Ft)&&!D(r,Se)&&!D(r,_e)&&!D(r,ke)&&!D(r,ye)&&!D(r,we)){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,_e)&&this.gateways.push(r),D(r,Me)?this.webhooks.push(r):D(r,Se)&&this.eventProviders.push(r),D(r,ke)&&this.cronProviders.push(r),D(r,ye)&&this.taskProviders.push(r),D(r,we)&&this.templateProviders.push(r)}}for(let t of this.owner.keys())for(let n of Da)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,g)=>{if(Na.has(m)||typeof m!="function")throw new J("unresolvable dependency",s,`${t.name} constructor parameter ${g}`,`parameter ${g} 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 u=new t(...d);return this.instances.set(t,u),this.order.push(u),u}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 Ua,HttpError as st}from"palgres";import{z as $e}from"zod";import{BadRequest as Pd,Conflict as Cd,DeadlockDetected as jd,HttpError as Md,NotFound as Dd,SerializationFailure as Nd,TooManyRequests as Ud,UniqueViolation as Ld}from"palgres";function at(e){if(typeof e!="object"||e===null||e[Ua]!==!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 Pr=class extends st{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},Cr=class extends st{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},jr=class extends st{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function Dr(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 La=Symbol.for("palbase.backend.errorRegistry"),Ia={bad_request:$e.object({fields:$e.array($e.object({field:$e.string(),message:$e.string()})),more:$e.number().int().optional()}),too_many_requests:$e.object({retryAfter:$e.number().int()})},za=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 Ha(){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=Ia[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function Ga(){let e=globalThis;return e[La]??=Ha()}var Fa=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function Od(e,t,n){if(typeof e!="string"||e.length>100||!Fa.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(za.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=Ga(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&Mr(s.data)!==Mr(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(" "),u=d.charAt(0).toUpperCase()+d.slice(1),k=n?(S=>class extends st{static code=e;static status=t;constructor(I,H){let z=Ba(e,S,I);super(t,e,H??(typeof z=="string"?z:u),z),this.name=o}})(n):class extends st{static code=e;static status=t;constructor(S){super(t,e,S??u),this.name=o}};return Object.defineProperty(k,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),k}function Ba(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 Mr(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as Ka}from"palgres";var Nr="/_palbase/ai/tools",Ur="/_palbase/ai/agents",Lr="/_palbase/ai/repos",Be=4<<20,qa=Symbol.for("palbase.ai.tool_error");function Ir(e){return e instanceof Error&&e[qa]===!0}var Ja=Symbol.for("palbase.ai.declared");function zr(){let e=globalThis[Ja];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 Fe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Hr(e){let t={};if(e==null)return t;if(Fe(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 Gr(e){if(!Fe(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(!Fe(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=Hr(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 Fr(e){let t=Gr(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 Br(e){let t=Gr(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=Fe(a)?Hr(a.metadata):void 0;if(!Fe(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:Ka(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!Fe(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 Wa=1e4,Va=10*6e4,St=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<=Va&&this.seen.size<=Wa)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},Za=1e3,Qa=256*1024,_t=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>Qa)&&(this.answers.set(t,n),this.answers.size>Za&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as ys,isEngineRaised as Tn,markData as le}from"palgres";import{createHash as ws}from"node:crypto";import{createHash as Ya,randomInt as Xa}from"node:crypto";import{ago as cn,isRetryable as eo,now as Kr}from"palgres";import{defineSchema as to,defineTable as no,index as ro,integer as so,jsonb as ao,raw as oo,text as un,timestamp as qr}from"palgres/dsl";var Yr=new Set(["POST","PUT","PATCH","DELETE"]),Jr=255,Wr=35,Vr=24,io=65536,Zr=1e3,co=64,fn={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"}},uo=no("idempotency_keys",{columns:{key:un().primaryKey(),fingerprint:un(),started_at:qr().defaultNow(),completed_at:qr().nullable(),status_code:so().nullable(),response_headers:ao().nullable(),response_body:un().nullable()},indexes:e=>[ro("idempotency_keys_started").on(e.col("started_at"))]}),Jd=to("palbase",{tables:[uo],raw:[oo("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)"})]}),lo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},fo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},po={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},mo={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},Ot=class extends Error{};function ot(e){return Yr.has(e.method)&&e.meta.upload===void 0}function Xr(e,t){if(!Yr.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function ho(e,t){return es([e.role,e.uid,t]).digest("hex")}function go(e){return es([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function es(e){let t=Ya("sha256");for(let n of e)t.update(n).update("\0");return t}function yo(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function ln(e){return e<500&&e!==429&&e!==499}function wo(e,t){return t&&ln(e)}function ts(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 bo={role:"service",claims:{}},Rt=class{constructor(t){this.db=t}db;async serve(t,n,r){if(t.key.length>Jr)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Jr} characters`});let s;try{s=await this.begin(ho(t.caller,t.key),go(t))}catch(d){return E.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:d}),r.refusal(mo)}if("kept"in s)return ko(s.kept,r.requestId);if("refused"in s)return r.refusal(s.refused==="reused"?lo:fo);let a=s.claim,o;try{o=await n(d=>this.record(a,d))}catch(d){if(d instanceof Ot)return r.refusal(po);let u=r.failure(d);return wo(u.status,r.ran())&&!eo(d)?this.keep(a,u):(await this.release(a),u)}return ln(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:cn({hours:Vr})}}}))}async begin(t,n){return Xa(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:cn({hours:Vr})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let d=yo(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[u]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:cn({seconds:Wr})}},set:{started_at:Kr()}});return u?{claim:{key:t,started:u.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!ln(n.status))return n;let{response:r,kept:s}=await Qr(n),a=ae.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let[o]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),s.body]);if(o?.answered!==!0)throw new Ot;return r}async keep(t,n){let{response:r,kept:s}=await Qr(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Kr(),status_code:s.status,response_headers:s.headers,response_body: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()+Wr*1e3,r=()=>{Date.now()+Zr>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},Zr).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(bo),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 ko(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 xt=Symbol("waits");function vo(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(xt));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function Qr(e){let t=[];e.headers.forEach((d,u)=>{u!=="x-request-id"&&t.push([u,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(),u=await vo(d);if(u!==xt&&u.done)break;if(u!==xt&&(s.push(u.value),a+=u.value.byteLength,a<=io))continue;let m=u===xt?d:void 0,g=new ReadableStream({start(k){for(let S of s)k.enqueue(S)},async pull(k){let S=await(m??r.read());m=void 0,S.done?k.close():k.enqueue(S.value)},cancel:k=>r.cancel(k)});return{response:n(g),kept:{status:e.status,headers:t.filter(([k])=>k!=="content-length"&&k!=="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 To}from"node:crypto";var pn="/webhooks/palbase",is="PalbaseErrorEnvelope",ns="PalbaseBearer",$o={$ref:`#/components/schemas/${is}`},Eo={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"]},rs={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Ke={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function ds(e,t,n){let r={[is]:Eo},s={},a=[],o=[],d=new Set,u=new Map;for(let v of e){let Q=o.find(X=>xo(X,v));if(Q){a.push({route:v.id,handler:ss(v),answeredBy:Q.id});continue}o.push(v);let w=v.segments.map(X=>typeof X=="string"?X:"{}").join("/");u.has(w)||u.set(w,Ro(v.segments.flatMap(X=>typeof X=="string"?[]:[X.param])));let _=u.get(w),b=0,x=`/${v.segments.map(X=>typeof X=="string"?X:`{${_[b++]}}`).join("/")}`,P=t(v),N=At(Oo(v),d),F=v.method!=="GET"&&v.method!=="HEAD",K=X=>{let be=v.params.filter(Ee=>Ee.kind===X&&Ee.schema).map((Ee,pt)=>jt(Ee.schema,`${N}.${X}${pt===0?"":`.${pt+1}`}`,r));return be.length===0?void 0:be.length===1?be[0]:{allOf:be}},G=_.map(X=>({name:X,in:"path",required:!0,schema:{type:"string"}})),U=K("query");U&&G.push(...os(U,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:U}]);let W=K("headers");W&&G.push(...os(W,"header")??[]);let V=n.idempotency===!0&&ot(v);V&&G.push({...fn,schema:{...fn.schema}});let Y=F?K("body"):void 0,ne={operationId:N};v.controller.name!==""&&(ne.tags=[v.controller.name]),G.length>0&&(ne.parameters=G),Y&&(ne.requestBody={required:!Mo(Y),content:{"application/json":{schema:Y}}});let Qe=v.params.some(X=>X.schema!==void 0),ft=n.routes?.(v),Ye=No(N,ft?.throws??[],n.errors);ne.responses={...Do(ft,N,r),...Io(P,{validates:Qe,hasPathParams:_.length>0,readsBody:F,keyed:V}),...Lo(Ye,N,r)},Ye.length>0&&(ne["x-palbase-errors"]=Uo(N,Ye)),P.auth.required&&(ne.security=[{[ns]:[]}]),ne["x-palbase-handler"]=ss(v);let Lt=v.params.some(X=>X.kind==="optionalUser")||n.databaseSeesCaller;ne["x-palbase-auth"]=P.auth.required?"required":Lt?"optional":"public",ne["x-palbase-verified-email"]=P.auth.verifiedEmail,ne["x-palbase-rate-limit"]=P.limit===!1?!1:{max:P.limit.max,window:P.limit.window},v.meta.upload&&(ne["x-palbase-upload"]={bucket:v.meta.upload.bucket,pathTemplate:v.meta.upload.pathTemplate}),(s[x]??={})[v.method.toLowerCase()]=ne}for(let v of n.webhooks??[]){let Q={operationId:At(`webhooks.${v.name}`,d)};v.cls!==""&&(Q.tags=[v.cls]),Q.description=v.provider?`${rs[v.provider]??v.provider}'s deliveries: verified with ${rs[v.provider]??v.provider}'s signature scheme under the secret in ${v.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${v.signatureHeader} header: verified under the secret in ${v.secretEnv}, then handed to the @On of their event type.`,Q.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":{},[v.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:re("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:re("in_progress: the same delivery is being handled; the sender delivers it again",Ke),413:re("payload_too_large: the body is over what this sender sends"),500:re("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:re("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",Ke)},Q["x-palbase-webhook"]=v.provider?{provider:v.provider,secretEnv:v.secretEnv,events:v.events}:{signatureHeader:v.signatureHeader,secretEnv:v.secretEnv,events:v.events},s[`/webhooks/${v.name}`]={post:Q}}let m=[...new Set(n.platformEvents??[])].sort();if(m.length>0){let v={operationId:At("webhooks.palbase",d)};v.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.",v.responses={204:{description:"Taken: handled, or a delivery already run"},401:re("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:re("in_progress: the same event is being handled; the platform delivers it again",Ke),500:re("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:re("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let Q=[...new Set(n.platformEventBuckets??[])].sort();v["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:m,...Q.length>0?{buckets:Q}:{}},s[pn]={post:v}}let g=n.gateways??[],k=So(g,r),S=g.length>0,I=Object.fromEntries(g.filter(Le).map(v=>[v.pattern,{events:k[v.name].events,messages:Object.fromEntries(Object.entries(k[v.name].messages).map(([Q,w])=>[Q,w.payload])),graceMs:v.graceMs,...v.logKeepSeconds>0?{logKeepSeconds:v.logKeepSeconds}:{}}])),H=Object.keys(I).length>0,z=g.filter(v=>!Le(v)).map(v=>({pattern:v.pattern,kind:v.access,publish:v.publish,state_read:!1,state_write:!1,...v.logKeepSeconds>0?{log_keep_seconds:v.logKeepSeconds}:{}})),te=z.length>0,ee={schemas:r,securitySchemes:{[ns]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},se={openapi:"3.2.0",info:{title:"Palbase backend",version:To("sha256").update(JSON.stringify({paths:s,components:ee,unreachable:a,...S?{gateways:k}:{},...H?{rooms:I}:{},...te?{channels:z}:{}})).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&&(se["x-palbase-unreachable"]=a),S&&(se["x-palbase-gateways"]=k),H&&(se["x-palbase-room"]=I),te&&(se["x-palbase-channels"]=z),se}function So(e,t){let n=[];for(let r of e){let s=(d,u,m,g)=>{let k=Ct(`${r.name}_${d}_${u}`),S={},I=jt(m,k,S,g);I.$ref===void 0&&(S[k]=I),_o(r.pattern,d,u,S[k]);for(let[H,z]of Object.entries(S)){if(Object.hasOwn(t,H)&&JSON.stringify(t[H])!==JSON.stringify(z))throw new Error(`@Gateway("${r.pattern}") ${d} "${u}": its schema is the component ${H}, which another gateway's names with another schema \u2014 rename one of them`);t[H]=z}return{$ref:`#/components/schemas/${k}`}},a=Object.fromEntries(Object.entries(r.events).map(([d,u])=>[d,s("event",d,u,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([d,u])=>[d,{payload:s("message",d,u.schema,"sent"),...u.reply?{reply:s("reply",d,u.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 _o(e,t,n,r){if(!(!de(r)||!de(r.properties))){for(let[s,a]of Object.entries(r.properties))if(a===!0||de(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 xo(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 ss(e){return`${e.controller.name}.${e.fn}`}function Oo(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 At(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function Ro(e){let t=new Set;return e.map(n=>At(n,t))}function jt(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:Ao}:{}}})}catch{return{}}let d=Ct(t);for(;Object.keys(n).some(u=>u===d||u.startsWith(`${d}.`));)d=`${d}_`;return Po(o,d,n,r)}function Ao(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function Po(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}.${Ct(jo(m.slice(8)))}`:m,d="all";if(r==="sent"){let m=new Set;for(let g of[e,...Object.values(s)])Pt(g,m);d=m}for(let[m,g]of Object.entries(s))n[`${t}.${Ct(m)}`]=dt(it(g,o,d));let u=dt(it(e,o,d));return a?(n[t]=u,{$ref:`#/components/schemas/${t}`}):u}var Co=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"]),mn=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),hn=new Set(["anyOf","oneOf","allOf","prefixItems"]),gn=new Set(["properties","patternProperties","dependentSchemas"]),de=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function it(e,t,n){if(!de(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):Co.has(s)?r[s]=a:mn.has(s)?r[s]=it(a,t,n):hn.has(s)&&Array.isArray(a)?r[s]=a.map(o=>it(o,t,n)):gn.has(s)&&de(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,d])=>[o,it(d,t,n)])));return r}var as=Number.MAX_SAFE_INTEGER;function dt(e){if(!de(e))return e;let t={};for(let[r,s]of Object.entries(e))mn.has(r)?t[r]=dt(s):hn.has(r)&&Array.isArray(s)?t[r]=s.map(dt):gn.has(r)&&de(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,dt(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-as&&delete t.minimum,t.maximum===as&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,de(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=>de(a)&&Object.keys(a).length===1&&a.type==="null"),s=n[1-r];if(r!==-1&&de(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function Pt(e,t){if(de(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(de))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=>de(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(o=>de(o[a])&&"const"in o[a]))for(let o of s)t.add(o[a])}for(let[n,r]of Object.entries(e))if(mn.has(n))Pt(r,t);else if(hn.has(n)&&Array.isArray(r))for(let s of r)Pt(s,t);else if(gn.has(n)&&de(r))for(let s of Object.values(r))Pt(s,t)}}function jo(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Ct(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function os(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 Mo(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function re(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:$o}}}}function Do(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=jt(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function No(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 Uo(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 Lo(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(u=>{let m={error:{type:"string",const:u.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},g=["error","error_description","status","request_id"];return u.data&&(m.data=jt(u.data,`${t}.${u.code}.data`,n,"answered"),g.push("data")),{type:"object",properties:m,required:g}});s[String(a)]={description:o.map(u=>u.code).join(" | "),content:{"application/json":{schema:d.length===1?d[0]:{oneOf:d}}}}}return s}function Io(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]=re(s.join("; "))),e.auth.required&&(n[401]=re("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]=re("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=re("idempotency_key_in_use: a request with this Idempotency-Key is still running",Ke)),t.readsBody&&(n[413]=re("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=re("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=re("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Ke)),n[500]=re("internal_error: the handler failed; the app's log has it under the request id"),n[503]=re(`${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":""}`,Ke),n}var Mt=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 Dt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return zo(r??t??"unknown")}function zo(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(u=>!/^[0-9a-f]{1,4}$/i.test(u))?t:`${d.slice(0,4).map(u=>parseInt(u,16).toString(16)).join(":")}::/64`}function cs(e){let t=[];for(let n of e){let r=D(n,Ce),s=D(n,je)??[];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,Gt)??new Map;for(let o of s){let d=`${r.basePath}${o.subpath}`||"/",u=d.split("/").filter(Boolean).map(g=>{let k=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(g)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(g);return k?{param:k[1]}:g});if(typeof u[0]=="string"&&De.has(u[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${d} \u2014 /${u[0]} is the platform's; a route is served elsewhere`);let m=[...a.get(o.fn)??[]].sort((g,k)=>g.index-k.index);for(let g of m)if(g.kind==="param"&&!u.some(k=>typeof k!="string"&&k.param===g.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${g.name}") names no {${g.name}} in ${o.method} ${d}`);t.push({id:`${o.method} ${d}`,method:o.method,segments:u,controller:n,fn:o.fn,params:m,meta:o,controllerAuth:r.options.auth})}}return or(t),t}function yn(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 u=s.segments[d];if(typeof u=="string")o=u===r[d];else try{a[u.param]=decodeURIComponent(r[d])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function bn(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 Ze(e,e?bn(e.requests,t):void 0,n,r,s)}var ct={role:"service",claims:{}};async function Ze(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=ae.getStore();d&&(d.database=o.database);let u;try{u=await s()}catch(m){throw await o.rollback(m).catch(g=>E.error("[palbase] the request's transaction could not be rolled back",{error:g})),m}try{await o.commit()}catch(m){throw await o.rollback(m).catch(g=>E.error("[palbase] the request's transaction could not be rolled back",{error:g})),m}return u}var Go=1024*1024,Fo=20,Bo={max:300,window:60},Je="/_palbase/crons",We="/_palbase/tasks",us=50,ls=50,Ko=4096,qo=69632,fs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,Ve=1e4,Jo=6e4;function Wo(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 ie=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 Vo(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 Zo=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Qo(e,t){let n=new Headers(e.headers);for(let r of Zo)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 ps(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Nt(e.headers,"Accept-Language")),e}function Nt(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 me(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),me(e.status,n,t,r)}var bs=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 ie)return T({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(at(e)){let a=e;return a.status>=500&&E.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),me(a.status,Dr(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Ut(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 Ut(e,t){if(e instanceof gt)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&&bs.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=ys(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 Yo(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return Ir(e)?t(e.message):at(e)&&!Tn(e)&&!kn(e)?t(e.errorDescription):kn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function kn(e){return e instanceof gt||e instanceof ce&&bs.has(e.status)||ys(e)!==void 0||at(e)&&e.status===503&&Tn(e)}async function wn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,Fo).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 ie(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function ut(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new ie(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:u,value:m}=await r.read();if(u)break;if(a+=m.byteLength,a>t)throw await r.cancel().catch(()=>{}),new ie(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(m)}let o=new Uint8Array(a),d=0;for(let u of s)o.set(u,d),d+=u.byteLength;return o}function Xo(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return le(t)}function ei(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 ti(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 ni=/^[A-Za-z0-9._:-]{8,128}$/,ri=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,si={max:20,window:60},ai=10*6e4,oi=1e4,lt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},vn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=ws("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,si);if("wait"in m)throw new lt(m.wait);d=m}let u=await r();if(!u)throw this.known.delete(s),new ht("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()+ai),this.known.size>oi&&this.known.delete(this.known.keys().next().value),u}};function $c(e){let t=new Et(e.modules),n=cs(t.controllers.map(i=>i.cls)),r=new Map(n.map(i=>[i,Wo(i,e.auth)]));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 s=new Map;for(let i of n)for(let c of i.params)c.kind==="resolve"&&s.set(c,t.dependencyOf(i.controller,c.resolver,`${i.id} @Resolve(${c.resolver?.name})`));let a=new Map;for(let i of t.cronProviders){let c=t.get(i),f=D(i,ke),l=a.get(f.name);if(l)throw new TypeError(`@Cron "${f.name}" is ${l.owner} and ${i.name}: a cron's name is its own \u2014 name one of them`);a.set(f.name,{declaration:f,owner:i.name,run:h=>c.run(h)})}let o=new Map;for(let i of t.taskProviders){let c=t.get(i),f=D(i,ye),l=o.get(f.name);if(l)throw new TypeError(`@Task "${f.name}" is ${l.owner} and ${i.name}: a task type's name is its own \u2014 name one of them`);o.set(f.name,{declaration:f,owner:i.name,run:(h,p)=>c.run(h,p)})}let d=new Map;for(let i of t.templateProviders){let c=t.get(i),f=D(i,we),l=d.get(f.name);if(l)throw new TypeError(`@TestUserTemplate "${f.name}" is ${l.owner} and ${i.name}: a template's name is its own \u2014 name one of them`);d.set(f.name,{owner:i.name,seed:(h,p)=>c.seed(h,p),...typeof c.undo=="function"?{undo:(h,p)=>c.undo(h,p)}:{}})}d.size>0&&!e.platform&&E.info(`[palbase] ${d.size} @TestUserTemplate(s): the platform calls a machine for its test users; nothing does here`);let u=new Map,m=new Set,g=new Set,k=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(a.size>us)throw new TypeError(`${a.size} @Cron classes: a machine runs ${us} crons at most`);if(o.size>ls)throw new TypeError(`${o.size} @Task classes: a machine runs ${ls} task types at most`);a.size>0&&!e.platform&&E.info(`[palbase] ${a.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let S=wr(t.gateways.map(i=>({cls:i,instance:t.get(i)})),{run:(i,c,f,l)=>ae.run({requestId:ae.getStore()?.requestId??"",...i?.id?{userId:i.id}:{}},()=>Ze(e.database,e.database?i?.id?bn(e.database.requests,Tt(i)):ct:void 0,f,c,async()=>{let h=await l();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:kn});S.declarations.length>0&&!e.platform&&E.info(`[palbase] ${S.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let I=zr();(I.tools.size>0||I.agents.size>0)&&!e.platform&&E.info(`[palbase] ${I.tools.size} ai.tool(s) and ${I.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let H=i=>c=>t.provider(c,`${i} ctx.inject(${typeof c=="function"?c.name:String(c)})`),z=new _t,te=new St(e.now??Date.now),ee=new Set,se=e.database!==void 0||e.contractOnly?.database===!0;if(se){for(let i of n)if(ot(i)&&i.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&ts(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 v=e.database?new Rt(e.database.app):void 0,Q=mi(e.cors),w=e.now??Date.now,_=new Mt(e.now),b=new vn(_,e.now??Date.now),x=e.maxBodyBytes??Go,P=i=>{let c=i.meta.options.rateLimit??e.rateLimit??Bo;return c!==!1&&c.max>0&&c.window>0?c:!1},N=e.env??process.env,F=Er(t.webhooks,i=>t.get(i),N,{secrets:e.contractOnly===void 0}),K=F.size===0&&a.size===0&&o.size===0&&d.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(N).filter(i=>typeof i[1]=="string"&&!In(i[0])))),G=new Map([...F.keys()].map(i=>[i,{seen:new Set,inflight:new Set}])),U=new Map([...F.keys()].map(i=>[i,{counts:new Map,at:void 0}])),W,V=()=>W??=ds(n,i=>({auth:r.get(i),limit:P(i)}),{databaseSeesCaller:se,idempotency:se,webhooks:[...F.values()].map(i=>({name:i.name,cls:i.cls.name,provider:i.provider,signatureHeader:i.signatureHeader,secretEnv:i.secretEnv,events:[...i.events.keys()]})),platformEvents:[...Y.keys()],gateways:S.declarations,platformEventBuckets:di(Y),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),Y=new Map;for(let[i,c]of Object.entries(e.events??{}))Y.set(i,c.map(f=>({name:`palbase(${i})`,call:l=>f(l)})));for(let i of t.eventProviders){let c=t.get(i);for(let{event:f,fn:l,bucket:h}of D(i,Se)??[]){if(!Jn.test(f))throw new TypeError(`@On("${f}") on ${i.name}.${l}: 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`);Y.has(f)||Y.set(f,[]),Y.get(f).push({name:`${i.name}.${l}`,bucket:h,call:async(p,y)=>c[l](p,y)})}}let ne=new Set,Qe=new Set;zn(e.server),Hn({to:(i,c)=>({emit:(f,l)=>S.emit(i,c,f,l),pipe:f=>S.pipe(i,c,f),revalidate:f=>S.revalidate(i,c,f)})}),Vn(e.platform?Zn(N.PALBASE_MACHINE):new kt(new Map([...o].map(([i,c])=>[i,c.declaration])),(i,c)=>_n(i,c),e.now));async function ft(i,c){let f;try{f=await Un(i,e.webhookSecret,{now:e.now})}catch(l){if(l instanceof et)return T({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${l.code}`},c);throw l}if(le(f.data),ne.has(f.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(Qe.has(f.id))return T({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);Qe.add(f.id);try{let l;try{await qe(e.database,null,void 0,`event ${f.type}`,async()=>{for(let h of Y.get(f.type)??[])if(!(h.bucket!==void 0&&ii(f)!==h.bucket))try{await h.call(f,{requestId:c})}catch(p){throw l=h.name,p}})}catch(h){return E.error(`[palbase] ${l??"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 ne.add(f.id),ne.size>Ve&&ne.delete(ne.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{Qe.delete(f.id)}}async function Ye(i,c={}){let f=i.headers.get("origin");if(Q&&f!==null){let l=Q.allows(f);if(i.method==="OPTIONS"&&i.headers.has("access-control-request-method"))return l?new Response(null,{status:204,headers:Q.preflight(f,i.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let h=await An(i,c);if(l)for(let[p,y]of Object.entries(Q.headers(f)))p==="vary"?Nt(h.headers,y):h.headers.set(p,y);else Nt(h.headers,"Origin");return h}return An(i,c)}async function Lt(i,c,f,l){if(!i.headers.get(f.scheme.header))return be(f,"missing_signature",l);let h={headers:i.headers,body:await ut(i,f.scheme.maxBytes(x)),url:Sr(i,c)},p;try{p=f.scheme.check(h,w()/1e3)}catch{return be(f,"signature_mismatch",l,"check_failed")}if(typeof p=="string")return be(f,p,l);let y=f.events.get(p.type);if(!y)return E.info(`[palbase] webhook ${f.name}: no @On takes "${p.type}"; acknowledged`),me(200,{ok:!0,handled:!1},l);let $=G.get(f.name),O=p.event,j=[];if(p.id!==void 0){if($.seen.has(p.id))return me(200,{ok:!0,handled:!1,duplicate:!0},l);j=[p.id]}else if(p.ids&&Array.isArray(O)){let A=p.ids,R=O.map((M,Z)=>[M,A[Z]]).filter(([,M])=>M===void 0||!$.seen.has(M));if(R.length===0)return me(200,{ok:!0,handled:!1,duplicate:!0},l);O=R.map(([M])=>M),j=R.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},l);le(O);for(let A of j)$.inflight.add(A);let C;try{C=await qe(e.database,null,void 0,`webhook ${f.name}`,()=>y.call(O,{env:K,requestId:l,environmentId:e.projectId??""}))}catch(A){let R=Ut(A,`webhook ${f.name}`)??ci(A,f.name);return R?T(R,l):(E.error(`[palbase] ${y.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"},l))}finally{for(let A of j)$.inflight.delete(A)}for(let A of j)$.seen.add(A),$.seen.size>Ve&&$.seen.delete($.seen.values().next().value);return X(C,f,l)}function X(i,c,f){if(i instanceof Response)return i;if(typeof i=="string"){let l=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(i,{status:200,headers:{"content-type":l,"x-request-id":f}})}return me(200,i??{ok:!0,handled:!0},f)}function be(i,c,f,l=c){let h=U.get(i.name);h.counts.set(l,(h.counts.get(l)??0)+1);let p=w();return(h.at===void 0||p-h.at>=Jo)&&(Ee(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 Ee(i){let c=U.get(i).counts;if(c.size===0)return;let f=[...c.values()].reduce((l,h)=>l+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 pt(i){let c=i.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?F.get(c[1]):void 0}async function Ts(i,c,f,l){let h=c.pathname===Je;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"},l);let p=h?new Uint8Array(0):await ut(i,Ko);try{await mt({secret:f,signature:i.headers.get("palbase-signature"),body:p,now:e.now})}catch(L){if(L instanceof et)return T({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${L.code}`},l);throw L}if(h){let L=[...a.values()].map(({declaration:q})=>({name:q.name,schedule:q.schedule,time_zone:q.timeZone,timeout:q.timeout,retry:q.retries}));return me(200,{crons:L},l,{"cache-control":"no-store"})}let y=c.pathname.slice(Je.length+1),$=a.get(y);if(!$)return T({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(y)}`},l);let O;try{O=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}"},l)}let{cron:j,run_id:C,scheduled_at:A,attempt:R}=O??{};if(j!==y||typeof C!="string"||C===""||typeof A!="string"||!fs.test(A)||Number.isNaN(Date.parse(A))||!Number.isInteger(R)||R<1)return T({status:400,code:"bad_request",message:`A run of ${y} is the JSON {cron: "${y}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},l);let M=`${C}#${String(R)}`;if(g.has(M))return new Response(null,{status:204,headers:{"x-request-id":l}});if(k.has(M))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},l);k.add(M);let Z={env:K,environmentId:e.projectId??"",cron:y,runId:C,scheduledAt:new Date(A),attempt:R};try{await Ze(e.database,e.database?ct:void 0,i.signal,`cron ${y}`,async()=>{if(await $.run(Z),i.signal.aborted)throw new Error(`the platform gave up on this attempt of ${y} before it ended`)})}catch(L){return i.signal.aborted||E.error(`[palbase] cron ${y} failed (run ${C}, attempt ${String(R)})`,{error:L}),T({status:500,code:"cron_failed",message:`The cron ${y} failed; the platform tries it again`},l)}finally{k.delete(M)}return g.add(M),g.size>Ve&&g.delete(g.values().next().value),new Response(null,{status:204,headers:{"x-request-id":l}})}let _n=async({task:i,id:c,attempt:f,payload:l,createdAt:h},p)=>{let y=o.get(i);if(!y)return{status:404,message:`this version has no task ${JSON.stringify(i)}`};let $=le(l??null),O=y.declaration.payload;if(O){let C=await O["~standard"].validate($);if(C.issues){let A=C.issues.slice(0,5).map(R=>`${(R.path??[]).map(M=>String(typeof M=="object"&&M!==null&&"key"in M?M.key:M)).join(".")||"(payload)"}: ${R.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}`}}$=C.value}let j={env:K,environmentId:e.projectId??"",task:i,id:c,attempt:f,createdAt:h};try{await Ze(e.database,e.database?ct:void 0,p,`task ${i}`,async()=>{if(await y.run($,j),p.aborted)throw new Error(`the platform gave up on this attempt of ${i} before it ended`)})}catch(C){return C instanceof bt?(E.error(`[palbase] task ${i} ${c} can never be done: ${C.message}`),{status:422,message:C.message}):(p.aborted||E.error(`[palbase] task ${i} failed (task ${c}, attempt ${String(f)})`,{error:C}),{status:500,message:`the task ${i} failed; it is tried again`})}return{status:204}};async function $s(i,c,f,l){let h=c.pathname===We;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"},l);let p=h?new Uint8Array(0):await ut(i,qo);try{await mt({secret:f,signature:i.headers.get("palbase-signature"),body:p,now:e.now})}catch(L){if(L instanceof et)return T({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${L.code}`},l);throw L}if(h){let L=[...o.values()].map(({declaration:q})=>({name:q.name,timeout:q.timeout,retry:q.retries,concurrency:q.concurrency}));return me(200,{tasks:L},l,{"cache-control":"no-store"})}let y=c.pathname.slice(We.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}"},l)}let{task:O,id:j,attempt:C,payload:A,created_at:R}=$??{};if(O!==y||typeof j!="string"||j===""||typeof R!="string"||!fs.test(R)||Number.isNaN(Date.parse(R))||!Number.isInteger(C)||C<1)return T({status:400,code:"bad_request",message:`A task of ${y} is the JSON {task: "${y}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},l);let M=`task:${j}#${String(C)}`;if(g.has(M))return new Response(null,{status:204,headers:{"x-request-id":l}});if(k.has(M))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},l);k.add(M);let Z;try{Z=await _n({task:y,id:j,attempt:C,payload:A,createdAt:new Date(R)},i.signal)}finally{k.delete(M)}return Z.status===404?T({status:404,code:"task_not_found",message:Z.message??""},l):Z.status===422?T({status:422,code:"task_failure",message:Z.message??""},l):Z.status>=300?T({status:Z.status,code:"task_failed",message:Z.message??""},l):(g.add(M),g.size>Ve&&g.delete(g.values().next().value),new Response(null,{status:204,headers:{"x-request-id":l}}))}async function Re(i,c,f,l){if(i.method!=="POST")return T({status:405,code:"method_not_allowed",message:`${l} is POSTed`},f);let h;try{Nn({signature:i.headers.get("palbase-signature"),now:e.now}),h=await ut(i,1048576),await mt({secret:c,signature:i.headers.get("palbase-signature"),body:h,now:e.now})}catch(y){if(y instanceof et)return T({status:401,code:"invalid_signature",message:`${l} is the platform's to call: ${y.code}`},f);throw y}let p;try{p=JSON.parse(new TextDecoder().decode(h))}catch{return T({status:400,code:"bad_request",message:`${l} 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:`${l} is the platform's to call: signed_for_another_call`},f):{body:p}}async function Es(i,c,f,l,h){let p=await Re(c,f,l,`An upload's ${i}`);if(p instanceof Response)return p;let y=ir(i,p.body);if(typeof y=="string")return T({status:400,code:"bad_request",message:`An upload's ${i}: ${y}`},l);if(i==="complete"){if(ee.has(y.uploadId))return T({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},l);ee.add(y.uploadId),ee.size>Ve&&ee.delete(ee.values().next().value)}let $=yn(n,y.method,y.route);if(!$||"malformed"in $||!$.route.meta.upload)return T({status:404,code:"not_found",message:`No upload route for ${y.method} ${y.route}`},l);let{route:O,params:j}=$,C=$.route.meta.upload,A=ti(y.user);if(A&&Pn(h,A.id),r.get(O).required&&!A)throw new ie(401,"unauthorized","This route needs a signed-in user");if(i==="authorize"){let Z=P(O);if(Z!==!1){let q=_.take(`${O.id}\0${nr(y.user,y.client)}`,Z);if(q!==void 0)throw new ie(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:q},q)}let L=ar(C.pathTemplate,{userId:A?.id??null,uploadId:y.uploadId,filename:y.filename});if("problem"in L)throw new ie(400,"bad_request",L.problem);return await qe(e.database,Tt(y.user),c.signal,O.id,async()=>{let q={request:c,query:new URLSearchParams(y.query),params:j,user:A,body:y.body===void 0||y.body===null?{}:le(y.body),requestId:l};await Rn(O,q);for(let Ae of O.params)(Ae.kind==="query"||Ae.kind==="body"&&y.body!==void 0)&&await gs(Ae,q)}),me(200,{bucket:C.bucket,path:L.path},l)}h.endpoint=O.id.slice(O.id.indexOf(" ")+1);let R=new URLSearchParams(y.query),M=y.body===null||y.body===void 0?{}:le(y.body);return It(O,{request:c,query:R,params:j,user:A,body:M,requestId:l,uploadedObject:le(y.uploadedObject)},Tt(y.user))}async function Ss(i,c,f,l){let h=c.pathname.slice(vt.length+1),p=h.endsWith("/undo"),y=p?h.slice(0,-5):h,$=await Re(i,f,l,"A test user template");if($ instanceof Response)return $;let O=d.get(y);if(!O||p&&!O.undo)return T({status:404,code:"template_not_found",message:O?`@TestUserTemplate "${y}" has no undo: the user's deletion cleans up after it`:`This version has no test user template ${JSON.stringify(y)}`},l);let j=Qn(y,$.body);if(typeof j=="string")return T({status:400,code:"bad_request",message:`A test user template's call: ${j}`},l);let C=le(j.user),A;try{A=await Yn(e.server,C.id)}catch(L){return E.error(`[palbase] test user template ${y}: auth could not say whether ${C.id} is a test user; nothing was written`,{error:L}),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},l)}if(!A)return E.warn(`[palbase] test user template ${y}${p?" undo":""}: auth does not say ${C.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"},l);let R=`${C.id}\0${y}`;if(m.has(R))return T({status:409,code:"in_progress",message:`The template ${y} is being written for this user`,retryAfter:5},l);if(!p&&u.has(R))return me(200,{rows:u.get(R)},l);m.add(R);let M={env:K,environmentId:e.projectId??"",template:y},Z=`test user template ${y}${p?" undo":""}`;try{let L={};return await Ze(e.database,e.database?ct:void 0,i.signal,Z,async()=>{if(p?await O.undo(C,M):(await O.seed(C,M),L=await Xn(ae.getStore()?.database)),i.signal.aborted)throw new Error(`the platform gave up on ${Z} before it ended`)}),p?(u.delete(R),new Response(null,{status:204,headers:{"x-request-id":l}})):(u.set(R,L),u.size>Ve&&u.delete(u.keys().next().value),me(200,{rows:L},l))}catch(L){i.signal.aborted||E.error(`[palbase] ${Z} failed for ${C.id}: nothing of it was kept`,{error:L});let q=L instanceof Error&&L.message!==""?`: ${L.message.replace(/\s+/g," ").slice(0,300)}`:"";return T({status:500,code:p?"undo_failed":"template_failed",message:`${p?"The undo of":"The template"} ${y} failed${q}; nothing of it was kept`},l)}finally{m.delete(R)}}function xn(i,c,f,l){let h=i?{sub:i.id,role:"authenticated"}:null;return ae.run({requestId:ae.getStore()?.requestId??"",...i?{userId:i.id}:{}},()=>qe(e.database,h,f,c,async()=>{let p=await l();if(f.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return p}))}let On=(i,c)=>new Response(i,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function _s(i,c,f){let l=await Re(i,c,f,"A tool call");if(l instanceof Response)return l;let h=l.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 y=I.tools.get(p);if(!y)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,O=Fr(h.context);if(typeof $!="string"||$===""||$.length>256||typeof O=="string")return T({status:400,code:"bad_request",message:`A call of ${p} is {tool, call_id, input, context}${typeof O=="string"?`: ${O}`:""}`},f);let j=ws("sha256").update(JSON.stringify(h)).digest("hex"),C=z.answered($);if(C!==void 0)return C.digest!==j?T({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},f):On(C.answer,f);if(z.isRunning($))return T({status:409,code:"in_progress",message:"This call is running",retryAfter:2},f);z.start($);let A;try{let R=await xn(O.user,`ai.tool ${p}`,i.signal,()=>y.call(le(h.input??{}),{...O,callId:$,signal:i.signal,inject:H(`ai.tool ${p}`)}));A="deferred"in R?JSON.stringify({deferred:!0,...R.expires_in_seconds!==void 0?{expires_in_seconds:R.expires_in_seconds}:{}}):JSON.stringify({output:R.output,is_error:R.is_error});let M=new TextEncoder().encode(A).byteLength;M>Be&&(E.error(`[palbase] ai.tool ${p} answered ${M} bytes (call ${$}): a machine's answer is ${Be} at most; the agent is told it failed`),A=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${Be/(1<<20)} MiB it may be`}],is_error:!0}))}catch(R){if(i.signal.aborted)return z.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 ${O.chatId}); the agent is told`,{error:R}),A=JSON.stringify({output:[{type:"text",text:Yo(R)}],is_error:!0})}return z.end($,{digest:j,answer:A}),On(A,f)}async function xs(i,c,f){let l=await Re(i,c,f,"An agent's turn");if(l instanceof Response)return l;let h=Br(l.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,y=I.agents.get(p);if(!y)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 xn(h.user,`ai.agent ${p}`,i.signal,()=>y.resolve({...h,signal:i.signal,inject:H(`ai.agent ${p}`)}))}catch(C){if(i.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let A=Ut(C,`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:C}),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},f))}let O=$.tools.find(C=>I.tools.get(C.name)!==C);if(O)return E.error(`[palbase] ai.agent ${p} handed out ai.tool ${JSON.stringify(O.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>Be?(E.error(`[palbase] ai.agent ${p}'s definition is larger than the ${Be} 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 Os(i,c,f){let l=await Re(i,c,f,"A repository's token");if(l instanceof Response)return l;let h=l.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(!te.take(h.call_id))return T({status:409,code:"call_id_reused",message:"This token ask was answered already"},f);let p=I.repos.get(h.repo),y=p?O=>p.token(O):I.repoTokens;if(!y)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 Ze(e.database,e.database?ct:void 0,i.signal,`ai.repo ${h.repo}`,async()=>y({repo:h.repo,repository:h.repository,signal:i.signal,inject:H(p?`ai.repo ${h.repo}`:`ai.repoTokens for ${h.repo}`)}))}catch(O){if(i.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let j=Ut(O,`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:O}),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 Rs(i,c,f,l){let h=await Re(c,f,l,`A gateway's ${i}`);if(h instanceof Response)return h;let p=await S.serve(i,h.body,c.signal);return"code"in p?T({status:p.status,code:p.code,message:p.message,retryAfter:p.retryAfter},l):"body"in p?me(200,p.body,l):new Response(null,{status:204,headers:{"x-request-id":l}})}async function Rn(i,c){let f=[],l={params:Object.freeze({...c.params}),user:le(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 s.get(h).resolve(l,h.options));return f}async function It(i,c,f,l){let h=t.get(i.controller),p=await qe(e.database,f,c.request.signal,i.id,async()=>{let y=await Rn(i,c);for(let O of i.params)O.kind!=="resolve"&&(y[O.index]=await gs(O,c));l?.ran();let $=await h[i.fn](...y);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${i.id}'s upload before it was answered`);return l?l.record(ps(hs($,c.requestId),ae.getStore()?.usedLocales)):$});return l?p:ps(hs(p,c.requestId),ae.getStore()?.usedLocales)}async function An(i,c){let f=i.headers.get("x-request-id")??"",l=ni.test(f)?f:`req_${crypto.randomUUID()}`,h=performance.now(),p=new URL(i.url).pathname,y={endpoint:p},$=await As(i,c,l,y);return e.telemetry?.record({requestId:l,method:i.method,endpoint:y.endpoint,path:p,status:$.status,durationMs:performance.now()-h,userId:y.userId}),$}function Pn(i,c){i.userId=c;let f=ae.getStore();f&&(f.userId=c)}async function As(i,c,f,l){let h=e.strings,p=h?{requestId:f,strings:h,locales:Gn(i.headers.get("accept-language"),h.source),usedLocales:[]}:{requestId:f},y=await Ps(p,i,c,f,l);return h&&Nt(y.headers,"Accept-Language"),y}async function Ps(i,c,f,l,h){return ae.run(i,async()=>{let p=new URL(c.url),y=`${c.method} ${p.pathname}`;try{if(p.pathname===pn&&Y.size>0)return c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):e.webhookSecret?await ft(c,l):T({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},l);let $=pt(p.pathname);if($)return y=`webhook ${$.name}`,c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):await Lt(c,p,$,l);if(e.platform&&(p.pathname===Je||p.pathname.startsWith(`${Je}/`)))return y=p.pathname===Je?"crons":`cron ${p.pathname.slice(Je.length+1)}`,await Ts(c,p,e.platform.secret,l);if(e.platform&&(p.pathname===We||p.pathname.startsWith(`${We}/`)))return y=p.pathname===We?"tasks":`task ${p.pathname.slice(We.length+1)}`,await $s(c,p,e.platform.secret,l);if(e.platform&&(p.pathname===Qt||p.pathname===er)){let B=p.pathname===Qt?"authorize":"complete";return y=`upload ${B}`,await Es(B,c,e.platform.secret,l,h)}if(e.platform&&p.pathname.startsWith(`${Yt}/`)){let B=p.pathname.slice(Yt.length+1);return y=`gateway ${B}`,await Rs(B,c,e.platform.secret,l)}if(e.platform&&p.pathname===Nr)return y="ai tool call",await _s(c,e.platform.secret,l);if(e.platform&&p.pathname===Ur)return y="ai agent's turn",await xs(c,e.platform.secret,l);if(e.platform&&p.pathname===Lr)return y="ai repository's token",await Os(c,e.platform.secret,l);if(e.platform&&p.pathname.startsWith(`${vt}/`))return y=`test user template ${p.pathname.slice(vt.length+1)}`,await Ss(c,p,e.platform.secret,l);if(ui(p.pathname))return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},l);let O=yn(n,c.method,p.pathname);if(O&&"malformed"in O)return T({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},l);if(!O)return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},l);let{route:j,params:C}=O;if(y=j.id,h.endpoint=j.id.slice(j.id.indexOf(" ")+1),j.meta.upload)throw new ie(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),R=null,M=null,Z=c.headers.get("authorization")??"",L=/^(bearer|dpop)\s+(\S+)$/i.exec(Z),q=L?.[2],Ae=L?.[1].toLowerCase()==="dpop";if(q)try{let B=!Ae&&e.tokens&&!ri.test(q)&&e.tokens.accepts(q)?e.tokens:void 0,Pe=B?await b.ask(q,Dt(c.headers,f.remoteAddress),()=>qe(e.database,null,c.signal,"token",()=>B.resolve(q))):await e.verifier.verify(q,Ae?{proof:c.headers.get("dpop"),method:c.method,url:Ln(c.headers,p)}:void 0);R=ei(Pe),M=Pe.claims}catch(B){if(!A.required&&(B instanceof ht||B instanceof gt||B instanceof lt))R=null;else throw B instanceof lt?new ie(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:B.wait},B.wait):B instanceof ht?new ie(401,"invalid_token","The access token is not valid",{reason:B.reason},void 0,Vo(B.reason)):B}else if(Z!==""&&A.required)throw new ie(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(R&&Pn(h,R.id),A.required&&!R)throw new ie(401,"unauthorized","This route needs a signed-in user");if(A.verifiedEmail&&!R?.emailVerified)throw new ie(403,"email_not_verified","This route needs a verified email address");let Cn=P(j);if(Cn!==!1){let B=R?`u:${R.id}`:`a:${Dt(c.headers,f.remoteAddress)}`,Pe=_.take(`${j.id}\0${B}`,Cn);if(Pe!==void 0)throw new ie(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Pe},Pe)}let Xe=c.method==="GET"||c.method==="HEAD"?void 0:await ut(c,x),Cs=Xe===void 0?void 0:Xo(Xe),jn={request:c,query:p.searchParams,params:C,user:R,body:Cs,raw:Xe,requestId:l},Mn=v&&Xe!==void 0&&ot(j)?Xr(c.method,c.headers):void 0;if(!v||Mn===void 0)return await It(j,jn,M);let js={role:bn(e.database.requests,M).role,uid:R?.id??`a:${Dt(c.headers,f.remoteAddress)}`},Dn=!1;return await v.serve({key:Mn,caller:js,method:c.method,uri:`${p.pathname}${p.search}`,body:Xe},B=>It(j,jn,M,{record:B,ran:()=>{Dn=!0}}),{requestId:l,refusal:B=>T(B,l),failure:B=>ms(B,l,y,c.signal),ran:()=>Dn})}catch($){return ms($,l,y,c.signal)}})}return{handle:Ye,routes:n.map(i=>i.id),contract:V,start:()=>t.start(),stop:async()=>{S.close();for(let i of U.keys())Ee(i);await t.shutdown(),await e.telemetry?.flush()}}}function ii(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function di(e){let t=new Set;for(let[n,r]of e)if(qt(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 hs(e,t){return e instanceof Response?Qo(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):me(200,e,t)}function ci(e,t){if(!(!at(e)||e.status!==503||!Tn(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 ui(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return De.has(decodeURIComponent(t))}catch{return De.has(t)}}var li="GET, POST, PUT, PATCH, DELETE, QUERY",fi=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function pi(e){return fi.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function mi(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!pi(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":li,"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 gs(e,t){switch(e.kind){case"body":return wn(e.schema,t.body??{},"Request body");case"query":return wn(e.schema,le(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),le(n),e.schema?wn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return le(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 le({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 En=720*3600;function $n(e){return e instanceof ce&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function ks(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),En)}function vs(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Sn=class{filling=new Map;async get(t){try{let n=await ge.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!$n(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 ge.cache.putCacheEntry({query:{key:t},body:{value:vs(n),ttl:ks(r)}})}catch(s){if(!$n(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 ge.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await ge.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 ge.cache.getCacheEntry({query:{key:t}})).data}catch(u){if(!$n(u))throw u;E.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:u.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}},xc=yt("Cache",new Sn);function Oc(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=m=>{let g=r.get(m);if(g&&g.expiresAt<=n()){r.delete(m);return}return g},o=()=>{let m=n();for(let[k,S]of r)S.expiresAt<=m&&r.delete(k);if(r.size<t)return;let g=[...r.entries()].sort((k,S)=>k[1].expiresAt-S[1].expiresAt);for(let[k]of g.slice(0,Math.ceil(g.length/4)))r.delete(k)},d=async(m,g,k)=>{r.size>=t&&!r.has(m)&&o(),r.set(m,{value:vs(g),expiresAt:n()+(ks(k)??En)*1e3})};return{get:async m=>{let g=a(m);return g?structuredClone(g.value):null},set:d,async del(m){r.delete(m)},async incr(m){let g=a(m),k=(typeof g?.value=="number"&&Number.isInteger(g.value)?g.value:0)+1;return r.set(m,{value:k,expiresAt:g?.expiresAt??n()+En*1e3}),k},getOrSet(m,g,k){let S=a(m);if(S)return Promise.resolve(structuredClone(S.value));let I=s.get(m);if(I)return I;let H=(async()=>{try{let z=await k();return await d(m,z,g),z}finally{s.delete(m)}})();return s.set(m,H),H}}}export{Bt as a,Se as b,Me as c,wi as d,bi as e,ki as f,vi as g,Ti as h,$i as i,Ei as j,Si as k,_i as l,xi as m,Oi as n,Ri as o,Ai as p,Pi as q,Ci as r,ji as s,Mi as t,Di as u,Ni as v,Ui as w,Li as x,Ii as y,zi as z,D as A,Hi as B,Gi as C,bt as D,Ji as E,Wi as F,Yi as G,rd as H,sd as I,ea as J,cr as K,ud as L,ld as M,fd as N,pd as O,md as P,hd as Q,gd as R,kd as S,J as T,Pr as U,Cr as V,jr as W,Ga as X,Od as Y,Pd as Z,Cd as _,jd as $,Md as aa,Dd as ba,Nd as ca,Ud as da,Ld as ea,Jd as fa,Go as ga,$c as ha,pi as ia,En as ja,xc as ka,Oc as la};
|