palbase 0.14.2 → 0.16.0
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 +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{427AGWP3.js → 2JBRAHJV.js} +2 -2
- package/dist/chunks/{7DQ76T2V.js → 5W7IKTRI.js} +2 -2
- package/dist/chunks/{6NC5RYCS.js → 7HYPHYX5.js} +1 -1
- package/dist/chunks/{44ULNVPP.js → A4YMCQOP.js} +1 -1
- package/dist/chunks/{PRJZTG2I.js → C5PO7C6L.js} +1 -1
- package/dist/chunks/{4UQ4J7RV.js → CFGQWDV5.js} +3 -3
- package/dist/chunks/CXZ6WKOI.js +18 -0
- package/dist/chunks/{JKWWY2LJ.js → EHWHP4MD.js} +2 -2
- package/dist/chunks/{WXNFMEW7.js → EJHB65XA.js} +2 -2
- package/dist/chunks/{LUFWGH2V.js → HVC5H5HY.js} +2 -2
- package/dist/chunks/{CUL5OL4P.js → IA4LTPBJ.js} +2 -2
- package/dist/chunks/{RD5JFDGQ.js → JOWAWH33.js} +2 -2
- package/dist/chunks/L73SEFXF.js +21 -0
- package/dist/chunks/LY7D5Q3R.js +2 -0
- package/dist/chunks/NQNE5PZW.js +13 -0
- package/dist/chunks/{W3OCV3QH.js → QN5WMSP7.js} +2 -2
- package/dist/chunks/{SBUC7GHR.js → S7WYS4NC.js} +2 -2
- package/dist/chunks/TGVFGW5G.js +2 -0
- package/dist/chunks/{HHZSOYPP.js → TIC3NMUT.js} +1 -1
- package/dist/chunks/{DIOZGDFQ.js → VNLECYBD.js} +1 -1
- package/dist/chunks/{ZZNGA77G.js → VTUZYTKZ.js} +1 -1
- package/dist/chunks/{A46IASZE.js → WCTVLG4W.js} +2 -2
- package/dist/chunks/{P67I4TNQ.js → YUBOQ3NU.js} +1 -1
- package/dist/cli.js +127 -127
- 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/ai/src/ai.d.ts +18 -1
- package/types/ai/src/chats.d.ts +13 -2
- package/types/ai/src/index.d.ts +1 -1
- package/types/backend/src/decorators.d.ts +20 -0
- package/types/backend/src/engine.d.ts +9 -0
- package/types/backend/src/openapi.d.ts +3 -0
- package/types/backend/src/router.d.ts +2 -0
- package/types/internal/src/modules/ai.d.ts +67 -2
- package/types/internal/src/modules/analytics.d.ts +6 -2
- package/types/internal/src/modules/auth.d.ts +33 -14
- package/types/internal/src/modules/journeys.d.ts +45 -0
- package/types/web/src/backend-error.d.ts +6 -1
- package/types/web/src/inapp.d.ts +2 -0
- package/dist/chunks/3AENUHVO.js +0 -2
- package/dist/chunks/5H7UNNH6.js +0 -13
- package/dist/chunks/BRHGS5AI.js +0 -18
- package/dist/chunks/OMK2YEDZ.js +0 -2
- package/dist/chunks/QZH6GPCR.js +0 -21
package/dist/chunks/QZH6GPCR.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as xt,c as ne,d as rr,e as sr,f as ye,h as S,i as cr}from"./SBUC7GHR.js";import{c as ar,d as or,e as Yt,f as ir,g as dr}from"./CUL5OL4P.js";import{a as Qn,e as it,g as Et,h as Xn,i as er,j as St,k as _t,n as tr,t as nr}from"./LUFWGH2V.js";import{a as $t,b as Zn,n as Yn}from"./ZZNGA77G.js";import{b as oe}from"./JKWWY2LJ.js";import"reflect-metadata";var Qt=[{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}],ur="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)",Rt=/^\d+$/;function ra(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let w=s.slice(a+1);if(!Rt.test(w)||Number(w)<1||Number(w)>n)return;d=Number(w)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let w=o.indexOf("-"),k=o.slice(0,w),_=o.slice(w+1);if(!Rt.test(k)||!Rt.test(_)||Number(k)<t||Number(_)>n||Number(k)>Number(_))return;l=Number(k),h=Number(_)}else{if(!Rt.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let w=l;w<=h;w+=d)r.add(w)}return r}function lr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${ur}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let w=ra(t[h],Qt[h].lo,Qt[h].hi);if(!w)return`${ur}; its ${Qt[h].name} "${t[h]}" is not one`;n.push(w)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let w=r.has(l.getUTCDate()),k=a.has(l.getUTCDay());if(o||d?w&&k:w||k)return}return`"${e}" is never due: no date has that day in that month`}var Ue=Symbol.for("palbase.backend.controller"),Le=Symbol.for("palbase.backend.routes"),en=Symbol.for("palbase.backend.params"),tn=Symbol.for("palbase.backend.injectable"),nn=Symbol.for("palbase.backend.module"),Re=Symbol.for("palbase.backend.events"),Ie=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),we=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ie(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Xt=Symbol.for("palbase.backend.declared");function re(){let e=globalThis;return e[Xt]instanceof Set||(e[Xt]=new Set),e[Xt]}var ze=new Set(["webhooks","_palbase"]);function Ki(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&&ze.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ie(n,Ue,()=>({basePath:e,options:t})),re().add(n)}}function qe(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`);ie(r.constructor,Le,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Ji=qe("GET"),Bi=qe("POST"),Wi=qe("PUT"),Vi=qe("PATCH"),Zi=qe("DELETE"),Yi=qe("QUERY");function ue(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ie(n.constructor,en,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function rn(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 Qi=e=>ue("body",{schema:rn("Body",e)}),Xi=e=>ue("query",{schema:rn("QueryParams",e)}),ed=e=>ue("headers",e===void 0?{}:{schema:rn("Headers",e)}),td=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},nd=()=>ue("user"),rd=()=>ue("optionalUser"),sd=()=>ue("req"),ad=()=>ue("requestId"),od=()=>ue("requestId"),id=()=>ue("client");function dd(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 ue("resolve",{resolver:e,options:t[0]})}function cd(){return e=>{ie(e,tn,()=>!0),re().add(e)}}function ud(e){return t=>{ie(t,nn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var mr=/^[a-z]+(\.[a-z_]+)+$/,sa=/^[a-z][a-z0-9-]{1,62}$/,sn=e=>e.startsWith("file.");function ld(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!sa.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!sn(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`);ie(r.constructor,Re,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),re().add(r.constructor)}}var an=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,aa=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function fr(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!aa.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function fd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!an.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=lr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||fr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${fr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),re().add(a)}}var pr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],oa=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function pd(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!oa.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!pr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${pr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&ia(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=M(t,Re)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ie(t,Ie,()=>({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}))})),re().add(t)}}function ia(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function md(){return[...re()].filter(e=>M(e,Ue)!==void 0)}function hd(e){return(M(e,Le)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var At=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function kd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!an.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,we))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,we,{value:r,enumerable:!1}),re().add(s)}}var cn;function gr(e){cn=e}function on(){if(!cn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return cn}var da=720*3600;function ca(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>da))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function ua(e){if(typeof e=="string")return e;let t=e[we];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var vd=xt("Tasks",{async enqueue(e,t,n={}){return ca(n),on().enqueue(ua(e),t===void 0?null:t,n)},async cancel(e,t={}){return on().cancel(e,t.machine)},async get(e,t={}){return on().get(e,t.machine)}}),dn=(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 yr(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 ye.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 dn(a.data,a.status===200)},async cancel(n,r){return dn((await ye.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return dn((await ye.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var la=1e4,fa=36e5,hr=24*36e5,Ot=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 oe({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 oe({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 oe({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<hr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new oe({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 oe({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(la*2**Math.min(t.attempt-1,16),fa),S.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>=hr&&this.tasks.delete(s);n==="failed"&&S.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 Pt="/_palbase/test-user-templates",pa=/^[a-z][a-z0-9_-]{0,63}$/;function Sd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!pa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),re().add(s)}}function wr(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 br(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof oe&&n.status===404)return!1;throw n}}var ma="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function kr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,ma),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var un="/_palbase/storage/upload/authorize",vr="/_palbase/storage/upload/complete",ln="/_palbase/realtime/rooms";var ha=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function He(e){if(!ha(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Tr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function $r(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Ct(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var ga=/^[a-z][a-z0-9-]{1,62}$/,Er=1024,ya=new Set(["userId","uploadId","filename"]);function Od(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!ga.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=wa(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,l)=>{if(typeof d!="string"||l===void 0||typeof l.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ie(o.constructor,Le,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function Pd(){return ue("uploadedObject")}function wa(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ya.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!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>Er)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function ba(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ka(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ka(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function _r(e,t){let n=ba(e,t);return Sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Er} bytes)`}}function xr(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 fn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Rr(e,t){if(!fn(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=He(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 l=va(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function va(e){if(!fn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:w}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!fn(w)||!Object.values(w).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...w}}}import{markData as Ta}from"palgres";var Ae=Symbol.for("palbase.backend.gateway"),Ke=Symbol.for("palbase.backend.gatewayHooks"),Ar={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},$a={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Ar),output:()=>structuredClone(Ar)}}},Nr=Symbol.for("palbase.backend.gatewayRefusal"),Or=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,Nr,{value:!0})}},Ea=e=>typeof e=="object"&&e!==null&&e[Nr]===!0&&typeof e.reason=="string",Fe=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Sa=6e4,_a=86400,Pr=604800,Cr=65536,$e=255,xa=["roles:","flags:","messaging:","debug:"],Ra=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ge=e=>new TextEncoder().encode(e).byteLength,pn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",gn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Aa(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(Ge(e)>$e)return`a channel is ${$e} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=xa.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Ur(e){if(typeof e!="string"||e==="")return"is a name";if(Ge(e)>$e)return`is ${$e} 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=Aa(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"&&gn(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=Oa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||Ra.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[w,k]of Object.entries(d)){let _=Ur(w);if(_)throw new TypeError(`@Gateway("${e}") on ${o}: event "${w}" ${_}`);if(!pn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${w}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=ie(a,Ke,yn),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:$a}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Sa,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.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(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Fe(h))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(h.publish&&h.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(h.chat&&!Fe(h))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`);ie(a,Ae,()=>h),re().add(a)}}function Oa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return _a;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Pr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Pr} (a week)`);return n}var yn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Pa={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function dt(e){let t=Pa[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ie(n.constructor,Ke,yn),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,re().add(n.constructor)}}var Ld=dt("authorize"),Id=dt("first"),zd=dt("connect"),qd=dt("disconnect"),Hd=dt("empty");function Fd(e,t,n={}){let r=Ur(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!pn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!pn(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=ie(s.constructor,Ke,yn),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},re().add(s.constructor)}}function Ca(e){return M(e,Ae)}function ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Lr(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 Ge(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Ma(e,t,n){let r=gn(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))?Lr(e,t):Da(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Da(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Na=1e4,Ua=1e3,La=100,wn=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}:{}}),jr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Mr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Ir(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let m=Ca(b),v=a.get(m.name);if(v!==void 0&&v!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let C=s.get(Mr(m.pattern));if(C!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(C)?.cls.name}'s "${C}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Mr(m.pattern),m.pattern);for(let[J,B]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,N])=>[`message ${L}`,N.fn])])if(typeof E[B]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${J} is ${B}, which is no method of it`);let U={cls:b,instance:E,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,l=new Set,h=new hn(t.broadcast),w=b=>{let E=o.get(b);return E||(E=new AbortController,o.set(b,E)),E},k=(b,E)=>{E?.abort(),o.get(b)===E&&o.delete(b)},_=(b,E,m,v,C,U)=>{if(!Object.hasOwn(b.g.events,m)){S.warn(`[palbase] ${C}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){S.warn(`[palbase] ${C}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:m,payload:v??{},...U!==void 0?{conn_id:U}:{}},C)},H=async(b,E,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(E)};function I(b,E,m,v,C,U,J){let B=v?.signal??AbortSignal.abort(),L=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...m}),signal:B,count:C,user:U,emit:(N,W)=>_(b,E,N,W,L,J),pipe:N=>H(N,E,L),owner:{hold(N){ne.exit(async()=>{try{await N(B)}catch(W){B.aborted||S.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:W})}}).catch(()=>{})},release:()=>k(E,v)}}}function D(b){let{room:E,channel:m}=b;if(typeof E!="string"||typeof m!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let v=n.get(E);return!v||!Fe(v.g)?he(404,"not_found",`This app serves no gateway "${E}"`):{entry:v,channel:m,params:ja(E,m)}}let Y=(b,E)=>he(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function Q(b,E){let m=D(b);if("status"in m)return m;let{entry:v,channel:C,params:U}=m,J={status:200,body:{subscribe:!1,publish:!1}};if(!U)return S.warn(`[palbase] ${v.cls.name}: realtime asked about "${C}", which is not a channel of the gateway "${v.g.pattern}"; the join is refused`),J;let B=He(b.user),L=B?.id;if(!L)return J;if(v.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}};if(v.g.access==="owner")return U[gn(v.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}}:J;let N=v.g.hooks.authorize;if(!N)return J;let W,G;try{W=await t.run(B,`${v.cls.name}.${N}`,E,async()=>v.instance[N]({user:{id:L},params:Object.freeze({...U})})),G=Ia(W)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return S.error(`[palbase] ${v.cls.name}.${N} (@Authorize of ${C}) failed; the join is refused`,{error:te}),J}return G==="malformed"?(S.warn(`[palbase] ${v.cls.name}.${N} (@Authorize of ${C}) answered ${za(W)}, which is no grant (true, { read, write } or null); the join is refused`),J):{status:200,body:G}}async function fe(b,E){let m=D(b);if("status"in m)return m;if(!m.params)return Y(m.entry.g.pattern,m.channel);let v=He(b.user);if(!v?.id||typeof b.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let C=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!C)return{status:200,body:{ok:!1,reason:mn(`gateway "${m.channel}" takes no message "${b.event}"`,jt)}};let U=await C.schema["~standard"].validate(Ta(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Dr(U.issues)}};let J=w(m.channel),B={...I(m.entry,m.channel,m.params,J,0,{id:v.id}),payload:U.value},L=`${m.entry.cls.name}.${C.fn} (@Subscribe "${b.event}" of ${m.channel})`,N;try{N=await t.run(v,`${m.entry.cls.name}.${C.fn}`,E,async()=>m.entry.instance[C.fn](B))}catch(G){if(t.isOutage(G))throw G;return Ea(G)?{status:200,body:{ok:!1,reason:mn(G.reason,jt)}}:(E?.aborted||S.error(`[palbase] ${L} failed`,{error:G}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(C.reply){let G=await C.reply["~standard"].validate(N);if(G.issues)return S.error(`[palbase] ${L} returned an ack its reply schema refuses (${Dr(G.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=G.value}let W;try{W=JSON.stringify(N)}catch(G){return S.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:G}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return W===void 0?{status:200,body:{ok:!0}}:Ge(W)>Cr?(S.error(`[palbase] ${L} returned an ack of ${Ge(W)} bytes, past ${Cr}; 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 pe(b,E){let m=D(b);if("status"in m)return m;if(!m.params)return Y(m.entry.g.pattern,m.channel);let v=b.event;if(typeof v!="string"||!Object.hasOwn(jr,v))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let C=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(C===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let U=v==="join"||v==="leave",J=U?He(b.user):void 0,B=U?b.connId:void 0;if(U&&(!J?.id||typeof B!="string"||B===""))return he(400,"bad_request",`A ${v} names its member: user and connId`);let L=`${v}\0${m.channel}\0${typeof B=="string"?B:""}`;if(U&&d.has(L))return{status:204};if(l.has(L))return he(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let N=m.entry.g.hooks[jr[v]],W;if(v==="empty"?(W=o.get(m.channel),k(m.channel,W)):W=v==="leave"?o.get(m.channel):w(m.channel),N){let G=I(m.entry,m.channel,m.params,W,C,{id:J?.id??""},v==="join"?B:void 0);try{await t.run(J,`${m.entry.cls.name}.${N}`,E,async()=>m.entry.instance[N](G))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||S.error(`[palbase] ${m.entry.cls.name}.${N} (${v} of ${m.channel}) failed; realtime tells it again`,{error:te}),he(500,"handler_failed",`The gateway's ${v} could not be handled`)}}return U&&(d.add(L),d.size>Na&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function be(b,E){let m=r.get(b),v=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${v}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let C=Lr(m.g.pattern,E??{});if(typeof C!="string")throw new TypeError(`${v}: ${C.problem}`);return{entry:m,channel:C,where:v}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,m){return wn(E)?b==="authorize"?Q(E,m):b==="message"?fe(E,m):b==="lifecycle"?pe(E,m):he(404,"not_found",`No gateway call ${JSON.stringify(b)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,m,v){let{entry:C,channel:U,where:J}=be(b,E);_(C,U,m,v,J)},async pipe(b,E,m){let{channel:v,where:C}=be(b,E);await H(m,v,C)},async revalidate(b,E,m={}){let v=r.get(b),C=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!v)throw new TypeError(`${C}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Ma(v.g.pattern,E??{},m);if("problem"in U)throw new TypeError(`${C}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Ia(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!wn(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function za(e){return Array.isArray(e)?"an array":wn(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var qa=20,jt=256;function Dr(e){let t="";for(let n of e.slice(0,qa)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=jt)break}return mn(t,jt)}function mn(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 hn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ge(t.event)>$e){S.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){S.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ua?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,La);try{await this.broadcast(s)}catch(o){S.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),S.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as bn,createHmac as Ha,createPublicKey as Fr,timingSafeEqual as Fa,verify as Gr}from"node:crypto";function Bd(e){let t=M(e,Ie);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 Kr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=M(o,Ie),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,w=n[d.secret.env],k;if(r.secrets!==!1)if(w===void 0||w==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=Ga(d,w)}catch(I){a.push(`${h}: ${d.secret.env} ${I.message}`)}let _=t(o),H=new Map(d.events.map(({event:I,fn:D})=>[I,{name:`${o.name}.${D}`,call:(Y,Q)=>_[D](Y,Q)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:H})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
|
-
- ${a.join(`
|
|
4
|
-
- `)}`);return s}function Jr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Je=1024,zr=1024*Je;function Ga(e,t){if(e.signature)return Oe(void 0,e.signature.header,1/0,to(e.signature,t));switch(e.provider){case"stripe":return Oe("stripe","stripe-signature",512*Je,Ba(t));case"github":return Oe("github","x-hub-signature-256",25*zr,Wa(t));case"slack":return Oe("slack","x-slack-signature",64*Je,Va(t));case"discord":return Oe("discord","x-signature-ed25519",64*Je,Za(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Je),check:Qa(t)};case"sendgrid":return Oe("sendgrid","x-twilio-email-event-webhook-signature",zr,Xa(t));case"livekit":return Oe("livekit","authorization",512*Je,eo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function Oe(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??Br(e,s)}}function Br(e,t){let n=kn(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:Wr(e,t.headers,r),event:r,...Ka(e,t,r)}}function Wr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Pe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Yr(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return Pe(n,"EventType");case"livekit":return Pe(n,"event");default:return Pe(n,"type")}}function Ka(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Pe(n,"id"));case"slack":return r(Pe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${Vr(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Pe(s,"sg_event_id")||void 0)}:{};default:return{}}}var Ja=300;function Ba(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let l of r.split(",")){let h=l.indexOf("=");if(h<=0)continue;let w=l.slice(0,h).trim(),k=l.slice(h+1).trim();if(w==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(w==="v1"){let _=le(k,"hex");if(!_)return"malformed_signature";a.push(_)}}let o=ct(s);if(o===void 0||a.length===0)return"malformed_signature";if(ut(o,n))return"stale_timestamp";let d=Be("sha256",e,`${s}.`,t.body);return a.some(l=>Ee(l,d))?void 0:"signature_mismatch"}}function Wa(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?le(n.slice(7),"hex"):void 0;return r?Ee(r,Be("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function Va(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ct(s),o=r.startsWith("v0=")?le(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":ut(a,n)?"stale_timestamp":Ee(o,Be("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function Za(e){let t=le(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=Fr({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=ct(o),l=le(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":ut(d,s)?"stale_timestamp":Gr(null,Zr(o,r.body),n,l)?void 0:"signature_mismatch"}}var Ya=1e3;function Qa(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=le(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!Ee(Buffer.from(a.toLowerCase()),Buffer.from(bn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let H=1;for(let Y of t.body)if(Y===38&&++H>Ya)return"malformed_signature";let I=new Map;for(let[Y,Q]of new URLSearchParams(kn(t.body))){let fe=I.get(Y);fe||I.set(Y,fe=new Set),fe.add(Q)}let D=[];for(let Y of[...I.keys()].sort()){let Q=[...I.get(Y)].sort();for(let fe of Q)o+=Y+fe;D.push([Y,Q.length===1?Q[0]:Q])}d=Object.fromEntries(D)}let l=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,w=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![h,w].some(H=>Ee(r,Be("sha1",e,H,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),_=k?{id:`${k}:${Vr(`${h}
|
|
5
|
-
${o}`)}`}:{};return d?{type:Wr("twilio",t.headers,d),event:d,..._}:{...Br("twilio",t),..._}}}function Xa(e){let t;try{let n=le(e,"base64");if(!n)throw new Error;t=Fr({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=ct(a),d=le(s.trim(),"base64");return o===void 0||!d?"malformed_signature":ut(o,r)?"stale_timestamp":Gr("sha256",Zr(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var qr=60;function eo(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=Hr(le(s[0],"base64url")),o=le(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Ee(o,Be("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Hr(le(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+qr||typeof d.nbf=="number"&&n<d.nbf-qr)return"stale_timestamp";let l=typeof d.sha256=="string"?le(d.sha256,"base64"):void 0;return l&&Ee(l,bn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function to(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ct(d);if(h===void 0)return"malformed_signature";if(ut(h,a))return"stale_timestamp"}let l=le(o.trim(),e.encoding);return l?Ee(l,Be(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var no=new TextEncoder;function Be(e,t,...n){let r=Ha(e,t);for(let s of n)r.update(s);return r.digest()}function Vr(e){return bn("sha256").update(e).digest("hex")}function Zr(e,t){return Buffer.concat([no.encode(e),t])}function Ee(e,t){return e.byteLength===t.byteLength&&Fa(e,t)}var ro={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function le(e,t){return ro[t].test(e)?Buffer.from(e,t):void 0}function ct(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function ut(e,t){return Math.abs(t-e)>Ja}function kn(e){return new TextDecoder().decode(e)}function Hr(e){if(e)try{return JSON.parse(kn(e))}catch{return}}function Yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e,t){let n=Yr(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var K=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
|
|
6
|
-
Kind: ${t}
|
|
7
|
-
Path: ${n.join(" -> ")}
|
|
8
|
-
At: ${r}
|
|
9
|
-
${s}
|
|
10
|
-
|
|
11
|
-
Potential solutions:
|
|
12
|
-
${a.map(o=>` - ${o}`).join(`
|
|
13
|
-
`)}`),this.name="DiError",this.kind=t,this.path=n}},so=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],ao=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),Mt=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=M(r,nn);if(!a)throw new K("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 K("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 K("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(!M(a,Ue))throw new K("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(M(a,Te))throw new K("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(M(a,we))throw new K("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(M(a,ke))throw new K("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(M(a,Ae)||M(a,Ke))throw new K("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 re())if(!this.owner.has(t))throw new K("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 K("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(M(r,Ke)&&!M(r,Ae))throw new K("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(!M(r,tn)&&!M(r,Re)&&!M(r,Ae)&&!M(r,Te)&&!M(r,we)&&!M(r,ke)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new K("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 K("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()"])}M(r,Ae)&&this.gateways.push(r),M(r,Ie)?this.webhooks.push(r):M(r,Re)&&this.eventProviders.push(r),M(r,Te)&&this.cronProviders.push(r),M(r,we)&&this.taskProviders.push(r),M(r,ke)&&this.templateProviders.push(r)}}for(let t of this.owner.keys())for(let n of so)if(typeof t.prototype[n]=="function")throw new K("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 K("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 K("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((h,w)=>{if(ao.has(h)||typeof h!="function")throw new K("unresolvable dependency",s,`${t.name} constructor parameter ${w}`,`parameter ${w} of ${t.name} is typed as ${h===void 0?"something with no runtime class":h.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,h,s),s))});let l=new t(...d);return this.instances.set(t,l),this.order.push(l),l}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}provider(t,n){if(typeof t!="function")throw new TypeError(`${n}: inject takes a provider's class \u2014 it was given ${t===null?"null":typeof t}`);let r=t;if(!this.owner.has(r)&&![...this.owner.keys()].some(a=>a.prototype instanceof r))throw new K("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 K("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 K("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 K("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 K("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 K("unowned class",[...n,t.name],t.name,`${t.name} is needed but no module lists it`,[`list ${t.name} in a module's providers (and export it if another module needs it)`])}async start(){let t=[];for(let n of this.order){let r=n.onStart;if(typeof r=="function")try{await r.call(n)}catch(s){throw await this.shutdown(t),new Error(`[palbase] ${n.constructor.name}.onStart() failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}t.push(n)}}async shutdown(t=this.order){for(let n of[...t].reverse()){let r=n.onShutdown;if(typeof r=="function")try{await r.call(n)}catch(s){console.error(`[palbase] ${n.constructor.name}.onShutdown() failed`,s)}}}};import{HTTP_ERROR_BRAND as oo,HttpError as lt}from"palgres";import{z as Se}from"zod";import{BadRequest as sc,Conflict as ac,DeadlockDetected as oc,HttpError as ic,NotFound as dc,SerializationFailure as cc,TooManyRequests as uc,UniqueViolation as lc}from"palgres";function ft(e){if(typeof e!="object"||e===null||e[oo]!==!0)return!1;let t=e;return Number.isInteger(t.status)&&t.status>=400&&t.status<=599&&typeof t.error=="string"&&typeof t.errorDescription=="string"}var Qr=class extends lt{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},Xr=class extends lt{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},es=class extends lt{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function ns(e,t){let n={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(n.data=e.data),n}var io=Symbol.for("palbase.backend.errorRegistry"),co={bad_request:Se.object({fields:Se.array(Se.object({field:Se.string(),message:Se.string()})),more:Se.number().int().optional()}),too_many_requests:Se.object({retryAfter:Se.number().int()})},uo=new Set(["auth_unavailable","check_failed","client_closed_request","database_unavailable","duplicate_upload","email_not_verified","handler_failed","idempotency_key_in_use","idempotency_key_reused","in_progress","internal_error","invalid_idempotency_key","invalid_signature","invalid_token","job_failed","job_not_found","method_not_allowed","missing_signature","payload_too_large","service_unavailable","signature_mismatch","temporarily_unavailable","unknown_token","upload_required","webhook_secret_missing"]);function lo(){let e=new Map;for(let[t,n,r]of[["bad_request",400,"BadRequest"],["unauthorized",401,"Unauthorized"],["forbidden",403,"Forbidden"],["not_found",404,"NotFound"],["conflict",409,"Conflict"],["unique_violation",409,"UniqueViolation"],["too_many_requests",429,"TooManyRequests"]]){let s=co[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function fo(){let e=globalThis;return e[io]??=lo()}var po=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function tc(e,t,n){if(typeof e!="string"||e.length>100||!po.test(e))throw new TypeError(`defineError(code, status): code is a wire code like room_locked or invite.notFound \u2014 a letter, then letters and digits in parts joined by . _ or - \u2014 not ${JSON.stringify(e)}`);if(!Number.isInteger(t)||t<400||t>599)throw new TypeError(`defineError("${e}", status): status is a 4xx or 5xx integer, not ${String(t)} \u2014 an error is never a success`);if(n!==void 0&&typeof n?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if(uo.has(e))throw new TypeError(`defineError("${e}", ${t}): "${e}" is the framework's own answer \u2014 a client would read the framework's refusal as the project's error; give the project's its own code`);let r=fo(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&ts(s.data)!==ts(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(_=>_.split(/(?=[A-Z])/)),o=a.map(_=>_.charAt(0).toUpperCase()+_.slice(1)).join(""),d=a.map(_=>_.toLowerCase()).join(" "),l=d.charAt(0).toUpperCase()+d.slice(1),k=n?(_=>class extends lt{static code=e;static status=t;constructor(H,I){let D=mo(e,_,H);super(t,e,I??(typeof D=="string"?D:l),D),this.name=o}})(n):class extends lt{static code=e;static status=t;constructor(_){super(t,e,_??l),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 mo(e,t,n){let r=t["~standard"].validate(n);if(r instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(r.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${r.issues.map(s=>s.message).join("; ")}`);return r.value}function ts(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as ho}from"palgres";var rs="/_palbase/ai/tools",ss="/_palbase/ai/agents",as="/_palbase/ai/repos",Ve=4<<20,go=Symbol.for("palbase.ai.tool_error");function os(e){return e instanceof Error&&e[go]===!0}var yo=Symbol.for("palbase.ai.declared");function is(){let e=globalThis[yo];if(!e)return{tools:new Map,clientTools:new Map,agents:new Map,repos:new Map,repoTokens:void 0};let t=new Set(e.twice);for(let n of e.clientTools?.keys()??[])e.tools.has(n)&&t.add(`tool:${n}`);if(t.size>0){let n=[...t].map(r=>r.replace(":"," "));throw new TypeError(`[palbase] ${n.join(", ")}: declared twice with different values \u2014 an ai.tool's, an ai.clientTool's and an ai.agent's name is its own (an agent is given one tool of a name, and the build's contract names it once), and ai.repoTokens is given once; make each once, at a module's top level`)}return{tools:new Map(e.tools),clientTools:new Map(e.clientTools??[]),agents:new Map(e.agents),repos:new Map(e.repos??[]),repoTokens:e.repoTokens}}var We=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ds(e){let t={};if(e==null)return t;if(We(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 cs(e){if(!We(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(!We(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=ds(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 us(e){let t=cs(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 ls(e){let t=cs(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=We(a)?ds(a.metadata):void 0;if(!We(a)||typeof a.id!="string"||typeof a.client_id!="string"||a.author!==null&&typeof a.author!="string"||typeof a.author_name!="string"||typeof a.text!="string"||typeof a.delivery!="string"||o===void 0)return"message is {id, client_id, author, author_name, text, delivery, metadata}, or null";r={id:a.id,clientId:a.client_id,author:a.author,authorName:a.author_name,text:a.text,delivery:a.delivery,metadata:ho(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!We(n.goal)||typeof n.goal.objective!="string"||typeof n.goal.rubric!="string")return"goal is {objective, rubric}";s={objective:n.goal.objective,rubric:n.goal.rubric}}return{...t,message:r,goal:s}}var wo=1e4,bo=10*6e4,Dt=class{constructor(t=Date.now){this.now=t}now;seen=new Map;take(t){let n=this.now();for(let[r,s]of this.seen){if(n-s<=bo&&this.seen.size<=wo)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},ko=1e3,vo=256*1024,Nt=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,n){this.running.delete(t),!(n===void 0||n.answer.length>vo)&&(this.answers.set(t,n),this.answers.size>ko&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as zs,isEngineRaised as Nn,markData as ce}from"palgres";import{createHash as qs}from"node:crypto";import{createHash as To,randomInt as $o}from"node:crypto";import{ago as vn,isRetryable as Eo,now as fs}from"palgres";import{defineSchema as So,defineTable as _o,index as xo,integer as Ro,jsonb as Ao,raw as Oo,text as Tn,timestamp as ps}from"palgres/dsl";var ks=new Set(["POST","PUT","PATCH","DELETE"]),ms=255,hs=35,gs=24,Po=65536,ys=1e3,Co=64,En={description:"Makes the write safe to send again (at most 255 characters). A retry with the same key and the same request gets the first answer back, marked `Idempotent-Replayed: true`, and changes nothing; the same key with a different request is refused with 422, and while the first request still runs a retry gets 409 with Retry-After. Answers are kept for 24 hours.",in:"header",name:"Idempotency-Key",required:!1,schema:{maxLength:255,type:"string"}},jo=_o("idempotency_keys",{columns:{key:Tn().primaryKey(),fingerprint:Tn(),started_at:ps().defaultNow(),completed_at:ps().nullable(),status_code:Ro().nullable(),response_headers:Ao().nullable(),response_body:Tn().nullable()},indexes:e=>[xo("idempotency_keys_started").on(e.col("started_at"))]}),kc=So("palbase",{tables:[jo],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)"})]}),Mo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Do={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},No={status:409,code:"idempotency_key_in_use",message:"This request's Idempotency-Key was taken over by a retry; what it did is not kept",retryAfter:1},ws={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},Lt=class extends Error{};function pt(e){return ks.has(e.method)&&e.meta.upload===void 0}function vs(e,t){if(!ks.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Uo(e,t){return Ts([e.role,e.uid,t]).digest("hex")}function Lo(e){return Ts([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Ts(e){let t=To("sha256");for(let n of e)t.update(n).update("\0");return t}function Io(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function $n(e){return e<500&&e!==429&&e!==499}function zo(e,t){return t&&$n(e)}function $s(e){let t=e["~standard"].jsonSchema?.input,n;try{n=t?.({target:"draft-2020-12"})}catch{return!1}let r=n?.properties;return typeof r=="object"&&r!==null&&Object.keys(r).some(s=>s.toLowerCase()==="idempotency-key")}var qo={role:"service",claims:{}},Ho={seal:e=>e,open:async e=>e},It=class{db;answers;constructor(t,n=Ho){this.db=t,this.answers=n}async serve(t,n,r){if(t.key.length>ms)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${ms} characters`});let s;try{s=await this.begin(Uo(t.caller,t.key),Lo(t))}catch(d){return S.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:d}),r.refusal(ws)}if("kept"in s){let d;try{d=s.kept.body===null?null:await this.answers.open(s.kept.body)}catch(l){return S.warn("[palbase] the answer kept against an Idempotency-Key could not be opened; the write is not run again",{error:l}),r.refusal(ws)}return Fo({...s.kept,body:d},r.requestId)}if("refused"in s)return r.refusal(s.refused==="reused"?Mo:Do);let a=s.claim,o;try{o=await n(d=>this.record(a,d))}catch(d){if(d instanceof Lt)return r.refusal(No);let l=r.failure(d);return zo(l.status,r.ran())&&!Eo(d)?this.keep(a,l):(await this.release(a),l)}return $n(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:vn({hours:gs})}}}))}async begin(t,n){return $o(Co)===0&&await this.sweep().catch(r=>S.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:vn({hours:gs})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let d=Io(o,n);if(d==="reused")return{refused:"reused"};if(d==="replay")return{kept:{status:o.status_code,headers:o.response_headers??[],body:o.response_body}};let[l]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:vn({seconds:hs})}},set:{started_at:fs()}});return l?{claim:{key:t,started:l.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!$n(n.status))return n;let{response:r,kept:s}=await bs(n),a=ne.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let o=s.body===null?null:this.answers.seal(s.body),[d]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),o]);if(d?.answered!==!0)throw new Lt;return r}async keep(t,n){let{response:r,kept:s}=await bs(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:fs(),status_code:s.status,response_headers:s.headers,response_body:s.body===null?null:this.answers.seal(s.body)}}))}catch(a){S.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()+hs*1e3,r=()=>{Date.now()+ys>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},ys).unref()};r()}async releaseOnce(t){try{return await this.asService(n=>n.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let n=this.db.request(qo),r;try{r=await t(n.database.palbase.idempotency_keys)}catch(s){throw await n.rollback(s).catch(()=>{}),s}try{await n.commit()}catch(s){throw await n.rollback(s).catch(()=>{}),s}return r}};function Fo(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 Ut=Symbol("waits");function Go(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(Ut));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function bs(e){let t=[];e.headers.forEach((d,l)=>{l!=="x-request-id"&&t.push([l,d])});let n=d=>new Response(d,{status:e.status,statusText:e.statusText,headers:e.headers});if(e.body===null)return{response:n(null),kept:{status:e.status,headers:t,body:null}};let r=e.body.getReader(),s=[],a=0;for(;;){let d=r.read(),l=await Go(d);if(l!==Ut&&l.done)break;if(l!==Ut&&(s.push(l.value),a+=l.value.byteLength,a<=Po))continue;let h=l===Ut?d:void 0,w=new ReadableStream({start(k){for(let _ of s)k.enqueue(_)},async pull(k){let _=await(h??r.read());h=void 0,_.done?k.close():k.enqueue(_.value)},cancel:k=>r.cancel(k)});return{response:n(w),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 Ko}from"node:crypto";var Sn="/webhooks/palbase",As="PalbaseErrorEnvelope",Es="PalbaseBearer",Jo={$ref:`#/components/schemas/${As}`},Bo={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"]},Ss={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Ze={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Os(e,t,n){let r={[As]:Bo},s={},a=[],o=[],d=new Set,l=new Map;for(let m of e){let v=o.find(V=>Qo(V,m));if(v){a.push({route:m.id,handler:_s(m),answeredBy:v.id});continue}o.push(m);let C=m.segments.map(V=>typeof V=="string"?V:"{}").join("/");l.has(C)||l.set(C,ei(m.segments.flatMap(V=>typeof V=="string"?[]:[V.param])));let U=l.get(C),J=0,B=`/${m.segments.map(V=>typeof V=="string"?V:`{${U[J++]}}`).join("/")}`,L=t(m),N=zt(Xo(m),d),W=m.method!=="GET"&&m.method!=="HEAD",G=V=>{let Ce=m.params.filter(je=>je.kind===V&&je.schema).map((je,at)=>Ft(je.schema,`${N}.${V}${at===0?"":`.${at+1}`}`,r));return Ce.length===0?void 0:Ce.length===1?Ce[0]:{allOf:Ce}},te=U.map(V=>({name:V,in:"path",required:!0,schema:{type:"string"}})),nt=G("query");nt&&te.push(...Rs(nt,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:nt}]);let me=G("headers");me&&te.push(...Rs(me,"header")??[]);let ve=n.idempotency===!0&&pt(m);ve&&te.push({...En,schema:{...En.schema}});let _e=W?G("body"):void 0,ae={operationId:N};m.controller.name!==""&&(ae.tags=[m.controller.name]),te.length>0&&(ae.parameters=te),_e&&(ae.requestBody={required:!ai(_e),content:{"application/json":{schema:_e}}});let Wt=m.params.some(V=>V.schema!==void 0),bt=n.routes?.(m),rt=ii(N,bt?.throws??[],n.errors);ae.responses={...oi(bt,N,r),...ui(L,{validates:Wt,hasPathParams:U.length>0,readsBody:W,keyed:ve}),...ci(rt,N,r)},rt.length>0&&(ae["x-palbase-errors"]=di(N,rt)),L.auth.required&&(ae.security=[{[Es]:[]}]),ae["x-palbase-handler"]=_s(m);let st=m.params.some(V=>V.kind==="optionalUser")||n.databaseSeesCaller;ae["x-palbase-auth"]=L.auth.required?"required":st?"optional":"public",ae["x-palbase-verified-email"]=L.auth.verifiedEmail,ae["x-palbase-rate-limit"]=L.limit===!1?!1:{max:L.limit.max,window:L.limit.window},m.meta.upload&&(ae["x-palbase-upload"]={bucket:m.meta.upload.bucket,pathTemplate:m.meta.upload.pathTemplate}),(s[B]??={})[m.method.toLowerCase()]=ae}for(let m of n.webhooks??[]){let v={operationId:zt(`webhooks.${m.name}`,d)};m.cls!==""&&(v.tags=[m.cls]),v.description=m.provider?`${Ss[m.provider]??m.provider}'s deliveries: verified with ${Ss[m.provider]??m.provider}'s signature scheme under the secret in ${m.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${m.signatureHeader} header: verified under the secret in ${m.secretEnv}, then handed to the @On of their event type.`,v.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":{},[m.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:X("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:X("in_progress: the same delivery is being handled; the sender delivers it again",Ze),413:X("payload_too_large: the body is over what this sender sends"),500:X("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:X("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",Ze)},v["x-palbase-webhook"]=m.provider?{provider:m.provider,secretEnv:m.secretEnv,events:m.events}:{signatureHeader:m.signatureHeader,secretEnv:m.secretEnv,events:m.events},s[`/webhooks/${m.name}`]={post:v}}let h=[...new Set(n.platformEvents??[])].sort();if(h.length>0){let m={operationId:zt("webhooks.palbase",d)};m.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.",m.responses={204:{description:"Taken: handled, or a delivery already run"},401:X("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:X("in_progress: the same event is being handled; the platform delivers it again",Ze),500:X("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:X("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let v=[...new Set(n.platformEventBuckets??[])].sort();m["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:h,...v.length>0?{buckets:v}:{}},s[Sn]={post:m}}let w=n.gateways??[],k=Zo(w,r),_=w.length>0,H=Object.fromEntries(w.filter(Fe).map(m=>[m.pattern,{events:k[m.name].events,messages:Object.fromEntries(Object.entries(k[m.name].messages).map(([v,C])=>[v,C.payload])),graceMs:m.graceMs,...m.logKeepSeconds>0?{logKeepSeconds:m.logKeepSeconds}:{}}])),I=Object.keys(H).length>0,D=w.filter(m=>!Fe(m)).map(m=>({pattern:m.pattern,kind:m.access,publish:m.publish,state_read:!1,state_write:!1,...m.logKeepSeconds>0?{log_keep_seconds:m.logKeepSeconds}:{}})),Y=D.length>0,Q=Wo(n.ai?.agents??[]),fe=Object.keys(Q).length>0,pe=Vo(n.ai?.tools??[]),be=Object.keys(pe).length>0,b={schemas:r,securitySchemes:{[Es]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},E={openapi:"3.2.0",info:{title:"Palbase backend",version:Ko("sha256").update(JSON.stringify({paths:s,components:b,unreachable:a,..._?{gateways:k}:{},...I?{rooms:H}:{},...Y?{channels:D}:{},...fe?{agents:Q}:{},...be?{aiTools:pe}:{}})).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:b};return a.length>0&&(E["x-palbase-unreachable"]=a),_&&(E["x-palbase-gateways"]=k),I&&(E["x-palbase-room"]=H),Y&&(E["x-palbase-channels"]=D),fe&&(E["x-palbase-agents"]=Q),be&&(E["x-palbase-ai-tools"]=pe),E}function Wo(e){let t=new Map;for(let n of e){if(t.has(n.name))throw new Error(`ai.agent "${n.name}" is declared twice: an agent's name is its own \u2014 make each once, at a module's top level`);t.set(n.name,{...n.description!==void 0?{description:n.description}:{},...n.machine!==void 0?{machine:n.machine}:{}})}return Object.fromEntries([...t].sort(([n],[r])=>n<r?-1:n>r?1:0))}function Vo(e){let t=new Map;for(let n of e){let r=t.get(n.name);if(r)throw new Error(`ai tool "${n.name}" is declared twice (${r.kind===n.kind?`two ai.${n.kind==="backend"?"tool":"clientTool"}s`:"an ai.tool and an ai.clientTool"}): an agent is given one tool of a name \u2014 rename one of them`);t.set(n.name,{kind:n.kind,description:n.description,parameters:n.parameters,...n.approval?{approval:!0}:{},...n.kind==="backend"&&n.machine!==void 0?{machine:n.machine}:{}})}return Object.fromEntries([...t].sort(([n],[r])=>n<r?-1:n>r?1:0))}function Zo(e,t){let n=[];for(let r of e){let s=(d,l,h,w)=>{let k=Ht(`${r.name}_${d}_${l}`),_={},H=Ft(h,k,_,w);H.$ref===void 0&&(_[k]=H),Yo(r.pattern,d,l,_[k]);for(let[I,D]of Object.entries(_)){if(Object.hasOwn(t,I)&&JSON.stringify(t[I])!==JSON.stringify(D))throw new Error(`@Gateway("${r.pattern}") ${d} "${l}": its schema is the component ${I}, which another gateway's names with another schema \u2014 rename one of them`);t[I]=D}return{$ref:`#/components/schemas/${k}`}},a=Object.fromEntries(Object.entries(r.events).map(([d,l])=>[d,s("event",d,l,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([d,l])=>[d,{payload:s("message",d,l.schema,"sent"),...l.reply?{reply:s("reply",d,l.reply,"answered")}:{}}]));n.push([r.name,{pattern:r.pattern,...r.access?{access:r.access}:{},...r.logKeepSeconds>0?{durable:r.logKeepSeconds}:{},...r.chat?{chat:!0}:{},events:a,messages:o}])}return Object.fromEntries(n)}function Yo(e,t,n,r){if(!(!se(r)||!se(r.properties))){for(let[s,a]of Object.entries(r.properties))if(a===!0||se(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 Qo(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 _s(e){return`${e.controller.name}.${e.fn}`}function Xo(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 zt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function ei(e){let t=new Set;return e.map(n=>zt(n,t))}function Ft(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:ti}:{}}})}catch{return{}}let d=Ht(t);for(;Object.keys(n).some(l=>l===d||l.startsWith(`${d}.`));)d=`${d}_`;return ni(o,d,n,r)}function ti(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function ni(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=h=>h==="#"?(a=!0,`#/components/schemas/${t}`):h.startsWith("#/$defs/")?`#/components/schemas/${t}.${Ht(si(h.slice(8)))}`:h,d="all";if(r==="sent"){let h=new Set;for(let w of[e,...Object.values(s)])qt(w,h);d=h}for(let[h,w]of Object.entries(s))n[`${t}.${Ht(h)}`]=ht(mt(w,o,d));let l=ht(mt(e,o,d));return a?(n[t]=l,{$ref:`#/components/schemas/${t}`}):l}var ri=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",Zn]),_n=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),xn=new Set(["anyOf","oneOf","allOf","prefixItems"]),Rn=new Set(["properties","patternProperties","dependentSchemas"]),se=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function mt(e,t,n){if(!se(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):ri.has(s)?r[s]=a:_n.has(s)?r[s]=mt(a,t,n):xn.has(s)&&Array.isArray(a)?r[s]=a.map(o=>mt(o,t,n)):Rn.has(s)&&se(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,d])=>[o,mt(d,t,n)])));return r}var xs=Number.MAX_SAFE_INTEGER;function ht(e){if(!se(e))return e;let t={};for(let[r,s]of Object.entries(e))_n.has(r)?t[r]=ht(s):xn.has(r)&&Array.isArray(s)?t[r]=s.map(ht):Rn.has(r)&&se(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,ht(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-xs&&delete t.minimum,t.maximum===xs&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,se(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=>se(a)&&Object.keys(a).length===1&&a.type==="null"),s=n[1-r];if(r!==-1&&se(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function qt(e,t){if(se(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(se))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=>se(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(o=>se(o[a])&&"const"in o[a]))for(let o of s)t.add(o[a])}for(let[n,r]of Object.entries(e))if(_n.has(n))qt(r,t);else if(xn.has(n)&&Array.isArray(r))for(let s of r)qt(s,t);else if(Rn.has(n)&&se(r))for(let s of Object.values(r))qt(s,t)}}function si(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Ht(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function Rs(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 ai(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function X(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:Jo}}}}function oi(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=Ft(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function ii(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 di(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 ci(e,t,n){let r=new Map;for(let a of e)r.set(a.status,[...r.get(a.status)??[],a]);let s={};for(let a of[...r.keys()].sort((o,d)=>o-d)){let o=r.get(a),d=o.map(l=>{let h={error:{type:"string",const:l.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},w=["error","error_description","status","request_id"];return l.data&&(h.data=Ft(l.data,`${t}.${l.code}.data`,n,"answered"),w.push("data")),{type:"object",properties:h,required:w}});s[String(a)]={description:o.map(l=>l.code).join(" | "),content:{"application/json":{schema:d.length===1?d[0]:{oneOf:d}}}}}return s}function ui(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]=X(s.join("; "))),e.auth.required&&(n[401]=X("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]=X("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=X("idempotency_key_in_use: a request with this Idempotency-Key is still running",Ze)),t.readsBody&&(n[413]=X("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=X("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=X("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Ze)),n[500]=X("internal_error: the handler failed; the app's log has it under the request id"),n[503]=X(`${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":""}`,Ze),n}var Gt=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 Kt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return li(r??t??"unknown")}function li(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(n)return n[1];let[r,s=""]=t.split("::"),a=r?r.split(":"):[],o=s?s.split(":"):[],d=t.includes("::")?[...a,...Array(8-a.length-o.length).fill("0"),...o]:a;return d.length!==8||d.some(l=>!/^[0-9a-f]{1,4}$/i.test(l))?t:`${d.slice(0,4).map(l=>parseInt(l,16).toString(16)).join(":")}::/64`}function Ps(e){let t=[];for(let n of e){let r=M(n,Ue),s=M(n,Le)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=M(n,en)??new Map;for(let o of s){let d=`${r.basePath}${o.subpath}`||"/",l=d.split("/").filter(Boolean).map(w=>{let k=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(w)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(w);return k?{param:k[1]}:w});if(typeof l[0]=="string"&&ze.has(l[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${d} \u2014 /${l[0]} is the platform's; a route is served elsewhere`);let h=[...a.get(o.fn)??[]].sort((w,k)=>w.index-k.index);for(let w of h)if(w.kind==="param"&&!l.some(k=>typeof k!="string"&&k.param===w.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${w.name}") names no {${w.name}} in ${o.method} ${d}`);t.push({id:`${o.method} ${d}`,method:o.method,segments:l,controller:n,fn:o.fn,params:h,meta:o,controllerAuth:r.options.auth})}}return xr(t),t}function An(e,t,n){let r=n.split("/").filter(Boolean);for(let s of e){if(s.method!==t||s.segments.length!==r.length)continue;let a={},o=!0;for(let d=0;d<r.length&&o;d++){let l=s.segments[d];if(typeof l=="string")o=l===r[d];else try{a[l.param]=decodeURIComponent(r[d])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function Cn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Ye(e,t,n,r,s){return tt(e,e?Cn(e.requests,t):void 0,n,r,s)}var gt={role:"service",claims:{}};async function tt(e,t,n,r,s){if(!e||!t)return s();let a=h=>S.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 ${h} 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:h}),o=e.app.request(t,{signal:n,heldIdle:a}),d=ne.getStore();d&&(d.database=o.database);let l;try{l=await s()}catch(h){throw await o.rollback(h).catch(w=>S.error("[palbase] the request's transaction could not be rolled back",{error:w})),h}try{await o.commit()}catch(h){throw await o.rollback(h).catch(w=>S.error("[palbase] the request's transaction could not be rolled back",{error:w})),h}return l}var pi=1024*1024,mi=20,hi={max:300,window:60},Qe="/_palbase/crons",Xe="/_palbase/tasks",Cs=50,js=50,gi=4096,yi=69632,Ms=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,et=1e4,wi=6e4;function bi(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 ee=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 ki(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 vi=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Ti(e,t){let n=new Headers(e.headers);for(let r of vi)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 Ds(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Jt(e.headers,"Accept-Language")),e}function Jt(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 de(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),de(e.status,n,t,r)}var Hs=new Set([0,429,502,503,504]);function Ns(e,t,n,r){if(r?.aborted)return S.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 ee)return T({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(ft(e)){let a=e;return a.status>=500&&S.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),de(a.status,ns(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Bt(e,n);return s?T(s,t):(e instanceof oe?S.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):S.error(`[palbase] unhandled error in ${n}`,{error:e}),T({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Bt(e,t){if(e instanceof _t)return S.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 oe&&Hs.has(e.status))return S.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=zs(e);if(n!==void 0)return S.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 $i(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return os(e)?t(e.message):ft(e)&&!Nn(e)&&!jn(e)?t(e.errorDescription):jn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function jn(e){return e instanceof _t||e instanceof oe&&Hs.has(e.status)||zs(e)!==void 0||ft(e)&&e.status===503&&Nn(e)}async function On(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,mi).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 ee(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function yt(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new ee(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let r=e.body.getReader(),s=[],a=0;for(;;){let{done:l,value:h}=await r.read();if(l)break;if(a+=h.byteLength,a>t)throw await r.cancel().catch(()=>{}),new ee(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(h)}let o=new Uint8Array(a),d=0;for(let l of s)o.set(l,d),d+=l.byteLength;return o}function Ei(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ce(t)}function Si(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 _i(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 xi=/^[A-Za-z0-9._:-]{8,128}$/,Ri=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ai={max:20,window:60},Oi=10*6e4,Pi=1e4,wt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},Mn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=qs("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,d;if(!a){let h=this.limiter.reserve(o,Ai);if("wait"in h)throw new wt(h.wait);d=h}let l=await r();if(!l)throw this.known.delete(s),new St("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()+Oi),this.known.size>Pi&&this.known.delete(this.known.keys().next().value),l}};function eu(e){let t=new Mt(e.modules),n=Ps(t.controllers.map(i=>i.cls)),r=new Map(n.map(i=>[i,bi(i,e.auth)])),s=new Map;for(let i of n){let c={body:[],query:[]};for(let f of i.params){if(!f.schema)continue;let u=ir(f.schema);if(f.kind==="body")c.body.push(...Yt(u,"/body",i.id));else if(f.kind==="query"){let g=Yt(u,"/query",i.id),p=g.find(y=>y.split("/").length!==3);if(p)throw new TypeError(`${i.id}: ${p} \u2014 an encrypted query field is one of the query's own names`);c.query.push(...g)}else if(dr(u))throw new TypeError(`${i.id}: its ${f.kind} carry no encrypted field \u2014 its body's or its query's do`)}if(c.body.length+c.query.length!==0){if(i.meta.upload)throw new TypeError(`${i.id}: an upload's body comes through storage, which seals nothing \u2014 it carries no encrypted field`);s.set(i,c)}}async function a(i,c,f,u){let g=e.server.transit;try{return g.loaded||await g.load(),await g.request({header:f,method:u,path:Di(i),params:i.segments.flatMap(p=>typeof p=="string"?[]:[c[p.param]??""])})}catch(p){throw Ls(p)}}for(let[i,c]of r){if(!c.required&&i.params.some(f=>f.kind==="user"))throw new TypeError(`${i.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(i.meta.upload&&c.verifiedEmail)throw new TypeError(`${i.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`)}let o=new Map;for(let i of n)for(let c of i.params)c.kind==="resolve"&&o.set(c,t.dependencyOf(i.controller,c.resolver,`${i.id} @Resolve(${c.resolver?.name})`));let d=new Map;for(let i of t.cronProviders){let c=t.get(i),f=M(i,Te),u=d.get(f.name);if(u)throw new TypeError(`@Cron "${f.name}" is ${u.owner} and ${i.name}: a cron's name is its own \u2014 name one of them`);d.set(f.name,{declaration:f,owner:i.name,run:g=>c.run(g)})}let l=new Map;for(let i of t.taskProviders){let c=t.get(i),f=M(i,we),u=l.get(f.name);if(u)throw new TypeError(`@Task "${f.name}" is ${u.owner} and ${i.name}: a task type's name is its own \u2014 name one of them`);l.set(f.name,{declaration:f,owner:i.name,run:(g,p)=>c.run(g,p)})}let h=new Map;for(let i of t.templateProviders){let c=t.get(i),f=M(i,ke),u=h.get(f.name);if(u)throw new TypeError(`@TestUserTemplate "${f.name}" is ${u.owner} and ${i.name}: a template's name is its own \u2014 name one of them`);h.set(f.name,{owner:i.name,seed:(g,p)=>c.seed(g,p),...typeof c.undo=="function"?{undo:(g,p)=>c.undo(g,p)}:{}})}h.size>0&&!e.platform&&S.info(`[palbase] ${h.size} @TestUserTemplate(s): the platform calls a machine for its test users; nothing does here`);let w=new Map,k=new Set,_=new Set,H=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(d.size>Cs)throw new TypeError(`${d.size} @Cron classes: a machine runs ${Cs} crons at most`);if(l.size>js)throw new TypeError(`${l.size} @Task classes: a machine runs ${js} task types at most`);d.size>0&&!e.platform&&S.info(`[palbase] ${d.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let I=Ir(t.gateways.map(i=>({cls:i,instance:t.get(i)})),{run:(i,c,f,u)=>ne.run({requestId:ne.getStore()?.requestId??"",...i?.id?{userId:i.id}:{}},()=>tt(e.database,e.database?i?.id?Cn(e.database.requests,Ct(i)):gt:void 0,f,c,async()=>{let g=await u();if(f?.aborted)throw new Error(`realtime gave up on ${c} before it ended`);return g})),broadcast:i=>e.server.realtime.broadcast({body:{messages:i}}),revalidate:i=>e.server.realtime.revalidate({body:i}),isOutage:jn});I.declarations.length>0&&!e.platform&&S.info(`[palbase] ${I.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let D=is();(D.tools.size>0||D.agents.size>0)&&!e.platform&&S.info(`[palbase] ${D.tools.size} ai.tool(s) and ${D.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let Y=i=>c=>t.provider(c,`${i} ctx.inject(${typeof c=="function"?c.name:String(c)})`),Q=new Nt,fe=new Dt(e.now??Date.now),pe=new Set,be=e.database!==void 0||e.contractOnly?.database===!0;if(be){for(let i of n)if(pt(i)&&i.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&$s(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 b=e.database?new It(e.database.app,e.database.keptAnswers):void 0,E=qi(e.cors),m=e.now??Date.now,v=new Gt(e.now),C=new Mn(v,e.now??Date.now),U=e.maxBodyBytes??pi,J=i=>{let c=i.meta.options.rateLimit??e.rateLimit??hi;return c!==!1&&c.max>0&&c.window>0?c:!1},B=e.env??process.env,L=Kr(t.webhooks,i=>t.get(i),B,{secrets:e.contractOnly===void 0}),N=L.size===0&&d.size===0&&l.size===0&&h.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(B).filter(i=>typeof i[1]=="string"&&!nr(i[0])))),W=new Map([...L.keys()].map(i=>[i,{seen:new Set,inflight:new Set}])),G=new Map([...L.keys()].map(i=>[i,{counts:new Map,at:void 0}])),te,nt=()=>te??=Os(n,i=>({auth:r.get(i),limit:J(i)}),{databaseSeesCaller:be,idempotency:be,webhooks:[...L.values()].map(i=>({name:i.name,cls:i.cls.name,provider:i.provider,signatureHeader:i.signatureHeader,secretEnv:i.secretEnv,events:[...i.events.keys()]})),platformEvents:[...me.keys()],gateways:I.declarations,ai:{agents:[...D.agents.values()].map(i=>({name:i.name,...i.description!==void 0?{description:i.description}:{},...i.machine!==void 0?{machine:i.machine}:{}})),tools:[...[...D.tools.values()].map(i=>({name:i.name,kind:"backend",description:i.description,parameters:i.parameters,approval:i.approval,...i.machine!==void 0?{machine:i.machine}:{}})),...[...D.clientTools.values()].map(i=>({name:i.name,kind:"client",description:i.description,parameters:i.parameters,approval:i.approval}))]},platformEventBuckets:ji(me),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),me=new Map;for(let[i,c]of Object.entries(e.events??{}))me.set(i,c.map(f=>({name:`palbase(${i})`,call:u=>f(u)})));for(let i of t.eventProviders){let c=t.get(i);for(let{event:f,fn:u,bucket:g}of M(i,Re)??[]){if(!mr.test(f))throw new TypeError(`@On("${f}") on ${i.name}.${u}: a platform event's type is dotted lowercase words, like user.deleted \u2014 a third party's event is taken by an @On in its @Webhook class`);me.has(f)||me.set(f,[]),me.get(f).push({name:`${i.name}.${u}`,bucket:g,call:async(p,y)=>c[u](p,y)})}}let ve=new Set,_e=new Set;rr(e.server),sr({to:(i,c)=>({emit:(f,u)=>I.emit(i,c,f,u),pipe:f=>I.pipe(i,c,f),revalidate:f=>I.revalidate(i,c,f)})}),gr(e.platform?yr(B.PALBASE_MACHINE):new Ot(new Map([...l].map(([i,c])=>[i,c.declaration])),(i,c)=>at(i,c),e.now));async function ae(i,c){let f;try{f=await er(i,e.webhookSecret,{now:e.now})}catch(u){if(u instanceof it)return T({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${u.code}`},c);throw u}if(ce(f.data),ve.has(f.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(_e.has(f.id))return T({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);_e.add(f.id);try{let u;try{await Ye(e.database,null,void 0,`event ${f.type}`,async()=>{for(let g of me.get(f.type)??[])if(!(g.bucket!==void 0&&Ci(f)!==g.bucket))try{await g.call(f,{requestId:c})}catch(p){throw u=g.name,p}})}catch(g){return S.error(`[palbase] ${u??"the delivery"} failed on ${f.type} ${f.id}; the platform delivers it again`,{error:g}),T({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return ve.add(f.id),ve.size>et&&ve.delete(ve.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{_e.delete(f.id)}}async function Wt(i,c={}){let f=i.headers.get("origin");if(E&&f!==null){let u=E.allows(f);if(i.method==="OPTIONS"&&i.headers.has("access-control-request-method"))return u?new Response(null,{status:204,headers:E.preflight(f,i.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let g=await Fn(i,c);if(u)for(let[p,y]of Object.entries(E.headers(f)))p==="vary"?Jt(g.headers,y):g.headers.set(p,y);else Jt(g.headers,"Origin");return g}return Fn(i,c)}async function bt(i,c,f,u){if(!i.headers.get(f.scheme.header))return st(f,"missing_signature",u);let g={headers:i.headers,body:await yt(i,f.scheme.maxBytes(U)),url:Jr(i,c)},p;try{p=f.scheme.check(g,m()/1e3)}catch{return st(f,"signature_mismatch",u,"check_failed")}if(typeof p=="string")return st(f,p,u);let y=f.events.get(p.type);if(!y)return S.info(`[palbase] webhook ${f.name}: no @On takes "${p.type}"; acknowledged`),de(200,{ok:!0,handled:!1},u);let $=W.get(f.name),x=p.event,P=[];if(p.id!==void 0){if($.seen.has(p.id))return de(200,{ok:!0,handled:!1,duplicate:!0},u);P=[p.id]}else if(p.ids&&Array.isArray(x)){let A=p.ids,R=x.map((j,Z)=>[j,A[Z]]).filter(([,j])=>j===void 0||!$.seen.has(j));if(R.length===0)return de(200,{ok:!0,handled:!1,duplicate:!0},u);x=R.map(([j])=>j),P=R.flatMap(([,j])=>j===void 0?[]:[j])}if(P.some(A=>$.inflight.has(A)))return T({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},u);ce(x);for(let A of P)$.inflight.add(A);let O;try{O=await Ye(e.database,null,void 0,`webhook ${f.name}`,()=>y.call(x,{env:N,requestId:u,environmentId:e.projectId??""}))}catch(A){let R=Bt(A,`webhook ${f.name}`)??Ni(A,f.name);return R?T(R,u):(S.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"},u))}finally{for(let A of P)$.inflight.delete(A)}for(let A of P)$.seen.add(A),$.seen.size>et&&$.seen.delete($.seen.values().next().value);return rt(O,f,u)}function rt(i,c,f){if(i instanceof Response)return i;if(typeof i=="string"){let u=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(i,{status:200,headers:{"content-type":u,"x-request-id":f}})}return de(200,i??{ok:!0,handled:!0},f)}function st(i,c,f,u=c){let g=G.get(i.name);g.counts.set(u,(g.counts.get(u)??0)+1);let p=m();return(g.at===void 0||p-g.at>=wi)&&(V(i.name),g.at=p),T({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},f)}function V(i){let c=G.get(i).counts;if(c.size===0)return;let f=[...c.values()].reduce((u,g)=>u+g,0);S.warn(`[palbase] webhook ${i}: ${f} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function Ce(i){let c=i.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?L.get(c[1]):void 0}async function je(i,c,f,u){let g=c.pathname===Qe;if(i.method!==(g?"GET":"POST"))return T({status:405,code:"method_not_allowed",message:g?"The crons are listed with GET":"A cron is run with POST"},u);let p=g?new Uint8Array(0):await yt(i,gi);try{await Et({secret:f,signature:i.headers.get("palbase-signature"),body:p,now:e.now})}catch(q){if(q instanceof it)return T({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${q.code}`},u);throw q}if(g){let q=[...d.values()].map(({declaration:F})=>({name:F.name,schedule:F.schedule,time_zone:F.timeZone,timeout:F.timeout,retry:F.retries}));return de(200,{crons:q},u,{"cache-control":"no-store"})}let y=c.pathname.slice(Qe.length+1),$=d.get(y);if(!$)return T({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(y)}`},u);let x;try{x=JSON.parse(new TextDecoder().decode(p))}catch{return T({status:400,code:"bad_request",message:"A run is the JSON {cron, run_id, scheduled_at, attempt}"},u)}let{cron:P,run_id:O,scheduled_at:A,attempt:R}=x??{};if(P!==y||typeof O!="string"||O===""||typeof A!="string"||!Ms.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)}`},u);let j=`${O}#${String(R)}`;if(_.has(j))return new Response(null,{status:204,headers:{"x-request-id":u}});if(H.has(j))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);H.add(j);let Z={env:N,environmentId:e.projectId??"",cron:y,runId:O,scheduledAt:new Date(A),attempt:R};try{await tt(e.database,e.database?gt: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(q){return i.signal.aborted||S.error(`[palbase] cron ${y} failed (run ${O}, attempt ${String(R)})`,{error:q}),T({status:500,code:"cron_failed",message:`The cron ${y} failed; the platform tries it again`},u)}finally{H.delete(j)}return _.add(j),_.size>et&&_.delete(_.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}let at=async({task:i,id:c,attempt:f,payload:u,createdAt:g},p)=>{let y=l.get(i);if(!y)return{status:404,message:`this version has no task ${JSON.stringify(i)}`};let $=ce(u??null),x=y.declaration.payload;if(x){let O=await x["~standard"].validate($);if(O.issues){let A=O.issues.slice(0,5).map(R=>`${(R.path??[]).map(j=>String(typeof j=="object"&&j!==null&&"key"in j?j.key:j)).join(".")||"(payload)"}: ${R.message}`).join("; ");return S.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}`}}$=O.value}let P={env:N,environmentId:e.projectId??"",task:i,id:c,attempt:f,createdAt:g};try{await tt(e.database,e.database?gt:void 0,p,`task ${i}`,async()=>{if(await y.run($,P),p.aborted)throw new Error(`the platform gave up on this attempt of ${i} before it ended`)})}catch(O){return O instanceof At?(S.error(`[palbase] task ${i} ${c} can never be done: ${O.message}`),{status:422,message:O.message}):(p.aborted||S.error(`[palbase] task ${i} failed (task ${c}, attempt ${String(f)})`,{error:O}),{status:500,message:`the task ${i} failed; it is tried again`})}return{status:204}};async function Ks(i,c,f,u){let g=c.pathname===Xe;if(i.method!==(g?"GET":"POST"))return T({status:405,code:"method_not_allowed",message:g?"The task types are listed with GET":"A task is run with POST"},u);let p=g?new Uint8Array(0):await yt(i,yi);try{await Et({secret:f,signature:i.headers.get("palbase-signature"),body:p,now:e.now})}catch(q){if(q instanceof it)return T({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${q.code}`},u);throw q}if(g){let q=[...l.values()].map(({declaration:F})=>({name:F.name,timeout:F.timeout,retry:F.retries,concurrency:F.concurrency}));return de(200,{tasks:q},u,{"cache-control":"no-store"})}let y=c.pathname.slice(Xe.length+1),$;try{$=JSON.parse(new TextDecoder().decode(p))}catch{return T({status:400,code:"bad_request",message:"A task is the JSON {task, id, attempt, payload, created_at}"},u)}let{task:x,id:P,attempt:O,payload:A,created_at:R}=$??{};if(x!==y||typeof P!="string"||P===""||typeof R!="string"||!Ms.test(R)||Number.isNaN(Date.parse(R))||!Number.isInteger(O)||O<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)}`},u);let j=`task:${P}#${String(O)}`;if(_.has(j))return new Response(null,{status:204,headers:{"x-request-id":u}});if(H.has(j))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);H.add(j);let Z;try{Z=await at({task:y,id:P,attempt:O,payload:A,createdAt:new Date(R)},i.signal)}finally{H.delete(j)}return Z.status===404?T({status:404,code:"task_not_found",message:Z.message??""},u):Z.status===422?T({status:422,code:"task_failure",message:Z.message??""},u):Z.status>=300?T({status:Z.status,code:"task_failed",message:Z.message??""},u):(_.add(j),_.size>et&&_.delete(_.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}}))}async function Me(i,c,f,u){if(i.method!=="POST")return T({status:405,code:"method_not_allowed",message:`${u} is POSTed`},f);let g;try{Xn({signature:i.headers.get("palbase-signature"),now:e.now}),g=await yt(i,1048576),await Et({secret:c,signature:i.headers.get("palbase-signature"),body:g,now:e.now})}catch(y){if(y instanceof it)return T({status:401,code:"invalid_signature",message:`${u} is the platform's to call: ${y.code}`},f);throw y}let p;try{p=JSON.parse(new TextDecoder().decode(g))}catch{return T({status:400,code:"bad_request",message:`${u} is JSON`},f)}return typeof p!="object"||p===null||!Object.hasOwn(p,"call")||p.call!==new URL(i.url).pathname?T({status:401,code:"invalid_signature",message:`${u} is the platform's to call: signed_for_another_call`},f):{body:p}}async function Js(i,c,f,u,g){let p=await Me(c,f,u,`An upload's ${i}`);if(p instanceof Response)return p;let y=Rr(i,p.body);if(typeof y=="string")return T({status:400,code:"bad_request",message:`An upload's ${i}: ${y}`},u);if(i==="complete"){if(pe.has(y.uploadId))return T({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},u);pe.add(y.uploadId),pe.size>et&&pe.delete(pe.values().next().value)}let $=An(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}`},u);let{route:x,params:P}=$,O=$.route.meta.upload,A=_i(y.user);if(A&&Gn(g,A.id),r.get(x).required&&!A)throw new ee(401,"unauthorized","This route needs a signed-in user");if(i==="authorize"){let Z=J(x);if(Z!==!1){let F=v.take(`${x.id}\0${$r(y.user,y.client)}`,Z);if(F!==void 0)throw new ee(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:F},F)}let q=_r(O.pathTemplate,{userId:A?.id??null,uploadId:y.uploadId,filename:y.filename});if("problem"in q)throw new ee(400,"bad_request",q.problem);return await Ye(e.database,Ct(y.user),c.signal,x.id,async()=>{let F={request:c,query:new URLSearchParams(y.query),params:P,user:A,body:y.body===void 0||y.body===null?{}:ce(y.body),requestId:u};await Hn(x,F);for(let De of x.params)(De.kind==="query"||De.kind==="body"&&y.body!==void 0)&&await Is(De,F)}),de(200,{bucket:O.bucket,path:q.path},u)}g.endpoint=x.id.slice(x.id.indexOf(" ")+1);let R=new URLSearchParams(y.query),j=y.body===null||y.body===void 0?{}:ce(y.body);return Pn(await Vt(x,{request:c,query:R,params:P,user:A,body:j,requestId:u,uploadedObject:ce(y.uploadedObject)},Ct(y.user)),void 0,u)}async function Bs(i,c,f,u){let g=c.pathname.slice(Pt.length+1),p=g.endsWith("/undo"),y=p?g.slice(0,-5):g,$=await Me(i,f,u,"A test user template");if($ instanceof Response)return $;let x=h.get(y);if(!x||p&&!x.undo)return T({status:404,code:"template_not_found",message:x?`@TestUserTemplate "${y}" has no undo: the user's deletion cleans up after it`:`This version has no test user template ${JSON.stringify(y)}`},u);let P=wr(y,$.body);if(typeof P=="string")return T({status:400,code:"bad_request",message:`A test user template's call: ${P}`},u);let O=ce(P.user),A;try{A=await br(e.server,O.id)}catch(q){return S.error(`[palbase] test user template ${y}: auth could not say whether ${O.id} is a test user; nothing was written`,{error:q}),T({status:503,code:"auth_unavailable",message:"Auth could not say whether the user is a test user: the template did not run",retryAfter:5},u)}if(!A)return S.warn(`[palbase] test user template ${y}${p?" undo":""}: auth does not say ${O.id} is a test user \u2014 nothing was run`),T({status:403,code:"not_a_test_user",message:"Auth does not say this user is a test user: a template writes for test users alone"},u);let R=`${O.id}\0${y}`;if(k.has(R))return T({status:409,code:"in_progress",message:`The template ${y} is being written for this user`,retryAfter:5},u);if(!p&&w.has(R))return de(200,{rows:w.get(R)},u);k.add(R);let j={env:N,environmentId:e.projectId??"",template:y},Z=`test user template ${y}${p?" undo":""}`;try{let q={};return await tt(e.database,e.database?gt:void 0,i.signal,Z,async()=>{if(p?await x.undo(O,j):(await x.seed(O,j),q=await kr(ne.getStore()?.database)),i.signal.aborted)throw new Error(`the platform gave up on ${Z} before it ended`)}),p?(w.delete(R),new Response(null,{status:204,headers:{"x-request-id":u}})):(w.set(R,q),w.size>et&&w.delete(w.keys().next().value),de(200,{rows:q},u))}catch(q){i.signal.aborted||S.error(`[palbase] ${Z} failed for ${O.id}: nothing of it was kept`,{error:q});let F=q instanceof Error&&q.message!==""?`: ${q.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${F}; nothing of it was kept`},u)}finally{k.delete(R)}}function zn(i,c,f,u){let g=i?{sub:i.id,role:"authenticated"}:null;return ne.run({requestId:ne.getStore()?.requestId??"",...i?{userId:i.id}:{}},()=>Ye(e.database,g,f,c,async()=>{let p=await u();if(f.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return p}))}let qn=(i,c)=>new Response(i,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function Ws(i,c,f){let u=await Me(i,c,f,"A tool call");if(u instanceof Response)return u;let g=u.body,p=g.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=D.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 $=g.call_id,x=us(g.context);if(typeof $!="string"||$===""||$.length>256||typeof x=="string")return T({status:400,code:"bad_request",message:`A call of ${p} is {tool, call_id, input, context}${typeof x=="string"?`: ${x}`:""}`},f);let P=qs("sha256").update(JSON.stringify(g)).digest("hex"),O=Q.answered($);if(O!==void 0)return O.digest!==P?T({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},f):qn(O.answer,f);if(Q.isRunning($))return T({status:409,code:"in_progress",message:"This call is running",retryAfter:2},f);Q.start($);let A;try{let R=await zn(x.user,`ai.tool ${p}`,i.signal,()=>y.call(ce(g.input??{}),{...x,callId:$,signal:i.signal,inject:Y(`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 j=new TextEncoder().encode(A).byteLength;j>Ve&&(S.error(`[palbase] ai.tool ${p} answered ${j} bytes (call ${$}): a machine's answer is ${Ve} at most; the agent is told it failed`),A=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${Ve/(1<<20)} MiB it may be`}],is_error:!0}))}catch(R){if(i.signal.aborted)return Q.end($,void 0),T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);S.error(`[palbase] ai.tool ${p} failed (call ${$}, chat ${x.chatId}); the agent is told`,{error:R}),A=JSON.stringify({output:[{type:"text",text:$i(R)}],is_error:!0})}return Q.end($,{digest:P,answer:A}),qn(A,f)}async function Vs(i,c,f){let u=await Me(i,c,f,"An agent's turn");if(u instanceof Response)return u;let g=ls(u.body);if(typeof g=="string"||g.agent==="")return T({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata, message}${typeof g=="string"?`: ${g}`:": agent names it"}`},f);let p=g.agent,y=D.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 zn(g.user,`ai.agent ${p}`,i.signal,()=>y.resolve({...g,signal:i.signal,inject:Y(`ai.agent ${p}`)}))}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 A=Bt(O,`ai.agent ${p}`);return A?T(A,f):(S.error(`[palbase] ai.agent ${p} failed for chat ${g.chatId}; the turn is not started`,{error:O}),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},f))}let x=$.tools.find(O=>D.tools.get(O.name)!==O);if(x)return S.error(`[palbase] ai.agent ${p} handed out ai.tool ${JSON.stringify(x.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 P=JSON.stringify($.definition);return new TextEncoder().encode(P).byteLength>Ve?(S.error(`[palbase] ai.agent ${p}'s definition is larger than the ${Ve} 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(P,{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function Zs(i,c,f){let u=await Me(i,c,f,"A repository's token");if(u instanceof Response)return u;let g=u.body;if(typeof g.repo!="string"||g.repo===""||typeof g.repository!="string"||typeof g.call_id!="string"||g.call_id===""||g.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(!fe.take(g.call_id))return T({status:409,code:"call_id_reused",message:"This token ask was answered already"},f);let p=D.repos.get(g.repo),y=p?x=>p.token(x):D.repoTokens;if(!y)return T({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(g.repo.slice(0,64))}, and no ai.repoTokens`},f);let $;try{$=await tt(e.database,e.database?gt:void 0,i.signal,`ai.repo ${g.repo}`,async()=>y({repo:g.repo,repository:g.repository,signal:i.signal,inject:Y(p?`ai.repo ${g.repo}`:`ai.repoTokens for ${g.repo}`)}))}catch(x){if(i.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let P=Bt(x,`ai.repo ${g.repo}`);return P?T(P,f):(S.error(`[palbase] ai.repo ${g.repo} gave no token; the workspace's clone or push is refused`,{error:x}),T({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},f))}return!p&&$==null?T({status:404,code:"repo_not_found",message:`ai.repoTokens gives no token for ${JSON.stringify(g.repo.slice(0,64))}`},f):typeof $!="string"||$.trim()===""?(S.error(`[palbase] ai.repo ${g.repo}'s token function answered no token`),T({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},f)):new Response(JSON.stringify({token:$}),{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function Ys(i,c,f,u){let g=await Me(c,f,u,`A gateway's ${i}`);if(g instanceof Response)return g;let p=await I.serve(i,g.body,c.signal);return"code"in p?T({status:p.status,code:p.code,message:p.message,retryAfter:p.retryAfter},u):"body"in p?de(200,p.body,u):new Response(null,{status:204,headers:{"x-request-id":u}})}async function Hn(i,c){let f=[],u={params:Object.freeze({...c.params}),user:ce(c.user),headers:i.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let g of i.params)g.kind==="resolve"&&(f[g.index]=await o.get(g).resolve(u,g.options));return f}async function Vt(i,c,f,u){let g=t.get(i.controller),p=await Ye(e.database,f,c.request.signal,i.id,async()=>{let y=await Hn(i,c);for(let x of i.params)x.kind!=="resolve"&&(y[x.index]=await Is(x,c));u?.ran();let $=await g[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 u?u.record(Ds(Us($,c.requestId),ne.getStore()?.usedLocales)):$});return u?p:Ds(Us(p,c.requestId),ne.getStore()?.usedLocales)}async function Fn(i,c){let f=i.headers.get("x-request-id")??"",u=xi.test(f)?f:`req_${crypto.randomUUID()}`,g=performance.now(),p=new URL(i.url).pathname,y={endpoint:p},$=await Qs(i,c,u,y);return e.telemetry?.record({requestId:u,method:i.method,endpoint:y.endpoint,path:p,status:$.status,durationMs:performance.now()-g,userId:y.userId}),$}function Gn(i,c){i.userId=c;let f=ne.getStore();f&&(f.userId=c)}async function Qs(i,c,f,u){let g=e.strings,p=g?{requestId:f,strings:g,locales:cr(i.headers.get("accept-language"),g.source),usedLocales:[]}:{requestId:f},y=await Xs(p,i,c,f,u);return g&&Jt(y.headers,"Accept-Language"),y}async function Xs(i,c,f,u,g){return ne.run(i,async()=>{let p=new URL(c.url),y=`${c.method} ${p.pathname}`;try{if(p.pathname===Sn&&me.size>0)return c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):e.webhookSecret?await ae(c,u):T({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},u);let $=Ce(p.pathname);if($)return y=`webhook ${$.name}`,c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):await bt(c,p,$,u);if(e.platform&&(p.pathname===Qe||p.pathname.startsWith(`${Qe}/`)))return y=p.pathname===Qe?"crons":`cron ${p.pathname.slice(Qe.length+1)}`,await je(c,p,e.platform.secret,u);if(e.platform&&(p.pathname===Xe||p.pathname.startsWith(`${Xe}/`)))return y=p.pathname===Xe?"tasks":`task ${p.pathname.slice(Xe.length+1)}`,await Ks(c,p,e.platform.secret,u);if(e.platform&&(p.pathname===un||p.pathname===vr)){let z=p.pathname===un?"authorize":"complete";return y=`upload ${z}`,await Js(z,c,e.platform.secret,u,g)}if(e.platform&&p.pathname.startsWith(`${ln}/`)){let z=p.pathname.slice(ln.length+1);return y=`gateway ${z}`,await Ys(z,c,e.platform.secret,u)}if(e.platform&&p.pathname===rs)return y="ai tool call",await Ws(c,e.platform.secret,u);if(e.platform&&p.pathname===ss)return y="ai agent's turn",await Vs(c,e.platform.secret,u);if(e.platform&&p.pathname===as)return y="ai repository's token",await Zs(c,e.platform.secret,u);if(e.platform&&p.pathname.startsWith(`${Pt}/`))return y=`test user template ${p.pathname.slice(Pt.length+1)}`,await Bs(c,p,e.platform.secret,u);if(Ui(p.pathname))return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},u);let x=An(n,c.method,p.pathname);if(x&&"malformed"in x)return T({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},u);if(!x)return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},u);let{route:P,params:O}=x;if(y=P.id,g.endpoint=P.id.slice(P.id.indexOf(" ")+1),P.meta.upload)throw new ee(400,"upload_required",`${P.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let A=r.get(P),R=null,j=null,Z=c.headers.get("authorization")??"",q=/^(bearer|dpop)\s+(\S+)$/i.exec(Z),F=q?.[2],De=q?.[1].toLowerCase()==="dpop";if(F)try{let z=!De&&e.tokens&&!Ri.test(F)&&e.tokens.accepts(F)?e.tokens:void 0,ge=z?await C.ask(F,Kt(c.headers,f.remoteAddress),()=>Ye(e.database,null,c.signal,"token",()=>z.resolve(F))):await e.verifier.verify(F,De?{proof:c.headers.get("dpop"),method:c.method,url:tr(c.headers,p)}:void 0);R=Si(ge),j=ge.claims}catch(z){if(!A.required&&(z instanceof St||z instanceof _t||z instanceof wt))R=null;else throw z instanceof wt?new ee(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:z.wait},z.wait):z instanceof St?new ee(401,"invalid_token","The access token is not valid",{reason:z.reason},void 0,ki(z.reason)):z}else if(Z!==""&&A.required)throw new ee(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(R&&Gn(g,R.id),A.required&&!R)throw new ee(401,"unauthorized","This route needs a signed-in user");if(A.verifiedEmail&&!R?.emailVerified)throw new ee(403,"email_not_verified","This route needs a verified email address");let Kn=J(P);if(Kn!==!1){let z=R?`u:${R.id}`:`a:${Kt(c.headers,f.remoteAddress)}`,ge=v.take(`${P.id}\0${z}`,Kn);if(ge!==void 0)throw new ee(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:ge},ge)}let Ne=c.method==="GET"||c.method==="HEAD"?void 0:await yt(c,U),kt=Ne===void 0?void 0:Ei(Ne),Zt=p.searchParams,xe=s.get(P),vt=c.headers.get($t),ot=xe!==void 0||vt!==null?await a(P,O,vt,c.method):void 0;if(ot&&xe)try{if(xe.body.length>0&&kt!==void 0&&(kt=await ot.open(kt,"/body",xe.body)),xe.query.length>0){let z=await ot.open(Object.fromEntries(p.searchParams),"/query",xe.query);Zt=new URLSearchParams(p.searchParams);for(let ge of xe.query){let Vn=Yn(ge.slice(7)),Tt=z[Vn];Tt!==void 0&&Zt.set(Vn,typeof Tt=="string"?Tt:JSON.stringify(Tt))}}}catch(z){throw Ls(z)}let Jn={request:c,query:Zt,params:O,user:R,body:kt,raw:Ne,requestId:u},Bn=b&&Ne!==void 0&&pt(P)?vs(c.method,c.headers):void 0;if(!b||Bn===void 0)return await Pn(await Vt(P,Jn,j),ot,u);let ea={role:Cn(e.database.requests,j).role,uid:R?.id??`a:${Kt(c.headers,f.remoteAddress)}`},Wn=!1,ta=vt!==null?{uri:`${p.pathname}${p.search}`,body:Mi(new TextEncoder().encode(`${vt}
|
|
21
|
-
`),Ne)}:{uri:`${p.pathname}${p.search}`,body:Ne},na=z=>async ge=>z(await Pn(ge,ot,u));return await b.serve({key:Bn,caller:ea,method:c.method,...ta},z=>Vt(P,Jn,j,{record:na(z),ran:()=>{Wn=!0}}),{requestId:u,refusal:z=>T(z,u),failure:z=>Ns(z,u,y,c.signal),ran:()=>Wn})}catch($){return Ns($,u,y,c.signal)}})}return{handle:Wt,routes:n.map(i=>i.id),contract:nt,start:()=>t.start(),stop:async()=>{I.close();for(let i of G.keys())V(i);await t.shutdown(),await e.telemetry?.flush()}}}function Ci(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function ji(e){let t=new Set;for(let[n,r]of e)if(sn(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 Us(e,t){if(e instanceof Response)return Ti(e,t);if(e==null)return new Response(null,{status:204,headers:{"x-request-id":t}});if(ar()===0)return de(200,e,t);let{value:n,pointers:r}=or(e);return de(200,n,t,r.length>0?{[Dn]:JSON.stringify(r)}:{})}var Dn="x-palbase-answer-encrypted";async function Pn(e,t,n){let r=e.headers.get(Dn);if(r===null)return e;if(!t)return await e.body?.cancel(),T({status:400,code:"encryption_required",message:`This route answers encrypted fields: the request names its key in ${$t}`,data:{field:$t}},n);let s=new Headers(e.headers);s.delete(Dn),s.delete("content-length");let a=await t.seal(await e.json(),JSON.parse(r));return new Response(JSON.stringify(a),{status:e.status,statusText:e.statusText,headers:s})}function Mi(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Ls(e){return e instanceof Qn?new ee(e.status,e.code,e.message,e.data):e}function Di(e){return`/${e.segments.map(t=>typeof t=="string"?t:"{}").join("/")}`}function Ni(e,t){if(!(!ft(e)||e.status!==503||!Nn(e)))return S.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 ze.has(decodeURIComponent(t))}catch{return ze.has(t)}}var Li="GET, POST, PUT, PATCH, DELETE, QUERY",Ii=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function zi(e){return Ii.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function qi(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!zi(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 Is(e,t){switch(e.kind){case"body":return On(e.schema,t.body??{},"Request body");case"query":return On(e.schema,ce(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),ce(n),e.schema?On(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return ce(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 ce({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 Ln=720*3600;function Un(e){return e instanceof oe&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function Fs(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),Ln)}function Gs(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var In=class{filling=new Map;async get(t){try{let n=await ye.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!Un(n))throw n;return S.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 ye.cache.putCacheEntry({query:{key:t},body:{value:Gs(n),ttl:Fs(r)}})}catch(s){if(!Un(s))throw s;S.warn("cache: a write could not reach the cache; it is let go",{key:t,status:s.status})}}async del(t){await ye.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await ye.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 ye.cache.getCacheEntry({query:{key:t}})).data}catch(l){if(!Un(l))throw l;S.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:l.status})}if(o?.found)return o.value??null;let d=await r();return await this.set(t,d,n),d}finally{this.filling.delete(t)}})();return this.filling.set(t,a),a}},su=xt("Cache",new In);function au(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=h=>{let w=r.get(h);if(w&&w.expiresAt<=n()){r.delete(h);return}return w},o=()=>{let h=n();for(let[k,_]of r)_.expiresAt<=h&&r.delete(k);if(r.size<t)return;let w=[...r.entries()].sort((k,_)=>k[1].expiresAt-_[1].expiresAt);for(let[k]of w.slice(0,Math.ceil(w.length/4)))r.delete(k)},d=async(h,w,k)=>{r.size>=t&&!r.has(h)&&o(),r.set(h,{value:Gs(w),expiresAt:n()+(Fs(k)??Ln)*1e3})};return{get:async h=>{let w=a(h);return w?structuredClone(w.value):null},set:d,async del(h){r.delete(h)},async incr(h){let w=a(h),k=(typeof w?.value=="number"&&Number.isInteger(w.value)?w.value:0)+1;return r.set(h,{value:k,expiresAt:w?.expiresAt??n()+Ln*1e3}),k},getOrSet(h,w,k){let _=a(h);if(_)return Promise.resolve(structuredClone(_.value));let H=s.get(h);if(H)return H;let I=(async()=>{try{let D=await k();return await d(h,D,w),D}finally{s.delete(h)}})();return s.set(h,I),I}}}export{nn as a,Re as b,Ie as c,Ki as d,Ji as e,Bi as f,Wi as g,Vi as h,Zi as i,Yi as j,Qi as k,Xi as l,ed as m,td as n,nd as o,rd as p,sd as q,ad as r,od as s,id as t,dd as u,cd as v,ud as w,ld as x,fd as y,pd as z,M as A,md as B,hd as C,At as D,kd as E,vd as F,Sd as G,Od as H,Pd as I,$a as J,Or as K,Ud as L,Ld as M,Id as N,zd as O,qd as P,Hd as Q,Fd as R,Bd as S,K as T,Qr as U,Xr as V,es as W,fo as X,tc as Y,sc as Z,ac as _,oc as $,ic as aa,dc as ba,cc as ca,uc as da,lc as ea,kc as fa,pi as ga,eu as ha,zi as ia,Ln as ja,su as ka,au as la};
|