palbase 0.78.1 → 0.80.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 (62) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai-sdk/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/{35KQJQ77.js → 2NB7UENO.js} +2 -2
  9. package/dist/chunks/{3XF644A5.js → 5BQM5XTX.js} +2 -2
  10. package/dist/chunks/{VNUCKM7H.js → 6INSGN37.js} +1 -1
  11. package/dist/chunks/{ROV6TJZK.js → 6PUARVHY.js} +1 -1
  12. package/dist/chunks/{TFPVJ3C3.js → 7NOXAQOX.js} +2 -2
  13. package/dist/chunks/{L63FWRZX.js → 7QS5ABCT.js} +2 -2
  14. package/dist/chunks/{RB4JQXKZ.js → 7XQVUV65.js} +2 -2
  15. package/dist/chunks/{UUDOMSKW.js → BQUNZH5E.js} +2 -2
  16. package/dist/chunks/{FCCX2OTM.js → DP6WZPTF.js} +2 -2
  17. package/dist/chunks/{WTFMJKDB.js → FUNHIQCH.js} +2 -2
  18. package/dist/chunks/G4PGGIAO.js +2 -0
  19. package/dist/chunks/{LXS7JHPJ.js → IK4MB3HQ.js} +2 -2
  20. package/dist/chunks/{JY7YG3BO.js → IS5HMTJX.js} +2 -2
  21. package/dist/chunks/{2T3EX52E.js → LZXD4SBY.js} +1 -1
  22. package/dist/chunks/{6Y4ICGZ7.js → N767RMLK.js} +2 -2
  23. package/dist/chunks/{ZIHVYOXE.js → OY6JSD3B.js} +2 -2
  24. package/dist/chunks/{EUMY6SCM.js → QV53HO4D.js} +1 -1
  25. package/dist/chunks/{ZBTOHVML.js → RGCK6WN2.js} +2 -2
  26. package/dist/chunks/{QWKOKJKM.js → RU3A4ASQ.js} +1 -1
  27. package/dist/chunks/{25KG2TVU.js → T2XBJBUC.js} +1 -1
  28. package/dist/chunks/TNNTPBI3.js +23 -0
  29. package/dist/chunks/{5KGMQFET.js → TOGOOVTU.js} +1 -1
  30. package/dist/chunks/{LONPNPNX.js → UKM6LWJ3.js} +2 -2
  31. package/dist/chunks/{IO5HB5B6.js → VZQI2MW2.js} +2 -2
  32. package/dist/chunks/WUOSCBJ3.js +13 -0
  33. package/dist/cli.js +5 -4
  34. package/dist/cloud/index.js +2 -2
  35. package/dist/refuse/ai-sdk.js +1 -1
  36. package/dist/refuse/ai.js +1 -1
  37. package/dist/refuse/backend.js +1 -1
  38. package/dist/refuse/cloud.js +1 -1
  39. package/dist/refuse/server.js +1 -1
  40. package/dist/server/index.js +2 -2
  41. package/dist/server/testing.js +2 -2
  42. package/dist/web/index.js +2 -2
  43. package/dist/web/message.js +2 -2
  44. package/dist/web/palbe.js +2 -2
  45. package/dist/web/payments-ui.js +2 -2
  46. package/dist/web/paywall.js +2 -2
  47. package/dist/web/push-sw.js +1 -1
  48. package/dist/web/ssr.js +2 -2
  49. package/dist/web/vite.js +2 -2
  50. package/package.json +2 -2
  51. package/types/cloud/src/generated/project.d.ts +2 -2
  52. package/types/internal/src/chat.d.ts +17 -0
  53. package/types/internal/src/modules/ai.d.ts +48 -3
  54. package/types/internal/src/modules/commerce.d.ts +38 -12
  55. package/types/internal/src/modules/events.d.ts +2 -2
  56. package/types/internal/src/modules/iap.d.ts +112 -101
  57. package/types/internal/src/modules/payments.d.ts +828 -18
  58. package/types/web/src/chat.d.ts +4 -2
  59. package/types/web/src/iap.d.ts +6 -0
  60. package/dist/chunks/3TJFV35H.js +0 -2
  61. package/dist/chunks/426QPZNS.js +0 -13
  62. package/dist/chunks/4XE4HLPK.js +0 -23
