palbase 0.10.2 → 0.11.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.
Files changed (56) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +11 -11
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{RYWIWH4U.js → 2CQIOY2Z.js} +1 -1
  8. package/dist/chunks/{5TVS7F23.js → 2MS22NJC.js} +2 -2
  9. package/dist/chunks/476DZPIV.js +2 -0
  10. package/dist/chunks/{IW34A4TV.js → 52DZTUF7.js} +2 -2
  11. package/dist/chunks/{7PBQ3LI2.js → 5D7BAVO5.js} +1 -1
  12. package/dist/chunks/{6JUQZ4D4.js → 63TWL4SB.js} +2 -2
  13. package/dist/chunks/{SCXHU5B7.js → 7JE4KOPN.js} +2 -2
  14. package/dist/chunks/{SBVBCENU.js → AEAFASN2.js} +2 -2
  15. package/dist/chunks/{QTAPRS4Q.js → BAOQMZPI.js} +2 -2
  16. package/dist/chunks/CQBT2Z2T.js +20 -0
  17. package/dist/chunks/{ZOAWYN6L.js → D6RL5OCI.js} +2 -2
  18. package/dist/chunks/{L4SCG6HT.js → DAYQLOBB.js} +2 -2
  19. package/dist/chunks/GCVVMTWI.js +2 -0
  20. package/dist/chunks/{XJEZB4MI.js → GUFHH4DP.js} +2 -2
  21. package/dist/chunks/{BMCC423W.js → KXY2SF4N.js} +2 -2
  22. package/dist/chunks/{S4F256W2.js → LJ3VOTHH.js} +2 -2
  23. package/dist/chunks/{MAPLN2FY.js → NHNXW6EK.js} +1 -1
  24. package/dist/chunks/{D2UQQWJC.js → QX7E6TNL.js} +1 -1
  25. package/dist/chunks/{O5CJJFEU.js → S4GBHZOR.js} +1 -1
  26. package/dist/chunks/WYUC5N2T.js +2 -0
  27. package/dist/chunks/{5NZGW67E.js → XBT3QJRS.js} +2 -2
  28. package/dist/cli.js +124 -122
  29. package/dist/refuse/ai.js +1 -1
  30. package/dist/refuse/backend.js +1 -1
  31. package/dist/refuse/server.js +1 -1
  32. package/dist/server/index.js +2 -2
  33. package/dist/server/testing.js +2 -2
  34. package/dist/web/index.js +2 -2
  35. package/dist/web/message.js +2 -2
  36. package/dist/web/palbe.js +2 -2
  37. package/dist/web/paywall.js +2 -2
  38. package/dist/web/push-sw.js +1 -1
  39. package/dist/web/ssr.js +2 -2
  40. package/dist/web/vite.js +2 -2
  41. package/package.json +2 -2
  42. package/types/backend/src/database.d.ts +8 -1
  43. package/types/backend/src/engine-db.d.ts +3 -1
  44. package/types/backend/src/engine.d.ts +2 -0
  45. package/types/backend/src/idempotency.d.ts +136 -0
  46. package/types/internal/src/modules/auth.d.ts +25 -8
  47. package/types/internal/src/modules/purchases.d.ts +39 -3
  48. package/types/internal/src/modules/secrets.d.ts +138 -3
  49. package/types/internal/src/modules/stores.d.ts +30 -1
  50. package/types/server/src/fields.d.ts +62 -0
  51. package/types/server/src/index.d.ts +1 -0
  52. package/types/server/src/server.d.ts +8 -0
  53. package/types/server/src/testing.d.ts +8 -0
  54. package/dist/chunks/I2TY2GLY.js +0 -2
  55. package/dist/chunks/PKBCMWTM.js +0 -2
  56. package/dist/chunks/QCKQXIQV.js +0 -20
