palbase 0.7.0 → 0.8.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 +9 -9
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/5VTGMNPL.js +20 -0
- package/dist/chunks/{ZBOJEH7K.js → BO5KR2EQ.js} +2 -2
- package/dist/chunks/{PJVWGUIT.js → BRBCWPR3.js} +1 -1
- package/dist/chunks/DB3SIBKB.js +2 -0
- package/dist/chunks/EGNEXFTZ.js +2 -0
- package/dist/chunks/{HEXIIGWS.js → FZ3MQOVA.js} +2 -2
- package/dist/chunks/{SU7BP6VF.js → JSJVV43D.js} +1 -1
- package/dist/chunks/K6RRNI23.js +4 -0
- package/dist/chunks/{KDSWK3XW.js → KDWDPSL2.js} +1 -1
- package/dist/chunks/P4Z5E6ZI.js +2 -0
- package/dist/chunks/PDOHT46N.js +2 -0
- package/dist/chunks/PGPQGKH2.js +18 -0
- package/dist/chunks/{G3BK7L3J.js → RBA6V3UO.js} +2 -2
- package/dist/chunks/{X3MTLJRV.js → RO5Y5YU4.js} +1 -1
- package/dist/chunks/{BKVU4I5R.js → TUGRIOFX.js} +2 -2
- package/dist/chunks/WEI32SAJ.js +13 -0
- package/dist/chunks/{5ZJCEQV5.js → WINBISC2.js} +3 -3
- package/dist/chunks/Z5JVQNAZ.js +2 -0
- package/dist/cli.js +121 -120
- 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/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- 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 +44 -15
- package/types/ai/src/chats.d.ts +442 -12
- package/types/ai/src/index.d.ts +4 -4
- package/types/ai/src/tools.d.ts +158 -21
- package/types/backend/src/bootstrap.d.ts +8 -0
- package/types/backend/src/container.d.ts +9 -0
- package/types/backend/src/database.d.ts +17 -2
- package/types/backend/src/engine.d.ts +2 -0
- package/types/backend/src/gateways.d.ts +19 -0
- package/types/backend/src/index.d.ts +1 -0
- package/types/backend/src/runtime.d.ts +12 -0
- package/types/backend/src/testing/unit.d.ts +3 -1
- package/types/internal/src/chat.d.ts +168 -3
- package/types/internal/src/modules/ai.d.ts +1305 -57
- package/types/internal/src/modules/auth.d.ts +14 -2
- package/types/internal/src/modules/events.d.ts +2 -2
- package/types/internal/src/modules/machines.d.ts +57 -1
- package/types/internal/src/modules/notify.d.ts +6 -6
- package/types/internal/src/modules/purchases.d.ts +357 -13
- package/types/internal/src/modules/realtime.d.ts +36 -0
- package/types/internal/src/modules/stores.d.ts +259 -22
- package/types/internal/src/transport.d.ts +5 -0
- package/types/server/src/auth/jwt.d.ts +1 -6
- package/types/web/src/auth.d.ts +15 -4
- package/types/web/src/backends.d.ts +1 -1
- package/types/web/src/chat.d.ts +215 -4
- package/types/web/src/client.d.ts +28 -0
- package/types/web/src/gateways.d.ts +4 -3
- package/types/web/src/index.d.ts +3 -2
- package/types/web/src/session.d.ts +11 -1
- package/types/web/src/voice.d.ts +36 -0
- package/dist/chunks/3ALGILOX.js +0 -2
- package/dist/chunks/AIIKXCWN.js +0 -2
- package/dist/chunks/ELEE7XO2.js +0 -18
- package/dist/chunks/G7E26S3Y.js +0 -13
- package/dist/chunks/H2EPK74V.js +0 -20
- package/dist/chunks/JS3TTUHS.js +0 -2
- package/dist/chunks/L3NTI4AZ.js +0 -2
- package/dist/chunks/LEBVOSG6.js +0 -4
- package/dist/chunks/OIA7KLRW.js +0 -2
package/dist/chunks/H2EPK74V.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.7.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as lt,c as se,d as Nn,e as Un,f as ge,h as T,i as Ln}from"./LEBVOSG6.js";import{b as Ve,d as dt,e as Cn,f as Mn,g as ct,h as ut,k as jn,q as Dn}from"./L3NTI4AZ.js";import{b as pe}from"./JS3TTUHS.js";import"reflect-metadata";var Dt=[{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}],In="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)",ft=/^\d+$/;function ks(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),i=1;if(a!==-1){let g=s.slice(a+1);if(!ft.test(g)||Number(g)<1||Number(g)>n)return;i=Number(g)}let c=t,p=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),A=o.slice(g+1);if(!ft.test(k)||!ft.test(A)||Number(k)<t||Number(A)>n||Number(k)>Number(A))return;c=Number(k),p=Number(A)}else{if(!ft.test(o)||Number(o)<t||Number(o)>n)return;c=Number(o),p=a===-1?c:n}for(let g=c;g<=p;g+=i)r.add(g)}return r}function zn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${In}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let g=ks(t[p],Dt[p].lo,Dt[p].hi);if(!g)return`${In}; its ${Dt[p].name} "${t[p]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,c.setUTCDate(c.getUTCDate()+1)){if(!s.has(c.getUTCMonth()+1))continue;let g=r.has(c.getUTCDate()),k=a.has(c.getUTCDay());if(o||i?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Me=Symbol.for("palbase.backend.controller"),je=Symbol.for("palbase.backend.routes"),Ut=Symbol.for("palbase.backend.params"),Lt=Symbol.for("palbase.backend.injectable"),It=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),De=Symbol.for("palbase.backend.webhook"),be=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Nt=Symbol.for("palbase.backend.declared");function ce(){let e=globalThis;return e[Nt]instanceof Set||(e[Nt]=new Set),e[Nt]}var Ne=new Set(["webhooks","_palbase"]);function Yo(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&&Ne.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,Me,()=>({basePath:e,options:t})),ce().add(n)}}function Ue(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`);de(r.constructor,je,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Xo=Ue("GET"),ei=Ue("POST"),ti=Ue("PUT"),ni=Ue("PATCH"),ri=Ue("DELETE"),si=Ue("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=de(n.constructor,Ut,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function zt(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 ai=e=>ue("body",{schema:zt("Body",e)}),oi=e=>ue("query",{schema:zt("QueryParams",e)}),ii=e=>ue("headers",e===void 0?{}:{schema:zt("Headers",e)}),di=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},ci=()=>ue("user"),ui=()=>ue("optionalUser"),li=()=>ue("req"),fi=()=>ue("requestId"),pi=()=>ue("requestId"),mi=()=>ue("client");function hi(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 gi(){return e=>{de(e,Lt,()=>!0),ce().add(e)}}function yi(e){return t=>{de(t,It,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Gn=/^[a-z]+(\.[a-z_]+)+$/,vs=/^[a-z][a-z0-9-]{1,62}$/,Ht=e=>e.startsWith("file.");function wi(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"||!vs.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(!Ht(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`);de(r.constructor,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),ce().add(r.constructor)}}var qt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,$s=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Hn(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(!$s.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 bi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!qt.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=zn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Hn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Hn(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,be))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,be,{value:s,enumerable:!1}),ce().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ts=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function ki(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(!Ts.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!qn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${qn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Ss(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=N(t,Se)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:i}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,De,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:i})=>({event:o,fn:i}))})),ce().add(t)}}function Ss(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 N(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function vi(){return[...ce()].filter(e=>N(e,Me)!==void 0)}function $i(e){return(N(e,je)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function xi(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!qt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),ce().add(s)}}var Kt;function Kn(e){Kt=e}function Gt(){if(!Kt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Kt}var Es=720*3600;function _s(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Es))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 xs(e){if(typeof e=="string")return e;let t=e[ye];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Oi=lt("Tasks",{async enqueue(e,t,n={}){return _s(n),Gt().enqueue(xs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Gt().cancel(e,t.machine)},async get(e,t={}){return Gt().get(e,t.machine)}}),Bt=(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 Fn(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await ge.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return Bt(a.data,a.status===200)},async cancel(n,r){return Bt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Bt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Os=1e4,As=36e5,Bn=24*36e5,mt=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 pe({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 pe({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 pe({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 c of this.tasks.values())if(c.task===t&&c.key===r.key&&(c.finishedAt===void 0||this.now()-c.finishedAt<Bn))return this.view(c,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,i={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(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new pe({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 pe({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(i){a={status:500,message:i.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(Os*2**Math.min(t.attempt-1,16),As),T.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>=Bn&&this.tasks.delete(s);n==="failed"&&T.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 Ft="/_palbase/storage/upload/authorize",Jn="/_palbase/storage/upload/complete",Jt="/_palbase/realtime/rooms";var Rs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Le(e){if(!Rs(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 Wn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Vn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function ht(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ps=/^[a-z][a-z0-9-]{1,62}$/,Zn=1024,Cs=new Set(["userId","uploadId","filename"]);function Mi(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(!Ps.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=Ms(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,i,c)=>{if(typeof i!="string"||c===void 0||typeof c.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(o.constructor,je,()=>[]).push({method:"POST",subpath:e,fn:i,options:a,upload:s})}}function ji(){return ue("uploadedObject")}function Ms(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Cs.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(!Qn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Qn(e){if(e===""||new TextEncoder().encode(e).byteLength>Zn)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 js(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ds(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ds(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 Yn(e,t){let n=js(e,t);return Qn(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Zn} bytes)`}}function Xn(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 Wt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function er(e,t){if(!Wt(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=Le(t.user);if(!o)return"user is { id?, session?, role }";let i=Wn(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,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Ns(t.uploadedObject);return c?c.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:"",uploadedObject:c,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Ns(e){if(!Wt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:i,height:c,thumbhash:p,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||p!==void 0&&typeof p!="string")&&!(!Wt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...p!==void 0?{thumbhash:p}:{},variants:{...g}}}import{markData as Us}from"palgres";var Ee=Symbol.for("palbase.backend.gateway"),He=Symbol.for("palbase.backend.gatewayHooks"),tr={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"]},Ls={"~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(tr),output:()=>structuredClone(tr)}}},dr=Symbol.for("palbase.backend.gatewayRefusal"),nr=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,dr,{value:!0})}},Is=e=>typeof e=="object"&&e!==null&&e[dr]===!0&&typeof e.reason=="string",Ie=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,zs=6e4,Hs=86400,rr=604800,sr=65536,ke=255,qs=["roles:","flags:","messaging:","debug:"],Gs=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(" ")),ze=e=>new TextEncoder().encode(e).byteLength,Vt=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",cr=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Bs(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(ze(e)>ke)return`a channel is ${ke} 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=qs.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(ze(e)>ke)return`is ${ke} bytes at most`}function zi(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Bs(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"&&cr(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=Ks(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)||Gs.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 i=a.events??{};if(typeof i!="object"||i===null||Array.isArray(i))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(i,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,k]of Object.entries(i)){let A=ur(g);if(A)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${A}`);if(!Vt(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let c=de(a,He,Yt),p={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...i,chat:Ls}:{...i},chat:r.chat===!0,graceMs:r.graceMs??zs,hooks:{...c.hooks},messages:Object.assign(Object.create(null),c.messages)};if(p.access===void 0&&p.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(p.access!==void 0&&p.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${p.access}' and @Authorize both say who may join \u2014 keep one`);if(p.publish&&Ie(p))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(p.publish&&p.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(p.chat&&!Ie(p))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`);de(a,Ee,()=>p),ce().add(a)}}function Ks(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Hs;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>rr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${rr} (a week)`);return n}var Yt=()=>({hooks:Object.create(null),messages:Object.create(null)}),Fs={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function Ze(e){let t=Fs[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=de(n.constructor,He,Yt),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,ce().add(n.constructor)}}var Hi=Ze("authorize"),qi=Ze("first"),Gi=Ze("connect"),Bi=Ze("disconnect"),Ki=Ze("empty");function Fi(e,t,n={}){let r=ur(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!Vt(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!Vt(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 i=de(s.constructor,He,Yt),c=i.messages[e];if(c!==void 0&&c.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${c.fn} and ${a}).`);i.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},ce().add(s.constructor)}}function Js(e){return N(e,Ee)}function Ws(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 Vs(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 ze(r)>ke?{problem:`a channel is ${ke} bytes at most`}:r}var Zs=1e4,Qs=1e3,Ys=100,Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),me=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),ar={first:"first",join:"connect",leave:"disconnect",empty:"empty"},or=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function lr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let w=Js(b),_=a.get(w.name);if(_!==void 0&&_!==b)throw new TypeError(`@Gateway("${w.pattern}"): two gateways are named ${w.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(w.name,b);let R=s.get(or(w.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(or(w.pattern),w.pattern);for(let[K,F]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([D,L])=>[`message ${D}`,L.fn])])if(typeof E[F]!="function")throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: its ${K} is ${F}, which is no method of it`);let U={cls:b,instance:E,g:w};n.set(w.pattern,U),r.set(b,U)}let o=new Map,i=new Set,c=new Set,p=new Qt(t.broadcast),g=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)},A=(b,E,w,_,R,U)=>{if(!Object.hasOwn(b.g.events,w)){T.warn(`[palbase] ${R}: emit("${w}") is not sent \u2014 ${b.cls.name} declares no event "${w}" (static events)`);return}if(b.g.chat&&w==="chat"){T.warn(`[palbase] ${R}: 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}p.send({topic:E,event:w,payload:_??{},...U!==void 0?{conn_id:U}:{}},R)},H=async(b,E,w)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${w}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(E)};function I(b,E,w,_,R,U,K){let F=_?.signal??AbortSignal.abort(),D=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...w}),signal:F,count:R,user:U,emit:(L,q)=>A(b,E,L,q,D,K),pipe:L=>H(L,E,D),owner:{hold(L){se.exit(async()=>{try{await L(F)}catch(q){F.aborted||T.error(`[palbase] ${D}: a task owner.hold ran failed`,{error:q})}}).catch(()=>{})},release:()=>k(E,_)}}}function B(b){let{room:E,channel:w}=b;if(typeof E!="string"||typeof w!="string")return me(400,"bad_request","A gateway's call names its pattern (room) and its channel");let _=n.get(E);return!_||!Ie(_.g)?me(404,"not_found",`This app serves no gateway "${E}"`):{entry:_,channel:w,params:Ws(E,w)}}let V=(b,E)=>me(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function ne(b,E){let w=B(b);if("status"in w)return w;let{entry:_,channel:R,params:U}=w,K={status:200,body:{subscribe:!1,publish:!1}};if(!U)return T.warn(`[palbase] ${_.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${_.g.pattern}"; the join is refused`),K;let F=Le(b.user),D=F?.id;if(!D)return K;if(_.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(_.g.messages).length>0}};if(_.g.access==="owner")return U[cr(_.g.pattern)[0].slice(1,-1)]===D?{status:200,body:{subscribe:!0,publish:Object.keys(_.g.messages).length>0}}:K;let L=_.g.hooks.authorize;if(!L)return K;let q,J;try{q=await t.run(F,`${_.cls.name}.${L}`,E,async()=>_.instance[L]({user:{id:D},params:Object.freeze({...U})})),J=Xs(q)}catch(oe){if(t.isOutage(oe)||E?.aborted)throw oe;return T.error(`[palbase] ${_.cls.name}.${L} (@Authorize of ${R}) failed; the join is refused`,{error:oe}),K}return J==="malformed"?(T.warn(`[palbase] ${_.cls.name}.${L} (@Authorize of ${R}) answered ${ea(q)}, which is no grant (true, { read, write } or null); the join is refused`),K):{status:200,body:J}}async function te(b,E){let w=B(b);if("status"in w)return w;if(!w.params)return V(w.entry.g.pattern,w.channel);let _=Le(b.user);if(!_?.id||typeof b.event!="string")return me(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(w.entry.g.messages,b.event)?w.entry.g.messages[b.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:Zt(`gateway "${w.channel}" takes no message "${b.event}"`,gt)}};let U=await R.schema["~standard"].validate(Us(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:ir(U.issues)}};let K=g(w.channel),F={...I(w.entry,w.channel,w.params,K,0,{id:_.id}),payload:U.value},D=`${w.entry.cls.name}.${R.fn} (@Subscribe "${b.event}" of ${w.channel})`,L;try{L=await t.run(_,`${w.entry.cls.name}.${R.fn}`,E,async()=>w.entry.instance[R.fn](F))}catch(J){if(t.isOutage(J))throw J;return Is(J)?{status:200,body:{ok:!1,reason:Zt(J.reason,gt)}}:(E?.aborted||T.error(`[palbase] ${D} failed`,{error:J}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(L===void 0)return{status:200,body:{ok:!0}};if(R.reply){let J=await R.reply["~standard"].validate(L);if(J.issues)return T.error(`[palbase] ${D} returned an ack its reply schema refuses (${ir(J.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};L=J.value}let q;try{q=JSON.stringify(L)}catch(J){return T.error(`[palbase] ${D} returned an ack that is not JSON; the member is told it failed`,{error:J}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return q===void 0?{status:200,body:{ok:!0}}:ze(q)>sr?(T.error(`[palbase] ${D} returned an ack of ${ze(q)} bytes, past ${sr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(q)}}}async function v(b,E){let w=B(b);if("status"in w)return w;if(!w.params)return V(w.entry.g.pattern,w.channel);let _=b.event;if(typeof _!="string"||!Object.hasOwn(ar,_))return me(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(R===void 0)return me(400,"bad_request","A gateway's moment says its count of members");let U=_==="join"||_==="leave",K=U?Le(b.user):void 0,F=U?b.connId:void 0;if(U&&(!K?.id||typeof F!="string"||F===""))return me(400,"bad_request",`A ${_} names its member: user and connId`);let D=`${_}\0${w.channel}\0${typeof F=="string"?F:""}`;if(U&&i.has(D))return{status:204};if(c.has(D))return me(503,"in_progress","This moment of the gateway is being handled",5);c.add(D);try{let L=w.entry.g.hooks[ar[_]],q;if(_==="empty"?(q=o.get(w.channel),k(w.channel,q)):q=_==="leave"?o.get(w.channel):g(w.channel),L){let J=I(w.entry,w.channel,w.params,q,R,{id:K?.id??""},_==="join"?F:void 0);try{await t.run(K,`${w.entry.cls.name}.${L}`,E,async()=>w.entry.instance[L](J))}catch(oe){if(t.isOutage(oe))throw oe;return E?.aborted||T.error(`[palbase] ${w.entry.cls.name}.${L} (${_} of ${w.channel}) failed; realtime tells it again`,{error:oe}),me(500,"handler_failed",`The gateway's ${_} could not be handled`)}}return U&&(i.add(D),i.size>Zs&&i.delete(i.values().next().value)),{status:204}}finally{c.delete(D)}}function Y(b,E){let w=r.get(b),_=`Palbase.gateways.to(${b?.name??String(b)})`;if(!w)throw new TypeError(`${_}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Vs(w.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${_}: ${R.problem}`);return{entry:w,channel:R,where:_}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,w){return Xt(E)?b==="authorize"?ne(E,w):b==="message"?te(E,w):b==="lifecycle"?v(E,w):me(404,"not_found",`No gateway call ${JSON.stringify(b)}`):me(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,w,_){let{entry:R,channel:U,where:K}=Y(b,E);A(R,U,w,_,K)},async pipe(b,E,w){let{channel:_,where:R}=Y(b,E);await H(w,_,R)},close(){for(let b of o.values())b.abort();o.clear()}}}function Xs(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!Xt(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 ea(e){return Array.isArray(e)?"an array":Xt(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 ta=20,gt=256;function ir(e){let t="";for(let n of e.slice(0,ta)){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)>=gt)break}return Zt(t,gt)}function Zt(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 Qt=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||ze(t.event)>ke){T.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${ke} bytes`);return}try{JSON.stringify(t.payload)}catch(a){T.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>=Qs?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),se.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,Ys);try{await this.broadcast(s)}catch(o){T.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),T.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as en,createHmac as na,createPublicKey as hr,timingSafeEqual as ra,verify as gr}from"node:crypto";function Zi(e){let t=N(e,De);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 yr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let i=N(o,De),c=s.get(i.name);if(c)throw new TypeError(`@Webhook "${i.name}" is declared by ${c.cls.name} and by ${o.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${o.name})`,g=n[i.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=sa(i,g)}catch(I){a.push(`${p}: ${i.secret.env} ${I.message}`)}let A=t(o),H=new Map(i.events.map(({event:I,fn:B})=>[I,{name:`${o.name}.${B}`,call:(V,ne)=>A[B](V,ne)}]));s.set(i.name,{name:i.name,cls:o,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.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 wr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var qe=1024,fr=1024*qe;function sa(e,t){if(e.signature)return _e(void 0,e.signature.header,1/0,ha(e.signature,t));switch(e.provider){case"stripe":return _e("stripe","stripe-signature",512*qe,ia(t));case"github":return _e("github","x-hub-signature-256",25*fr,da(t));case"slack":return _e("slack","x-slack-signature",64*qe,ca(t));case"discord":return _e("discord","x-signature-ed25519",64*qe,ua(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*qe),check:fa(t)};case"sendgrid":return _e("sendgrid","x-twilio-email-event-webhook-signature",fr,pa(t));case"livekit":return _e("livekit","authorization",512*qe,ma(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function _e(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=tn(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:kr(e,t.headers,r),event:r,...aa(e,t,r)}}function kr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=xe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Tr(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 xe(n,"EventType");case"livekit":return xe(n,"event");default:return xe(n,"type")}}function aa(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(xe(n,"id"));case"slack":return r(xe(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=>xe(s,"sg_event_id")||void 0)}:{};default:return{}}}var oa=300;function ia(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let c of r.split(",")){let p=c.indexOf("=");if(p<=0)continue;let g=c.slice(0,p).trim(),k=c.slice(p+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(g==="v1"){let A=le(k,"hex");if(!A)return"malformed_signature";a.push(A)}}let o=Qe(s);if(o===void 0||a.length===0)return"malformed_signature";if(Ye(o,n))return"stale_timestamp";let i=Ge("sha256",e,`${s}.`,t.body);return a.some(c=>ve(c,i))?void 0:"signature_mismatch"}}function da(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?ve(r,Ge("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function ca(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=Qe(s),o=r.startsWith("v0=")?le(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":Ye(a,n)?"stale_timestamp":ve(o,Ge("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function ua(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=hr({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,i=Qe(o),c=le(a,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Ye(i,s)?"stale_timestamp":gr(null,$r(o,r.body),n,c)?void 0:"signature_mismatch"}}var la=1e3;function fa(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="",i;if(a!==null){if(!ve(Buffer.from(a.toLowerCase()),Buffer.from(en("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let H=1;for(let V of t.body)if(V===38&&++H>la)return"malformed_signature";let I=new Map;for(let[V,ne]of new URLSearchParams(tn(t.body))){let te=I.get(V);te||I.set(V,te=new Set),te.add(ne)}let B=[];for(let V of[...I.keys()].sort()){let ne=[...I.get(V)].sort();for(let te of ne)o+=V+te;B.push([V,ne.length===1?ne[0]:ne])}i=Object.fromEntries(B)}let c=s.protocol==="https:"?"443":"80",p=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||c}${s.pathname}${s.search}`;if(![p,g].some(H=>ve(r,Ge("sha1",e,H,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),A=k?{id:`${k}:${vr(`${p}
|
|
5
|
-
${o}`)}`}:{};return i?{type:kr("twilio",t.headers,i),event:i,...A}:{...br("twilio",t),...A}}}function pa(e){let t;try{let n=le(e,"base64");if(!n)throw new Error;t=hr({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=Qe(a),i=le(s.trim(),"base64");return o===void 0||!i?"malformed_signature":Ye(o,r)?"stale_timestamp":gr("sha256",$r(a,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var pr=60;function ma(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=mr(le(s[0],"base64url")),o=le(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!ve(o,Ge("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=mr(le(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+pr||typeof i.nbf=="number"&&n<i.nbf-pr)return"stale_timestamp";let c=typeof i.sha256=="string"?le(i.sha256,"base64"):void 0;return c&&ve(c,en("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function ha(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 i="";if(n.includes("{ts}")){i=s.headers.get(e.timestampHeader)?.trim()??"";let p=Qe(i);if(p===void 0)return"malformed_signature";if(Ye(p,a))return"stale_timestamp"}let c=le(o.trim(),e.encoding);return c?ve(c,Ge(r,t,...n.map(p=>p==="{body}"?s.body:p==="{ts}"?i:p)))?void 0:"signature_mismatch":"malformed_signature"}}var ga=new TextEncoder;function Ge(e,t,...n){let r=na(e,t);for(let s of n)r.update(s);return r.digest()}function vr(e){return en("sha256").update(e).digest("hex")}function $r(e,t){return Buffer.concat([ga.encode(e),t])}function ve(e,t){return e.byteLength===t.byteLength&&ra(e,t)}var ya={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 ya[t].test(e)?Buffer.from(e,t):void 0}function Qe(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Ye(e,t){return Math.abs(t-e)>oa}function tn(e){return new TextDecoder().decode(e)}function mr(e){if(e)try{return JSON.parse(tn(e))}catch{return}}function Tr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xe(e,t){let n=Tr(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var W=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}},wa=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],ba=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),yt=class{owner=new Map;defs=new Map;instances=new Map;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];gateways=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let a=N(r,It);if(!a)throw new W("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 W("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 W("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.controllers){if(!N(a,Me))throw new W("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(N(a,be))throw new W("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(N(a,ye))throw new W("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(N(a,Ee)||N(a,He))throw new W("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 ce())if(!this.owner.has(t))throw new W("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 W("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(N(r,He)&&!N(r,Ee))throw new W("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(!N(r,Lt)&&!N(r,Se)&&!N(r,Ee)&&!N(r,be)&&!N(r,ye)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new W("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 W("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 or a @Task)`,["decorate it with @Injectable()"])}N(r,Ee)&&this.gateways.push(r),N(r,De)?this.webhooks.push(r):N(r,Se)&&this.eventProviders.push(r),N(r,be)&&this.cronProviders.push(r),N(r,ye)&&this.taskProviders.push(r)}}for(let t of this.owner.keys())for(let n of wa)if(typeof t.prototype[n]=="function")throw new W("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 W("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 W("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 i=[];o.slice(0,a).forEach((p,g)=>{if(ba.has(p)||typeof p!="function")throw new W("unresolvable dependency",s,`${t.name} constructor parameter ${g}`,`parameter ${g} of ${t.name} is typed as ${p===void 0?"something with no runtime class":p.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);i.push(this.resolve(this.reachable(t,p,s),s))});let c=new t(...i);return this.instances.set(t,c),this.order.push(c),c}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}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 W("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 W("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 W("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 W("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 ka,HttpError as Xe}from"palgres";import{z as $e}from"zod";import{BadRequest as id,Conflict as dd,DeadlockDetected as cd,HttpError as ud,NotFound as ld,SerializationFailure as fd,TooManyRequests as pd,UniqueViolation as md}from"palgres";function et(e){if(typeof e!="object"||e===null||e[ka]!==!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 Sr=class extends Xe{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},Er=class extends Xe{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},_r=class extends Xe{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function Or(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 va=Symbol.for("palbase.backend.errorRegistry"),$a={bad_request:$e.object({fields:$e.array($e.object({field:$e.string(),message:$e.string()})),more:$e.number().int().optional()}),too_many_requests:$e.object({retryAfter:$e.number().int()})},Ta=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 Sa(){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=$a[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function Ea(){let e=globalThis;return e[va]??=Sa()}function sd(e,t,n){if(typeof e!="string"||!/^[a-z][a-z0-9_]*$/.test(e))throw new TypeError(`defineError(code, status): code is a lowercase wire code like room_locked, 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(Ta.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=Ea(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&xr(s.data)!==xr(n)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${s.builtin?`the built-in ${s.className}`:`defined with status ${s.status}${s.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let a=e.split("_").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(""),o=e.replace(/_/g," "),i=o.charAt(0).toUpperCase()+o.slice(1),g=n?(k=>class extends Xe{static code=e;static status=t;constructor(A,H){let I=_a(e,k,A);super(t,e,H??(typeof I=="string"?I:i),I),this.name=a}})(n):class extends Xe{static code=e;static status=t;constructor(k){super(t,e,k??i),this.name=a}};return Object.defineProperty(g,"name",{value:a}),r.set(e,{code:e,status:t,className:a,builtin:!1,...n?{data:n}:{}}),g}function _a(e,t,n){let r=t["~standard"].validate(n);if(r instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(r.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${r.issues.map(s=>s.message).join("; ")}`);return r.value}function xr(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}var Ar="/_palbase/ai/tools",Rr="/_palbase/ai/agents",Pr="/_palbase/ai/repos";var xa=Symbol.for("palbase.ai.tool_error");function Cr(e){return e instanceof Error&&e[xa]===!0}var Oa=Symbol.for("palbase.ai.declared");function Mr(){let e=globalThis[Oa];if(!e)return{tools:new Map,agents:new Map,repos:new Map};if(e.twice.size>0){let t=[...e.twice].map(n=>n.replace(":"," "));throw new TypeError(`[palbase] ${t.join(", ")}: declared twice with different values \u2014 an ai.tool's and an ai.agent's name is its own; make each once, at a module's top level`)}return{tools:new Map(e.tools),agents:new Map(e.agents),repos:new Map(e.repos??[])}}var nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function rn(e){if(!nn(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(!nn(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={};if(e.metadata!==void 0&&e.metadata!==null){if(!nn(e.metadata))return"context.metadata is an object of strings";for(let[r,s]of Object.entries(e.metadata)){if(typeof s!="string")return"context.metadata is an object of strings";Object.defineProperty(n,r,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return{chatId:e.chat_id,agent:e.agent,user:t,metadata:n}}var Aa=1e4,Ra=10*6e4,wt=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<=Ra&&this.seen.size<=Aa)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},Pa=1e3,Ca=256*1024,bt=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>Ca)&&(this.answers.set(t,n),this.answers.size>Pa&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as os,isEngineRaised as bn,markData as fe}from"palgres";import{createHash as is}from"node:crypto";import{createHash as Ma,randomInt as ja}from"node:crypto";import{ago as sn,isRetryable as Da,now as jr}from"palgres";import{defineSchema as Na,defineTable as Ua,index as La,integer as Ia,jsonb as za,raw as Ha,text as an,timestamp as Dr}from"palgres/dsl";var Hr=new Set(["POST","PUT","PATCH","DELETE"]),Nr=255,Ur=35,Lr=24,qa=65536,Ir=1e3,Ga=64,dn={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"}},Ba=Ua("idempotency_keys",{columns:{key:an().primaryKey(),fingerprint:an(),started_at:Dr().defaultNow(),completed_at:Dr().nullable(),status_code:Ia().nullable(),response_headers:za().nullable(),response_body:an().nullable()},indexes:e=>[La("idempotency_keys_started").on(e.col("started_at"))]}),$d=Na("palbase",{tables:[Ba],raw:[Ha("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)"})]}),Ka={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Fa={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},Ja={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},Wa={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},vt=class extends Error{};function tt(e){return Hr.has(e.method)&&e.meta.upload===void 0}function qr(e,t){if(!Hr.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Va(e,t){return Gr([e.role,e.uid,t]).digest("hex")}function Za(e){return Gr([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Gr(e){let t=Ma("sha256");for(let n of e)t.update(n).update("\0");return t}function Qa(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function on(e){return e<500&&e!==429&&e!==499}function Ya(e,t){return t&&on(e)}function Br(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 Xa={role:"service",claims:{}},$t=class{constructor(t){this.db=t}db;async serve(t,n,r){if(t.key.length>Nr)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Nr} characters`});let s;try{s=await this.begin(Va(t.caller,t.key),Za(t))}catch(i){return T.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),r.refusal(Wa)}if("kept"in s)return eo(s.kept,r.requestId);if("refused"in s)return r.refusal(s.refused==="reused"?Ka:Fa);let a=s.claim,o;try{o=await n(i=>this.record(a,i))}catch(i){if(i instanceof vt)return r.refusal(Ja);let c=r.failure(i);return Ya(c.status,r.ran())&&!Da(i)?this.keep(a,c):(await this.release(a),c)}return on(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:sn({hours:Lr})}}}))}async begin(t,n){return ja(Ga)===0&&await this.sweep().catch(r=>T.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:sn({hours:Lr})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let i=Qa(o,n);if(i==="reused")return{refused:"reused"};if(i==="replay")return{kept:{status:o.status_code,headers:o.response_headers??[],body:o.response_body}};let[c]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:sn({seconds:Ur})}},set:{started_at:jr()}});return c?{claim:{key:t,started:c.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!on(n.status))return n;let{response:r,kept:s}=await zr(n),a=se.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let[o]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),s.body]);if(o?.answered!==!0)throw new vt;return r}async keep(t,n){let{response:r,kept:s}=await zr(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:jr(),status_code:s.status,response_headers:s.headers,response_body:s.body}}))}catch(a){T.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()+Ur*1e3,r=()=>{Date.now()+Ir>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},Ir).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(Xa),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 eo(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 kt=Symbol("waits");function to(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(kt));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function zr(e){let t=[];e.headers.forEach((i,c)=>{c!=="x-request-id"&&t.push([c,i])});let n=i=>new Response(i,{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 i=r.read(),c=await to(i);if(c!==kt&&c.done)break;if(c!==kt&&(s.push(c.value),a+=c.value.byteLength,a<=qa))continue;let p=c===kt?i:void 0,g=new ReadableStream({start(k){for(let A of s)k.enqueue(A)},async pull(k){let A=await(p??r.read());p=void 0,A.done?k.close():k.enqueue(A.value)},cancel:k=>r.cancel(k)});return{response:n(g),kept:{status:e.status,headers:t.filter(([k])=>k!=="content-length"&&k!=="content-encoding"),body:null}}}let o=Buffer.concat(s);return{response:n(o),kept:{status:e.status,headers:t,body:o.byteLength===0?null:o.toString("base64")}}}import{createHash as no}from"node:crypto";var cn="/webhooks/palbase",Zr="PalbaseErrorEnvelope",Kr="PalbaseBearer",ro={$ref:`#/components/schemas/${Zr}`},so={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"]},Fr={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Be={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Qr(e,t,n){let r={[Zr]:so},s={},a=[],o=[],i=new Set,c=new Map;for(let v of e){let Y=o.find(Z=>io(Z,v));if(Y){a.push({route:v.id,handler:Jr(v),answeredBy:Y.id});continue}o.push(v);let b=v.segments.map(Z=>typeof Z=="string"?Z:"{}").join("/");c.has(b)||c.set(b,uo(v.segments.flatMap(Z=>typeof Z=="string"?[]:[Z.param])));let E=c.get(b),w=0,_=`/${v.segments.map(Z=>typeof Z=="string"?Z:`{${E[w++]}}`).join("/")}`,R=t(v),U=Tt(co(v),i),K=v.method!=="GET"&&v.method!=="HEAD",F=Z=>{let Te=v.params.filter(Re=>Re.kind===Z&&Re.schema).map((Re,we)=>_t(Re.schema,`${U}.${Z}${we===0?"":`.${we+1}`}`,r));return Te.length===0?void 0:Te.length===1?Te[0]:{allOf:Te}},D=E.map(Z=>({name:Z,in:"path",required:!0,schema:{type:"string"}})),L=F("query");L&&D.push(...Vr(L,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:L}]);let q=F("headers");q&&D.push(...Vr(q,"header")??[]);let J=n.idempotency===!0&&tt(v);J&&D.push({...dn,schema:{...dn.schema}});let oe=K?F("body"):void 0,ie={operationId:U};v.controller.name!==""&&(ie.tags=[v.controller.name]),D.length>0&&(ie.parameters=D),oe&&(ie.requestBody={required:!ho(oe),content:{"application/json":{schema:oe}}});let Ct=v.params.some(Z=>Z.schema!==void 0),Oe=n.routes?.(v),Ae=yo(U,Oe?.throws??[],n.errors);ie.responses={...go(Oe,U,r),...ko(R,{validates:Ct,hasPathParams:E.length>0,readsBody:K,keyed:J}),...bo(Ae,U,r)},Ae.length>0&&(ie["x-palbase-errors"]=wo(U,Ae)),R.auth.required&&(ie.security=[{[Kr]:[]}]),ie["x-palbase-handler"]=Jr(v);let Mt=v.params.some(Z=>Z.kind==="optionalUser")||n.databaseSeesCaller;ie["x-palbase-auth"]=R.auth.required?"required":Mt?"optional":"public",ie["x-palbase-verified-email"]=R.auth.verifiedEmail,ie["x-palbase-rate-limit"]=R.limit===!1?!1:{max:R.limit.max,window:R.limit.window},v.meta.upload&&(ie["x-palbase-upload"]={bucket:v.meta.upload.bucket,pathTemplate:v.meta.upload.pathTemplate}),(s[_]??={})[v.method.toLowerCase()]=ie}for(let v of n.webhooks??[]){let Y={operationId:Tt(`webhooks.${v.name}`,i)};v.cls!==""&&(Y.tags=[v.cls]),Y.description=v.provider?`${Fr[v.provider]??v.provider}'s deliveries: verified with ${Fr[v.provider]??v.provider}'s signature scheme under the secret in ${v.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${v.signatureHeader} header: verified under the secret in ${v.secretEnv}, then handed to the @On of their event type.`,Y.responses={200:{description:"Taken: { ok: true, handled } \u2014 handled is false when no @On takes the event's type, and duplicate is true for a delivery already run; or the handler's answer: a Response as it is, text as text, anything else as JSON",content:{"application/json":{},[v.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:ee("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:ee("in_progress: the same delivery is being handled; the sender delivers it again",Be),413:ee("payload_too_large: the body is over what this sender sends"),500:ee("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:ee("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",Be)},Y["x-palbase-webhook"]=v.provider?{provider:v.provider,secretEnv:v.secretEnv,events:v.events}:{signatureHeader:v.signatureHeader,secretEnv:v.secretEnv,events:v.events},s[`/webhooks/${v.name}`]={post:Y}}let p=[...new Set(n.platformEvents??[])].sort();if(p.length>0){let v={operationId:Tt("webhooks.palbase",i)};v.description="The project's events, delivered by the platform to the app's machine: verified under the secret in PALBASE_WEBHOOK_SECRET, then handed to the @On of their type \u2014 user.deleted first to forgetting the rows the app keeps of that user.",v.responses={204:{description:"Taken: handled, or a delivery already run"},401:ee("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:ee("in_progress: the same event is being handled; the platform delivers it again",Be),500:ee("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:ee("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let Y=[...new Set(n.platformEventBuckets??[])].sort();v["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:p,...Y.length>0?{buckets:Y}:{}},s[cn]={post:v}}let g=n.gateways??[],k=ao(g,r),A=g.length>0,H=Object.fromEntries(g.filter(Ie).map(v=>[v.pattern,{events:k[v.name].events,messages:Object.fromEntries(Object.entries(k[v.name].messages).map(([Y,b])=>[Y,b.payload])),graceMs:v.graceMs,...v.logKeepSeconds>0?{logKeepSeconds:v.logKeepSeconds}:{}}])),I=Object.keys(H).length>0,B=g.filter(v=>!Ie(v)).map(v=>({pattern:v.pattern,kind:v.access,publish:v.publish,state_read:!1,state_write:!1,...v.logKeepSeconds>0?{log_keep_seconds:v.logKeepSeconds}:{}})),V=B.length>0,ne={schemas:r,securitySchemes:{[Kr]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},te={openapi:"3.2.0",info:{title:"Palbase backend",version:no("sha256").update(JSON.stringify({paths:s,components:ne,unreachable:a,...A?{gateways:k}:{},...I?{rooms:H}:{},...V?{channels:B}:{}})).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:ne};return a.length>0&&(te["x-palbase-unreachable"]=a),A&&(te["x-palbase-gateways"]=k),I&&(te["x-palbase-room"]=H),V&&(te["x-palbase-channels"]=B),te}function ao(e,t){let n=[];for(let r of e){let s=(i,c,p,g)=>{let k=Et(`${r.name}_${i}_${c}`),A={},H=_t(p,k,A,g);H.$ref===void 0&&(A[k]=H),oo(r.pattern,i,c,A[k]);for(let[I,B]of Object.entries(A)){if(Object.hasOwn(t,I)&&JSON.stringify(t[I])!==JSON.stringify(B))throw new Error(`@Gateway("${r.pattern}") ${i} "${c}": its schema is the component ${I}, which another gateway's names with another schema \u2014 rename one of them`);t[I]=B}return{$ref:`#/components/schemas/${k}`}},a=Object.fromEntries(Object.entries(r.events).map(([i,c])=>[i,s("event",i,c,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([i,c])=>[i,{payload:s("message",i,c.schema,"sent"),...c.reply?{reply:s("reply",i,c.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 oo(e,t,n,r){if(!(!ae(r)||!ae(r.properties))){for(let[s,a]of Object.entries(r.properties))if(a===!0||ae(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 io(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 Jr(e){return`${e.controller.name}.${e.fn}`}function co(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 Tt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function uo(e){let t=new Set;return e.map(n=>Tt(n,t))}function _t(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:lo}:{}}})}catch{return{}}let i=Et(t);for(;Object.keys(n).some(c=>c===i||c.startsWith(`${i}.`));)i=`${i}_`;return fo(o,i,n,r)}function lo(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function fo(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=p=>p==="#"?(a=!0,`#/components/schemas/${t}`):p.startsWith("#/$defs/")?`#/components/schemas/${t}.${Et(mo(p.slice(8)))}`:p,i="all";if(r==="sent"){let p=new Set;for(let g of[e,...Object.values(s)])St(g,p);i=p}for(let[p,g]of Object.entries(s))n[`${t}.${Et(p)}`]=rt(nt(g,o,i));let c=rt(nt(e,o,i));return a?(n[t]=c,{$ref:`#/components/schemas/${t}`}):c}var po=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"]),un=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),ln=new Set(["anyOf","oneOf","allOf","prefixItems"]),fn=new Set(["properties","patternProperties","dependentSchemas"]),ae=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function nt(e,t,n){if(!ae(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):po.has(s)?r[s]=a:un.has(s)?r[s]=nt(a,t,n):ln.has(s)&&Array.isArray(a)?r[s]=a.map(o=>nt(o,t,n)):fn.has(s)&&ae(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,i])=>[o,nt(i,t,n)])));return r}var Wr=Number.MAX_SAFE_INTEGER;function rt(e){if(!ae(e))return e;let t={};for(let[r,s]of Object.entries(e))un.has(r)?t[r]=rt(s):ln.has(r)&&Array.isArray(s)?t[r]=s.map(rt):fn.has(r)&&ae(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,rt(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Wr&&delete t.minimum,t.maximum===Wr&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,ae(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=>ae(a)&&Object.keys(a).length===1&&a.type==="null"),s=n[1-r];if(r!==-1&&ae(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function St(e,t){if(ae(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(ae))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=>ae(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(o=>ae(o[a])&&"const"in o[a]))for(let o of s)t.add(o[a])}for(let[n,r]of Object.entries(e))if(un.has(n))St(r,t);else if(ln.has(n)&&Array.isArray(r))for(let s of r)St(s,t);else if(fn.has(n)&&ae(r))for(let s of Object.values(r))St(s,t)}}function mo(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Et(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function Vr(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 ho(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function ee(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:ro}}}}function go(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=_t(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function yo(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 wo(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 bo(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,i)=>o-i)){let o=r.get(a),i=o.map(c=>{let p={error:{type:"string",const:c.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},g=["error","error_description","status","request_id"];return c.data&&(p.data=_t(c.data,`${t}.${c.code}.data`,n,"answered"),g.push("data")),{type:"object",properties:p,required:g}});s[String(a)]={description:o.map(c=>c.code).join(" | "),content:{"application/json":{schema:i.length===1?i[0]:{oneOf:i}}}}}return s}function ko(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]=ee(s.join("; "))),e.auth.required&&(n[401]=ee("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]=ee("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=ee("idempotency_key_in_use: a request with this Idempotency-Key is still running",Be)),t.readsBody&&(n[413]=ee("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=ee("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=ee("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Be)),n[500]=ee("internal_error: the handler failed; the app's log has it under the request id"),n[503]=ee(`${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":""}`,Be),n}var xt=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 Ot(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return vo(r??t??"unknown")}function vo(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(":"):[],i=t.includes("::")?[...a,...Array(8-a.length-o.length).fill("0"),...o]:a;return i.length!==8||i.some(c=>!/^[0-9a-f]{1,4}$/i.test(c))?t:`${i.slice(0,4).map(c=>parseInt(c,16).toString(16)).join(":")}::/64`}function Yr(e){let t=[];for(let n of e){let r=N(n,Me),s=N(n,je)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=N(n,Ut)??new Map;for(let o of s){let i=`${r.basePath}${o.subpath}`||"/",c=i.split("/").filter(Boolean).map(g=>{let k=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(g)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(g);return k?{param:k[1]}:g});if(typeof c[0]=="string"&&Ne.has(c[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${i} \u2014 /${c[0]} is the platform's; a route is served elsewhere`);let p=[...a.get(o.fn)??[]].sort((g,k)=>g.index-k.index);for(let g of p)if(g.kind==="param"&&!c.some(k=>typeof k!="string"&&k.param===g.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${g.name}") names no {${g.name}} in ${o.method} ${i}`);t.push({id:`${o.method} ${i}`,method:o.method,segments:c,controller:n,fn:o.fn,params:p,meta:o,controllerAuth:r.options.auth})}}return Xn(t),t}function pn(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 i=0;i<r.length&&o;i++){let c=s.segments[i];if(typeof c=="string")o=c===r[i];else try{a[c.param]=decodeURIComponent(r[i])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function gn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Ke(e,t,n,r,s){return At(e,e?gn(e.requests,t):void 0,n,r,s)}var mn={role:"service",claims:{}};async function At(e,t,n,r,s){if(!e||!t)return s();let a=p=>T.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 ${p} 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:p}),o=e.app.request(t,{signal:n,heldIdle:a}),i=se.getStore();i&&(i.database=o.database);let c;try{c=await s()}catch(p){throw await o.rollback(p).catch(g=>T.error("[palbase] the request's transaction could not be rolled back",{error:g})),p}try{await o.commit()}catch(p){throw await o.rollback(p).catch(g=>T.error("[palbase] the request's transaction could not be rolled back",{error:g})),p}return c}var To=1024*1024,So=20,Eo={max:300,window:60},Fe="/_palbase/crons",Je="/_palbase/tasks",Xr=50,es=50,_o=4096,xo=69632,ts=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,at=1e4,Oo=6e4;function Ao(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 } were checked against v2's database; v3 has none yet \u2014 check the role in the service`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0}}var re=class extends Error{constructor(n,r,s,a,o,i){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=o;this.challenge=i}status;code;data;retryAfter;challenge};function Ro(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 Po=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Co(e,t){let n=new Headers(e.headers);for(let r of Po)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 ns(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Rt(e.headers,"Accept-Language")),e}function Rt(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 he(e,t,n,r={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}})}function $(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),he(e.status,n,t,r)}var ds=new Set([0,429,502,503,504]);function rs(e,t,n,r){if(r?.aborted)return T.info(`[palbase] ${n}: the client left before its answer`),$({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof re)return $({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(et(e)){let a=e;return a.status>=500&&T.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),he(a.status,Or(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Pt(e,n);return s?$(s,t):(e instanceof pe?T.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):T.error(`[palbase] unhandled error in ${n}`,{error:e}),$({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Pt(e,t){if(e instanceof ut)return T.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 pe&&ds.has(e.status))return T.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=os(e);if(n!==void 0)return T.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 Mo(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return Cr(e)?t(e.message):et(e)&&!bn(e)&&!yn(e)?t(e.errorDescription):yn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function yn(e){return e instanceof ut||e instanceof pe&&ds.has(e.status)||os(e)!==void 0||et(e)&&e.status===503&&bn(e)}async function hn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,So).map(o=>({field:(o.path??[]).map(i=>String(typeof i=="object"&&i!==null&&"key"in i?i.key:i)).join("."),message:o.message})),a=r.issues.length-s.length;throw new re(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function ot(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new re(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:c,value:p}=await r.read();if(c)break;if(a+=p.byteLength,a>t)throw await r.cancel().catch(()=>{}),new re(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(p)}let o=new Uint8Array(a),i=0;for(let c of s)o.set(c,i),i+=c.byteLength;return o}function jo(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return fe(t)}function Do(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 No(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 Uo=/^[A-Za-z0-9._:-]{8,128}$/,Lo=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Io={max:20,window:60},zo=10*6e4,Ho=1e4,it=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},wn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=is("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,i;if(!a){let p=this.limiter.reserve(o,Io);if("wait"in p)throw new it(p.wait);i=p}let c=await r();if(!c)throw this.known.delete(s),new ct("unknown_token","The token is not one of the app's");return i&&this.limiter.give(o,i.window),this.known.delete(s),this.known.set(s,this.now()+zo),this.known.size>Ho&&this.known.delete(this.known.keys().next().value),c}};function Qd(e){let t=new yt(e.modules),n=Yr(t.controllers.map(d=>d.cls)),r=new Map(n.map(d=>[d,Ao(d,e.auth)]));for(let[d,u]of r){if(!u.required&&d.params.some(l=>l.kind==="user"))throw new TypeError(`${d.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(d.meta.upload&&u.verifiedEmail)throw new TypeError(`${d.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`)}let s=new Map;for(let d of n)for(let u of d.params)u.kind==="resolve"&&s.set(u,t.dependencyOf(d.controller,u.resolver,`${d.id} @Resolve(${u.resolver?.name})`));let a=new Map;for(let d of t.cronProviders){let u=t.get(d),l=N(d,be),f=a.get(l.name);if(f)throw new TypeError(`@Cron "${l.name}" is ${f.owner} and ${d.name}: a cron's name is its own \u2014 name one of them`);a.set(l.name,{declaration:l,owner:d.name,run:h=>u.run(h)})}let o=new Map;for(let d of t.taskProviders){let u=t.get(d),l=N(d,ye),f=o.get(l.name);if(f)throw new TypeError(`@Task "${l.name}" is ${f.owner} and ${d.name}: a task type's name is its own \u2014 name one of them`);o.set(l.name,{declaration:l,owner:d.name,run:(h,m)=>u.run(h,m)})}let i=new Set,c=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(a.size>Xr)throw new TypeError(`${a.size} @Cron classes: a machine runs ${Xr} crons at most`);if(o.size>es)throw new TypeError(`${o.size} @Task classes: a machine runs ${es} task types at most`);a.size>0&&!e.platform&&T.info(`[palbase] ${a.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let p=lr(t.gateways.map(d=>({cls:d,instance:t.get(d)})),{run:(d,u,l,f)=>se.run({requestId:se.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>At(e.database,e.database?d?.id?gn(e.database.requests,ht(d)):mn:void 0,l,u,async()=>{let h=await f();if(l?.aborted)throw new Error(`realtime gave up on ${u} before it ended`);return h})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),isOutage:yn});p.declarations.length>0&&!e.platform&&T.info(`[palbase] ${p.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let g=Mr();(g.tools.size>0||g.agents.size>0)&&!e.platform&&T.info(`[palbase] ${g.tools.size} ai.tool(s) and ${g.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let k=new bt,A=new wt(e.now??Date.now),H=new Set,I=e.database!==void 0||e.contractOnly?.database===!0;if(I){for(let d of n)if(tt(d)&&d.params.some(u=>u.kind==="headers"&&u.schema!==void 0&&Br(u.schema)))throw new TypeError(`${d.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 $t(e.database.app):void 0,V=Wo(e.cors),ne=e.now??Date.now,te=new xt(e.now),v=new wn(te,e.now??Date.now),Y=e.maxBodyBytes??To,b=d=>{let u=d.meta.options.rateLimit??e.rateLimit??Eo;return u!==!1&&u.max>0&&u.window>0?u:!1},E=e.env??process.env,w=yr(t.webhooks,d=>t.get(d),E,{secrets:e.contractOnly===void 0}),_=w.size===0&&a.size===0&&o.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(E).filter(d=>typeof d[1]=="string"&&!Dn(d[0])))),R=new Map([...w.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),U=new Map([...w.keys()].map(d=>[d,{counts:new Map,at:void 0}])),K,F=()=>K??=Qr(n,d=>({auth:r.get(d),limit:b(d)}),{databaseSeesCaller:I,idempotency:I,webhooks:[...w.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...D.keys()],gateways:p.declarations,platformEventBuckets:Go(D),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),D=new Map;for(let[d,u]of Object.entries(e.events??{}))D.set(d,u.map(l=>({name:`palbase(${d})`,call:f=>l(f)})));for(let d of t.eventProviders){let u=t.get(d);for(let{event:l,fn:f,bucket:h}of N(d,Se)??[]){if(!Gn.test(l))throw new TypeError(`@On("${l}") on ${d.name}.${f}: 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`);D.has(l)||D.set(l,[]),D.get(l).push({name:`${d.name}.${f}`,bucket:h,call:async(m,y)=>u[f](m,y)})}}let L=new Set,q=new Set;Nn(e.server),Un({to:(d,u)=>({emit:(l,f)=>p.emit(d,u,l,f),pipe:l=>p.pipe(d,u,l)})}),Kn(e.platform?Fn(E.PALBASE_MACHINE):new mt(new Map([...o].map(([d,u])=>[d,u.declaration])),(d,u)=>Te(d,u),e.now));async function J(d,u){let l;try{l=await Mn(d,e.webhookSecret,{now:e.now})}catch(f){if(f instanceof Ve)return $({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${f.code}`},u);throw f}if(fe(l.data),L.has(l.id))return new Response(null,{status:204,headers:{"x-request-id":u}});if(q.has(l.id))return $({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},u);q.add(l.id);try{let f;try{await Ke(e.database,null,void 0,`event ${l.type}`,async()=>{for(let h of D.get(l.type)??[])if(!(h.bucket!==void 0&&qo(l)!==h.bucket))try{await h.call(l,{requestId:u})}catch(m){throw f=h.name,m}})}catch(h){return T.error(`[palbase] ${f??"the delivery"} failed on ${l.type} ${l.id}; the platform delivers it again`,{error:h}),$({status:500,code:"handler_failed",message:"The event could not be handled"},u)}return L.add(l.id),L.size>at&&L.delete(L.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}finally{q.delete(l.id)}}async function oe(d,u={}){let l=d.headers.get("origin");if(V&&l!==null){let f=V.allows(l);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return f?new Response(null,{status:204,headers:V.preflight(l,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let h=await _n(d,u);if(f)for(let[m,y]of Object.entries(V.headers(l)))m==="vary"?Rt(h.headers,y):h.headers.set(m,y);else Rt(h.headers,"Origin");return h}return _n(d,u)}async function ie(d,u,l,f){if(!d.headers.get(l.scheme.header))return Oe(l,"missing_signature",f);let h={headers:d.headers,body:await ot(d,l.scheme.maxBytes(Y)),url:wr(d,u)},m;try{m=l.scheme.check(h,ne()/1e3)}catch{return Oe(l,"signature_mismatch",f,"check_failed")}if(typeof m=="string")return Oe(l,m,f);let y=l.events.get(m.type);if(!y)return T.info(`[palbase] webhook ${l.name}: no @On takes "${m.type}"; acknowledged`),he(200,{ok:!0,handled:!1},f);let S=R.get(l.name),x=m.event,j=[];if(m.id!==void 0){if(S.seen.has(m.id))return he(200,{ok:!0,handled:!1,duplicate:!0},f);j=[m.id]}else if(m.ids&&Array.isArray(x)){let O=m.ids,P=x.map((M,X)=>[M,O[X]]).filter(([,M])=>M===void 0||!S.seen.has(M));if(P.length===0)return he(200,{ok:!0,handled:!1,duplicate:!0},f);x=P.map(([M])=>M),j=P.flatMap(([,M])=>M===void 0?[]:[M])}if(j.some(O=>S.inflight.has(O)))return $({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},f);fe(x);for(let O of j)S.inflight.add(O);let C;try{C=await Ke(e.database,null,void 0,`webhook ${l.name}`,()=>y.call(x,{env:_,requestId:f,environmentId:e.projectId??""}))}catch(O){let P=Pt(O,`webhook ${l.name}`)??Bo(O,l.name);return P?$(P,f):(T.error(`[palbase] ${y.name} failed on ${l.name} "${m.type}"; the sender delivers it again`,{error:O}),$({status:500,code:"handler_failed",message:"The event could not be handled"},f))}finally{for(let O of j)S.inflight.delete(O)}for(let O of j)S.seen.add(O),S.seen.size>at&&S.seen.delete(S.seen.values().next().value);return Ct(C,l,f)}function Ct(d,u,l){if(d instanceof Response)return d;if(typeof d=="string"){let f=u.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(d,{status:200,headers:{"content-type":f,"x-request-id":l}})}return he(200,d??{ok:!0,handled:!0},l)}function Oe(d,u,l,f=u){let h=U.get(d.name);h.counts.set(f,(h.counts.get(f)??0)+1);let m=ne();return(h.at===void 0||m-h.at>=Oo)&&(Ae(d.name),h.at=m),$({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${u}`},l)}function Ae(d){let u=U.get(d).counts;if(u.size===0)return;let l=[...u.values()].reduce((f,h)=>f+h,0);T.warn(`[palbase] webhook ${d}: ${l} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(u)}),u.clear()}function Mt(d){let u=d.split("/").filter(Boolean);return u.length===2&&u[0]==="webhooks"?w.get(u[1]):void 0}async function Z(d,u,l,f){let h=u.pathname===Fe;if(d.method!==(h?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:h?"The crons are listed with GET":"A cron is run with POST"},f);let m=h?new Uint8Array(0):await ot(d,_o);try{await dt({secret:l,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Q){if(Q instanceof Ve)return $({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${Q.code}`},f);throw Q}if(h){let Q=[...a.values()].map(({declaration:G})=>({name:G.name,schedule:G.schedule,time_zone:G.timeZone,timeout:G.timeout,retry:G.retries}));return he(200,{crons:Q},f,{"cache-control":"no-store"})}let y=u.pathname.slice(Fe.length+1),S=a.get(y);if(!S)return $({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(y)}`},f);let x;try{x=JSON.parse(new TextDecoder().decode(m))}catch{return $({status:400,code:"bad_request",message:"A run is the JSON {cron, run_id, scheduled_at, attempt}"},f)}let{cron:j,run_id:C,scheduled_at:O,attempt:P}=x??{};if(j!==y||typeof C!="string"||C===""||typeof O!="string"||!ts.test(O)||Number.isNaN(Date.parse(O))||!Number.isInteger(P)||P<1)return $({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)}`},f);let M=`${C}#${String(P)}`;if(i.has(M))return new Response(null,{status:204,headers:{"x-request-id":f}});if(c.has(M))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},f);c.add(M);let X={env:_,environmentId:e.projectId??"",cron:y,runId:C,scheduledAt:new Date(O),attempt:P};try{await At(e.database,e.database?mn:void 0,d.signal,`cron ${y}`,async()=>{if(await S.run(X),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${y} before it ended`)})}catch(Q){return d.signal.aborted||T.error(`[palbase] cron ${y} failed (run ${C}, attempt ${String(P)})`,{error:Q}),$({status:500,code:"cron_failed",message:`The cron ${y} failed; the platform tries it again`},f)}finally{c.delete(M)}return i.add(M),i.size>at&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":f}})}let Te=async({task:d,id:u,attempt:l,payload:f,createdAt:h},m)=>{let y=o.get(d);if(!y)return{status:404,message:`this version has no task ${JSON.stringify(d)}`};let S=fe(f??null),x=y.declaration.payload;if(x){let C=await x["~standard"].validate(S);if(C.issues){let O=C.issues.slice(0,5).map(P=>`${(P.path??[]).map(M=>String(typeof M=="object"&&M!==null&&"key"in M?M.key:M)).join(".")||"(payload)"}: ${P.message}`).join("; ");return T.error(`[palbase] task ${d} ${u}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${O}`),{status:422,message:`what it carries is not what @Task "${d}" takes: ${O}`}}S=C.value}let j={env:_,environmentId:e.projectId??"",task:d,id:u,attempt:l,createdAt:h};try{await At(e.database,e.database?mn:void 0,m,`task ${d}`,async()=>{if(await y.run(S,j),m.aborted)throw new Error(`the platform gave up on this attempt of ${d} before it ended`)})}catch(C){return C instanceof pt?(T.error(`[palbase] task ${d} ${u} can never be done: ${C.message}`),{status:422,message:C.message}):(m.aborted||T.error(`[palbase] task ${d} failed (task ${u}, attempt ${String(l)})`,{error:C}),{status:500,message:`the task ${d} failed; it is tried again`})}return{status:204}};async function Re(d,u,l,f){let h=u.pathname===Je;if(d.method!==(h?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:h?"The task types are listed with GET":"A task is run with POST"},f);let m=h?new Uint8Array(0):await ot(d,xo);try{await dt({secret:l,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Q){if(Q instanceof Ve)return $({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${Q.code}`},f);throw Q}if(h){let Q=[...o.values()].map(({declaration:G})=>({name:G.name,timeout:G.timeout,retry:G.retries,concurrency:G.concurrency}));return he(200,{tasks:Q},f,{"cache-control":"no-store"})}let y=u.pathname.slice(Je.length+1),S;try{S=JSON.parse(new TextDecoder().decode(m))}catch{return $({status:400,code:"bad_request",message:"A task is the JSON {task, id, attempt, payload, created_at}"},f)}let{task:x,id:j,attempt:C,payload:O,created_at:P}=S??{};if(x!==y||typeof j!="string"||j===""||typeof P!="string"||!ts.test(P)||Number.isNaN(Date.parse(P))||!Number.isInteger(C)||C<1)return $({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)}`},f);let M=`task:${j}#${String(C)}`;if(i.has(M))return new Response(null,{status:204,headers:{"x-request-id":f}});if(c.has(M))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},f);c.add(M);let X;try{X=await Te({task:y,id:j,attempt:C,payload:O,createdAt:new Date(P)},d.signal)}finally{c.delete(M)}return X.status===404?$({status:404,code:"task_not_found",message:X.message??""},f):X.status===422?$({status:422,code:"task_failure",message:X.message??""},f):X.status>=300?$({status:X.status,code:"task_failed",message:X.message??""},f):(i.add(M),i.size>at&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":f}}))}async function we(d,u,l,f){if(d.method!=="POST")return $({status:405,code:"method_not_allowed",message:`${f} is POSTed`},l);let h;try{Cn({signature:d.headers.get("palbase-signature"),now:e.now}),h=await ot(d,1048576),await dt({secret:u,signature:d.headers.get("palbase-signature"),body:h,now:e.now})}catch(y){if(y instanceof Ve)return $({status:401,code:"invalid_signature",message:`${f} is the platform's to call: ${y.code}`},l);throw y}let m;try{m=JSON.parse(new TextDecoder().decode(h))}catch{return $({status:400,code:"bad_request",message:`${f} is JSON`},l)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(d.url).pathname?$({status:401,code:"invalid_signature",message:`${f} is the platform's to call: signed_for_another_call`},l):{body:m}}async function ls(d,u,l,f,h){let m=await we(u,l,f,`An upload's ${d}`);if(m instanceof Response)return m;let y=er(d,m.body);if(typeof y=="string")return $({status:400,code:"bad_request",message:`An upload's ${d}: ${y}`},f);if(d==="complete"){if(H.has(y.uploadId))return $({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},f);H.add(y.uploadId),H.size>at&&H.delete(H.values().next().value)}let S=pn(n,y.method,y.route);if(!S||"malformed"in S||!S.route.meta.upload)return $({status:404,code:"not_found",message:`No upload route for ${y.method} ${y.route}`},f);let{route:x,params:j}=S,C=S.route.meta.upload,O=No(y.user);if(O&&xn(h,O.id),r.get(x).required&&!O)throw new re(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let X=b(x);if(X!==!1){let G=te.take(`${x.id}\0${Vn(y.user,y.client)}`,X);if(G!==void 0)throw new re(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:G},G)}let Q=Yn(C.pathTemplate,{userId:O?.id??null,uploadId:y.uploadId,filename:y.filename});if("problem"in Q)throw new re(400,"bad_request",Q.problem);return await Ke(e.database,ht(y.user),u.signal,x.id,async()=>{let G={request:u,query:new URLSearchParams(y.query),params:j,user:O,body:y.body===void 0||y.body===null?{}:fe(y.body),requestId:f};await En(x,G);for(let Pe of x.params)(Pe.kind==="query"||Pe.kind==="body"&&y.body!==void 0)&&await as(Pe,G)}),he(200,{bucket:C.bucket,path:Q.path},f)}h.endpoint=x.id.slice(x.id.indexOf(" ")+1);let P=new URLSearchParams(y.query),M=y.body===null||y.body===void 0?{}:fe(y.body);return jt(x,{request:u,query:P,params:j,user:O,body:M,requestId:f,uploadedObject:fe(y.uploadedObject)},ht(y.user))}function Tn(d,u,l,f){let h=d?{sub:d.id,role:"authenticated"}:null;return se.run({requestId:se.getStore()?.requestId??"",...d?{userId:d.id}:{}},()=>Ke(e.database,h,l,u,async()=>{let m=await f();if(l.aborted)throw new Error(`the platform gave up on ${u} before it ended`);return m}))}let Sn=(d,u)=>new Response(d,{status:200,headers:{"content-type":"application/json","x-request-id":u}});async function fs(d,u,l){let f=await we(d,u,l,"A tool call");if(f instanceof Response)return f;let h=f.body,m=h.tool;if(typeof m!="string"||m==="")return $({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},l);let y=g.tools.get(m);if(!y)return $({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},l);let S=h.call_id,x=rn(h.context);if(typeof S!="string"||S===""||S.length>256||typeof x=="string")return $({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof x=="string"?`: ${x}`:""}`},l);let j=is("sha256").update(JSON.stringify(h)).digest("hex"),C=k.answered(S);if(C!==void 0)return C.digest!==j?$({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},l):Sn(C.answer,l);if(k.isRunning(S))return $({status:409,code:"in_progress",message:"This call is running",retryAfter:2},l);k.start(S);let O;try{let P=await Tn(x.user,`ai.tool ${m}`,d.signal,()=>y.call(fe(h.input??{}),{...x,callId:S,signal:d.signal}));O=JSON.stringify({output:P.output,is_error:P.is_error});let M=new TextEncoder().encode(O).byteLength;M>4194304&&(T.error(`[palbase] ai.tool ${m} answered ${M} bytes (call ${S}): a machine's answer is ${4194304} at most; the agent is told it failed`),O=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${4194304/(1<<20)} MiB it may be`}],is_error:!0}))}catch(P){if(d.signal.aborted)return k.end(S,void 0),$({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);T.error(`[palbase] ai.tool ${m} failed (call ${S}, chat ${x.chatId}); the agent is told`,{error:P}),O=JSON.stringify({output:[{type:"text",text:Mo(P)}],is_error:!0})}return k.end(S,{digest:j,answer:O}),Sn(O,l)}async function ps(d,u,l){let f=await we(d,u,l,"An agent's turn");if(f instanceof Response)return f;let h=rn(f.body);if(typeof h=="string"||h.agent==="")return $({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata}${typeof h=="string"?`: ${h}`:": agent names it"}`},l);let m=h.agent,y=g.agents.get(m);if(!y)return $({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},l);let S;try{S=await Tn(h.user,`ai.agent ${m}`,d.signal,()=>y.resolve({...h,signal:d.signal}))}catch(C){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let O=Pt(C,`ai.agent ${m}`);return O?$(O,l):(T.error(`[palbase] ai.agent ${m} failed for chat ${h.chatId}; the turn is not started`,{error:C}),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},l))}let x=S.tools.find(C=>g.tools.get(C.name)!==C);if(x)return T.error(`[palbase] ai.agent ${m} 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`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},l);let j=JSON.stringify(S.definition);return new TextEncoder().encode(j).byteLength>4194304?(T.error(`[palbase] ai.agent ${m}'s definition is larger than the ${4194304} bytes a machine's answer may be`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},l)):new Response(j,{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function ms(d,u,l){let f=await we(d,u,l,"A repository's token");if(f instanceof Response)return f;let h=f.body;if(typeof h.repo!="string"||h.repo===""||typeof h.repository!="string"||typeof h.call_id!="string"||h.call_id===""||h.call_id.length>256)return $({status:400,code:"bad_request",message:"A repository's token is asked as {call_id, repo, repository}"},l);if(!A.take(h.call_id))return $({status:409,code:"call_id_reused",message:"This token ask was answered already"},l);let m=g.repos.get(h.repo);if(!m)return $({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(h.repo.slice(0,64))}`},l);let y;try{y=await m.token({repo:h.repo,repository:h.repository,signal:d.signal})}catch(S){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let x=Pt(S,`ai.repo ${h.repo}`);return x?$(x,l):(T.error(`[palbase] ai.repo ${h.repo} gave no token; the workspace's clone or push is refused`,{error:S}),$({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},l))}return typeof y!="string"||y.trim()===""?(T.error(`[palbase] ai.repo ${h.repo}'s token function answered no token`),$({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},l)):new Response(JSON.stringify({token:y}),{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function hs(d,u,l,f){let h=await we(u,l,f,`A gateway's ${d}`);if(h instanceof Response)return h;let m=await p.serve(d,h.body,u.signal);return"code"in m?$({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},f):"body"in m?he(200,m.body,f):new Response(null,{status:204,headers:{"x-request-id":f}})}async function En(d,u){let l=[],f={params:Object.freeze({...u.params}),user:fe(u.user),headers:d.meta.upload?new Headers:u.request.headers,requestId:u.requestId};for(let h of d.params)h.kind==="resolve"&&(l[h.index]=await s.get(h).resolve(f,h.options));return l}async function jt(d,u,l,f){let h=t.get(d.controller),m=await Ke(e.database,l,u.request.signal,d.id,async()=>{let y=await En(d,u);for(let x of d.params)x.kind!=="resolve"&&(y[x.index]=await as(x,u));f?.ran();let S=await h[d.fn](...y);if(u.uploadedObject&&u.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return f?f.record(ns(ss(S,u.requestId),se.getStore()?.usedLocales)):S});return f?m:ns(ss(m,u.requestId),se.getStore()?.usedLocales)}async function _n(d,u){let l=d.headers.get("x-request-id")??"",f=Uo.test(l)?l:`req_${crypto.randomUUID()}`,h=performance.now(),m=new URL(d.url).pathname,y={endpoint:m},S=await gs(d,u,f,y);return e.telemetry?.record({requestId:f,method:d.method,endpoint:y.endpoint,path:m,status:S.status,durationMs:performance.now()-h,userId:y.userId}),S}function xn(d,u){d.userId=u;let l=se.getStore();l&&(l.userId=u)}async function gs(d,u,l,f){let h=e.strings,m=h?{requestId:l,strings:h,locales:Ln(d.headers.get("accept-language"),h.source),usedLocales:[]}:{requestId:l},y=await ys(m,d,u,l,f);return h&&Rt(y.headers,"Accept-Language"),y}async function ys(d,u,l,f,h){return se.run(d,async()=>{let m=new URL(u.url),y=`${u.method} ${m.pathname}`;try{if(m.pathname===cn&&D.size>0)return u.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},f):e.webhookSecret?await J(u,f):$({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},f);let S=Mt(m.pathname);if(S)return y=`webhook ${S.name}`,u.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},f):await ie(u,m,S,f);if(e.platform&&(m.pathname===Fe||m.pathname.startsWith(`${Fe}/`)))return y=m.pathname===Fe?"crons":`cron ${m.pathname.slice(Fe.length+1)}`,await Z(u,m,e.platform.secret,f);if(e.platform&&(m.pathname===Je||m.pathname.startsWith(`${Je}/`)))return y=m.pathname===Je?"tasks":`task ${m.pathname.slice(Je.length+1)}`,await Re(u,m,e.platform.secret,f);if(e.platform&&(m.pathname===Ft||m.pathname===Jn)){let z=m.pathname===Ft?"authorize":"complete";return y=`upload ${z}`,await ls(z,u,e.platform.secret,f,h)}if(e.platform&&m.pathname.startsWith(`${Jt}/`)){let z=m.pathname.slice(Jt.length+1);return y=`gateway ${z}`,await hs(z,u,e.platform.secret,f)}if(e.platform&&m.pathname===Ar)return y="ai tool call",await fs(u,e.platform.secret,f);if(e.platform&&m.pathname===Rr)return y="ai agent's turn",await ps(u,e.platform.secret,f);if(e.platform&&m.pathname===Pr)return y="ai repository's token",await ms(u,e.platform.secret,f);if(Ko(m.pathname))return $({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},f);let x=pn(n,u.method,m.pathname);if(x&&"malformed"in x)return $({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},f);if(!x)return $({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},f);let{route:j,params:C}=x;if(y=j.id,h.endpoint=j.id.slice(j.id.indexOf(" ")+1),j.meta.upload)throw new re(400,"upload_required",`${j.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let O=r.get(j),P=null,M=null,X=u.headers.get("authorization")??"",Q=/^(bearer|dpop)\s+(\S+)$/i.exec(X),G=Q?.[2],Pe=Q?.[1].toLowerCase()==="dpop";if(G)try{let z=!Pe&&e.tokens&&!Lo.test(G)&&e.tokens.accepts(G)?e.tokens:void 0,Ce=z?await v.ask(G,Ot(u.headers,l.remoteAddress),()=>Ke(e.database,null,u.signal,"token",()=>z.resolve(G))):await e.verifier.verify(G,Pe?{proof:u.headers.get("dpop"),method:u.method,url:jn(u.headers,m)}:void 0);P=Do(Ce),M=Ce.claims}catch(z){if(!O.required&&(z instanceof ct||z instanceof ut||z instanceof it))P=null;else throw z instanceof it?new re(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:z.wait},z.wait):z instanceof ct?new re(401,"invalid_token","The access token is not valid",{reason:z.reason},void 0,Ro(z.reason)):z}else if(X!==""&&O.required)throw new re(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(P&&xn(h,P.id),O.required&&!P)throw new re(401,"unauthorized","This route needs a signed-in user");if(O.verifiedEmail&&!P?.emailVerified)throw new re(403,"email_not_verified","This route needs a verified email address");let On=b(j);if(On!==!1){let z=P?`u:${P.id}`:`a:${Ot(u.headers,l.remoteAddress)}`,Ce=te.take(`${j.id}\0${z}`,On);if(Ce!==void 0)throw new re(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Ce},Ce)}let We=u.method==="GET"||u.method==="HEAD"?void 0:await ot(u,Y),ws=We===void 0?void 0:jo(We),An={request:u,query:m.searchParams,params:C,user:P,body:ws,raw:We,requestId:f},Rn=B&&We!==void 0&&tt(j)?qr(u.method,u.headers):void 0;if(!B||Rn===void 0)return await jt(j,An,M);let bs={role:gn(e.database.requests,M).role,uid:P?.id??`a:${Ot(u.headers,l.remoteAddress)}`},Pn=!1;return await B.serve({key:Rn,caller:bs,method:u.method,uri:`${m.pathname}${m.search}`,body:We},z=>jt(j,An,M,{record:z,ran:()=>{Pn=!0}}),{requestId:f,refusal:z=>$(z,f),failure:z=>rs(z,f,y,u.signal),ran:()=>Pn})}catch(S){return rs(S,f,y,u.signal)}})}return{handle:oe,routes:n.map(d=>d.id),contract:F,start:()=>t.start(),stop:async()=>{p.close();for(let d of U.keys())Ae(d);await t.shutdown(),await e.telemetry?.flush()}}}function qo(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Go(e){let t=new Set;for(let[n,r]of e)if(Ht(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 ss(e,t){return e instanceof Response?Co(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):he(200,e,t)}function Bo(e,t){if(!(!et(e)||e.status!==503||!bn(e)))return T.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 Ko(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return Ne.has(decodeURIComponent(t))}catch{return Ne.has(t)}}var Fo="GET, POST, PUT, PATCH, DELETE, QUERY",Jo=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function Wo(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!Jo.test(r)||r.startsWith("http://")&&!/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(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":Fo,"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 as(e,t){switch(e.kind){case"body":return hn(e.schema,t.body??{},"Request body");case"query":return hn(e.schema,fe(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),fe(n),e.schema?hn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return fe(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"client":{let n=t.request.headers;return fe({sdkVersion:n.get("x-palbase-sdk-version"),appVersion:n.get("x-palbase-client-version"),platform:n.get("x-platform"),osVersion:n.get("x-os-version")})}}}var vn=720*3600;function kn(e){return e instanceof pe&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function cs(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),vn)}function us(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var $n=class{filling=new Map;async get(t){try{let n=await ge.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!kn(n))throw n;return T.warn("cache: a read could not reach the cache; it is a miss",{key:t,status:n.status}),null}}async set(t,n,r){try{await ge.cache.putCacheEntry({query:{key:t},body:{value:us(n),ttl:cs(r)}})}catch(s){if(!kn(s))throw s;T.warn("cache: a write could not reach the cache; it is let go",{key:t,status:s.status})}}async del(t){await ge.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await ge.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,n,r){let s=this.filling.get(t);if(s)return s;let a=(async()=>{try{let o;try{o=(await ge.cache.getCacheEntry({query:{key:t}})).data}catch(c){if(!kn(c))throw c;T.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:c.status})}if(o?.found)return o.value??null;let i=await r();return await this.set(t,i,n),i}finally{this.filling.delete(t)}})();return this.filling.set(t,a),a}},tc=lt("Cache",new $n);function nc(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=p=>{let g=r.get(p);if(g&&g.expiresAt<=n()){r.delete(p);return}return g},o=()=>{let p=n();for(let[k,A]of r)A.expiresAt<=p&&r.delete(k);if(r.size<t)return;let g=[...r.entries()].sort((k,A)=>k[1].expiresAt-A[1].expiresAt);for(let[k]of g.slice(0,Math.ceil(g.length/4)))r.delete(k)},i=async(p,g,k)=>{r.size>=t&&!r.has(p)&&o(),r.set(p,{value:us(g),expiresAt:n()+(cs(k)??vn)*1e3})};return{get:async p=>{let g=a(p);return g?structuredClone(g.value):null},set:i,async del(p){r.delete(p)},async incr(p){let g=a(p),k=(typeof g?.value=="number"&&Number.isInteger(g.value)?g.value:0)+1;return r.set(p,{value:k,expiresAt:g?.expiresAt??n()+vn*1e3}),k},getOrSet(p,g,k){let A=a(p);if(A)return Promise.resolve(structuredClone(A.value));let H=s.get(p);if(H)return H;let I=(async()=>{try{let B=await k();return await i(p,B,g),B}finally{s.delete(p)}})();return s.set(p,I),I}}}export{It as a,Se as b,De as c,Yo as d,Xo as e,ei as f,ti as g,ni as h,ri as i,si as j,ai as k,oi as l,ii as m,di as n,ci as o,ui as p,li as q,fi as r,pi as s,mi as t,hi as u,gi as v,yi as w,wi as x,bi as y,ki as z,N as A,vi as B,$i as C,pt as D,xi as E,Oi as F,Mi as G,ji as H,Ls as I,nr as J,zi as K,Hi as L,qi as M,Gi as N,Bi as O,Ki as P,Fi as Q,Zi as R,W as S,Sr as T,Er as U,_r as V,Ea as W,sd as X,id as Y,dd as Z,cd as _,ud as $,ld as aa,fd as ba,pd as ca,md as da,$d as ea,To as fa,Qd as ga,vn as ha,tc as ia,nc as ja};
|
package/dist/chunks/JS3TTUHS.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.7.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as g,b}from"./X3MTLJRV.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=v(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=E(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await U(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status];if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await P(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function U(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:$(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function $(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function v(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function E(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+O(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!e.secretKey;case"userJWT":return!!a;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function O(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function P(t,e){let n=await _(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=B(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function _(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function B(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,v as e,R as f};
|
package/dist/chunks/L3NTI4AZ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.7.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as D}from"./KDSWK3XW.js";import{a as P,b as R,c as b,d as x,e as O,f as j,g as M,h as C,i as U,j as L,k as K,l as N}from"./AIIKXCWN.js";import{a as $,b as I}from"./ZBOJEH7K.js";import{b as v,d as w}from"./JS3TTUHS.js";var ae=/^pb_[a-z0-9]+_s/;function E(n){if(D())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ae.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=I(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??$);return{ai:P.client(e),analytics:R.client(e),auth:b.client(e),cache:x.client(e),flags:O.client(e),machines:j.client(e),notify:M.client(e),purchases:C.client(e),realtime:U.client(e),secrets:L.client(e),storage:K.client(e),stores:N.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,de=/^[0-9]{1,12}$/,le=/^[0-9a-f]{64}$/,W=8,fe=/^whsec_[0-9A-Za-z]{32,}$/,he=1024*1024;async function B(n){if(typeof n.secret!="string"||!fe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await F(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(z(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!be(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function F(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=z(n.body),{t,v1:r}=H(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,we(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let u of r)me(o,ge(u))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function H(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let a of r.split(",")){let u=a.indexOf("=");if(u<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,u).trim(),i=a.slice(u+1).trim();if(c==="t"){if(s!==void 0||!de.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!le.test(i))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(i)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function pe(n,e,t={}){let r=await ye(n,t.maxBytes??he);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ye(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],a=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;if(a+=l.byteLength,a>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let u=new Uint8Array(a),c=0;for(let i of o)u.set(i,c),c+=i.byteLength;return u}function z(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function ge(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function me(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function we(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function be(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var V=60,ke=60,Se=8*1024,ve=1e5;function _(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function J(n){let e=Y(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var k=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ve){this.max=e}spend(e,t){if(t>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new d("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,a]of s)a>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Ee(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return _(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function q(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function G(n,e,t,r){let s=ie=>{throw new d("proof",`the DPoP proof is not taken: ${ie}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>Se)return s("it is too long");let a=o.split(".");if(a.length!==3)return s("it is not a JWS of three parts");let u=J(a[0]),c=J(a[1]);if(!u||!c)return s("its header or claims are not base64url JSON");if(u.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(u.alg!=="ES256")return s(`it is signed with ${String(u.alg)}; only ES256 is taken`);let i=u.jwk;if(!i||typeof i!="object"||i.kty!=="EC"||i.crv!=="P-256"||typeof i.x!="string"||typeof i.y!="string")return s("its header carries no P-256 public key");if("d"in i)return s("its header carries a private key");if(await Ee(i.x,i.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:i.x,y:i.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=Y(a[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${a[0]}.${a[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?q(c.htu):void 0,y=q(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let re=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-re)>V)return s("it was not made within a minute of now");let se=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:oe,until:(c.iat+V+ke)*1e3+1}}var d=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}};function _e(n){return async e=>{let t=b.client(w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch}));try{return await t.verifyTokenUser(),!0}catch(r){if(r instanceof v&&r.status===401)return!1;throw r}}}var T={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},X=60,Te=16*1024,Ae=10*6e4,Pe=5e4,Z=n=>typeof n=="string"&&Object.hasOwn(T,n),A=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new k;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Te)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let s=Q(r[0]),o=Q(r[1]);if(!s||!o)throw new d("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Z(a))throw new d("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let u=s.kid;if(typeof u!="string"||u==="")throw new d("malformed","the token header names no kid");let c=await this.key(u);if(!c)throw new d("unknown_key",`no key ${u} in the project's key set`);if(c.alg!==a)throw new d("algorithm",`key ${u} is ${c.alg}, the token says ${a}`);let i=te(r[2]);if(!i)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(T[c.alg].verify,c.key,i,l).catch(()=>!1))throw new d("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");y=await G(e,h.jkt,t,this.now())}else if(t)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:xe(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",a=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:ee(t,a)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let a;try{a=await o}catch(c){let i=this.standings.get(t),l=this.now();if(i&&l<i.at+this.standingStaleMs)return i.until=Math.min(l+this.standingTtlMs,i.at+this.standingStaleMs),i.live;throw new g("a session's standing cannot be read now",{cause:c})}let u=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:u,until:u+this.standingTtlMs}),this.standings.size>Pe&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+X<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-X>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Ae;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let a=o.alg;if(typeof o.kid!="string"||!Z(a))continue;let u=T[a];if(o.kty!==u.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...i}=o;try{r.set(o.kid,{alg:a,key:await crypto.subtle.importKey("jwk",i,u.import,!1,["verify"])})}catch{}}this.keys=r;let s=Oe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Re.test(s)?`${r}://${s}${e.pathname}`:""}var Re=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function xe(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Oe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function te(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Q(n){let e=te(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function je(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var S=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Me(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:u}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...a!==void 0?{ttl_seconds:a}:{},...u!==void 0?{metadata:u}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new S(i);let l={customer_id:i.customer,spend_id:i.id},p;try{p=await r(i)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Ce(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Ue=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Le=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ne(n){return!Ue.test(n)||Le.test(n)||/_PROXY$/i.test(n)}var Ke=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function Ne(n){return Ke.test(n)}async function $e(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=E({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:a}=await o.secrets.getEnvironmentValues({path:{environment:t}}),u=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(ne(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,u.push(l)}return{set:t,loaded:u.sort(),kept:c.sort(),refused:i.sort()}}export{E as a,f as b,B as c,F as d,H as e,pe as f,d as g,g as h,_e as i,A as j,ee as k,je as l,S as m,Me as n,Ce as o,ne as p,Ne as q,$e as r};
|
package/dist/chunks/LEBVOSG6.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.7.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{f as m}from"./ELEE7XO2.js";import{AsyncLocalStorage as A}from"node:async_hooks";function O(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new A,d,w,E,T={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function M(n){d=n}function H(n){w=n}var F=new Proxy({},{get(n,e){if(e==="gateways"){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w}if(e==="ai")return E??=m({server:T});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),Z=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
|
|
3
|
-
`):process.stdout.write(`${o}
|
|
4
|
-
`)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var h=O("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var G=512,L=8,_=64,q=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,v={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function D(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function $(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function j(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>_)return;let s=e.toLowerCase(),t=Object.hasOwn(v,s)?v[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales($(e))[0]}catch{return}if(t===void 0)return}let i=D(t);if(!(i===""||i==="und"||i==="mul"))return t}function I(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function X(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=G){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let x=r.slice(f+1);r=r.slice(0,f).trim();for(let p of x.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=q.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,L)){let r=j(o);if(r!==void 0)for(let a of I(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function z(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var N=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function S(n,e){return n.replace(N,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function Y(n){u=n===void 0?void 0:{root:n,said:!1}}function W(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,h.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),S(n,e);let{text:i,locale:o}=z(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),S(i,e)}export{O as a,R as b,c,M as d,H as e,F as f,Z as g,h,X as i,Y as j,W as k};
|
package/dist/chunks/OIA7KLRW.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.7.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as u,b as a}from"./JS3TTUHS.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:e=>`this user has sent as many messages this minute as the project allows${e.retryAfter!==void 0?`: write again in ${e.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:e=>`the project's storage did not answer when the model was to read a picture${e.retryAfter!==void 0?`: try again in ${e.retryAfter} s`:"; try again shortly"}`},d=new WeakSet;function f(e){if(!(e instanceof a)||d.has(e))return e;let n=p[e.code];if(!n)return e;let s=new a({op:e.op,status:e.status,code:e.code,message:`${n(e)} (${e.op}: ${e.status} ${e.code})`,requestId:e.requestId,retryAfter:e.retryAfter,body:e.body,cause:e});return d.add(s),s}function m(e){return e.catch(n=>{throw f(n)})}function y(e){if(typeof e!="object"||e===null)return;let n=e,s=n.data;if(typeof n.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let t=u(s),o=typeof n.id=="number"&&Number.isSafeInteger(n.id)?n.id:0;switch(n.type){case"message":return typeof t.client_id=="string"?{type:"message",seq:o,message:t}:void 0;case"turn":{if(typeof t.response_id!="string"||typeof t.status!="string")return;let r={...t,type:"turn",seq:o};return r.waiting??=null,r.error??=null,r}case"text":{let r=t.offset;return typeof t.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"text",response_id:t.response_id,offset:r,text:typeof t.text=="string"?t.text:""}}case"reset":{let r=t.offset;return typeof t.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"reset",response_id:t.response_id,offset:r}}case"tool":return typeof t.call_id=="string"&&typeof t.response_id=="string"?{...t,type:"tool",seq:o}:void 0;case"agent":return typeof t.parent_response_id=="string"?{...t,type:"agent",seq:o}:void 0;default:return}}function _(e){let n=0;for(let s=0;s<e.length;s++){let t=e.charCodeAt(s);t<128?n+=1:t<2048?n+=2:t>=55296&&t<=56319&&s+1<e.length&&(e.charCodeAt(s+1)&64512)===56320?(n+=4,s++):n+=3}return n}function g(e,n){if(n<=0)return 0;let s=0;for(let t=0;t<e.length;t++){let o=e.charCodeAt(t),r=3,i=1;if(o<128?r=1:o<2048?r=2:o>=55296&&o<=56319&&t+1<e.length&&(e.charCodeAt(t+1)&64512)===56320&&(r=4,i=2),s+=r,s>=n)return t+i;t+=i-1}return e.length}function x(e,n){return e.slice(g(e,n))}export{m as a,y as b,_ as c,g as d,x as e};
|