@@ -1,5 +1,5 @@
1
- /*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
2
- import{c as gr,d as yr,e as nn,f as wr,g as br}from"./UUDOMSKW.js";import{a as Rt,c as ne,d as mr,e as hr,f as be,h as _,i as kr}from"./LONPNPNX.js";import{F as pr,a as cr,e as dt,g as St,h as ur,i as lr,j as At,k as xt,n as fr}from"./JY7YG3BO.js";import{a as Et,b as ir,n as dr}from"./25KG2TVU.js";import{b as ie}from"./35KQJQ77.js";import"reflect-metadata";var rn=[{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}],vr="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)",Ot=/^\d+$/;function ka(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function Tr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${vr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ka(t[h],rn[h].lo,rn[h].hi);if(!g)return`${vr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var Ge=new Set(["webhooks","_palbase"]);function gd(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&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function ze(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var yd=ze("GET"),wd=ze("POST"),bd=ze("PUT"),kd=ze("PATCH"),vd=ze("DELETE"),Td=ze("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(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 $d=e=>pe("body",{schema:cn("Body",e)}),_d=e=>pe("query",{schema:cn("QueryParams",e)}),Ed=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Sd=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Ad=()=>pe("user"),xd=()=>pe("optionalUser"),Rd=()=>pe("req"),Od=()=>pe("requestId"),Pd=()=>pe("client"),Cd=()=>pe("attestedDevice");function Md(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function jd(){return e=>{de(e,on,()=>!0),se().add(e)}}function Dd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Er=/^[a-z]+(\.[a-z_]+)+$/,va=/^[a-z][a-z0-9-]{1,62}$/,un=e=>e.startsWith("file.");function Nd(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"||!va.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(!un(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ta=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function $r(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(!Ta.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Ud(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.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=Tr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||$r(t.timeZone)!==void 0))throw new TypeError(`${n}: ${$r(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,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var _r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$a=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ld(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!$a.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&&!_r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${_r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&_a(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,Me)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,Be,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function _a(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 Id(){return[...se()].filter(e=>D(e,qe)!==void 0)}function qd(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.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,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Ar(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var Ea=720*3600;function Sa(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ea))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 Aa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Wd=Rt("Tasks",{async enqueue(e,t,n={}){return Sa(n),fn().enqueue(Aa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(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 xr(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 be.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 pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var xa=1e4,Ra=36e5,Sr=24*36e5,Ct=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 ie({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 ie({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 ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Sr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({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 ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(xa*2**Math.min(t.attempt-1,16),Ra),_.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>=Sr&&this.tasks.delete(s);n==="failed"&&_.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 Mt="/_palbase/test-user-templates",Oa=/^[a-z][a-z0-9_-]{0,63}$/;function Zd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Oa.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,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function Rr(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 Or(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Pa="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 Pr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Pa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Cr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Mr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ca=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Ca(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 jr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Dr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ma=/^[a-z][a-z0-9-]{1,62}$/,Nr=1024,ja=new Set(["userId","uploadId","filename"]);function tc(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`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ma.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" 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 s=Da(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function nc(){return pe("uploadedObject")}function Da(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ja.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(!Ur(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Ur(e){if(e===""||new TextEncoder().encode(e).byteLength>Nr)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 Na(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ua(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ua(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 Lr(e,t){let n=Na(e,t);return Ur(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Nr} bytes)`}}function Ir(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 wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function qr(e,t){if(!wn(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=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=jr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=La(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function La(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as Ia}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),Hr={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."},at:{type:"string",description:"When it happened, as the journal took it (a voice's end: when its record says it ended): RFC 3339 in UTC, to the microsecond, at a fixed width \u2014 2026-11-28T06:36:15.321369Z \u2014 so its text sorts as its time: kept as this text, never parsed and written again. Absent for text the channel tells ahead of the journal."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},qa={"~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?, at?, data}"}]},jsonSchema:{input:()=>structuredClone(Hr),output:()=>structuredClone(Hr)}}},Jr=Symbol.for("palbase.backend.gatewayRefusal"),Br=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,Jr,{value:!0})}},Ha=e=>typeof e=="object"&&e!==null&&e[Jr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,bn=e=>({id:e.id??"",...e.session?{session:e.session}:{}}),Ba=6e4,Ga=86400,Gr=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Fa=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(" ")),Ke=e=>new TextEncoder().encode(e).byteLength,kn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",$n=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Wa(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(Ke(e)>Se)return`a channel is ${Se} 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=za.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 Vr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} bytes at most`}function dc(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Wa(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"&&$n(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=Ka(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)||Fa.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,b]of Object.entries(d)){let k=Vr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!kn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,_n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:qa}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ba,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!We(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,je,()=>h),se().add(a)}}function Ka(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ga;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Gr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Gr} (a week)`);return n}var _n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ja={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ja[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Je,_n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var cc=ct("authorize"),uc=ct("first"),lc=ct("connect"),fc=ct("disconnect"),pc=ct("empty");function mc(e,t,n={}){let r=Vr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!kn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!kn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=de(s.constructor,Je,_n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Va(e){return D(e,je)}function Za(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 Zr(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 Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Ya(e,t,n){let r=$n(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Zr(e,t):Qa(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Qa(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 Xa=1e4,eo=1e3,to=100,En=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Wr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Yr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Va(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Wr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Wr(f.pattern),f.pattern);for(let[G,z]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([I,N])=>[`message ${I}`,N.fn])])if(typeof E[z]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${G} is ${z}, which is no method of it`);let L={cls:v,instance:E,g:f};n.set(f.pattern,L),r.set(v,L)}let o=new Map,d=new Set,l=new Set,h=new Tn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,L)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...L!==void 0?{conn_id:L}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,L,G){let z=T?.signal??AbortSignal.abort(),I=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:z,count:R,user:L,emit:(N,F)=>k(v,E,N,F,I,G),pipe:N=>B(N,E,I),owner:{hold(N){ne.exit(async()=>{try{await N(z)}catch(F){z.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:F})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Za(E,f)}}let K=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function J(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:L}=f,G={status:200,body:{subscribe:!1,publish:!1}};if(!L)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),G;let z=Fe(v.user);if(!z?.id)return G;let I=z.id;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return L[$n(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:G;let N=T.g.hooks.authorize;if(!N)return G;let F,Q;try{F=await t.run(z,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:bn(z),params:Object.freeze({...L})})),Q=no(F)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),G}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${ro(F)}, which is no grant (true, { read, write } or null); the join is refused`),G):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:vn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let L=await R.schema["~standard"].validate(Ia(v.payload??{}));if(L.issues)return{status:200,body:{ok:!1,reason:Kr(L.issues)}};let G=g(f.channel),z={...U(f.entry,f.channel,f.params,G,0,bn(T)),payload:L.value},I=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](z))}catch(Q){if(t.isOutage(Q))throw Q;return Ha(Q)?{status:200,body:{ok:!1,reason:vn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${Kr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let F;try{F=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return F===void 0?{status:200,body:{ok:!0}}:Ke(F)>zr?(_.error(`[palbase] ${I} returned an ack of ${Ke(F)} bytes, past ${zr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(F)}}}async function he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Fr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let L=T==="join"||T==="leave",G=L?Fe(v.user):void 0,z=L?v.connId:void 0;if(L&&(!G?.id||typeof z!="string"||z===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${f.channel}\0${typeof z=="string"?z:""}`;if(L&&d.has(I))return{status:204};if(l.has(I))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(I);try{let N=f.entry.g.hooks[Fr[T]],F;if(T==="empty"?(F=o.get(f.channel),b(f.channel,F)):F=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,F,R,G?bn(G):{id:""},T==="join"?z:void 0);try{await t.run(G,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return L&&(d.add(I),d.size>Xa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(I)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Zr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return En(E)?v==="authorize"?J(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:L,where:G}=ge(v,E);k(R,L,f,T,G)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let L=Ya(T.g.pattern,E??{},f);if("problem"in L)throw new TypeError(`${R}: ${L.problem}`);let G=ne.getStore()?.saying;if(G){G.push(()=>{t.revalidate(L).catch(z=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:z}))});return}await t.revalidate(L)},close(){for(let v of o.values())v.abort();o.clear()}}}function no(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!En(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 ro(e){return Array.isArray(e)?"an array":En(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 so=20,Dt=256;function Kr(e){let t="";for(let n of e.slice(0,so)){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)>=Dt)break}return vn(t,Dt)}function vn(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 Tn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=eo?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,to);try{await this.broadcast(s)}catch(o){_.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),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Sn,createHmac as ao,createPublicKey as ts,timingSafeEqual as oo,verify as ns}from"node:crypto";function wc(e){let t=D(e,Be);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 rs(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=io(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(K,J)=>k[q](K,J)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
1
+ /*! palbase 0.80.0 — Palbase SDK License (see LICENSE) */
2
+ import{c as gr,d as yr,e as nn,f as wr,g as br}from"./BQUNZH5E.js";import{a as Rt,c as ne,d as mr,e as hr,f as be,h as _,i as kr}from"./UKM6LWJ3.js";import{F as pr,a as cr,e as dt,g as St,h as ur,i as lr,j as At,k as xt,n as fr}from"./IS5HMTJX.js";import{a as Et,b as ir,n as dr}from"./T2XBJBUC.js";import{b as ie}from"./2NB7UENO.js";import"reflect-metadata";var rn=[{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}],vr="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)",Ot=/^\d+$/;function ka(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function Tr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${vr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ka(t[h],rn[h].lo,rn[h].hi);if(!g)return`${vr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var Ge=new Set(["webhooks","_palbase"]);function gd(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&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function ze(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var yd=ze("GET"),wd=ze("POST"),bd=ze("PUT"),kd=ze("PATCH"),vd=ze("DELETE"),Td=ze("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(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 $d=e=>pe("body",{schema:cn("Body",e)}),_d=e=>pe("query",{schema:cn("QueryParams",e)}),Ed=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Sd=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Ad=()=>pe("user"),xd=()=>pe("optionalUser"),Rd=()=>pe("req"),Od=()=>pe("requestId"),Pd=()=>pe("client"),Cd=()=>pe("attestedDevice");function Md(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function jd(){return e=>{de(e,on,()=>!0),se().add(e)}}function Dd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Er=/^[a-z]+(\.[a-z_]+)+$/,va=/^[a-z][a-z0-9-]{1,62}$/,un=e=>e.startsWith("file.");function Nd(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"||!va.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(!un(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ta=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function $r(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(!Ta.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Ud(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.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=Tr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||$r(t.timeZone)!==void 0))throw new TypeError(`${n}: ${$r(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,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var _r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$a=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ld(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!$a.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&&!_r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${_r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&_a(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,Me)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,Be,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function _a(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 Id(){return[...se()].filter(e=>D(e,qe)!==void 0)}function qd(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.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,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Ar(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var Ea=720*3600;function Sa(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ea))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 Aa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Wd=Rt("Tasks",{async enqueue(e,t,n={}){return Sa(n),fn().enqueue(Aa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(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 xr(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 be.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 pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var xa=1e4,Ra=36e5,Sr=24*36e5,Ct=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 ie({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 ie({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 ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Sr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({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 ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(xa*2**Math.min(t.attempt-1,16),Ra),_.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>=Sr&&this.tasks.delete(s);n==="failed"&&_.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 Mt="/_palbase/test-user-templates",Oa=/^[a-z][a-z0-9_-]{0,63}$/;function Zd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Oa.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,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function Rr(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 Or(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Pa="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 Pr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Pa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Cr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Mr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ca=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Ca(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 jr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Dr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ma=/^[a-z][a-z0-9-]{1,62}$/,Nr=1024,ja=new Set(["userId","uploadId","filename"]);function tc(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`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ma.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" 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 s=Da(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function nc(){return pe("uploadedObject")}function Da(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ja.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(!Ur(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Ur(e){if(e===""||new TextEncoder().encode(e).byteLength>Nr)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 Na(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ua(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ua(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 Lr(e,t){let n=Na(e,t);return Ur(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Nr} bytes)`}}function Ir(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 wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function qr(e,t){if(!wn(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=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=jr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=La(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function La(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as Ia}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),Hr={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."},at:{type:"string",description:"When it happened, as the journal took it (a voice's end: when its record says it ended): RFC 3339 in UTC, to the microsecond, at a fixed width \u2014 2026-11-28T06:36:15.321369Z \u2014 so its text sorts as its time: kept as this text, never parsed and written again. Absent for text the channel tells ahead of the journal."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},qa={"~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?, at?, data}"}]},jsonSchema:{input:()=>structuredClone(Hr),output:()=>structuredClone(Hr)}}},Jr=Symbol.for("palbase.backend.gatewayRefusal"),Br=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,Jr,{value:!0})}},Ha=e=>typeof e=="object"&&e!==null&&e[Jr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,bn=e=>({id:e.id??"",...e.session?{session:e.session}:{}}),Ba=6e4,Ga=86400,Gr=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Fa=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(" ")),Ke=e=>new TextEncoder().encode(e).byteLength,kn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",$n=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Wa(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(Ke(e)>Se)return`a channel is ${Se} 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=za.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 Vr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} bytes at most`}function dc(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Wa(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"&&$n(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=Ka(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)||Fa.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,b]of Object.entries(d)){let k=Vr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!kn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,_n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:qa}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ba,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!We(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,je,()=>h),se().add(a)}}function Ka(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ga;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Gr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Gr} (a week)`);return n}var _n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ja={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ja[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Je,_n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var cc=ct("authorize"),uc=ct("first"),lc=ct("connect"),fc=ct("disconnect"),pc=ct("empty");function mc(e,t,n={}){let r=Vr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!kn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!kn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=de(s.constructor,Je,_n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Va(e){return D(e,je)}function Za(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 Zr(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 Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Ya(e,t,n){let r=$n(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Zr(e,t):Qa(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Qa(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 Xa=1e4,eo=1e3,to=100,En=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Wr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Yr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Va(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Wr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Wr(f.pattern),f.pattern);for(let[G,z]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([I,N])=>[`message ${I}`,N.fn])])if(typeof E[z]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${G} is ${z}, which is no method of it`);let L={cls:v,instance:E,g:f};n.set(f.pattern,L),r.set(v,L)}let o=new Map,d=new Set,l=new Set,h=new Tn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,L)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...L!==void 0?{conn_id:L}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,L,G){let z=T?.signal??AbortSignal.abort(),I=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:z,count:R,user:L,emit:(N,F)=>k(v,E,N,F,I,G),pipe:N=>B(N,E,I),owner:{hold(N){ne.exit(async()=>{try{await N(z)}catch(F){z.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:F})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Za(E,f)}}let K=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function J(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:L}=f,G={status:200,body:{subscribe:!1,publish:!1}};if(!L)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),G;let z=Fe(v.user);if(!z?.id)return G;let I=z.id;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return L[$n(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:G;let N=T.g.hooks.authorize;if(!N)return G;let F,Q;try{F=await t.run(z,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:bn(z),params:Object.freeze({...L})})),Q=no(F)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),G}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${ro(F)}, which is no grant (true, { read, write } or null); the join is refused`),G):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:vn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let L=await R.schema["~standard"].validate(Ia(v.payload??{}));if(L.issues)return{status:200,body:{ok:!1,reason:Kr(L.issues)}};let G=g(f.channel),z={...U(f.entry,f.channel,f.params,G,0,bn(T)),payload:L.value},I=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](z))}catch(Q){if(t.isOutage(Q))throw Q;return Ha(Q)?{status:200,body:{ok:!1,reason:vn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${Kr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let F;try{F=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return F===void 0?{status:200,body:{ok:!0}}:Ke(F)>zr?(_.error(`[palbase] ${I} returned an ack of ${Ke(F)} bytes, past ${zr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(F)}}}async function he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Fr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let L=T==="join"||T==="leave",G=L?Fe(v.user):void 0,z=L?v.connId:void 0;if(L&&(!G?.id||typeof z!="string"||z===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${f.channel}\0${typeof z=="string"?z:""}`;if(L&&d.has(I))return{status:204};if(l.has(I))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(I);try{let N=f.entry.g.hooks[Fr[T]],F;if(T==="empty"?(F=o.get(f.channel),b(f.channel,F)):F=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,F,R,G?bn(G):{id:""},T==="join"?z:void 0);try{await t.run(G,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return L&&(d.add(I),d.size>Xa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(I)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Zr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return En(E)?v==="authorize"?J(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:L,where:G}=ge(v,E);k(R,L,f,T,G)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let L=Ya(T.g.pattern,E??{},f);if("problem"in L)throw new TypeError(`${R}: ${L.problem}`);let G=ne.getStore()?.saying;if(G){G.push(()=>{t.revalidate(L).catch(z=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:z}))});return}await t.revalidate(L)},close(){for(let v of o.values())v.abort();o.clear()}}}function no(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!En(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 ro(e){return Array.isArray(e)?"an array":En(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 so=20,Dt=256;function Kr(e){let t="";for(let n of e.slice(0,so)){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)>=Dt)break}return vn(t,Dt)}function vn(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 Tn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=eo?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,to);try{await this.broadcast(s)}catch(o){_.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),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Sn,createHmac as ao,createPublicKey as ts,timingSafeEqual as oo,verify as ns}from"node:crypto";function wc(e){let t=D(e,Be);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 rs(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=io(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(K,J)=>k[q](K,J)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
3
  - ${a.join(`
4
4
  - `)}`);return s}function ss(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Qr=1024*Ve;function io(e,t){if(e.signature)return De(void 0,e.signature.header,1/0,bo(e.signature,t));switch(e.provider){case"stripe":return De("stripe","stripe-signature",512*Ve,lo(t));case"github":return De("github","x-hub-signature-256",25*Qr,fo(t));case"slack":return De("slack","x-slack-signature",64*Ve,po(t));case"discord":return De("discord","x-signature-ed25519",64*Ve,mo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:go(t)};case"sendgrid":return De("sendgrid","x-twilio-email-event-webhook-signature",Qr,yo(t));case"livekit":return De("livekit","authorization",512*Ve,wo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function De(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??as(e,s)}}function as(e,t){let n=An(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:os(e,t.headers,r),event:r,...co(e,t,r)}}function os(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Ne(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=cs(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 Ne(n,"EventType");case"livekit":return Ne(n,"event");default:return Ne(n,"type")}}function co(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Ne(n,"id"));case"slack":return r(Ne(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${is(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Ne(s,"sg_event_id")||void 0)}:{};default:return{}}}var uo=300;function lo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let l of r.split(",")){let h=l.indexOf("=");if(h<=0)continue;let g=l.slice(0,h).trim(),b=l.slice(h+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=b}else if(g==="v1"){let k=me(b,"hex");if(!k)return"malformed_signature";a.push(k)}}let o=ut(s);if(o===void 0||a.length===0)return"malformed_signature";if(lt(o,n))return"stale_timestamp";let d=Ze("sha256",e,`${s}.`,t.body);return a.some(l=>Ae(l,d))?void 0:"signature_mismatch"}}function fo(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?Ae(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function po(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=ut(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":lt(a,n)?"stale_timestamp":Ae(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function mo(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=ts({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ut(o),l=me(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":ns(null,ds(o,r.body),n,l)?void 0:"signature_mismatch"}}var ho=1e3;function go(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!Ae(Buffer.from(a.toLowerCase()),Buffer.from(Sn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let B=1;for(let K of t.body)if(K===38&&++B>ho)return"malformed_signature";let U=new Map;for(let[K,J]of new URLSearchParams(An(t.body))){let le=U.get(K);le||U.set(K,le=new Set),le.add(J)}let q=[];for(let K of[...U.keys()].sort()){let J=[...U.get(K)].sort();for(let le of J)o+=K+le;q.push([K,J.length===1?J[0]:J])}d=Object.fromEntries(q)}let l=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![h,g].some(B=>Ae(r,Ze("sha1",e,B,o))))return"signature_mismatch";let b=t.headers.get("i-twilio-idempotency-token"),k=b?{id:`${b}:${is(`${h}
5
5
  ${o}`)}`}:{};return d?{type:os("twilio",t.headers,d),event:d,...k}:{...as("twilio",t),...k}}}function yo(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=ts({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=ut(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":lt(o,r)?"stale_timestamp":ns("sha256",ds(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Xr=60;function wo(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=es(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Ae(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=es(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Xr||typeof d.nbf=="number"&&n<d.nbf-Xr)return"stale_timestamp";let l=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return l&&Ae(l,Sn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function bo(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ut(d);if(h===void 0)return"malformed_signature";if(lt(h,a))return"stale_timestamp"}let l=me(o.trim(),e.encoding);return l?Ae(l,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var ko=new TextEncoder;function Ze(e,t,...n){let r=ao(e,t);for(let s of n)r.update(s);return r.digest()}function is(e){return Sn("sha256").update(e).digest("hex")}function ds(e,t){return Buffer.concat([ko.encode(e),t])}function Ae(e,t){return e.byteLength===t.byteLength&&oo(e,t)}var vo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return vo[t].test(e)?Buffer.from(e,t):void 0}function ut(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function lt(e,t){return Math.abs(t-e)>uo}function An(e){return new TextDecoder().decode(e)}function es(e){if(e)try{return JSON.parse(An(e))}catch{return}}function cs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,t){let n=cs(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var Y=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
@@ -0,0 +1,13 @@
1
+ /*! palbase 0.80.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as D,d as I,e as R}from"./N767RMLK.js";import{a as Y,f as Z,g as X,j as ee,k as te,l as ne,o as N,p as se,q as re}from"./T2XBJBUC.js";import{d as G}from"./5BQM5XTX.js";import{a as E,b as Q,c as T,e as q}from"./2NB7UENO.js";var f=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=e,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function ae(n){return n instanceof f||typeof n=="object"&&n!==null&&n.name==="BackendError"&&typeof n.kind=="string"}function B(n){let e=n.body,t={code:n.code,message:n.message,status:n.status,requestId:n.requestId??Qe(e,"request_id"),data:S(e,"data"),cause:n};if(n.code==="network_error")return new f("network",t);if(n.status===401&&n.code==="insufficient_user_authentication")return new f("stepUpRequired",t);if(n.status===401&&n.code==="app_attest_required")return new f("attestationRequired",t);if(n.status===401)return new f("unauthorized",t);if(n.status===429)return new f("rateLimited",{...t,retryAfter:ze(e)??n.retryAfter});let s=Ue(e);return n.status===400&&s?new f("validation",{...t,fields:s}):new f("server",t)}function P(n){return n instanceof Q||n instanceof Error&&n.name==="PalbaseError"}function oe(n){return Array.isArray(n)&&n.length>0&&n.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Ue(n){let e=S(S(n,"data"),"fields");if(oe(e))return e;let t=S(n,"fields");return oe(t)?t:void 0}function ze(n){return ie(n,"retry_after")??ie(S(n,"data"),"retryAfter")}function S(n,e){if(typeof n=="object"&&n!==null)return n[e]}function ie(n,e){let t=S(n,e);return typeof t=="number"?t:void 0}function Qe(n,e){let t=S(n,e);return typeof t=="string"?t:void 0}var Ye=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ze=Object.freeze(["adoptSession","ai","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","commerce","campaigns","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Xe=new Set(Ze),et=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(n){return n==="then"||n==="toJSON"||et.has(n)}function de(n){return n==="call"||n==="join"||O(n)}function le(n){return typeof n=="string"&&Ye.test(n)&&!Xe.has(n)&&!O(n)}function ce(n){return typeof n=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(n)}function ue(n){q(n)}function pe(n){return q(n).origin}var $=class n{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},t,s,r=!0){this.me=e,this.reader=t,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let t=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...t!==void 0?{turns:t}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let h=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(h,d)}if(this.ended)return!1;let c=(a?.parts??[]).map(h=>D(h)).filter(h=>h!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(c),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=c):this.racing&&(this.racedPages=c.concat(this.racedPages)),t===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;t-=a.turns}while(t>0);return this.olderLeft}idFor(e,t){let s=t??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let p=w(i);p<=0||(this.paged.add(p),(this.pagedFrom===void 0||p<this.pagedFrom)&&(this.pagedFrom=p),(this.pagedTo===void 0||p>this.pagedTo)&&(this.pagedTo=p))}let t=new n(this.me);t.thoughts=this.thoughts,t.lowest=this.lowest-e.length;let s=t.lowest;for(let i of e)t.at=s++,t.fold(i);this.folded+=t.folded,this.lowest=t.lowest,this.chatId??=t.chatId;let r=new Map;for(let[i,p]of t.messages){let y=this.told.get(i)??[],b=p;if(y.length>0)for(let C of y)b=ve(b,C);else b=this.messages.get(i)??p;r.set(i,b);let _=[...t.told.get(i)??[],...y];_.length>0&&this.told.set(i,_)}for(let[i,p]of this.messages)r.has(i)||r.set(i,p);this.messages.clear();for(let[i,p]of r)this.messages.set(i,p);let o=new Map;for(let[i,p]of t.responses){let y=this.responses.get(i);o.set(i,y?nt(p,y):p)}for(let[i,p]of this.responses)o.has(i)||o.set(i,p);this.responses.clear();for(let[i,p]of o)this.responses.set(i,p);let d=new Set;for(let i of t.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...t.order],c=new Set([...t.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&t.goalWords.has(i.event.seq))&&!(i.type==="voice"&&t.voiceWords.has(K(i.event)))&&!(i.type==="handoff"&&t.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&t.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let p=this.responses.get(i.turn);c.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:p&&p.at<i.arrived?p.at-.5:i.arrived});continue}a.push(i)}a.sort((i,p)=>i.at-p.at),this.order=a;for(let i of t.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of t.voiceWords)this.voiceWords.add(i);let h=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=ye(this.voice,i.event,h));for(let i of t.handoffGens)this.handoffGens.add(i);for(let i of t.compactionSeqs)this.compactionSeqs.add(i);for(let i of t.offloadKeys)this.offloadKeys.add(i);t.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:t.execution.target,generation:t.execution.generation,workspaceSeq:t.execution.workspaceSeq,lastHandoff:t.execution.lastHandoff}),this.execution.machineStatus===null&&t.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:t.execution.machineId,machineStatus:t.execution.machineStatus,failoverAt:t.execution.failoverAt});let l=[];for(let i of a)i.type==="compaction"&&l.push(i.event);let u=[...t.execution.offloads,...this.execution.offloads.filter(i=>!t.offloadKeys.has(me(i)))];this.execution={...this.execution,compactions:l,offloads:u},this.turn??=t.turn;let g=new Map([...t.calls,...this.calls]);this.calls.clear();for(let[i,p]of g)this.calls.set(i,p);for(let[i,p]of t.history)this.history.has(i)||this.history.set(i,p);this.forkedFrom??=t.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,t,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==t){t=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let t=D(e);t&&this.take(t)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let t=w(e);t>0&&this.pagedTo!==void 0&&t>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=ge(setTimeout(()=>this.quiet(),fe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<tt?this.heldTimer=ge(setTimeout(()=>this.quiet(),fe)):this.sortHeld()}takeNow(e){let t=w(e);t>0&&this.paged.has(t)||(t>0&&(this.oldestLive===void 0||t<this.oldestLive)&&(this.oldestLive=t),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),t=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(w(a))),d=o<0?-1:t.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&he(e[o-1-a],t[d-1-a]);)a++;let c=0;for(;o+c<e.length&&d+c<t.length&&he(e[o+c],t[d+c]);)c++;s=e.slice(0,o-a),r=e.slice(o+c)}else{let a=e.find(h=>w(h)>0),c=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let h of e){let l=w(h);l>0&&!(this.pagedFrom!==void 0&&l<this.pagedFrom)&&(c=!1),(c?s:r).push(h)}}if(s.length>0){let a=Math.min(...s.map(w).filter(c=>c>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let t=this.response(e.response_id);t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=typeof e.end=="string"?e.end:null,t.stoppedBy=e.stopped_by??null,e.user_id!==void 0&&(t.startedBy=e.user_id),e.goal&&(t.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),A(t.times,e.status,e.at),this.turn=e;break}case"thinking":{let t=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){t.marks.set("thinking:unavailable",{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:null,runId:e.run_id,text:"",startedAt:e.at??null,endedAt:e.at??null,unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=t.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text,...Ee(r.thinking,e.at??null,e.at??null)}:t.marks.set(s,{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,startedAt:e.at??null,endedAt:e.at??null,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let t=K(e);if(this.voiceWords.has(t))return!1;this.voice=ye(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let t=this.response(e.response_id);ot(t,e.offset,e.text),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"reset":{let t=this.response(e.response_id);e.offset<=t.from?(t.text="",t.from=Math.max(0,e.offset)):t.text=t.text.slice(0,R(t.text,e.offset-t.from)),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"tool":{let t=this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id);t.marks.set(`tool:${e.call_id}`,e),we(t,`tool:${e.call_id}`,e.status,e.at),this.calls.set(e.call_id,e);break}case"agent":{let t=this.response(e.parent_response_id),s=e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`;if(t.marks.set(s,e),we(t,s,e.status,e.at),!e.response_id)break;let r=this.response(e.response_id);r.runId=e.run_id,r.agent=e.name,r.named=!0,r.parentId??=e.parent_response_id,A(r.times,e.status,e.at);break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let t=me(e);if(this.offloadKeys.has(t))return!1;this.offloadKeys.add(t),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let t=this.goal;if(!t||t.id!==e.goal_id)return;let s={...t,events:[...t.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let t=rt(e),s=this.messages.get(t);this.messages.set(t,ve(s,e));let r=this.told.get(t);r?r.push(e):this.told.set(t,[e]),s||this.place(e,t),this.changed()}said(e){let t=`voice\0${e.id}`,s=this.messages.get(t);this.messages.set(t,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:t,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,t){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([c,h])=>c!==t&&h.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:t,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(c=>c.type==="response"&&c.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let t=this.responses.get(e);return t||(t={id:e,status:null,waiting:null,end:null,error:null,stoppedBy:null,text:"",from:0,cut:null,marks:new Map,markTimes:new Map,times:{},runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,t),this.order.push({type:"response",key:e,at:this.at})),t}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let t of[...this.listeners])try{t(e)}catch{}}))}build(){let e=this.me(),t=l=>e!==void 0&&l.startedBy===e,s=new Map;for(let l of this.responses.values()){let u=l.parentId!==null?this.responses.get(l.parentId)??l:l;s.set(l.id,it(l,u.startedBy??null,t(u),l.goal??u.goal))}let r=new Map([...this.messages].map(([l,u])=>[l,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([l],[u])=>l-u).flatMap(([l,u])=>u.map((g,i)=>dt(g,`${l}:${i}`,e))),d=[...o];for(let l of this.order)l.type==="goal"?d.push({type:"goal",goal:l.event}):l.type==="voice"?d.push({type:"voice",voice:l.event}):l.type==="handoff"?d.push({type:"handoff",handoff:l.event}):l.type==="compaction"?d.push({type:"compaction",compaction:l.event}):l.type==="message"?d.push({type:"message",message:r.get(l.key)}):this.responses.get(l.key).parentId===null&&d.push({type:"response",response:s.get(l.key)});let a=o.flatMap(l=>l.type==="message"?[l.message]:[]),c=o.flatMap(l=>l.type==="response"?[l.response]:[]),h=[...this.calls.values()].filter(l=>s.get(l.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:h.filter(l=>l.status==="awaiting_approval"),outputs:h.filter(l=>l.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?st(this.voice,e):null,execution:this.execution}}},fe=150,tt=2e3;function he(n,e){let t=w(n);return t>0||w(e)>0?t===w(e):JSON.stringify({...n,at:void 0})===JSON.stringify({...e,at:void 0})}function w(n){let e=n.seq;return typeof e=="number"&&e>0?e:0}function ge(n){return n.unref?.(),n}function K(n){return`${n.voice_id}\0${n.status}`}function me(n){return n.seq>0?`seq:${n.seq}`:`call:${n.call_id}:${n.ref??""}`}function ye(n,e,t){return t.add(K(e)),(e.status==="closed"?n===null||n.voice_id===e.voice_id:!t.has(`${e.voice_id}\0closed`))?e:n}function ve(n,e){let t=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??n?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:n?.status==="delivered"?"delivered":t,error:e.error??null,responseId:e.response_id??n?.responseId??null,createdAt:e.created_at??n?.createdAt??"",mine:!1,metadata:e.metadata??n?.metadata??{},history:!1,truncated:!1,kind:e.kind??n?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:n?.voice??null,attachments:e.attachments?xe(e.attachments):n?.attachments??[]}}function nt(n,e){let t={...n,marks:new Map(n.marks),times:ke(n.times,e.times),markTimes:new Map(n.markTimes)};for(let[r,o]of e.markTimes)t.markTimes.set(r,ke(t.markTimes.get(r)??{},o));e.status!==null&&(t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=e.end,t.stoppedBy=e.stoppedBy),e.startedBy!==void 0&&(t.startedBy=e.startedBy),e.goal&&(t.goal=e.goal),e.named&&(t.runId=e.runId,t.agent=e.agent,t.named=!0),t.parentId=n.parentId??e.parentId,e.cut!==null&&(n.text===""||e.cut<=n.from?(t.text=e.text,t.from=e.text===""?Math.max(0,e.cut):e.from):t.text=n.text.slice(0,R(n.text,e.cut-n.from))+e.text,t.cut=n.cut===null?e.cut:Math.min(n.cut,e.cut));let s=r=>{if(n.text==="")return null;if(r!==null&&r<=n.from)return r;let o=I(n.text);return n.from+(r===null?o:Math.min(o,r-n.from))};for(let[r,o]of e.marks){let d=t.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")t.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text,...Ee(d.thinking,o.thinking.startedAt,o.thinking.endedAt)}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);t.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?n.cut:n.cut===null?o.cutAt:Math.min(o.cutAt,n.cut)})}else t.marks.set(r,o)}return t}function st(n,e){return{id:n.voice_id,userId:n.user_id,mine:e!==void 0&&n.user_id===e,delegation:n.delegation,status:n.status,seconds:typeof n.seconds=="number"?n.seconds:null,closeReason:n.close_reason??""}}function xe(n){return n.map((e,t)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:t,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function rt(n){return`${n.author??""}\0${n.client_id}`}function ot(n,e,t){if(n.text===""||e<=n.from){n.from=Math.max(0,e),n.text=t;return}n.text=n.text.slice(0,R(n.text,e-n.from))+t}function it(n,e,t,s){let r=[...n.marks].map(([l,u],g)=>({key:l,m:u,i:g,at:R(n.text,Math.max(0,(Number(u.text_offset)||0)-n.from))}));r.sort((l,u)=>l.at-u.at||l.i-u.i);let o=[],d=[],a=0;for(let{key:l,m:u,at:g}of r)if(g>a&&o.push({type:"text",text:n.text.slice(a,g)}),a=Math.max(a,g),u.type==="thinking")o.push({type:"thinking",thinking:u.thinking}),d.push(u.thinking);else{let i={...n.markTimes.get(l)};o.push(u.type==="tool"?{type:"tool",tool:u,times:i}:{type:"agent",agent:u,times:i})}a<n.text.length&&o.push({type:"text",text:n.text.slice(a)});let c=Object.values(n.times).sort(),h=at.map(l=>n.times[l]).find(l=>l!==void 0)??null;return{id:n.id,status:n.status,waiting:n.waiting,end:n.end,error:n.error,stoppedBy:n.stoppedBy,text:n.text,parts:o,runId:n.runId,agent:n.agent,parentId:n.parentId,startedBy:e,mine:t,thinking:d,goal:s,history:!1,truncated:!1,times:{...n.times},startedAt:c[0]??null,endedAt:h}}var at=["completed","failed","canceled","timed_out","budget_exceeded","denied","failed_with_uncertain_side_effect"];function A(n,e,t){if(typeof t!="string"||t==="")return;let s=n[e];(s===void 0||t<s)&&(n[e]=t)}function we(n,e,t,s){if(typeof s!="string"||s==="")return;let r=n.markTimes.get(e);r||n.markTimes.set(e,r={}),A(r,t,s)}function ke(n,e){let t={...n};for(let[s,r]of Object.entries(e))A(t,s,r);return t}function Ee(n,e,t){return{startedAt:n.startedAt===null||e!==null&&e<n.startedAt?e??n.startedAt:n.startedAt,endedAt:n.endedAt===null||t!==null&&t>n.endedAt?t??n.endedAt:n.endedAt}}function dt(n,e,t){let s=n.text_truncated===!0;if(n.role==="user"){let r=n.author??null;return{type:"message",message:{clientId:n.client_id??"",id:n.message_id??null,text:n.text,author:r,authorName:n.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:n.created_at??"",mine:t!==void 0&&r===t,metadata:n.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:xe(n.attachments??[])}}}return{type:"response",response:{id:n.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,stoppedBy:null,text:n.text,parts:n.text===""?[]:[{type:"text",text:n.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s,times:{},startedAt:null,endedAt:null}}}var be=[["ApiKeyAuth","userJWT"]];function _e(n){return{async parts(e,t){let s={};t.limit!==void 0&&(s.limit=t.limit),t.turns!==void 0&&(s.turns=t.turns),t.cursor!==void 0?s.cursor=t.cursor:t.before!==void 0&&(s.before=t.before);let r=(await n.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${T("ListChatParts","chat_id",e)}/parts`,auth:be,answers:{200:"json"},query:s,signal:t.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,t,s){if(typeof t!="string"||t==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await n.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",t)}`,auth:be,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}}}}var M=class extends Error{reason;constructor(e,t){super(e),this.name="GatewayError",this.reason=t}},Se=new WeakMap;async function Te(n,e,t,s={},r=()=>{},o){let{pattern:d,events:a,messages:c,durable:h,chat:l}=lt(e),u=ct(d,t),g=Se.get(n);g||Se.set(n,g=new Map);let i=g,p=i.get(u)??{count:0};i.set(u,p),p.count++;let y=n.channel(u,h&&s.history!==!1?{after:0}:{});if(l&&!p.chat){let m=t.chatId,x=new $(r,o,typeof m=="string"&&m!==""?m:void 0,h&&s.history!==!1);p.chat=x,p.unchat=y.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let b=()=>{--p.count>0||(i.delete(u),p.unchat?.(),p.chat?.end(),y.leave())};try{await y.join()}catch{let m=y.state==="refused"?Ce(y.refusal,"unavailable"):"socket closed";throw b(),new M(`gateway ${JSON.stringify(u)} was not joined: ${m}`,m)}let _=!1,C=new Set,V=()=>{if(!_){_=!0,Ve();for(let m of[...C])m();b()}},Ve=y.onClosed(V),U=m=>{if(_)return()=>{};let x=y.on("broadcast",k=>{typeof k.event=="string"&&a.has(k.event)&&m(k.event,E(k.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},z={topic:u,get seq(){return y.logSeq},on(m,x){if(typeof m=="function")return U((v,k)=>m({event:v,payload:k}));if(!a.has(m))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(m))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(m)}, \u2026) takes the function the event is handed to`);return U((v,k)=>{v===m&&x(k)})},off(m){C.has(m)&&m()},async send(m,x){if(!c.has(m))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(m))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:m,payload:x});if(v.status==="ok")return E(v.response.reply);let k=Ce(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(m)}: ${k}`,k)},leave:V};return l&&Object.defineProperty(z,"chat",{value:p.chat,enumerable:!0}),z}function lt(n){let e=typeof n=="object"&&n!==null?n:{},t=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!t(e.events)||!t(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function ct(n,e){let t=typeof e=="object"&&e!==null?e:{};return n.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(t,r)?t[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(n)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(n)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function Ce(n,e){let t=n?.reason;return typeof t=="string"&&t!==""?t:e}var ut=3600*1e3,j=new Map;function pt(n,e,t=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!t&&r&&Date.now()-r.at<ut)return r.list;let o=(async()=>{let d=se(),a;try{a=(await n.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new f("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await re(a,e.signer,e.projectId,d)}catch(c){throw new f("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:c})}})();return j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function Re(n,e,t,s,r,o){let a=(await pt(n,e,o)).keys[0];return X(a.kid,a.key,Z(e.projectId,t,s,r))}function L(n,e,t,s){return e==null||!s||s.length===0?Promise.resolve(e):N(e,t,s,(r,o)=>ee(n.key,r,o))}function Ie(n,e,t,s){return e===void 0||!t||t.length===0?Promise.resolve(e):N(e,"/response",t,async(r,o)=>{if(!te(o))throw new f("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ne(n.key,r,o)}catch(d){throw new f("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Pe(n){return n instanceof f&&(n.code==="encryption_key_retired"||n.code==="encryption_key_unknown")}var F=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
+ `);let t=[],s=this.pending.indexOf(`
4
+ `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
5
+ `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let d=o.slice(5);this.dataLines.push(d.startsWith(" ")?d.slice(1):d)}else if(o.startsWith("event:")){let d=o.slice(6);this.eventName=d.startsWith(" ")?d.slice(1):d}}s=this.pending.indexOf(`
6
+ `)}return t}};async function*Oe(n,e){let t=n.getReader(),s=new TextDecoder,r=new F;try{for(;;){let{done:o,value:d}=await t.read();if(o)break;for(let a of r.consume(s.decode(d,{stream:!0}))){if(a.event==="error")throw new f("network",{code:"stream_failed",message:`stream failed: ${a.payload}`});let c;try{c=JSON.parse(a.payload)}catch{throw new f("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${a.payload.slice(0,120)}`})}yield E(c)}}}finally{e.abort();try{await t.cancel()}catch{}}}var ft={},Ae=new WeakMap;function en(n,e,t,s,r,o=()=>{}){Ae.set(n,{project:e,machine:t,storage:s,socket:r,me:o})}var Me=new Map,$e=new WeakMap;function tn(n,e,t,s,r,o){if(!le(e))throw new f("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let d=pe(n);if(!ce(t))throw new TypeError(`${JSON.stringify(String(t))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);ue(s),Ge(r);for(let a of Object.keys(r))if(de(a))throw je(a);if(o!==void 0)vt(o);else if(qe(r))throw new f("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(Me.get(e)??ht(e)).set(d,{machine:t,url:s,tree:r,...o?{transit:{...o}}:{}})}function ht(n){let e=new Map;return Me.set(n,e),Object.defineProperty(ft,n,{configurable:!0,get(){return gt(this,n,e)}}),e}function gt(n,e,t){let s=Ae.get(n);if(!s)return;let r=t.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...t.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=$e.get(n);o||$e.set(n,o=new Map);let d=o.get(e);if(d?.registration===r)return d.ns;let a={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},c=Object.assign({call:(h,l,u)=>_t(a.machine,h,l,u),join:(h,l,u)=>Te(s.socket,h,l,u,s.me,_e(s.storage))},Ne(r.tree,a));return o.set(e,{registration:r,ns:c}),c}function je(n){return new f("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(n)}: the name is reserved.`})}function J(n){return typeof n.path=="string"&&typeof n.method=="string"}function mt(n,e){if(n.pathParams!==void 0){if(!Array.isArray(n.pathParams)||!n.pathParams.every(t=>typeof t=="string"))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let t of n.pathParams)if(!n.path.includes(`{${t}}`))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${t}' has no '{${t}}' placeholder in the path.`})}if(n.sse!==void 0&&typeof n.sse!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(n.idempotent!==void 0&&typeof n.idempotent!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(n.upload!==void 0&&typeof n.upload!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(n.upload===!0&&(n.method!=="POST"||n.sse===!0))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(n.sse===!0&&n.input==="query")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(n.input!==void 0&&n.input!=="body"&&n.input!=="query"&&n.input!=="none")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(n.encryption!==void 0&&yt(n,e),n.errors!==void 0){for(let[t,s]of Object.entries(n.errors))if(typeof s!="function")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${t}'] must be a function.`})}}function yt(n,e){let t=n.encryption,s=r=>new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof t!="object"||t===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let d=t[r];if(d!==void 0&&(!Array.isArray(d)||!d.every(a=>typeof a=="string"&&o.some(c=>a===c||a.startsWith(c.endsWith("/")?c:`${c}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(n.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(n.sse===!0&&(t.response?.length??0)>0)throw s("of a streamed answer is none")}function qe(n){return J(n)?n.encryption!==void 0:Object.values(n).some(e=>qe(e))}function vt(n){if(typeof n!="object"||n===null||typeof n.projectId!="string"||!/^[0-9a-f-]{36}$/.test(n.projectId)||typeof n.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(n.signer))throw new f("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Ge(n){if(typeof n!="object"||n===null)throw new f("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(n);if(e!==Object.prototype&&e!==null)throw new f("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[t,s]of Object.entries(n)){if(O(t))throw je(t);typeof s=="object"&&s!==null&&J(s)?(s.method=s.method.toUpperCase(),mt(s,s.path)):Ge(s)}}function Ne(n,e){if(J(n))return n.upload===!0?async(...s)=>xt(e,n,s):async(...s)=>Ke(e.machine(),n,s,e.transit);let t={};for(let[s,r]of Object.entries(n))t[s]=Ne(r,e);return t}function H(n){if(n==null)return"";let e=Object.entries(n).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new f("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function De(n,e,t){try{return T(n.path,e,t)}catch(s){if(!P(s)||s.code!=="invalid_path_parameter")throw s;let r=String(t);throw new f("validation",{code:"invalid_path_parameter",message:`${n.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function Be(n,e){let t=n.pathParams??[],s=n.path;for(let r=0;r<t.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new f("validation",{code:"missing_path_param",message:`${n.path}: path parameter '${t[r]}' must be a string or number`});s=s.replace(`{${t[r]}}`,De(n,`path parameter '${t[r]}'`,o))}return s}var wt=new Set(["POST","PUT","PATCH","DELETE"]);async function Ke(n,e,t,s){let r=e.pathParams??[],o=Be(e,t),d=o;if(e.input==="none"&&t.length>r.length+1)throw new f("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let a=e.input==="none"?void 0:t[r.length],c=e.input==="none"?r.length:r.length+1,h=t[c],l;if(e.input==="query")d+=H(a);else if(e.input!=="none")if(e.method==="GET"){if(a!==void 0)throw new f("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else l=a;let u={...h?.headers};if(wt.has(e.method)&&!Object.keys(u).some(g=>g.toLowerCase()==="idempotency-key")&&(u["Idempotency-Key"]=G()),e.encryption!==void 0){if(!s)throw new f("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return kt(n,e,o,a,l,u,h?.signal,r.map((g,i)=>String(t[i])),s)}try{return e.sse===!0?await We(n,e,d,l,u,h?.signal):await Je(n,e,d,l,u,h?.signal)}catch(g){throw W(e,g)}}async function kt(n,e,t,s,r,o,d,a,c){let h=e.encryption;for(let l=0;;l++){let u=await Re(c.project,c.config,e.method,e.path,a,l>0);try{let g=e.input==="query"?t+H(await L(u,s,"/query",h.request)):t,i=await L(u,r,"/body",h.request),p={...o,[Y]:u.header};return e.sse===!0?await We(n,e,g,i,p,d):E(await Ie(u,await Je(n,e,g,i,p,d),h.response,`${e.method} ${e.path}`))}catch(g){if(l===0&&Pe(g))continue;throw W(e,g)}}}function W(n,e){return n.errors&&ae(e)&&Object.hasOwn(n.errors,e.code)?n.errors[e.code](e):e}var bt=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function xt(n,e,t){let s=e.pathParams??[],r=Be(e,t),o=e.input==="none"?s.length:s.length+1;if(t.length>o+2)throw new f("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let d=e.input==="none"?void 0:t[s.length],a=t[o],c=t[o+1];if(!(a instanceof Blob))throw new f("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let h=`/storage/upload/${n.name}/${De(e,"the route",r.slice(1))}`;e.input==="query"&&(h+=H(d));let l=Et(e.input==="query"?void 0:d,a),u=l.body.size,g=0,i=p=>{g=p;try{c?.onProgress?.({loaded:p,total:u})}catch{}};c?.onProgress&&i(0);try{let p;try{let y={op:`Upload ${e.path}`,method:"POST",path:h,auth:bt,answers:Le,body:{kind:"raw",contentType:l.type,value:l.body},signal:c?.signal,...c?.onProgress?{onUploadProgress:b=>i(b)}:{}};p=(await n.storage.send(y)).data}catch(y){throw P(y)?B(y):y}return c?.onProgress&&g<u&&i(u),await He(e,p,c?.signal)}catch(p){throw W(e,p)}}function Et(n,e){let t=`Palbase-${G()}`,s=a=>a.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(a,c)=>`--${t}\r
7
+ Content-Disposition: form-data; ${a}\r
8
+ Content-Type: ${c}\r
9
+ \r
10
+ `,d=[];return n!==void 0&&d.push(o('name="body"',"application/json"),JSON.stringify(n),`\r
11
+ `),d.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
12
+ --${t}--\r
13
+ `),{body:new Blob(d),type:`multipart/form-data; boundary=${t}`}}async function _t(n,e,t,s){if(typeof e!="string"||e===""||e==="/")throw new f("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Ke(n(),{method:"POST",path:r},[t,s])}var Le=Object.fromEntries(Array.from({length:100},(n,e)=>[200+e,"raw"])),St=[["userJWT"],[]];async function Fe(n,e,t,s,r,o){let d={op:`${e.method} ${e.path}`,method:e.method,path:t,auth:St,answers:Le,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await n.send(d)).data}catch(a){throw P(a)?B(a):a}}async function Je(n,e,t,s,r,o){return He(e,await Fe(n,e,t,s,r,o),o)}async function He(n,e,t){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw t?.aborted?o:new f("network",{code:"network_error",message:`${n.method} ${n.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return E(JSON.parse(r))}catch(o){throw new f("decode",{code:"invalid_json",message:`${n.method} ${n.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function We(n,e,t,s,r,o){let d=new AbortController;o&&(o.aborted?d.abort():o.addEventListener("abort",()=>d.abort(),{once:!0}));let a=await Fe(n,e,t,s,{accept:"text/event-stream",...r},d.signal);if(!a.body)throw new f("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:a.status});return Oe(a.body,d)}export{f as a,ae as b,Ze as c,le as d,_e as e,M as f,ft as g,en as h,tn as i};