@@ -0,0 +1,20 @@
1
+ /*! palbase 0.11.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as yt,c as ae,d as zn,e as Hn,f as ge,h as E,i as Gn}from"./GUFHH4DP.js";import{b as et,d as mt,e as Nn,f as Un,g as ht,h as gt,k as Ln,q as In}from"./GCVVMTWI.js";import{b as ce}from"./7JE4KOPN.js";import"reflect-metadata";var zt=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],Kn="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",wt=/^\d+$/;function Ds(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(!wt.test(g)||Number(g)<1||Number(g)>n)return;i=Number(g)}let u=t,m=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),S=o.slice(g+1);if(!wt.test(k)||!wt.test(S)||Number(k)<t||Number(S)>n||Number(k)>Number(S))return;u=Number(k),m=Number(S)}else{if(!wt.test(o)||Number(o)<t||Number(o)>n)return;u=Number(o),m=a===-1?u:n}for(let g=u;g<=m;g+=i)r.add(g)}return r}function Fn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${Kn}; "${e}" is not`;let n=[];for(let m=0;m<5;m++){let g=Ds(t[m],zt[m].lo,zt[m].hi);if(!g)return`${Kn}; its ${zt[m].name} "${t[m]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),i=t[4].startsWith("*"),u=new Date(Date.UTC(2e3,0,1));for(let m=0;m<366*8+2;m++,u.setUTCDate(u.getUTCDate()+1)){if(!s.has(u.getUTCMonth()+1))continue;let g=r.has(u.getUTCDate()),k=a.has(u.getUTCDay());if(o||i?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Ce=Symbol.for("palbase.backend.controller"),je=Symbol.for("palbase.backend.routes"),Gt=Symbol.for("palbase.backend.params"),Kt=Symbol.for("palbase.backend.injectable"),Ft=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),Me=Symbol.for("palbase.backend.webhook"),ke=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks"),we=Symbol.for("palbase.backend.testUserTemplates");function ue(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Ht=Symbol.for("palbase.backend.declared");function oe(){let e=globalThis;return e[Ht]instanceof Set||(e[Ht]=new Set),e[Ht]}var De=new Set(["webhooks","_palbase"]);function bi(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&De.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ue(n,Ce,()=>({basePath:e,options:t})),oe().add(n)}}function Ne(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ue(r.constructor,je,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var ki=Ne("GET"),vi=Ne("POST"),Ti=Ne("PUT"),$i=Ne("PATCH"),Ei=Ne("DELETE"),Si=Ne("QUERY");function fe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ue(n.constructor,Gt,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function Bt(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 _i=e=>fe("body",{schema:Bt("Body",e)}),xi=e=>fe("query",{schema:Bt("QueryParams",e)}),Oi=e=>fe("headers",e===void 0?{}:{schema:Bt("Headers",e)}),Ri=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return fe("param",{name:e})},Ai=()=>fe("user"),Pi=()=>fe("optionalUser"),Ci=()=>fe("req"),ji=()=>fe("requestId"),Mi=()=>fe("requestId"),Di=()=>fe("client");function Ni(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return fe("resolve",{resolver:e,options:t[0]})}function Ui(){return e=>{ue(e,Kt,()=>!0),oe().add(e)}}function Li(e){return t=>{ue(t,Ft,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Jn=/^[a-z]+(\.[a-z_]+)+$/,Ns=/^[a-z][a-z0-9-]{1,62}$/,qt=e=>e.startsWith("file.");function Ii(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"||!Ns.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!qt(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ue(r.constructor,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),oe().add(r.constructor)}}var Jt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Us=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Bn(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(!Us.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 zi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Jt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=Fn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Bn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Bn(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,ke))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,ke,{value:s,enumerable:!1}),oe().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ls=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Hi(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(!Ls.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&&Is(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Se)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket: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)}ue(t,Me,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:i})=>({event:o,fn:i}))})),oe().add(t)}}function Is(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Gi(){return[...oe()].filter(e=>D(e,Ce)!==void 0)}function Ki(e){return(D(e,je)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var bt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Wi(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Jt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),oe().add(s)}}var Zt;function Vn(e){Zt=e}function Wt(){if(!Zt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Zt}var zs=720*3600;function Hs(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>zs))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 Gs(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 Vi=yt("Tasks",{async enqueue(e,t,n={}){return Hs(n),Wt().enqueue(Gs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Wt().cancel(e,t.machine)},async get(e,t={}){return Wt().get(e,t.machine)}}),Vt=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Zn(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await ge.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return Vt(a.data,a.status===200)},async cancel(n,r){return Vt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Vt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ks=1e4,Fs=36e5,Wn=24*36e5,kt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ce({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ce({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ce({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let u of this.tasks.values())if(u.task===t&&u.key===r.key&&(u.finishedAt===void 0||this.now()-u.finishedAt<Wn))return this.view(u,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,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 ce({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ce({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(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(Ks*2**Math.min(t.attempt-1,16),Fs),E.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Wn&&this.tasks.delete(s);n==="failed"&&E.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var vt="/_palbase/test-user-templates",Bs=/^[a-z][a-z0-9_-]{0,63}$/;function Xi(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bs.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,we))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,we,{value:r,enumerable:!1}),oe().add(s)}}function Qn(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Yn(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ce&&n.status===404)return!1;throw n}}var qs="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Xn(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,qs),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var Qt="/_palbase/storage/upload/authorize",er="/_palbase/storage/upload/complete",Yt="/_palbase/realtime/rooms";var Js=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ue(e){if(!Js(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function tr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function nr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Tt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ws=/^[a-z][a-z0-9-]{1,62}$/,rr=1024,Vs=new Set(["userId","uploadId","filename"]);function sd(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(!Ws.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=Zs(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,u)=>{if(typeof i!="string"||u===void 0||typeof u.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ue(o.constructor,je,()=>[]).push({method:"POST",subpath:e,fn:i,options:a,upload:s})}}function ad(){return fe("uploadedObject")}function Zs(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Vs.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!sr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function sr(e){if(e===""||new TextEncoder().encode(e).byteLength>rr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Qs(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ys(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ys(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function ar(e,t){let n=Qs(e,t);return sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${rr} bytes)`}}function or(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ir(e,t){if(!Xt(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Ue(t.user);if(!o)return"user is { id?, session?, role }";let i=tr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let u=Xs(t.uploadedObject);return u?u.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:"",uploadedObject:u,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Xs(e){if(!Xt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:i,height:u,thumbhash:m,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||u!==void 0&&typeof u!="number"||m!==void 0&&typeof m!="string")&&!(!Xt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...i!==void 0?{width:i}:{},...u!==void 0?{height:u}:{},...m!==void 0?{thumbhash:m}:{},variants:{...g}}}import{markData as ea}from"palgres";var _e=Symbol.for("palbase.backend.gateway"),ze=Symbol.for("palbase.backend.gatewayHooks"),dr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},ta={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(dr),output:()=>structuredClone(dr)}}},hr=Symbol.for("palbase.backend.gatewayRefusal"),cr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,hr,{value:!0})}},na=e=>typeof e=="object"&&e!==null&&e[hr]===!0&&typeof e.reason=="string",Le=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,ra=6e4,sa=86400,ur=604800,lr=65536,ve=255,aa=["roles:","flags:","messaging:","debug:"],oa=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ie=e=>new TextEncoder().encode(e).byteLength,en=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",rn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function ia(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ie(e)>ve)return`a channel is ${ve} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=aa.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function gr(e){if(typeof e!="string"||e==="")return"is a name";if(Ie(e)>ve)return`is ${ve} bytes at most`}function ld(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=ia(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&rn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=da(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)||oa.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 S=gr(g);if(S)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${S}`);if(!en(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let u=ue(a,ze,sn),m={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...i,chat:ta}:{...i},chat:r.chat===!0,graceMs:r.graceMs??ra,hooks:{...u.hooks},messages:Object.assign(Object.create(null),u.messages)};if(m.access===void 0&&m.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(m.access!==void 0&&m.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${m.access}' and @Authorize both say who may join \u2014 keep one`);if(m.publish&&Le(m))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(m.publish&&m.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(m.chat&&!Le(m))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ue(a,_e,()=>m),oe().add(a)}}function da(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return sa;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>ur)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${ur} (a week)`);return n}var sn=()=>({hooks:Object.create(null),messages:Object.create(null)}),ca={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function tt(e){let t=ca[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ue(n.constructor,ze,sn),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,oe().add(n.constructor)}}var fd=tt("authorize"),pd=tt("first"),md=tt("connect"),hd=tt("disconnect"),gd=tt("empty");function yd(e,t,n={}){let r=gr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!en(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!en(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let i=ue(s.constructor,ze,sn),u=i.messages[e];if(u!==void 0&&u.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${u.fn} and ${a}).`);i.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},oe().add(s.constructor)}}function ua(e){return D(e,_e)}function la(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function yr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ie(r)>ve?{problem:`a channel is ${ve} bytes at most`}:r}function fa(e,t,n){let r=rn(e).map(i=>i.slice(1,-1));for(let i of Object.keys(t))if(!r.includes(i))return{problem:`{${i}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(i=>Object.hasOwn(t,i))?yr(e,t):pa(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(i=>`{${i}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function pa(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var ma=1e4,ha=1e3,ga=100,an=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},pr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function wr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:w,instance:_}of e){let b=ua(w),x=a.get(b.name);if(x!==void 0&&x!==w)throw new TypeError(`@Gateway("${b.pattern}"): two gateways are named ${b.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(b.name,w);let P=s.get(pr(b.pattern));if(P!==void 0)throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: ${n.get(P)?.cls.name}'s "${P}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(pr(b.pattern),b.pattern);for(let[K,B]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([G,U])=>[`message ${G}`,U.fn])])if(typeof _[B]!="function")throw new TypeError(`@Gateway("${b.pattern}") on ${w.name}: its ${K} is ${B}, which is no method of it`);let N={cls:w,instance:_,g:b};n.set(b.pattern,N),r.set(w,N)}let o=new Map,i=new Set,u=new Set,m=new nn(t.broadcast),g=w=>{let _=o.get(w);return _||(_=new AbortController,o.set(w,_)),_},k=(w,_)=>{_?.abort(),o.get(w)===_&&o.delete(w)},S=(w,_,b,x,P,N)=>{if(!Object.hasOwn(w.g.events,b)){E.warn(`[palbase] ${P}: emit("${b}") is not sent \u2014 ${w.cls.name} declares no event "${b}" (static events)`);return}if(w.g.chat&&b==="chat"){E.warn(`[palbase] ${P}: emit("chat") is not sent \u2014 ${w.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}m.send({topic:_,event:b,payload:x??{},...N!==void 0?{conn_id:N}:{}},P)},I=async(w,_,b)=>{if(typeof w!="object"||w===null||typeof w.pipe!="function")throw new TypeError(`${b}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await w.pipe(_)};function H(w,_,b,x,P,N,K){let B=x?.signal??AbortSignal.abort(),G=`${w.cls.name} (${_})`;return{channel:_,params:Object.freeze({...b}),signal:B,count:P,user:N,emit:(U,W)=>S(w,_,U,W,G,K),pipe:U=>I(U,_,G),owner:{hold(U){ae.exit(async()=>{try{await U(B)}catch(W){B.aborted||E.error(`[palbase] ${G}: a task owner.hold ran failed`,{error:W})}}).catch(()=>{})},release:()=>k(_,x)}}}function z(w){let{room:_,channel:b}=w;if(typeof _!="string"||typeof b!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let x=n.get(_);return!x||!Le(x.g)?he(404,"not_found",`This app serves no gateway "${_}"`):{entry:x,channel:b,params:la(_,b)}}let te=(w,_)=>he(400,"bad_request",`"${_}" is not a channel of the gateway "${w}"`);async function ee(w,_){let b=z(w);if("status"in b)return b;let{entry:x,channel:P,params:N}=b,K={status:200,body:{subscribe:!1,publish:!1}};if(!N)return E.warn(`[palbase] ${x.cls.name}: realtime asked about "${P}", which is not a channel of the gateway "${x.g.pattern}"; the join is refused`),K;let B=Ue(w.user),G=B?.id;if(!G)return K;if(x.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}};if(x.g.access==="owner")return N[rn(x.g.pattern)[0].slice(1,-1)]===G?{status:200,body:{subscribe:!0,publish:Object.keys(x.g.messages).length>0}}:K;let U=x.g.hooks.authorize;if(!U)return K;let W,V;try{W=await t.run(B,`${x.cls.name}.${U}`,_,async()=>x.instance[U]({user:{id:G},params:Object.freeze({...N})})),V=ya(W)}catch(Y){if(t.isOutage(Y)||_?.aborted)throw Y;return E.error(`[palbase] ${x.cls.name}.${U} (@Authorize of ${P}) failed; the join is refused`,{error:Y}),K}return V==="malformed"?(E.warn(`[palbase] ${x.cls.name}.${U} (@Authorize of ${P}) answered ${wa(W)}, which is no grant (true, { read, write } or null); the join is refused`),K):{status:200,body:V}}async function se(w,_){let b=z(w);if("status"in b)return b;if(!b.params)return te(b.entry.g.pattern,b.channel);let x=Ue(w.user);if(!x?.id||typeof w.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let P=Object.hasOwn(b.entry.g.messages,w.event)?b.entry.g.messages[w.event]:void 0;if(!P)return{status:200,body:{ok:!1,reason:tn(`gateway "${b.channel}" takes no message "${w.event}"`,$t)}};let N=await P.schema["~standard"].validate(ea(w.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:mr(N.issues)}};let K=g(b.channel),B={...H(b.entry,b.channel,b.params,K,0,{id:x.id}),payload:N.value},G=`${b.entry.cls.name}.${P.fn} (@Subscribe "${w.event}" of ${b.channel})`,U;try{U=await t.run(x,`${b.entry.cls.name}.${P.fn}`,_,async()=>b.entry.instance[P.fn](B))}catch(V){if(t.isOutage(V))throw V;return na(V)?{status:200,body:{ok:!1,reason:tn(V.reason,$t)}}:(_?.aborted||E.error(`[palbase] ${G} failed`,{error:V}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(U===void 0)return{status:200,body:{ok:!0}};if(P.reply){let V=await P.reply["~standard"].validate(U);if(V.issues)return E.error(`[palbase] ${G} returned an ack its reply schema refuses (${mr(V.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};U=V.value}let W;try{W=JSON.stringify(U)}catch(V){return E.error(`[palbase] ${G} returned an ack that is not JSON; the member is told it failed`,{error:V}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return W===void 0?{status:200,body:{ok:!0}}:Ie(W)>lr?(E.error(`[palbase] ${G} returned an ack of ${Ie(W)} bytes, past ${lr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(W)}}}async function v(w,_){let b=z(w);if("status"in b)return b;if(!b.params)return te(b.entry.g.pattern,b.channel);let x=w.event;if(typeof x!="string"||!Object.hasOwn(fr,x))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let P=typeof w.count=="number"&&Number.isInteger(w.count)&&w.count>=0?w.count:void 0;if(P===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let N=x==="join"||x==="leave",K=N?Ue(w.user):void 0,B=N?w.connId:void 0;if(N&&(!K?.id||typeof B!="string"||B===""))return he(400,"bad_request",`A ${x} names its member: user and connId`);let G=`${x}\0${b.channel}\0${typeof B=="string"?B:""}`;if(N&&i.has(G))return{status:204};if(u.has(G))return he(503,"in_progress","This moment of the gateway is being handled",5);u.add(G);try{let U=b.entry.g.hooks[fr[x]],W;if(x==="empty"?(W=o.get(b.channel),k(b.channel,W)):W=x==="leave"?o.get(b.channel):g(b.channel),U){let V=H(b.entry,b.channel,b.params,W,P,{id:K?.id??""},x==="join"?B:void 0);try{await t.run(K,`${b.entry.cls.name}.${U}`,_,async()=>b.entry.instance[U](V))}catch(Y){if(t.isOutage(Y))throw Y;return _?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${U} (${x} of ${b.channel}) failed; realtime tells it again`,{error:Y}),he(500,"handler_failed",`The gateway's ${x} could not be handled`)}}return N&&(i.add(G),i.size>ma&&i.delete(i.values().next().value)),{status:204}}finally{u.delete(G)}}function Q(w,_){let b=r.get(w),x=`Palbase.gateways.to(${w?.name??String(w)})`;if(!b)throw new TypeError(`${x}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let P=yr(b.g.pattern,_??{});if(typeof P!="string")throw new TypeError(`${x}: ${P.problem}`);return{entry:b,channel:P,where:x}}return{declarations:[...n.values()].map(w=>w.g),async serve(w,_,b){return an(_)?w==="authorize"?ee(_,b):w==="message"?se(_,b):w==="lifecycle"?v(_,b):he(404,"not_found",`No gateway call ${JSON.stringify(w)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(w,_,b,x){let{entry:P,channel:N,where:K}=Q(w,_);S(P,N,b,x,K)},async pipe(w,_,b){let{channel:x,where:P}=Q(w,_);await I(b,x,P)},async revalidate(w,_,b={}){let x=r.get(w),P=`Palbase.gateways.to(${w?.name??String(w)}).revalidate`;if(!x)throw new TypeError(`${P}: ${w?.name??String(w)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=fa(x.g.pattern,_??{},b);if("problem"in N)throw new TypeError(`${P}: ${N.problem}`);await t.revalidate(N)},close(){for(let w of o.values())w.abort();o.clear()}}}function ya(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!an(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function wa(e){return Array.isArray(e)?"an array":an(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var ba=20,$t=256;function mr(e){let t="";for(let n of e.slice(0,ba)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=$t)break}return tn(t,$t)}function tn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var nn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ie(t.event)>ve){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${ve} bytes`);return}try{JSON.stringify(t.payload)}catch(a){E.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=ha?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ae.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,ga);try{await this.broadcast(s)}catch(o){E.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),E.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as on,createHmac as ka,createPublicKey as Tr,timingSafeEqual as va,verify as $r}from"node:crypto";function vd(e){let t=D(e,Me);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function Er(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let i=D(o,Me),u=s.get(i.name);if(u)throw new TypeError(`@Webhook "${i.name}" is declared by ${u.cls.name} and by ${o.name}: /webhooks/${i.name} is one endpoint`);let m=`@Webhook "${i.name}" (${o.name})`,g=n[i.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${m} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=Ta(i,g)}catch(H){a.push(`${m}: ${i.secret.env} ${H.message}`)}let S=t(o),I=new Map(i.events.map(({event:H,fn:z})=>[H,{name:`${o.name}.${z}`,call:(te,ee)=>S[z](te,ee)}]));s.set(i.name,{name:i.name,cls:o,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:I})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
+ - ${a.join(`
4
+ - `)}`);return s}function Sr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var He=1024,br=1024*He;function Ta(e,t){if(e.signature)return xe(void 0,e.signature.header,1/0,ja(e.signature,t));switch(e.provider){case"stripe":return xe("stripe","stripe-signature",512*He,Sa(t));case"github":return xe("github","x-hub-signature-256",25*br,_a(t));case"slack":return xe("slack","x-slack-signature",64*He,xa(t));case"discord":return xe("discord","x-signature-ed25519",64*He,Oa(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*He),check:Aa(t)};case"sendgrid":return xe("sendgrid","x-twilio-email-event-webhook-signature",br,Pa(t));case"livekit":return xe("livekit","authorization",512*He,Ca(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function xe(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??_r(e,s)}}function _r(e,t){let n=dn(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:xr(e,t.headers,r),event:r,...$a(e,t,r)}}function xr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Oe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Ar(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return Oe(n,"EventType");case"livekit":return Oe(n,"event");default:return Oe(n,"type")}}function $a(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Oe(n,"id"));case"slack":return r(Oe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${Or(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Oe(s,"sg_event_id")||void 0)}:{};default:return{}}}var Ea=300;function Sa(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let u of r.split(",")){let m=u.indexOf("=");if(m<=0)continue;let g=u.slice(0,m).trim(),k=u.slice(m+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(g==="v1"){let S=pe(k,"hex");if(!S)return"malformed_signature";a.push(S)}}let o=nt(s);if(o===void 0||a.length===0)return"malformed_signature";if(rt(o,n))return"stale_timestamp";let i=Ge("sha256",e,`${s}.`,t.body);return a.some(u=>Te(u,i))?void 0:"signature_mismatch"}}function _a(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?pe(n.slice(7),"hex"):void 0;return r?Te(r,Ge("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function xa(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=nt(s),o=r.startsWith("v0=")?pe(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":rt(a,n)?"stale_timestamp":Te(o,Ge("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function Oa(e){let t=pe(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=Tr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,i=nt(o),u=pe(a,"hex");return i===void 0||!u||u.byteLength!==64?"malformed_signature":rt(i,s)?"stale_timestamp":$r(null,Rr(o,r.body),n,u)?void 0:"signature_mismatch"}}var Ra=1e3;function Aa(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=pe(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",i;if(a!==null){if(!Te(Buffer.from(a.toLowerCase()),Buffer.from(on("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let I=1;for(let te of t.body)if(te===38&&++I>Ra)return"malformed_signature";let H=new Map;for(let[te,ee]of new URLSearchParams(dn(t.body))){let se=H.get(te);se||H.set(te,se=new Set),se.add(ee)}let z=[];for(let te of[...H.keys()].sort()){let ee=[...H.get(te)].sort();for(let se of ee)o+=te+se;z.push([te,ee.length===1?ee[0]:ee])}i=Object.fromEntries(z)}let u=s.protocol==="https:"?"443":"80",m=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||u}${s.pathname}${s.search}`;if(![m,g].some(I=>Te(r,Ge("sha1",e,I,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),S=k?{id:`${k}:${Or(`${m}
5
+ ${o}`)}`}:{};return i?{type:xr("twilio",t.headers,i),event:i,...S}:{..._r("twilio",t),...S}}}function Pa(e){let t;try{let n=pe(e,"base64");if(!n)throw new Error;t=Tr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=nt(a),i=pe(s.trim(),"base64");return o===void 0||!i?"malformed_signature":rt(o,r)?"stale_timestamp":$r("sha256",Rr(a,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var kr=60;function Ca(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=vr(pe(s[0],"base64url")),o=pe(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Te(o,Ge("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=vr(pe(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+kr||typeof i.nbf=="number"&&n<i.nbf-kr)return"stale_timestamp";let u=typeof i.sha256=="string"?pe(i.sha256,"base64"):void 0;return u&&Te(u,on("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function ja(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 m=nt(i);if(m===void 0)return"malformed_signature";if(rt(m,a))return"stale_timestamp"}let u=pe(o.trim(),e.encoding);return u?Te(u,Ge(r,t,...n.map(m=>m==="{body}"?s.body:m==="{ts}"?i:m)))?void 0:"signature_mismatch":"malformed_signature"}}var Ma=new TextEncoder;function Ge(e,t,...n){let r=ka(e,t);for(let s of n)r.update(s);return r.digest()}function Or(e){return on("sha256").update(e).digest("hex")}function Rr(e,t){return Buffer.concat([Ma.encode(e),t])}function Te(e,t){return e.byteLength===t.byteLength&&va(e,t)}var Da={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function pe(e,t){return Da[t].test(e)?Buffer.from(e,t):void 0}function nt(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function rt(e,t){return Math.abs(t-e)>Ea}function dn(e){return new TextDecoder().decode(e)}function vr(e){if(e)try{return JSON.parse(dn(e))}catch{return}}function Ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Oe(e,t){let n=Ar(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var J=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
6
+ Kind: ${t}
7
+ Path: ${n.join(" -> ")}
8
+ At: ${r}
9
+ ${s}
10
+
11
+ Potential solutions:
12
+ ${a.map(o=>` - ${o}`).join(`
13
+ `)}`),this.name="DiError",this.kind=t,this.path=n}},Na=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],Ua=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),Et=class{owner=new Map;defs=new Map;instances=new Map;providers=new Set;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];templateProviders=[];gateways=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let a=D(r,Ft);if(!a)throw new J("unknown import",[...s,r.name],r.name,`${r.name} is not a @Module`,["decorate it with @Module({ \u2026 })","or list the module itself, not one of its classes"]);this.defs.set(r,a);for(let o of a.imports){if(o===r)throw new J("unknown import",[r.name],r.name,`${r.name} imports itself`,["remove it from its own imports"]);n(o,[...s,r.name])}};for(let r of t)n(r,[]);for(let[r,s]of this.defs){for(let a of[...s.controllers,...s.providers]){let o=this.owner.get(a);if(o&&o!==r)throw new J("duplicate ownership",[o.name,a.name,r.name],a.name,`${a.name} is listed by ${o.name} and by ${r.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(a,r)}for(let a of s.providers)this.providers.add(a);for(let a of s.controllers){if(!D(a,Ce))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is in ${r.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(D(a,ke))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Cron: a cron is a provider's`,["give the cron a class of its own \u2014 @Cron({ name, schedule }) with run(meta) \u2014 listed in the module's providers"]);if(D(a,ye))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Task: a task is a provider's`,["give the task a class of its own \u2014 @Task({ name }) with run(payload, meta) \u2014 listed in the module's providers"]);if(D(a,we))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @TestUserTemplate: a template is a provider's`,["give the template a class of its own \u2014 @TestUserTemplate({ name }) with seed(user, meta) \u2014 listed in the module's providers"]);if(D(a,_e)||D(a,ze))throw new J("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Gateway: a gateway is a provider's`,["give the gateway a class of its own, listed in the module's providers"]);this.controllers.push({cls:a,module:r})}}}validate(){for(let t of oe())if(!this.owner.has(t))throw new J("unowned class",[t.name],t.name,`${t.name} is declared but no module lists it: it would never be built`,["list it in a module's controllers or providers","or delete it"]);for(let[t,n]of this.defs){for(let r of n.exports)if(this.owner.get(r)!==t)throw new J("unknown export",[t.name,r.name],t.name,`${t.name} exports ${r.name}, which it does not own`,[`list ${r.name} in ${t.name}'s providers`,"or export it from the module that owns it"]);for(let r of n.providers){if(D(r,ze)&&!D(r,_e))throw new J("undeclared provider",[t.name,r.name],r.name,`${r.name} has a gateway's methods (@Authorize, @OnFirst, @Subscribe\u2026) but is no @Gateway`,["decorate it with @Gateway(pattern, options)"]);if(!D(r,Kt)&&!D(r,Se)&&!D(r,_e)&&!D(r,ke)&&!D(r,ye)&&!D(r,we)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new J("metadata missing",[t.name,r.name],r.name,`${r.name} has constructor parameters but no emitted types`,["decorate it with @Injectable()","enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json"]):new J("undeclared provider",[t.name,r.name],r.name,`${r.name} is in ${t.name}'s providers but is not @Injectable() (nor an @On handler, a @Gateway, a @Cron, a @Task or a @TestUserTemplate)`,["decorate it with @Injectable()"])}D(r,_e)&&this.gateways.push(r),D(r,Me)?this.webhooks.push(r):D(r,Se)&&this.eventProviders.push(r),D(r,ke)&&this.cronProviders.push(r),D(r,ye)&&this.taskProviders.push(r),D(r,we)&&this.templateProviders.push(r)}}for(let t of this.owner.keys())for(let n of Na)if(typeof t.prototype[n]=="function")throw new J("nest lifecycle name",[t.name],`${t.name}.${n}`,`${n} is NestJS's; it is never called here`,["use onStart() and onShutdown()"]);for(let t of this.owner.keys())this.resolve(t,[])}get(t){let n=this.instances.get(t);if(!n)throw new Error(`${t.name} is not built by this app`);return n}resolve(t,n){let r=this.instances.get(t);if(r)return r;if(n.includes(t.name))throw new J("dependency cycle",[...n,t.name],t.name,`${[...n,t.name].join(" -> ")} goes round`,["move the shared part into a third class both depend on"]);let s=[...n,t.name],a=t.length,o=Reflect.getMetadata("design:paramtypes",t)??[];if(a>0&&o.length===0)throw new J("metadata missing",s,t.name,`${t.name} takes ${a} constructor parameter(s) but no types were emitted`,["enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json","build with tsc, Bun or SWC (esbuild does not emit them)"]);let i=[];o.slice(0,a).forEach((m,g)=>{if(Ua.has(m)||typeof m!="function")throw new J("unresolvable dependency",s,`${t.name} constructor parameter ${g}`,`parameter ${g} of ${t.name} is typed as ${m===void 0?"something with no runtime class":m.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);i.push(this.resolve(this.reachable(t,m,s),s))});let u=new t(...i);return this.instances.set(t,u),this.order.push(u),u}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}provider(t,n){if(typeof t!="function")throw new TypeError(`${n}: inject takes a provider's class \u2014 it was given ${t===null?"null":typeof t}`);let r=t;if(!this.owner.has(r)&&![...this.owner.keys()].some(a=>a.prototype instanceof r))throw new J("unowned class",[n,r.name],r.name,`${n} asks for ${r.name}, which no module provides: the app built none`,[`list ${r.name} in a module's providers`]);let s=this.target(r,[n]);if(!this.providers.has(s))throw new J("undeclared provider",[n,s.name],s.name,`${s.name} is a controller: only a module's providers are given`,[`move what ${n} needs into a provider, listed in a module's providers`]);return this.get(s)}reachable(t,n,r){let s=this.owner.get(t),a=this.target(n,r),o=this.owner.get(a);if(o!==s){if(!this.defs.get(s).imports.includes(o))throw new J("missing import",[...r,a.name],`${s.name}`,`${t.name} (in ${s.name}) needs ${a.name}, owned by ${o.name}, which ${s.name} does not import`,[`add ${o.name} to ${s.name}'s imports (imports are not transitive)`]);if(!this.defs.get(o).exports.includes(a))throw new J("private dependency",[...r,a.name],`${o.name}`,`${a.name} is ${o.name}'s own: it is not in its exports`,[`add ${a.name} to ${o.name}'s exports`])}return a}target(t,n){if(this.owner.has(t))return t;let r=[...this.owner.keys()].filter(s=>s.prototype instanceof t);if(r.length===1)return r[0];throw r.length>1?new J("duplicate ownership",[...n,t.name],t.name,`${t.name} has ${r.length} owned subclasses (${r.map(s=>s.name).join(", ")}): which one is meant cannot be told`,["ask for the subclass itself"]):new J("unowned class",[...n,t.name],t.name,`${t.name} is needed but no module lists it`,[`list ${t.name} in a module's providers (and export it if another module needs it)`])}async start(){let t=[];for(let n of this.order){let r=n.onStart;if(typeof r=="function")try{await r.call(n)}catch(s){throw await this.shutdown(t),new Error(`[palbase] ${n.constructor.name}.onStart() failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}t.push(n)}}async shutdown(t=this.order){for(let n of[...t].reverse()){let r=n.onShutdown;if(typeof r=="function")try{await r.call(n)}catch(s){console.error(`[palbase] ${n.constructor.name}.onShutdown() failed`,s)}}}};import{HTTP_ERROR_BRAND as La,HttpError as st}from"palgres";import{z as $e}from"zod";import{BadRequest as Cd,Conflict as jd,DeadlockDetected as Md,HttpError as Dd,NotFound as Nd,SerializationFailure as Ud,TooManyRequests as Ld,UniqueViolation as Id}from"palgres";function at(e){if(typeof e!="object"||e===null||e[La]!==!0)return!1;let t=e;return Number.isInteger(t.status)&&t.status>=400&&t.status<=599&&typeof t.error=="string"&&typeof t.errorDescription=="string"}var Pr=class extends st{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},Cr=class extends st{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},jr=class extends st{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function Dr(e,t){let n={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(n.data=e.data),n}var Ia=Symbol.for("palbase.backend.errorRegistry"),za={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()})},Ha=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 Ga(){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=za[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function Ka(){let e=globalThis;return e[Ia]??=Ga()}var Fa=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function Rd(e,t,n){if(typeof e!="string"||e.length>100||!Fa.test(e))throw new TypeError(`defineError(code, status): code is a wire code like room_locked or invite.notFound \u2014 a letter, then letters and digits in parts joined by . _ or - \u2014 not ${JSON.stringify(e)}`);if(!Number.isInteger(t)||t<400||t>599)throw new TypeError(`defineError("${e}", status): status is a 4xx or 5xx integer, not ${String(t)} \u2014 an error is never a success`);if(n!==void 0&&typeof n?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if(Ha.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=Ka(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&Mr(s.data)!==Mr(n)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${s.builtin?`the built-in ${s.className}`:`defined with status ${s.status}${s.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let a=e.split(/[._-]/).flatMap(S=>S.split(/(?=[A-Z])/)),o=a.map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(""),i=a.map(S=>S.toLowerCase()).join(" "),u=i.charAt(0).toUpperCase()+i.slice(1),k=n?(S=>class extends st{static code=e;static status=t;constructor(I,H){let z=Ba(e,S,I);super(t,e,H??(typeof z=="string"?z:u),z),this.name=o}})(n):class extends st{static code=e;static status=t;constructor(S){super(t,e,S??u),this.name=o}};return Object.defineProperty(k,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),k}function Ba(e,t,n){let r=t["~standard"].validate(n);if(r instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(r.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${r.issues.map(s=>s.message).join("; ")}`);return r.value}function Mr(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as qa}from"palgres";var Nr="/_palbase/ai/tools",Ur="/_palbase/ai/agents",Lr="/_palbase/ai/repos",Fe=4<<20,Ja=Symbol.for("palbase.ai.tool_error");function Ir(e){return e instanceof Error&&e[Ja]===!0}var Wa=Symbol.for("palbase.ai.declared");function zr(){let e=globalThis[Wa];if(!e)return{tools:new Map,agents:new Map,repos:new Map,repoTokens:void 0};if(e.twice.size>0){let t=[...e.twice].map(n=>n.replace(":"," "));throw new TypeError(`[palbase] ${t.join(", ")}: declared twice with different values \u2014 an ai.tool's and an ai.agent's name is its own, and ai.repoTokens is given once; make each once, at a module's top level`)}return{tools:new Map(e.tools),agents:new Map(e.agents),repos:new Map(e.repos??[]),repoTokens:e.repoTokens}}var Ke=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Hr(e){let t={};if(e==null)return t;if(Ke(e)){for(let[n,r]of Object.entries(e)){if(typeof r!="string")return;Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0})}return t}}function Gr(e){if(!Ke(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(!Ke(e.user)||typeof e.user.id!="string"||e.user.id===""||e.user.name!==void 0&&typeof e.user.name!="string")return"context.user is {id, name}, or null";t={id:e.user.id,name:typeof e.user.name=="string"?e.user.name:""}}let n=Hr(e.metadata);return n===void 0?"context.metadata is an object of strings":{chatId:e.chat_id,agent:e.agent,user:t,metadata:n}}function Kr(e){let t=Gr(e);if(typeof t=="string")return t;let n=e;return typeof n.turn_id!="string"||typeof n.run_id!="string"?"context.turn_id and context.run_id are the turn the call is made in and the run that made it":n.subagent!==null&&typeof n.subagent!="string"?"context.subagent is the subagent that made the call, or null":{...t,turnId:n.turn_id,runId:n.run_id,subagent:n.subagent}}function Fr(e){let t=Gr(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=Ke(a)?Hr(a.metadata):void 0;if(!Ke(a)||typeof a.id!="string"||typeof a.client_id!="string"||a.author!==null&&typeof a.author!="string"||typeof a.author_name!="string"||typeof a.text!="string"||typeof a.delivery!="string"||o===void 0)return"message is {id, client_id, author, author_name, text, delivery, metadata}, or null";r={id:a.id,clientId:a.client_id,author:a.author,authorName:a.author_name,text:a.text,delivery:a.delivery,metadata:qa(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!Ke(n.goal)||typeof n.goal.objective!="string"||typeof n.goal.rubric!="string")return"goal is {objective, rubric}";s={objective:n.goal.objective,rubric:n.goal.rubric}}return{...t,message:r,goal:s}}var Va=1e4,Za=10*6e4,St=class{constructor(t=Date.now){this.now=t}now;seen=new Map;take(t){let n=this.now();for(let[r,s]of this.seen){if(n-s<=Za&&this.seen.size<=Va)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},Qa=1e3,Ya=256*1024,_t=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,n){this.running.delete(t),!(n===void 0||n.answer.length>Ya)&&(this.answers.set(t,n),this.answers.size>Qa&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as ws,isEngineRaised as Tn,markData as le}from"palgres";import{createHash as bs}from"node:crypto";import{createHash as Xa,randomInt as eo}from"node:crypto";import{ago as cn,isRetryable as to,now as Br}from"palgres";import{defineSchema as no,defineTable as ro,index as so,integer as ao,jsonb as oo,raw as io,text as un,timestamp as qr}from"palgres/dsl";var Xr=new Set(["POST","PUT","PATCH","DELETE"]),Jr=255,Wr=35,Vr=24,co=65536,Zr=1e3,uo=64,fn={description:"Makes the write safe to send again (at most 255 characters). A retry with the same key and the same request gets the first answer back, marked `Idempotent-Replayed: true`, and changes nothing; the same key with a different request is refused with 422, and while the first request still runs a retry gets 409 with Retry-After. Answers are kept for 24 hours.",in:"header",name:"Idempotency-Key",required:!1,schema:{maxLength:255,type:"string"}},lo=ro("idempotency_keys",{columns:{key:un().primaryKey(),fingerprint:un(),started_at:qr().defaultNow(),completed_at:qr().nullable(),status_code:ao().nullable(),response_headers:oo().nullable(),response_body:un().nullable()},indexes:e=>[so("idempotency_keys_started").on(e.col("started_at"))]}),Wd=no("palbase",{tables:[lo],raw:[io("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)"})]}),fo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},po={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},mo={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},Qr={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},Ot=class extends Error{};function ot(e){return Xr.has(e.method)&&e.meta.upload===void 0}function es(e,t){if(!Xr.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function ho(e,t){return ts([e.role,e.uid,t]).digest("hex")}function go(e){return ts([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function ts(e){let t=Xa("sha256");for(let n of e)t.update(n).update("\0");return t}function yo(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function ln(e){return e<500&&e!==429&&e!==499}function wo(e,t){return t&&ln(e)}function ns(e){let t=e["~standard"].jsonSchema?.input,n;try{n=t?.({target:"draft-2020-12"})}catch{return!1}let r=n?.properties;return typeof r=="object"&&r!==null&&Object.keys(r).some(s=>s.toLowerCase()==="idempotency-key")}var bo={role:"service",claims:{}},ko={seal:e=>e,open:async e=>e},Rt=class{db;answers;constructor(t,n=ko){this.db=t,this.answers=n}async serve(t,n,r){if(t.key.length>Jr)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Jr} characters`});let s;try{s=await this.begin(ho(t.caller,t.key),go(t))}catch(i){return E.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),r.refusal(Qr)}if("kept"in s){let i;try{i=s.kept.body===null?null:await this.answers.open(s.kept.body)}catch(u){return E.warn("[palbase] the answer kept against an Idempotency-Key could not be opened; the write is not run again",{error:u}),r.refusal(Qr)}return vo({...s.kept,body:i},r.requestId)}if("refused"in s)return r.refusal(s.refused==="reused"?fo:po);let a=s.claim,o;try{o=await n(i=>this.record(a,i))}catch(i){if(i instanceof Ot)return r.refusal(mo);let u=r.failure(i);return wo(u.status,r.ran())&&!to(i)?this.keep(a,u):(await this.release(a),u)}return ln(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:cn({hours:Vr})}}}))}async begin(t,n){return eo(uo)===0&&await this.sweep().catch(r=>E.warn("[palbase] the expired Idempotency-Keys could not be taken away; the next sweep tries again",{error:r})),this.asService(async r=>{for(let s=0;s<3;s++){let[a]=await r.insertMany([{key:t,fingerprint:n}],{onConflict:["key"],action:"ignore"});if(a)return{claim:{key:t,started:a.started_at}};if(await r.deleteMany({where:{key:t,started_at:{lt:cn({hours:Vr})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let i=yo(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[u]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:cn({seconds:Wr})}},set:{started_at:Br()}});return u?{claim:{key:t,started:u.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!ln(n.status))return n;let{response:r,kept:s}=await Yr(n),a=ae.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let o=s.body===null?null:this.answers.seal(s.body),[i]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),o]);if(i?.answered!==!0)throw new Ot;return r}async keep(t,n){let{response:r,kept:s}=await Yr(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Br(),status_code:s.status,response_headers:s.headers,response_body:s.body===null?null:this.answers.seal(s.body)}}))}catch(a){E.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:a})}return r}async release(t){if(await this.releaseOnce(t))return;let n=Date.now()+Wr*1e3,r=()=>{Date.now()+Zr>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},Zr).unref()};r()}async releaseOnce(t){try{return await this.asService(n=>n.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let n=this.db.request(bo),r;try{r=await t(n.database.palbase.idempotency_keys)}catch(s){throw await n.rollback(s).catch(()=>{}),s}try{await n.commit()}catch(s){throw await n.rollback(s).catch(()=>{}),s}return r}};function vo(e,t){let n=new Headers(e.headers);return n.set("x-request-id",t),n.set("idempotent-replayed","true"),new Response(e.body===null?null:Buffer.from(e.body,"base64"),{status:e.status,headers:n})}var xt=Symbol("waits");function To(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(xt));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function Yr(e){let t=[];e.headers.forEach((i,u)=>{u!=="x-request-id"&&t.push([u,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(),u=await To(i);if(u!==xt&&u.done)break;if(u!==xt&&(s.push(u.value),a+=u.value.byteLength,a<=co))continue;let m=u===xt?i:void 0,g=new ReadableStream({start(k){for(let S of s)k.enqueue(S)},async pull(k){let S=await(m??r.read());m=void 0,S.done?k.close():k.enqueue(S.value)},cancel:k=>r.cancel(k)});return{response:n(g),kept:{status:e.status,headers:t.filter(([k])=>k!=="content-length"&&k!=="content-encoding"),body:null}}}let o=Buffer.concat(s);return{response:n(o),kept:{status:e.status,headers:t,body:o.byteLength===0?null:o.toString("base64")}}}import{createHash as $o}from"node:crypto";var pn="/webhooks/palbase",ds="PalbaseErrorEnvelope",rs="PalbaseBearer",Eo={$ref:`#/components/schemas/${ds}`},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"]},ss={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 cs(e,t,n){let r={[ds]:So},s={},a=[],o=[],i=new Set,u=new Map;for(let v of e){let Q=o.find(X=>Oo(X,v));if(Q){a.push({route:v.id,handler:as(v),answeredBy:Q.id});continue}o.push(v);let w=v.segments.map(X=>typeof X=="string"?X:"{}").join("/");u.has(w)||u.set(w,Ao(v.segments.flatMap(X=>typeof X=="string"?[]:[X.param])));let _=u.get(w),b=0,x=`/${v.segments.map(X=>typeof X=="string"?X:`{${_[b++]}}`).join("/")}`,P=t(v),N=At(Ro(v),i),K=v.method!=="GET"&&v.method!=="HEAD",B=X=>{let be=v.params.filter(Ee=>Ee.kind===X&&Ee.schema).map((Ee,pt)=>jt(Ee.schema,`${N}.${X}${pt===0?"":`.${pt+1}`}`,r));return be.length===0?void 0:be.length===1?be[0]:{allOf:be}},G=_.map(X=>({name:X,in:"path",required:!0,schema:{type:"string"}})),U=B("query");U&&G.push(...is(U,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:U}]);let W=B("headers");W&&G.push(...is(W,"header")??[]);let V=n.idempotency===!0&&ot(v);V&&G.push({...fn,schema:{...fn.schema}});let Y=K?B("body"):void 0,ne={operationId:N};v.controller.name!==""&&(ne.tags=[v.controller.name]),G.length>0&&(ne.parameters=G),Y&&(ne.requestBody={required:!Do(Y),content:{"application/json":{schema:Y}}});let Qe=v.params.some(X=>X.schema!==void 0),ft=n.routes?.(v),Ye=Uo(N,ft?.throws??[],n.errors);ne.responses={...No(ft,N,r),...zo(P,{validates:Qe,hasPathParams:_.length>0,readsBody:K,keyed:V}),...Io(Ye,N,r)},Ye.length>0&&(ne["x-palbase-errors"]=Lo(N,Ye)),P.auth.required&&(ne.security=[{[rs]:[]}]),ne["x-palbase-handler"]=as(v);let Lt=v.params.some(X=>X.kind==="optionalUser")||n.databaseSeesCaller;ne["x-palbase-auth"]=P.auth.required?"required":Lt?"optional":"public",ne["x-palbase-verified-email"]=P.auth.verifiedEmail,ne["x-palbase-rate-limit"]=P.limit===!1?!1:{max:P.limit.max,window:P.limit.window},v.meta.upload&&(ne["x-palbase-upload"]={bucket:v.meta.upload.bucket,pathTemplate:v.meta.upload.pathTemplate}),(s[x]??={})[v.method.toLowerCase()]=ne}for(let v of n.webhooks??[]){let Q={operationId:At(`webhooks.${v.name}`,i)};v.cls!==""&&(Q.tags=[v.cls]),Q.description=v.provider?`${ss[v.provider]??v.provider}'s deliveries: verified with ${ss[v.provider]??v.provider}'s signature scheme under the secret in ${v.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${v.signatureHeader} header: verified under the secret in ${v.secretEnv}, then handed to the @On of their event type.`,Q.responses={200:{description:"Taken: { ok: true, handled } \u2014 handled is false when no @On takes the event's type, and duplicate is true for a delivery already run; or the handler's answer: a Response as it is, text as text, anything else as JSON",content:{"application/json":{},[v.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:re("invalid_signature: the delivery is not signed with the secret \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:re("in_progress: the same delivery is being handled; the sender delivers it again",Be),413:re("payload_too_large: the body is over what this sender sends"),500:re("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:re("service_unavailable, auth_unavailable or database_unavailable: what the handler needs of the platform did not answer \u2014 the sender delivers it again after Retry-After",Be)},Q["x-palbase-webhook"]=v.provider?{provider:v.provider,secretEnv:v.secretEnv,events:v.events}:{signatureHeader:v.signatureHeader,secretEnv:v.secretEnv,events:v.events},s[`/webhooks/${v.name}`]={post:Q}}let m=[...new Set(n.platformEvents??[])].sort();if(m.length>0){let v={operationId:At("webhooks.palbase",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:re("invalid_signature: the delivery is not the platform's \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:re("in_progress: the same event is being handled; the platform delivers it again",Be),500:re("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:re("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let Q=[...new Set(n.platformEventBuckets??[])].sort();v["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:m,...Q.length>0?{buckets:Q}:{}},s[pn]={post:v}}let g=n.gateways??[],k=_o(g,r),S=g.length>0,I=Object.fromEntries(g.filter(Le).map(v=>[v.pattern,{events:k[v.name].events,messages:Object.fromEntries(Object.entries(k[v.name].messages).map(([Q,w])=>[Q,w.payload])),graceMs:v.graceMs,...v.logKeepSeconds>0?{logKeepSeconds:v.logKeepSeconds}:{}}])),H=Object.keys(I).length>0,z=g.filter(v=>!Le(v)).map(v=>({pattern:v.pattern,kind:v.access,publish:v.publish,state_read:!1,state_write:!1,...v.logKeepSeconds>0?{log_keep_seconds:v.logKeepSeconds}:{}})),te=z.length>0,ee={schemas:r,securitySchemes:{[rs]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},se={openapi:"3.2.0",info:{title:"Palbase backend",version:$o("sha256").update(JSON.stringify({paths:s,components:ee,unreachable:a,...S?{gateways:k}:{},...H?{rooms:I}:{},...te?{channels:z}:{}})).digest("hex").slice(0,12),description:"The routes this app serves, as its decorators declare them, and \u2014 when its source was read as the contract was written \u2014 what each answers and the errors it throws (x-palbase-errors). Every refusal is the PalbaseErrorEnvelope; a declared error's carries its code and its data."},paths:s,components:ee};return a.length>0&&(se["x-palbase-unreachable"]=a),S&&(se["x-palbase-gateways"]=k),H&&(se["x-palbase-room"]=I),te&&(se["x-palbase-channels"]=z),se}function _o(e,t){let n=[];for(let r of e){let s=(i,u,m,g)=>{let k=Ct(`${r.name}_${i}_${u}`),S={},I=jt(m,k,S,g);I.$ref===void 0&&(S[k]=I),xo(r.pattern,i,u,S[k]);for(let[H,z]of Object.entries(S)){if(Object.hasOwn(t,H)&&JSON.stringify(t[H])!==JSON.stringify(z))throw new Error(`@Gateway("${r.pattern}") ${i} "${u}": its schema is the component ${H}, which another gateway's names with another schema \u2014 rename one of them`);t[H]=z}return{$ref:`#/components/schemas/${k}`}},a=Object.fromEntries(Object.entries(r.events).map(([i,u])=>[i,s("event",i,u,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([i,u])=>[i,{payload:s("message",i,u.schema,"sent"),...u.reply?{reply:s("reply",i,u.reply,"answered")}:{}}]));n.push([r.name,{pattern:r.pattern,...r.access?{access:r.access}:{},...r.logKeepSeconds>0?{durable:r.logKeepSeconds}:{},...r.chat?{chat:!0}:{},events:a,messages:o}])}return Object.fromEntries(n)}function xo(e,t,n,r){if(!(!de(r)||!de(r.properties))){for(let[s,a]of Object.entries(r.properties))if(a===!0||de(a)&&Object.keys(a).length===0)throw new Error(t==="message"?`@Gateway("${e}") message "${n}" has an untyped field "${s}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`:`@Gateway("${e}") ${t} "${n}" has an untyped field "${s}". An untyped payload makes every generated client opaque \u2014 declare its shape.`)}}function Oo(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 as(e){return`${e.controller.name}.${e.fn}`}function Ro(e){let t=e.controller.name;if(t.endsWith("Controller")&&(t=t.slice(0,-10)),t!=="")return`${t[0].toLowerCase()}${t.slice(1)}.${e.fn}`;let n=r=>r.charAt(0).toUpperCase()+r.slice(1);return e.method.toLowerCase()+e.segments.map(r=>typeof r=="string"?n(r):`By${n(r.param)}`).join("")}function At(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function Ao(e){let t=new Set;return e.map(n=>At(n,t))}function jt(e,t,n,r="sent"){let s=e["~standard"],a=s.jsonSchema?.input;if(typeof a!="function")return{};let o;try{o=a({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...s.vendor==="zod"?{override:Po}:{}}})}catch{return{}}let i=Ct(t);for(;Object.keys(n).some(u=>u===i||u.startsWith(`${i}.`));)i=`${i}_`;return Co(o,i,n,r)}function Po(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function Co(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=m=>m==="#"?(a=!0,`#/components/schemas/${t}`):m.startsWith("#/$defs/")?`#/components/schemas/${t}.${Ct(Mo(m.slice(8)))}`:m,i="all";if(r==="sent"){let m=new Set;for(let g of[e,...Object.values(s)])Pt(g,m);i=m}for(let[m,g]of Object.entries(s))n[`${t}.${Ct(m)}`]=dt(it(g,o,i));let u=dt(it(e,o,i));return a?(n[t]=u,{$ref:`#/components/schemas/${t}`}):u}var jo=new Set(["type","enum","required","dependentRequired","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","contentEncoding","contentMediaType","minItems","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties","readOnly","writeOnly","deprecated"]),mn=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),hn=new Set(["anyOf","oneOf","allOf","prefixItems"]),gn=new Set(["properties","patternProperties","dependentSchemas"]),de=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function it(e,t,n){if(!de(e))return typeof e=="boolean"?e:{};let r={};for(let[s,a]of Object.entries(e))s==="$ref"&&typeof a=="string"?r.$ref=t(a):s==="const"?(n==="all"||n.has(e))&&(r.const=a):jo.has(s)?r[s]=a:mn.has(s)?r[s]=it(a,t,n):hn.has(s)&&Array.isArray(a)?r[s]=a.map(o=>it(o,t,n)):gn.has(s)&&de(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,i])=>[o,it(i,t,n)])));return r}var os=Number.MAX_SAFE_INTEGER;function dt(e){if(!de(e))return e;let t={};for(let[r,s]of Object.entries(e))mn.has(r)?t[r]=dt(s):hn.has(r)&&Array.isArray(s)?t[r]=s.map(dt):gn.has(r)&&de(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,dt(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-os&&delete t.minimum,t.maximum===os&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,de(t.propertyNames)&&Object.keys(t.propertyNames).length===1&&t.propertyNames.type==="string"&&delete t.propertyNames,Array.isArray(t.type)&&t.type.filter(r=>r!=="null").length>1&&Object.keys(t).length===1)return{anyOf:t.type.map(r=>({type:r}))};let n=t.anyOf;if(Array.isArray(n)&&n.length===2&&Object.keys(t).length===1){let r=n.findIndex(a=>de(a)&&Object.keys(a).length===1&&a.type==="null"),s=n[1-r];if(r!==-1&&de(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function Pt(e,t){if(de(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(de))continue;if(r.every(a=>"const"in a||Array.isArray(a.enum)))for(let a of r)t.add(a);let s=r.map(a=>de(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(o=>de(o[a])&&"const"in o[a]))for(let o of s)t.add(o[a])}for(let[n,r]of Object.entries(e))if(mn.has(n))Pt(r,t);else if(hn.has(n)&&Array.isArray(r))for(let s of r)Pt(s,t);else if(gn.has(n)&&de(r))for(let s of Object.values(r))Pt(s,t)}}function Mo(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Ct(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function is(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 Do(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function re(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:Eo}}}}function No(e,t,n){if(!e)return{200:{description:"The handler's answer, as JSON",content:{"application/json":{}}},204:{description:"The handler answered nothing (undefined or null)"}};if(e.returns.kind==="void")return{204:{description:"No Content"}};if(e.returns.kind==="raw")return{default:{description:"The handler's own Response, as it built it"}};let r=jt(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function Uo(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 Lo(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 Io(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(u=>{let m={error:{type:"string",const:u.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},g=["error","error_description","status","request_id"];return u.data&&(m.data=jt(u.data,`${t}.${u.code}.data`,n,"answered"),g.push("data")),{type:"object",properties:m,required:g}});s[String(a)]={description:o.map(u=>u.code).join(" | "),content:{"application/json":{schema:i.length===1?i[0]:{oneOf:i}}}}}return s}function zo(e,t){let n={},r=[t.validates&&"a parameter failed its schema (data.fields names each field, data.more how many more)",t.hasPathParams&&"the path is not valid percent-encoding"].filter(Boolean),s=[r.length>0&&`bad_request: ${r.join("; or ")}`,t.keyed&&"invalid_idempotency_key: the Idempotency-Key is over 255 characters"].filter(Boolean);return s.length>0&&(n[400]=re(s.join("; "))),e.auth.required&&(n[401]=re("unauthorized: no access token was sent; invalid_token: the token is not valid (data.reason says why), or the Authorization header is not a Bearer token")),e.auth.verifiedEmail&&(n[403]=re("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=re("idempotency_key_in_use: a request with this Idempotency-Key is still running",Be)),t.readsBody&&(n[413]=re("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=re("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=re("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Be)),n[500]=re("internal_error: the handler failed; the app's log has it under the request id"),n[503]=re(`${e.auth.required?"auth_unavailable: sign-ins cannot be checked right now; ":""}service_unavailable: a platform service the request needs did not answer${t.keyed?"; temporarily_unavailable: the Idempotency-Key could not be recorded":""}`,Be),n}var Mt=class{windows=new Map;now;maxKeys;constructor(t=Date.now,n=1e5){this.now=t,this.maxKeys=n}take(t,n){let r=this.now(),s=this.windows.get(t);if((!s||r>=s.resetAt)&&(s={count:0,resetAt:r+n.window*1e3}),this.windows.delete(t),this.windows.set(t,s),this.windows.size>this.maxKeys&&this.windows.delete(this.windows.keys().next().value),s.count++,s.count>n.max)return Math.max(1,Math.ceil((s.resetAt-r)/1e3))}reserve(t,n){let r=this.take(t,n);return r!==void 0?{wait:r}:{window:this.windows.get(t).resetAt}}give(t,n){let r=this.windows.get(t);r&&r.resetAt===n&&r.count>0&&r.count--}};function Dt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return Ho(r??t??"unknown")}function Ho(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(u=>!/^[0-9a-f]{1,4}$/i.test(u))?t:`${i.slice(0,4).map(u=>parseInt(u,16).toString(16)).join(":")}::/64`}function us(e){let t=[];for(let n of e){let r=D(n,Ce),s=D(n,je)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=D(n,Gt)??new Map;for(let o of s){let i=`${r.basePath}${o.subpath}`||"/",u=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 u[0]=="string"&&De.has(u[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${i} \u2014 /${u[0]} is the platform's; a route is served elsewhere`);let m=[...a.get(o.fn)??[]].sort((g,k)=>g.index-k.index);for(let g of m)if(g.kind==="param"&&!u.some(k=>typeof k!="string"&&k.param===g.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${g.name}") names no {${g.name}} in ${o.method} ${i}`);t.push({id:`${o.method} ${i}`,method:o.method,segments:u,controller:n,fn:o.fn,params:m,meta:o,controllerAuth:r.options.auth})}}return or(t),t}function yn(e,t,n){let r=n.split("/").filter(Boolean);for(let s of e){if(s.method!==t||s.segments.length!==r.length)continue;let a={},o=!0;for(let i=0;i<r.length&&o;i++){let u=s.segments[i];if(typeof u=="string")o=u===r[i];else try{a[u.param]=decodeURIComponent(r[i])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function bn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function qe(e,t,n,r,s){return Ze(e,e?bn(e.requests,t):void 0,n,r,s)}var ct={role:"service",claims:{}};async function Ze(e,t,n,r,s){if(!e||!t)return s();let a=m=>E.warn(`[palbase] ${r}: a transaction of the request could not be given back \u2014 it wrote, locked, is an $atomic or an $attempt, ran SQL of its own, or the database keeps one snapshot for it \u2014 and sat ${m} ms with no statement running: the handler waited on something else, and a database connection waited with it. Make the outside call before the first write, or outside $atomic.`,{waitedMs:m}),o=e.app.request(t,{signal:n,heldIdle:a}),i=ae.getStore();i&&(i.database=o.database);let u;try{u=await s()}catch(m){throw await o.rollback(m).catch(g=>E.error("[palbase] the request's transaction could not be rolled back",{error:g})),m}try{await o.commit()}catch(m){throw await o.rollback(m).catch(g=>E.error("[palbase] the request's transaction could not be rolled back",{error:g})),m}return u}var Ko=1024*1024,Fo=20,Bo={max:300,window:60},Je="/_palbase/crons",We="/_palbase/tasks",ls=50,fs=50,qo=4096,Jo=69632,ps=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,Ve=1e4,Wo=6e4;function Vo(e,t){let n=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof n=="boolean")return{required:n,verifiedEmail:!1};if((n.role??"").trim()!==""||(n.permission??"").trim()!=="")throw new TypeError(`${e.id}: auth { role, permission } is not checked by Palbase \u2014 check the role in the service`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0}}var ie=class extends Error{constructor(n,r,s,a,o,i){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=o;this.challenge=i}status;code;data;retryAfter;challenge};function Zo(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 Qo=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Yo(e,t){let n=new Headers(e.headers);for(let r of Qo)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 ms(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Nt(e.headers,"Accept-Language")),e}function Nt(e,t){let n=(e.get("vary")??"").split(",").map(r=>r.trim()).filter(Boolean);n.includes("*")||n.some(r=>r.toLowerCase()===t.toLowerCase())||e.set("vary",[...n,t].join(", "))}function me(e,t,n,r={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}})}function T(e,t){let n={error:e.code,error_description:e.message,status:e.status,request_id:t};e.data!==void 0&&(n.data=e.data);let r={};return e.retryAfter!==void 0&&(r["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(r["www-authenticate"]=e.challenge),me(e.status,n,t,r)}var ks=new Set([0,429,502,503,504]);function hs(e,t,n,r){if(r?.aborted)return E.info(`[palbase] ${n}: the client left before its answer`),T({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof ie)return T({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(at(e)){let a=e;return a.status>=500&&E.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),me(a.status,Dr(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Ut(e,n);return s?T(s,t):(e instanceof ce?E.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):E.error(`[palbase] unhandled error in ${n}`,{error:e}),T({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Ut(e,t){if(e instanceof gt)return E.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ce&&ks.has(e.status))return E.warn(`[palbase] ${t}: a platform service did not answer (${e.op}: ${e.status} ${e.code})`,{error:e}),{status:503,code:"service_unavailable",message:"A service this request needs did not answer; try again shortly",retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))};let n=ws(e);if(n!==void 0)return E.warn(`[palbase] ${t}: the database connection ${n==="lost"?"was lost":"could not be opened"}`,{error:e}),{status:503,code:"database_unavailable",message:"The database is temporarily unavailable",data:{retrySafe:n==="never"},retryAfter:1}}function Xo(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return Ir(e)?t(e.message):at(e)&&!Tn(e)&&!kn(e)?t(e.errorDescription):kn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function kn(e){return e instanceof gt||e instanceof ce&&ks.has(e.status)||ws(e)!==void 0||at(e)&&e.status===503&&Tn(e)}async function wn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,Fo).map(o=>({field:(o.path??[]).map(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 ie(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function ut(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new ie(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let r=e.body.getReader(),s=[],a=0;for(;;){let{done:u,value:m}=await r.read();if(u)break;if(a+=m.byteLength,a>t)throw await r.cancel().catch(()=>{}),new ie(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(m)}let o=new Uint8Array(a),i=0;for(let u of s)o.set(u,i),i+=u.byteLength;return o}function ei(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return le(t)}function ti(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 ni(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 ri=/^[A-Za-z0-9._:-]{8,128}$/,si=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,ai={max:20,window:60},oi=10*6e4,ii=1e4,lt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},vn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=bs("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,i;if(!a){let m=this.limiter.reserve(o,ai);if("wait"in m)throw new lt(m.wait);i=m}let u=await r();if(!u)throw this.known.delete(s),new ht("unknown_token","The token is not one of the app's");return i&&this.limiter.give(o,i.window),this.known.delete(s),this.known.set(s,this.now()+oi),this.known.size>ii&&this.known.delete(this.known.keys().next().value),u}};function Ec(e){let t=new Et(e.modules),n=us(t.controllers.map(d=>d.cls)),r=new Map(n.map(d=>[d,Vo(d,e.auth)]));for(let[d,c]of r){if(!c.required&&d.params.some(f=>f.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&&c.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 c of d.params)c.kind==="resolve"&&s.set(c,t.dependencyOf(d.controller,c.resolver,`${d.id} @Resolve(${c.resolver?.name})`));let a=new Map;for(let d of t.cronProviders){let c=t.get(d),f=D(d,ke),l=a.get(f.name);if(l)throw new TypeError(`@Cron "${f.name}" is ${l.owner} and ${d.name}: a cron's name is its own \u2014 name one of them`);a.set(f.name,{declaration:f,owner:d.name,run:h=>c.run(h)})}let o=new Map;for(let d of t.taskProviders){let c=t.get(d),f=D(d,ye),l=o.get(f.name);if(l)throw new TypeError(`@Task "${f.name}" is ${l.owner} and ${d.name}: a task type's name is its own \u2014 name one of them`);o.set(f.name,{declaration:f,owner:d.name,run:(h,p)=>c.run(h,p)})}let i=new Map;for(let d of t.templateProviders){let c=t.get(d),f=D(d,we),l=i.get(f.name);if(l)throw new TypeError(`@TestUserTemplate "${f.name}" is ${l.owner} and ${d.name}: a template's name is its own \u2014 name one of them`);i.set(f.name,{owner:d.name,seed:(h,p)=>c.seed(h,p),...typeof c.undo=="function"?{undo:(h,p)=>c.undo(h,p)}:{}})}i.size>0&&!e.platform&&E.info(`[palbase] ${i.size} @TestUserTemplate(s): the platform calls a machine for its test users; nothing does here`);let u=new Map,m=new Set,g=new Set,k=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(a.size>ls)throw new TypeError(`${a.size} @Cron classes: a machine runs ${ls} crons at most`);if(o.size>fs)throw new TypeError(`${o.size} @Task classes: a machine runs ${fs} task types at most`);a.size>0&&!e.platform&&E.info(`[palbase] ${a.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let S=wr(t.gateways.map(d=>({cls:d,instance:t.get(d)})),{run:(d,c,f,l)=>ae.run({requestId:ae.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>Ze(e.database,e.database?d?.id?bn(e.database.requests,Tt(d)):ct:void 0,f,c,async()=>{let h=await l();if(f?.aborted)throw new Error(`realtime gave up on ${c} before it ended`);return h})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),revalidate:d=>e.server.realtime.revalidate({body:d}),isOutage:kn});S.declarations.length>0&&!e.platform&&E.info(`[palbase] ${S.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let I=zr();(I.tools.size>0||I.agents.size>0)&&!e.platform&&E.info(`[palbase] ${I.tools.size} ai.tool(s) and ${I.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let H=d=>c=>t.provider(c,`${d} ctx.inject(${typeof c=="function"?c.name:String(c)})`),z=new _t,te=new St(e.now??Date.now),ee=new Set,se=e.database!==void 0||e.contractOnly?.database===!0;if(se){for(let d of n)if(ot(d)&&d.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&ns(c.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 v=e.database?new Rt(e.database.app,e.database.keptAnswers):void 0,Q=hi(e.cors),w=e.now??Date.now,_=new Mt(e.now),b=new vn(_,e.now??Date.now),x=e.maxBodyBytes??Ko,P=d=>{let c=d.meta.options.rateLimit??e.rateLimit??Bo;return c!==!1&&c.max>0&&c.window>0?c:!1},N=e.env??process.env,K=Er(t.webhooks,d=>t.get(d),N,{secrets:e.contractOnly===void 0}),B=K.size===0&&a.size===0&&o.size===0&&i.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(N).filter(d=>typeof d[1]=="string"&&!In(d[0])))),G=new Map([...K.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),U=new Map([...K.keys()].map(d=>[d,{counts:new Map,at:void 0}])),W,V=()=>W??=cs(n,d=>({auth:r.get(d),limit:P(d)}),{databaseSeesCaller:se,idempotency:se,webhooks:[...K.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...Y.keys()],gateways:S.declarations,platformEventBuckets:ci(Y),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),Y=new Map;for(let[d,c]of Object.entries(e.events??{}))Y.set(d,c.map(f=>({name:`palbase(${d})`,call:l=>f(l)})));for(let d of t.eventProviders){let c=t.get(d);for(let{event:f,fn:l,bucket:h}of D(d,Se)??[]){if(!Jn.test(f))throw new TypeError(`@On("${f}") on ${d.name}.${l}: a platform event's type is dotted lowercase words, like user.deleted \u2014 a third party's event is taken by an @On in its @Webhook class`);Y.has(f)||Y.set(f,[]),Y.get(f).push({name:`${d.name}.${l}`,bucket:h,call:async(p,y)=>c[l](p,y)})}}let ne=new Set,Qe=new Set;zn(e.server),Hn({to:(d,c)=>({emit:(f,l)=>S.emit(d,c,f,l),pipe:f=>S.pipe(d,c,f),revalidate:f=>S.revalidate(d,c,f)})}),Vn(e.platform?Zn(N.PALBASE_MACHINE):new kt(new Map([...o].map(([d,c])=>[d,c.declaration])),(d,c)=>_n(d,c),e.now));async function ft(d,c){let f;try{f=await Un(d,e.webhookSecret,{now:e.now})}catch(l){if(l instanceof et)return T({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${l.code}`},c);throw l}if(le(f.data),ne.has(f.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(Qe.has(f.id))return T({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);Qe.add(f.id);try{let l;try{await qe(e.database,null,void 0,`event ${f.type}`,async()=>{for(let h of Y.get(f.type)??[])if(!(h.bucket!==void 0&&di(f)!==h.bucket))try{await h.call(f,{requestId:c})}catch(p){throw l=h.name,p}})}catch(h){return E.error(`[palbase] ${l??"the delivery"} failed on ${f.type} ${f.id}; the platform delivers it again`,{error:h}),T({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return ne.add(f.id),ne.size>Ve&&ne.delete(ne.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{Qe.delete(f.id)}}async function Ye(d,c={}){let f=d.headers.get("origin");if(Q&&f!==null){let l=Q.allows(f);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return l?new Response(null,{status:204,headers:Q.preflight(f,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let h=await An(d,c);if(l)for(let[p,y]of Object.entries(Q.headers(f)))p==="vary"?Nt(h.headers,y):h.headers.set(p,y);else Nt(h.headers,"Origin");return h}return An(d,c)}async function Lt(d,c,f,l){if(!d.headers.get(f.scheme.header))return be(f,"missing_signature",l);let h={headers:d.headers,body:await ut(d,f.scheme.maxBytes(x)),url:Sr(d,c)},p;try{p=f.scheme.check(h,w()/1e3)}catch{return be(f,"signature_mismatch",l,"check_failed")}if(typeof p=="string")return be(f,p,l);let y=f.events.get(p.type);if(!y)return E.info(`[palbase] webhook ${f.name}: no @On takes "${p.type}"; acknowledged`),me(200,{ok:!0,handled:!1},l);let $=G.get(f.name),O=p.event,j=[];if(p.id!==void 0){if($.seen.has(p.id))return me(200,{ok:!0,handled:!1,duplicate:!0},l);j=[p.id]}else if(p.ids&&Array.isArray(O)){let A=p.ids,R=O.map((M,Z)=>[M,A[Z]]).filter(([,M])=>M===void 0||!$.seen.has(M));if(R.length===0)return me(200,{ok:!0,handled:!1,duplicate:!0},l);O=R.map(([M])=>M),j=R.flatMap(([,M])=>M===void 0?[]:[M])}if(j.some(A=>$.inflight.has(A)))return T({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},l);le(O);for(let A of j)$.inflight.add(A);let C;try{C=await qe(e.database,null,void 0,`webhook ${f.name}`,()=>y.call(O,{env:B,requestId:l,environmentId:e.projectId??""}))}catch(A){let R=Ut(A,`webhook ${f.name}`)??ui(A,f.name);return R?T(R,l):(E.error(`[palbase] ${y.name} failed on ${f.name} "${p.type}"; the sender delivers it again`,{error:A}),T({status:500,code:"handler_failed",message:"The event could not be handled"},l))}finally{for(let A of j)$.inflight.delete(A)}for(let A of j)$.seen.add(A),$.seen.size>Ve&&$.seen.delete($.seen.values().next().value);return X(C,f,l)}function X(d,c,f){if(d instanceof Response)return d;if(typeof d=="string"){let l=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(d,{status:200,headers:{"content-type":l,"x-request-id":f}})}return me(200,d??{ok:!0,handled:!0},f)}function be(d,c,f,l=c){let h=U.get(d.name);h.counts.set(l,(h.counts.get(l)??0)+1);let p=w();return(h.at===void 0||p-h.at>=Wo)&&(Ee(d.name),h.at=p),T({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},f)}function Ee(d){let c=U.get(d).counts;if(c.size===0)return;let f=[...c.values()].reduce((l,h)=>l+h,0);E.warn(`[palbase] webhook ${d}: ${f} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function pt(d){let c=d.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?K.get(c[1]):void 0}async function $s(d,c,f,l){let h=c.pathname===Je;if(d.method!==(h?"GET":"POST"))return T({status:405,code:"method_not_allowed",message:h?"The crons are listed with GET":"A cron is run with POST"},l);let p=h?new Uint8Array(0):await ut(d,qo);try{await mt({secret:f,signature:d.headers.get("palbase-signature"),body:p,now:e.now})}catch(L){if(L instanceof et)return T({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${L.code}`},l);throw L}if(h){let L=[...a.values()].map(({declaration:q})=>({name:q.name,schedule:q.schedule,time_zone:q.timeZone,timeout:q.timeout,retry:q.retries}));return me(200,{crons:L},l,{"cache-control":"no-store"})}let y=c.pathname.slice(Je.length+1),$=a.get(y);if(!$)return T({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(y)}`},l);let O;try{O=JSON.parse(new TextDecoder().decode(p))}catch{return T({status:400,code:"bad_request",message:"A run is the JSON {cron, run_id, scheduled_at, attempt}"},l)}let{cron:j,run_id:C,scheduled_at:A,attempt:R}=O??{};if(j!==y||typeof C!="string"||C===""||typeof A!="string"||!ps.test(A)||Number.isNaN(Date.parse(A))||!Number.isInteger(R)||R<1)return T({status:400,code:"bad_request",message:`A run of ${y} is the JSON {cron: "${y}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},l);let M=`${C}#${String(R)}`;if(g.has(M))return new Response(null,{status:204,headers:{"x-request-id":l}});if(k.has(M))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},l);k.add(M);let Z={env:B,environmentId:e.projectId??"",cron:y,runId:C,scheduledAt:new Date(A),attempt:R};try{await Ze(e.database,e.database?ct:void 0,d.signal,`cron ${y}`,async()=>{if(await $.run(Z),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${y} before it ended`)})}catch(L){return d.signal.aborted||E.error(`[palbase] cron ${y} failed (run ${C}, attempt ${String(R)})`,{error:L}),T({status:500,code:"cron_failed",message:`The cron ${y} failed; the platform tries it again`},l)}finally{k.delete(M)}return g.add(M),g.size>Ve&&g.delete(g.values().next().value),new Response(null,{status:204,headers:{"x-request-id":l}})}let _n=async({task:d,id:c,attempt:f,payload:l,createdAt:h},p)=>{let y=o.get(d);if(!y)return{status:404,message:`this version has no task ${JSON.stringify(d)}`};let $=le(l??null),O=y.declaration.payload;if(O){let C=await O["~standard"].validate($);if(C.issues){let A=C.issues.slice(0,5).map(R=>`${(R.path??[]).map(M=>String(typeof M=="object"&&M!==null&&"key"in M?M.key:M)).join(".")||"(payload)"}: ${R.message}`).join("; ");return E.error(`[palbase] task ${d} ${c}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${A}`),{status:422,message:`what it carries is not what @Task "${d}" takes: ${A}`}}$=C.value}let j={env:B,environmentId:e.projectId??"",task:d,id:c,attempt:f,createdAt:h};try{await Ze(e.database,e.database?ct:void 0,p,`task ${d}`,async()=>{if(await y.run($,j),p.aborted)throw new Error(`the platform gave up on this attempt of ${d} before it ended`)})}catch(C){return C instanceof bt?(E.error(`[palbase] task ${d} ${c} can never be done: ${C.message}`),{status:422,message:C.message}):(p.aborted||E.error(`[palbase] task ${d} failed (task ${c}, attempt ${String(f)})`,{error:C}),{status:500,message:`the task ${d} failed; it is tried again`})}return{status:204}};async function Es(d,c,f,l){let h=c.pathname===We;if(d.method!==(h?"GET":"POST"))return T({status:405,code:"method_not_allowed",message:h?"The task types are listed with GET":"A task is run with POST"},l);let p=h?new Uint8Array(0):await ut(d,Jo);try{await mt({secret:f,signature:d.headers.get("palbase-signature"),body:p,now:e.now})}catch(L){if(L instanceof et)return T({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${L.code}`},l);throw L}if(h){let L=[...o.values()].map(({declaration:q})=>({name:q.name,timeout:q.timeout,retry:q.retries,concurrency:q.concurrency}));return me(200,{tasks:L},l,{"cache-control":"no-store"})}let y=c.pathname.slice(We.length+1),$;try{$=JSON.parse(new TextDecoder().decode(p))}catch{return T({status:400,code:"bad_request",message:"A task is the JSON {task, id, attempt, payload, created_at}"},l)}let{task:O,id:j,attempt:C,payload:A,created_at:R}=$??{};if(O!==y||typeof j!="string"||j===""||typeof R!="string"||!ps.test(R)||Number.isNaN(Date.parse(R))||!Number.isInteger(C)||C<1)return T({status:400,code:"bad_request",message:`A task of ${y} is the JSON {task: "${y}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},l);let M=`task:${j}#${String(C)}`;if(g.has(M))return new Response(null,{status:204,headers:{"x-request-id":l}});if(k.has(M))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},l);k.add(M);let Z;try{Z=await _n({task:y,id:j,attempt:C,payload:A,createdAt:new Date(R)},d.signal)}finally{k.delete(M)}return Z.status===404?T({status:404,code:"task_not_found",message:Z.message??""},l):Z.status===422?T({status:422,code:"task_failure",message:Z.message??""},l):Z.status>=300?T({status:Z.status,code:"task_failed",message:Z.message??""},l):(g.add(M),g.size>Ve&&g.delete(g.values().next().value),new Response(null,{status:204,headers:{"x-request-id":l}}))}async function Re(d,c,f,l){if(d.method!=="POST")return T({status:405,code:"method_not_allowed",message:`${l} is POSTed`},f);let h;try{Nn({signature:d.headers.get("palbase-signature"),now:e.now}),h=await ut(d,1048576),await mt({secret:c,signature:d.headers.get("palbase-signature"),body:h,now:e.now})}catch(y){if(y instanceof et)return T({status:401,code:"invalid_signature",message:`${l} is the platform's to call: ${y.code}`},f);throw y}let p;try{p=JSON.parse(new TextDecoder().decode(h))}catch{return T({status:400,code:"bad_request",message:`${l} is JSON`},f)}return typeof p!="object"||p===null||!Object.hasOwn(p,"call")||p.call!==new URL(d.url).pathname?T({status:401,code:"invalid_signature",message:`${l} is the platform's to call: signed_for_another_call`},f):{body:p}}async function Ss(d,c,f,l,h){let p=await Re(c,f,l,`An upload's ${d}`);if(p instanceof Response)return p;let y=ir(d,p.body);if(typeof y=="string")return T({status:400,code:"bad_request",message:`An upload's ${d}: ${y}`},l);if(d==="complete"){if(ee.has(y.uploadId))return T({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},l);ee.add(y.uploadId),ee.size>Ve&&ee.delete(ee.values().next().value)}let $=yn(n,y.method,y.route);if(!$||"malformed"in $||!$.route.meta.upload)return T({status:404,code:"not_found",message:`No upload route for ${y.method} ${y.route}`},l);let{route:O,params:j}=$,C=$.route.meta.upload,A=ni(y.user);if(A&&Pn(h,A.id),r.get(O).required&&!A)throw new ie(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let Z=P(O);if(Z!==!1){let q=_.take(`${O.id}\0${nr(y.user,y.client)}`,Z);if(q!==void 0)throw new ie(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:q},q)}let L=ar(C.pathTemplate,{userId:A?.id??null,uploadId:y.uploadId,filename:y.filename});if("problem"in L)throw new ie(400,"bad_request",L.problem);return await qe(e.database,Tt(y.user),c.signal,O.id,async()=>{let q={request:c,query:new URLSearchParams(y.query),params:j,user:A,body:y.body===void 0||y.body===null?{}:le(y.body),requestId:l};await Rn(O,q);for(let Ae of O.params)(Ae.kind==="query"||Ae.kind==="body"&&y.body!==void 0)&&await ys(Ae,q)}),me(200,{bucket:C.bucket,path:L.path},l)}h.endpoint=O.id.slice(O.id.indexOf(" ")+1);let R=new URLSearchParams(y.query),M=y.body===null||y.body===void 0?{}:le(y.body);return It(O,{request:c,query:R,params:j,user:A,body:M,requestId:l,uploadedObject:le(y.uploadedObject)},Tt(y.user))}async function _s(d,c,f,l){let h=c.pathname.slice(vt.length+1),p=h.endsWith("/undo"),y=p?h.slice(0,-5):h,$=await Re(d,f,l,"A test user template");if($ instanceof Response)return $;let O=i.get(y);if(!O||p&&!O.undo)return T({status:404,code:"template_not_found",message:O?`@TestUserTemplate "${y}" has no undo: the user's deletion cleans up after it`:`This version has no test user template ${JSON.stringify(y)}`},l);let j=Qn(y,$.body);if(typeof j=="string")return T({status:400,code:"bad_request",message:`A test user template's call: ${j}`},l);let C=le(j.user),A;try{A=await Yn(e.server,C.id)}catch(L){return E.error(`[palbase] test user template ${y}: auth could not say whether ${C.id} is a test user; nothing was written`,{error:L}),T({status:503,code:"auth_unavailable",message:"Auth could not say whether the user is a test user: the template did not run",retryAfter:5},l)}if(!A)return E.warn(`[palbase] test user template ${y}${p?" undo":""}: auth does not say ${C.id} is a test user \u2014 nothing was run`),T({status:403,code:"not_a_test_user",message:"Auth does not say this user is a test user: a template writes for test users alone"},l);let R=`${C.id}\0${y}`;if(m.has(R))return T({status:409,code:"in_progress",message:`The template ${y} is being written for this user`,retryAfter:5},l);if(!p&&u.has(R))return me(200,{rows:u.get(R)},l);m.add(R);let M={env:B,environmentId:e.projectId??"",template:y},Z=`test user template ${y}${p?" undo":""}`;try{let L={};return await Ze(e.database,e.database?ct:void 0,d.signal,Z,async()=>{if(p?await O.undo(C,M):(await O.seed(C,M),L=await Xn(ae.getStore()?.database)),d.signal.aborted)throw new Error(`the platform gave up on ${Z} before it ended`)}),p?(u.delete(R),new Response(null,{status:204,headers:{"x-request-id":l}})):(u.set(R,L),u.size>Ve&&u.delete(u.keys().next().value),me(200,{rows:L},l))}catch(L){d.signal.aborted||E.error(`[palbase] ${Z} failed for ${C.id}: nothing of it was kept`,{error:L});let q=L instanceof Error&&L.message!==""?`: ${L.message.replace(/\s+/g," ").slice(0,300)}`:"";return T({status:500,code:p?"undo_failed":"template_failed",message:`${p?"The undo of":"The template"} ${y} failed${q}; nothing of it was kept`},l)}finally{m.delete(R)}}function xn(d,c,f,l){let h=d?{sub:d.id,role:"authenticated"}:null;return ae.run({requestId:ae.getStore()?.requestId??"",...d?{userId:d.id}:{}},()=>qe(e.database,h,f,c,async()=>{let p=await l();if(f.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return p}))}let On=(d,c)=>new Response(d,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function xs(d,c,f){let l=await Re(d,c,f,"A tool call");if(l instanceof Response)return l;let h=l.body,p=h.tool;if(typeof p!="string"||p==="")return T({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},f);let y=I.tools.get(p);if(!y)return T({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(p.slice(0,64))}`},f);let $=h.call_id,O=Kr(h.context);if(typeof $!="string"||$===""||$.length>256||typeof O=="string")return T({status:400,code:"bad_request",message:`A call of ${p} is {tool, call_id, input, context}${typeof O=="string"?`: ${O}`:""}`},f);let j=bs("sha256").update(JSON.stringify(h)).digest("hex"),C=z.answered($);if(C!==void 0)return C.digest!==j?T({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},f):On(C.answer,f);if(z.isRunning($))return T({status:409,code:"in_progress",message:"This call is running",retryAfter:2},f);z.start($);let A;try{let R=await xn(O.user,`ai.tool ${p}`,d.signal,()=>y.call(le(h.input??{}),{...O,callId:$,signal:d.signal,inject:H(`ai.tool ${p}`)}));A="deferred"in R?JSON.stringify({deferred:!0,...R.expires_in_seconds!==void 0?{expires_in_seconds:R.expires_in_seconds}:{}}):JSON.stringify({output:R.output,is_error:R.is_error});let M=new TextEncoder().encode(A).byteLength;M>Fe&&(E.error(`[palbase] ai.tool ${p} answered ${M} bytes (call ${$}): a machine's answer is ${Fe} at most; the agent is told it failed`),A=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${Fe/(1<<20)} MiB it may be`}],is_error:!0}))}catch(R){if(d.signal.aborted)return z.end($,void 0),T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);E.error(`[palbase] ai.tool ${p} failed (call ${$}, chat ${O.chatId}); the agent is told`,{error:R}),A=JSON.stringify({output:[{type:"text",text:Xo(R)}],is_error:!0})}return z.end($,{digest:j,answer:A}),On(A,f)}async function Os(d,c,f){let l=await Re(d,c,f,"An agent's turn");if(l instanceof Response)return l;let h=Fr(l.body);if(typeof h=="string"||h.agent==="")return T({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata, message}${typeof h=="string"?`: ${h}`:": agent names it"}`},f);let p=h.agent,y=I.agents.get(p);if(!y)return T({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(p.slice(0,64))}`},f);let $;try{$=await xn(h.user,`ai.agent ${p}`,d.signal,()=>y.resolve({...h,signal:d.signal,inject:H(`ai.agent ${p}`)}))}catch(C){if(d.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let A=Ut(C,`ai.agent ${p}`);return A?T(A,f):(E.error(`[palbase] ai.agent ${p} failed for chat ${h.chatId}; the turn is not started`,{error:C}),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},f))}let O=$.tools.find(C=>I.tools.get(C.name)!==C);if(O)return E.error(`[palbase] ai.agent ${p} handed out ai.tool ${JSON.stringify(O.name)}, which this app did not declare when it was made \u2014 make each ai.tool once, at a module's top level, and hand that one out`),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},f);let j=JSON.stringify($.definition);return new TextEncoder().encode(j).byteLength>Fe?(E.error(`[palbase] ai.agent ${p}'s definition is larger than the ${Fe} bytes a machine's answer may be`),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},f)):new Response(j,{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function Rs(d,c,f){let l=await Re(d,c,f,"A repository's token");if(l instanceof Response)return l;let h=l.body;if(typeof h.repo!="string"||h.repo===""||typeof h.repository!="string"||typeof h.call_id!="string"||h.call_id===""||h.call_id.length>256)return T({status:400,code:"bad_request",message:"A repository's token is asked as {call_id, repo, repository}"},f);if(!te.take(h.call_id))return T({status:409,code:"call_id_reused",message:"This token ask was answered already"},f);let p=I.repos.get(h.repo),y=p?O=>p.token(O):I.repoTokens;if(!y)return T({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(h.repo.slice(0,64))}, and no ai.repoTokens`},f);let $;try{$=await Ze(e.database,e.database?ct:void 0,d.signal,`ai.repo ${h.repo}`,async()=>y({repo:h.repo,repository:h.repository,signal:d.signal,inject:H(p?`ai.repo ${h.repo}`:`ai.repoTokens for ${h.repo}`)}))}catch(O){if(d.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let j=Ut(O,`ai.repo ${h.repo}`);return j?T(j,f):(E.error(`[palbase] ai.repo ${h.repo} gave no token; the workspace's clone or push is refused`,{error:O}),T({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},f))}return!p&&$==null?T({status:404,code:"repo_not_found",message:`ai.repoTokens gives no token for ${JSON.stringify(h.repo.slice(0,64))}`},f):typeof $!="string"||$.trim()===""?(E.error(`[palbase] ai.repo ${h.repo}'s token function answered no token`),T({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},f)):new Response(JSON.stringify({token:$}),{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function As(d,c,f,l){let h=await Re(c,f,l,`A gateway's ${d}`);if(h instanceof Response)return h;let p=await S.serve(d,h.body,c.signal);return"code"in p?T({status:p.status,code:p.code,message:p.message,retryAfter:p.retryAfter},l):"body"in p?me(200,p.body,l):new Response(null,{status:204,headers:{"x-request-id":l}})}async function Rn(d,c){let f=[],l={params:Object.freeze({...c.params}),user:le(c.user),headers:d.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let h of d.params)h.kind==="resolve"&&(f[h.index]=await s.get(h).resolve(l,h.options));return f}async function It(d,c,f,l){let h=t.get(d.controller),p=await qe(e.database,f,c.request.signal,d.id,async()=>{let y=await Rn(d,c);for(let O of d.params)O.kind!=="resolve"&&(y[O.index]=await ys(O,c));l?.ran();let $=await h[d.fn](...y);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return l?l.record(ms(gs($,c.requestId),ae.getStore()?.usedLocales)):$});return l?p:ms(gs(p,c.requestId),ae.getStore()?.usedLocales)}async function An(d,c){let f=d.headers.get("x-request-id")??"",l=ri.test(f)?f:`req_${crypto.randomUUID()}`,h=performance.now(),p=new URL(d.url).pathname,y={endpoint:p},$=await Ps(d,c,l,y);return e.telemetry?.record({requestId:l,method:d.method,endpoint:y.endpoint,path:p,status:$.status,durationMs:performance.now()-h,userId:y.userId}),$}function Pn(d,c){d.userId=c;let f=ae.getStore();f&&(f.userId=c)}async function Ps(d,c,f,l){let h=e.strings,p=h?{requestId:f,strings:h,locales:Gn(d.headers.get("accept-language"),h.source),usedLocales:[]}:{requestId:f},y=await Cs(p,d,c,f,l);return h&&Nt(y.headers,"Accept-Language"),y}async function Cs(d,c,f,l,h){return ae.run(d,async()=>{let p=new URL(c.url),y=`${c.method} ${p.pathname}`;try{if(p.pathname===pn&&Y.size>0)return c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):e.webhookSecret?await ft(c,l):T({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},l);let $=pt(p.pathname);if($)return y=`webhook ${$.name}`,c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):await Lt(c,p,$,l);if(e.platform&&(p.pathname===Je||p.pathname.startsWith(`${Je}/`)))return y=p.pathname===Je?"crons":`cron ${p.pathname.slice(Je.length+1)}`,await $s(c,p,e.platform.secret,l);if(e.platform&&(p.pathname===We||p.pathname.startsWith(`${We}/`)))return y=p.pathname===We?"tasks":`task ${p.pathname.slice(We.length+1)}`,await Es(c,p,e.platform.secret,l);if(e.platform&&(p.pathname===Qt||p.pathname===er)){let F=p.pathname===Qt?"authorize":"complete";return y=`upload ${F}`,await Ss(F,c,e.platform.secret,l,h)}if(e.platform&&p.pathname.startsWith(`${Yt}/`)){let F=p.pathname.slice(Yt.length+1);return y=`gateway ${F}`,await As(F,c,e.platform.secret,l)}if(e.platform&&p.pathname===Nr)return y="ai tool call",await xs(c,e.platform.secret,l);if(e.platform&&p.pathname===Ur)return y="ai agent's turn",await Os(c,e.platform.secret,l);if(e.platform&&p.pathname===Lr)return y="ai repository's token",await Rs(c,e.platform.secret,l);if(e.platform&&p.pathname.startsWith(`${vt}/`))return y=`test user template ${p.pathname.slice(vt.length+1)}`,await _s(c,p,e.platform.secret,l);if(li(p.pathname))return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},l);let O=yn(n,c.method,p.pathname);if(O&&"malformed"in O)return T({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},l);if(!O)return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},l);let{route:j,params:C}=O;if(y=j.id,h.endpoint=j.id.slice(j.id.indexOf(" ")+1),j.meta.upload)throw new ie(400,"upload_required",`${j.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let A=r.get(j),R=null,M=null,Z=c.headers.get("authorization")??"",L=/^(bearer|dpop)\s+(\S+)$/i.exec(Z),q=L?.[2],Ae=L?.[1].toLowerCase()==="dpop";if(q)try{let F=!Ae&&e.tokens&&!si.test(q)&&e.tokens.accepts(q)?e.tokens:void 0,Pe=F?await b.ask(q,Dt(c.headers,f.remoteAddress),()=>qe(e.database,null,c.signal,"token",()=>F.resolve(q))):await e.verifier.verify(q,Ae?{proof:c.headers.get("dpop"),method:c.method,url:Ln(c.headers,p)}:void 0);R=ti(Pe),M=Pe.claims}catch(F){if(!A.required&&(F instanceof ht||F instanceof gt||F instanceof lt))R=null;else throw F instanceof lt?new ie(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:F.wait},F.wait):F instanceof ht?new ie(401,"invalid_token","The access token is not valid",{reason:F.reason},void 0,Zo(F.reason)):F}else if(Z!==""&&A.required)throw new ie(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(R&&Pn(h,R.id),A.required&&!R)throw new ie(401,"unauthorized","This route needs a signed-in user");if(A.verifiedEmail&&!R?.emailVerified)throw new ie(403,"email_not_verified","This route needs a verified email address");let Cn=P(j);if(Cn!==!1){let F=R?`u:${R.id}`:`a:${Dt(c.headers,f.remoteAddress)}`,Pe=_.take(`${j.id}\0${F}`,Cn);if(Pe!==void 0)throw new ie(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Pe},Pe)}let Xe=c.method==="GET"||c.method==="HEAD"?void 0:await ut(c,x),js=Xe===void 0?void 0:ei(Xe),jn={request:c,query:p.searchParams,params:C,user:R,body:js,raw:Xe,requestId:l},Mn=v&&Xe!==void 0&&ot(j)?es(c.method,c.headers):void 0;if(!v||Mn===void 0)return await It(j,jn,M);let Ms={role:bn(e.database.requests,M).role,uid:R?.id??`a:${Dt(c.headers,f.remoteAddress)}`},Dn=!1;return await v.serve({key:Mn,caller:Ms,method:c.method,uri:`${p.pathname}${p.search}`,body:Xe},F=>It(j,jn,M,{record:F,ran:()=>{Dn=!0}}),{requestId:l,refusal:F=>T(F,l),failure:F=>hs(F,l,y,c.signal),ran:()=>Dn})}catch($){return hs($,l,y,c.signal)}})}return{handle:Ye,routes:n.map(d=>d.id),contract:V,start:()=>t.start(),stop:async()=>{S.close();for(let d of U.keys())Ee(d);await t.shutdown(),await e.telemetry?.flush()}}}function di(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function ci(e){let t=new Set;for(let[n,r]of e)if(qt(n))for(let s of r){if(s.bucket===void 0)return;t.add(s.bucket)}return t.size===0?void 0:[...t].sort()}function gs(e,t){return e instanceof Response?Yo(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):me(200,e,t)}function ui(e,t){if(!(!at(e)||e.status!==503||!Tn(e)))return E.warn(`[palbase] webhook ${t}: the database did not answer (${e.error})`,{error:e}),{status:503,code:e.error,message:e.errorDescription,data:e.data,retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))}}function li(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return De.has(decodeURIComponent(t))}catch{return De.has(t)}}var fi="GET, POST, PUT, PATCH, DELETE, QUERY",pi=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function mi(e){return pi.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function hi(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!mi(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":fi,"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 ys(e,t){switch(e.kind){case"body":return wn(e.schema,t.body??{},"Request body");case"query":return wn(e.schema,le(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),le(n),e.schema?wn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return le(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"client":{let n=t.request.headers;return le({sdkVersion:n.get("x-palbase-sdk-version"),appVersion:n.get("x-palbase-client-version"),platform:n.get("x-platform"),osVersion:n.get("x-os-version")})}}}var En=720*3600;function $n(e){return e instanceof ce&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function vs(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),En)}function Ts(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Sn=class{filling=new Map;async get(t){try{let n=await ge.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!$n(n))throw n;return E.warn("cache: a read could not reach the cache; it is a miss",{key:t,status:n.status}),null}}async set(t,n,r){try{await ge.cache.putCacheEntry({query:{key:t},body:{value:Ts(n),ttl:vs(r)}})}catch(s){if(!$n(s))throw s;E.warn("cache: a write could not reach the cache; it is let go",{key:t,status:s.status})}}async del(t){await ge.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await ge.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,n,r){let s=this.filling.get(t);if(s)return s;let a=(async()=>{try{let o;try{o=(await ge.cache.getCacheEntry({query:{key:t}})).data}catch(u){if(!$n(u))throw u;E.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:u.status})}if(o?.found)return o.value??null;let i=await r();return await this.set(t,i,n),i}finally{this.filling.delete(t)}})();return this.filling.set(t,a),a}},Oc=yt("Cache",new Sn);function Rc(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=m=>{let g=r.get(m);if(g&&g.expiresAt<=n()){r.delete(m);return}return g},o=()=>{let m=n();for(let[k,S]of r)S.expiresAt<=m&&r.delete(k);if(r.size<t)return;let g=[...r.entries()].sort((k,S)=>k[1].expiresAt-S[1].expiresAt);for(let[k]of g.slice(0,Math.ceil(g.length/4)))r.delete(k)},i=async(m,g,k)=>{r.size>=t&&!r.has(m)&&o(),r.set(m,{value:Ts(g),expiresAt:n()+(vs(k)??En)*1e3})};return{get:async m=>{let g=a(m);return g?structuredClone(g.value):null},set:i,async del(m){r.delete(m)},async incr(m){let g=a(m),k=(typeof g?.value=="number"&&Number.isInteger(g.value)?g.value:0)+1;return r.set(m,{value:k,expiresAt:g?.expiresAt??n()+En*1e3}),k},getOrSet(m,g,k){let S=a(m);if(S)return Promise.resolve(structuredClone(S.value));let I=s.get(m);if(I)return I;let H=(async()=>{try{let z=await k();return await i(m,z,g),z}finally{s.delete(m)}})();return s.set(m,H),H}}}export{Ft as a,Se as b,Me as c,bi as d,ki as e,vi as f,Ti as g,$i as h,Ei as i,Si as j,_i as k,xi as l,Oi as m,Ri as n,Ai as o,Pi as p,Ci as q,ji as r,Mi as s,Di as t,Ni as u,Ui as v,Li as w,Ii as x,zi as y,Hi as z,D as A,Gi as B,Ki as C,bt as D,Wi as E,Vi as F,Xi as G,sd as H,ad as I,ta as J,cr as K,ld as L,fd as M,pd as N,md as O,hd as P,gd as Q,yd as R,vd as S,J as T,Pr as U,Cr as V,jr as W,Ka as X,Rd as Y,Cd as Z,jd as _,Md as $,Dd as aa,Nd as ba,Ud as ca,Ld as da,Id as ea,Wd as fa,Ko as ga,Ec as ha,mi as ia,En as ja,Oc as ka,Rc as la};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.10.2 — Palbase SDK License (see LICENSE) */
2
- import"./MAPLN2FY.js";import{realpathSync as Ue}from"node:fs";import{resolve as de}from"node:path";import Nt from"typescript";import{existsSync as Se,readFileSync as ye}from"node:fs";import{createRequire as qe}from"node:module";import{dirname as ne,join as W,relative as Je,resolve as Te,sep as te}from"node:path";var h=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},G=new Set(["palbase/backend","@palbase/backend","palgres"]),Qe=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function he(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new h(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var We={bun:"bun-types",node:"@types/node"},Ge=qe(import.meta.url);function Ze(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=We[i],a=e.resolveTypeReferenceDirective(i,W(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=Ge.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(ye(c,"utf8"));s.push(W(ne(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function be(e,t){he(e);let n=W(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(Se(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new h(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
1
+ /*! palbase 0.11.0 — Palbase SDK License (see LICENSE) */
2
+ import"./NHNXW6EK.js";import{realpathSync as Ue}from"node:fs";import{resolve as de}from"node:path";import Nt from"typescript";import{existsSync as Se,readFileSync as ye}from"node:fs";import{createRequire as qe}from"node:module";import{dirname as ne,join as W,relative as Je,resolve as Te,sep as te}from"node:path";var h=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},G=new Set(["palbase/backend","@palbase/backend","palgres"]),Qe=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function he(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new h(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var We={bun:"bun-types",node:"@types/node"},Ge=qe(import.meta.url);function Ze(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=We[i],a=e.resolveTypeReferenceDirective(i,W(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=Ge.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(ye(c,"utf8"));s.push(W(ne(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function be(e,t){he(e);let n=W(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(Se(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new h(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
3
3
  `)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Ze(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function xe(e,t,n,r,s){he(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=Te(t);return!n.includes(`${te}node_modules${te}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+te))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function we(e,t){let n=[],r=ne(Te(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=W(r,"package.json");if(Se(o)){try{let c=JSON.parse(ye(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=ne(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function re(e,t){if($(e,t))return!1;let n=we(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):G.has(n)}function ke(e,t){if($(e,t))return!1;let n=we(e,t)??"";return G.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${Je(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function Z(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=Z(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ge(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&G.has(ge(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&G.has(ge(n,i)??""))return(i.propertyName||i.name).text;if(re(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function pe(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function H(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>pe(e,o)==="Controller"))continue;if(!s.name)throw new h(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Qe.has(pe(e,a)??""))){if(P(n,o.name)===null)throw new h(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var He=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function Xe(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ee(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=f=>{throw new h(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${f}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let f=[];for(let p of n.getSourceFiles()){if(f.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ke(e,p.fileName)||f.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!He.has(x.code)))}f.length&&u(t.formatDiagnostics(f.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
4
4
  `})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(Xe(g))return{kind:"raw"};let S=new Set,d=0;function C(f,p){if(++d>2e3||S.size>24)return u(`${p}: contract is too large; name its schema`);let x=f.flags,y=t.TypeFlags;if(x&(y.Any|y.Unknown|y.Never|y.TypeParameter))return u(`${p}: ${r.typeToString(f)}`);let me=b=>{let w=r.getPropertiesOfType(b);if(!(b.flags&y.Object)||w.length!==1||w[0].name!=="__pg"||!(w[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(b).length)return!1;let N=r.getTypeOfSymbolAtLocation(w[0],o);return(N.isUnion()?N.types:[N]).every(k=>k.flags&(y.StringLiteral|y.Undefined))};if(f.isIntersection()){let b=f.types.filter(w=>!me(w));if(b.length===1&&b.length<f.types.length)return C(b[0],p)}if(me(f))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&y.StringLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.NumberLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.BooleanLiteral)return`z.literal(${r.typeToString(f)==="true"})`;if(x&y.String)return"z.string()";if(x&y.TemplateLiteral){let b=f;if(b.types.length>8||!b.types.every(k=>k.flags&y.String))return u(`${p}: template literal requires an explicit schema`);let w=k=>k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+w(b.texts[0]);for(let k of b.texts.slice(1,-1))if(k){let ee=w(k);N+=`(?:(?!${ee})[\\s\\S])*${ee}`}return N+="[\\s\\S]*"+w(b.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&y.Number)return"z.number().finite()";if(x&y.Boolean)return"z.boolean()";if(x&y.Null)return"z.null()";if(x&y.Undefined)return"z.undefined()";if(S.has(f))return u(`${p}: recursive response`);S.add(f);try{if(f.isUnion()){if(f.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=f.types.some(M=>M.flags&y.Null),Q=f.types.some(M=>M.flags&y.Undefined),j=f.types.filter(M=>!(M.flags&(y.Null|y.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?C(j[0],p):`z.union([${j.map(M=>C(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(Q?".optional()":"")}if(r.isTupleType(f))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(f)){let A=r.getTypeArguments(f)[0];return A.flags&y.Never?"z.array(z.string()).length(0)":`z.array(${C(A,`${p}[]`)})`}let b=f.isIntersection()&&f.types.every(A=>A.flags&y.Object);if(!(x&y.Object)&&!b||f.getCallSignatures().length||f.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(f)}`);let w=f.symbol?.declarations?.[0];if(w&&(t.isClassDeclaration(w)||t.isClassExpression(w)))return u(`${p}: class instance ${r.typeToString(f)}`);let N=r.getPropertiesOfType(f),k=r.getIndexInfosOfType(f);return k.length?k.length!==1||!(k[0].keyType.flags&y.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${C(k[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let Q=A.getName(),j=C(r.getTypeOfSymbolAtLocation(A,o),`${p}.${Q}`);return`${JSON.stringify(Q)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{S.delete(f)}}return{kind:"expression",expression:C(g,"return")}}}import{resolve as Ye}from"node:path";var se=Symbol("not a named schema");function Ce(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=d=>new h(`${i.fileName} \u2014 ${n}.${o}: ${d}`);function c(d){if(s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Promise"&&d.typeArguments&&d.typeArguments.length===1)return c(d.typeArguments[0]);if(d.kind===s.SyntaxKind.VoidKeyword||d.kind===s.SyntaxKind.UndefinedKeyword)return null;let C=s.isArrayTypeNode(d)?d.elementType:s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Array"&&d.typeArguments&&d.typeArguments.length===1?d.typeArguments[0]:void 0,f=l(C??d);return f===se?f:{...f,isArray:C!==void 0}}function l(d){if(s.isTypeReferenceNode(d)&&!d.typeArguments)return{typeName:d.typeName.getText(i),node:d.typeName};if(s.isTypeReferenceNode(d)&&d.typeArguments&&d.typeArguments.length===1){let C=d.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(C)){let f=d.typeArguments[0];if(s.isTypeQueryNode(f))return{typeName:f.exprName.getText(i),node:f.exprName};if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName}}}if(d.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return se}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===se)return u();let g=et(e,m.node);if(!g)return u();let S=tt(e,g.symbol);return S?{kind:"schema",...S,array:m.isArray}:u()}function et(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=Z(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function tt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>Z(e,i)===t).map(i=>i.name);return s.length===0?null:{file:Ye(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ce={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},nt=new Set(["HttpError","PalError"]),rt=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],st=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function Le(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=Ct(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function it(e,t,n){throw new h(`${O(e,t)} \u2014 ${n}`)}function U(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function ue(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Pe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function $e(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ot(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=$e(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function q(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Fe(e,t,n){for(let r=q(e,t);r;r=q(e,r))if(r===n)return!0;return!1}function V(e,t,n,r){let s=e.ts;for(let i=t;i;i=q(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||ue(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function at(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function Ne(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Pe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function Oe(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ct(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ie(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function J(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)J(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Pe(r,a)||n.add(a);for(let l of Ne(e))Fe(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of Ne(e)){let u=Oe(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function le(e,t,n){let r=ct(e,t);if(r){let s=at(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Fe(e,o,r));if(i.length===1){n.add(i[0]);return}}J(e,t,n)}function lt(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function Re(e,t){return t.fn&&lt(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function E(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(E(e,t.whenTrue,n,r)),a(E(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(E(e,t.left,n,r)),a(E(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(E(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of Y(e,t,n))for(let l of X(s,c.fn))a(E(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(E(e,c.initializer,Re(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&J(e,ie(e,c),i),i;if(c&&s.isParameter(c)){let l=ie(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?le(e,l,i):J(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(E(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):le(e,ie(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of X(s,c))a(E(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(E(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return J(e,e.checker.getTypeAtLocation(t),i),i}function X(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function ze(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function je(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function ut(e,t){let n=e.ts,r=ze(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(je(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!re(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of rt)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function ft(e,t){let n=e.checker.getSymbolAtLocation(je(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Me(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=q(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||ue(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function Y(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&q(e,n.owner);return c?Me(e,c,n.receiver):[]}let i=ze(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&q(e,n.owner),S=g&&V(e,g,i,!1);return S?[{fn:S.fn,ctx:{receiver:n.receiver,owner:S.owner,fn:S.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=V(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!ft(e,c))return[];let m=[];for(let g of E(e,l,n)){let S=V(e,g,i,!1);S&&m.push({fn:S.fn,ctx:{receiver:g,owner:S.owner,fn:S.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!ue(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function Ae(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of E(e,s.expression,n)){let l=V(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function ve(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function dt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function De(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ie(e,t,n,r,s){if(nt.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(ve(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:De(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ce,t)?ce[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!dt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return ve(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:De(c),code:c,status:i.status}))}function fe(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function Be(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&it(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function mt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ke(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(d=>d.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(d=>s.isConstructorDeclaration(d)&&!!d.body),c=n,l=r;if(a){let d=mt(s,a);if(!d)return[];c=d.arguments,l=d}let u=ot(s,t),m=I(e,o);if(m)return Ie(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let d=fe(e,g);return d?[{...Be(e,g,d),name:u||g.name.getText()}]:[]}let S=_(e,o);if(S){let d=Ke(e,S,c,l);return d.length===1&&u?[{...d[0],name:u}]:d}return[]}function gt(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ie(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=fe(e,o);if(c)return[Be(e,o,c)]}let a=$e(n,o);return a&&v(e,a)?Ke(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,gt(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of Y(e,t,n))for(let u of X(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?Re(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function oe(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function pt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function St(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function yt(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=pt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||St(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function Tt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ce))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=fe(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function ht(e,t){let n=Tt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new h(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)ht(e,o);let i=yt(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function _e(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function bt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?_e(e,n.body,r.name.text):!1:!0:!1}return!0}function xt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function ae(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,ae(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?_e(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(xt(e,o,"allSettled")){D(e,t.expression,n,r);let u=ae(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=bt(s,t.arguments[a]);D(e,u.expression,n,ae(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?st.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=ut(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of Y(e,t,n))R(e,r,t,oe(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of Ae(e,u,n))R(e,r,u,oe(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Me(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of Ae(e,a,n))R(e,r,a,oe(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of E(e,t.expression,n)){let c=V(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function Ve(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of Y(e,t,{receiver:null,owner:null,fn:null}))for(let o of X(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...Ve(e,a,n))}return s}function wt(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of Ve(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;le(e,Oe(e,c),l);for(let u of l){let m=V(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function kt(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Et(e,t,n){let r=new Map;for(let i of wt(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=kt(i.name),a=s.get(o);if(a)throw new h(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function Ct(e,t){let n=[];for(let{cls:r,routes:s}of H(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Et(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Qt(e,t,n={}){let r=n.typescript??Nt,s=Ue(de(e)),{options:i,ambient:o}=be(r,s);return At(xe(r,s,[Ue(de(t)),...o],i))}function At(e){let t=e.ts,n=Ee(e),r=Le(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=H(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ce(e,n,u.name.text,g))}catch(S){if(!(S instanceof h))throw S;o.push(S.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,S]of Object.entries(m))s.push({file:de(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:S})}if(o.length===1)throw new h(o[0]);if(o.length>1)throw new h(`${o.length} routes have no contract:
5
5
  ${o.map(a=>`- ${a}`).join(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.10.2 — Palbase SDK License (see LICENSE) */
2
- import{c as D,g as b,l as O,m as _,s as F}from"./7PBQ3LI2.js";import{b as w}from"./SCXHU5B7.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.10.2"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
1
+ /*! palbase 0.11.0 — Palbase SDK License (see LICENSE) */
2
+ import{c as D,g as b,l as O,m as _,s as F}from"./5D7BAVO5.js";import{b as w}from"./7JE4KOPN.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.11.0"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};