palbase 0.17.0 → 0.18.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 (54) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{KBO5NELQ.js → 32XY6IBN.js} +2 -2
  8. package/dist/chunks/{XAHQAK65.js → 3GWBIPGH.js} +2 -2
  9. package/dist/chunks/{MI5QEZ7Y.js → 4HFD24QY.js} +1 -1
  10. package/dist/chunks/{FQLY6TBH.js → 4S4ODZVM.js} +2 -2
  11. package/dist/chunks/{K2CN4CGB.js → 6IMY2J5W.js} +1 -1
  12. package/dist/chunks/{K3KCYVMN.js → 7QFBZLAK.js} +1 -1
  13. package/dist/chunks/{ENZI5RN5.js → 7R4WTDHI.js} +1 -1
  14. package/dist/chunks/{GL5Y2PAS.js → ART5HP5M.js} +2 -2
  15. package/dist/chunks/{55C2GHGA.js → BKGX3AZA.js} +2 -2
  16. package/dist/chunks/{KUTBWXNL.js → BW5DFI3C.js} +1 -1
  17. package/dist/chunks/{6VLC4QJY.js → CAZYHE64.js} +2 -2
  18. package/dist/chunks/EVBWED24.js +22 -0
  19. package/dist/chunks/{HPQSHDEH.js → FT7G3QQ4.js} +2 -2
  20. package/dist/chunks/{IG2INK7Z.js → JKA2W4E5.js} +2 -2
  21. package/dist/chunks/{45DR7TF6.js → KRQZOF2L.js} +2 -2
  22. package/dist/chunks/{56S5CF3M.js → OC32TP3L.js} +2 -2
  23. package/dist/chunks/{O6LRXDFY.js → PMQOJ7FF.js} +2 -2
  24. package/dist/chunks/{6CEXEK2F.js → PPK2UEAY.js} +2 -2
  25. package/dist/chunks/{CPQR6PSB.js → T2O6XEQO.js} +1 -1
  26. package/dist/chunks/{25FDQIKY.js → VQXYHAU4.js} +2 -2
  27. package/dist/chunks/{4GIYAC3R.js → XF3JEDIQ.js} +1 -1
  28. package/dist/chunks/{WW4HVDSO.js → XHNZDLR4.js} +2 -2
  29. package/dist/chunks/{V72PBUK4.js → ZXV3ZKVM.js} +2 -2
  30. package/dist/cli.js +114 -113
  31. package/dist/refuse/ai.js +1 -1
  32. package/dist/refuse/backend.js +1 -1
  33. package/dist/refuse/server.js +1 -1
  34. package/dist/server/index.js +2 -2
  35. package/dist/server/testing.js +2 -2
  36. package/dist/web/index.js +2 -2
  37. package/dist/web/message.js +2 -2
  38. package/dist/web/palbe.js +2 -2
  39. package/dist/web/paywall.js +2 -2
  40. package/dist/web/push-sw.js +1 -1
  41. package/dist/web/ssr.js +2 -2
  42. package/dist/web/vite.js +2 -2
  43. package/package.json +2 -2
  44. package/types/internal/src/messaging/engine.d.ts +31 -0
  45. package/types/internal/src/messaging/files.d.ts +11 -0
  46. package/types/internal/src/messaging/index.d.ts +5 -0
  47. package/types/internal/src/messaging/local.d.ts +31 -0
  48. package/types/internal/src/messaging/outbox.d.ts +53 -0
  49. package/types/internal/src/messaging/store.d.ts +67 -0
  50. package/types/internal/src/modules/purchases.d.ts +383 -0
  51. package/types/web/src/client.d.ts +5 -0
  52. package/types/web/src/index.d.ts +1 -0
  53. package/types/web/src/messaging.d.ts +280 -0
  54. package/dist/chunks/JGUQKVFH.js +0 -22
package/dist/ai/index.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
2
- import{a,b,c,d,e,f}from"../chunks/XAHQAK65.js";import"../chunks/WW4HVDSO.js";import"../chunks/K3KCYVMN.js";import"../chunks/V72PBUK4.js";import"../chunks/HPQSHDEH.js";import"../chunks/25FDQIKY.js";import"../chunks/K2CN4CGB.js";import"../chunks/CPQR6PSB.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
2
+ import{a,b,c,d,e,f}from"../chunks/3GWBIPGH.js";import"../chunks/XHNZDLR4.js";import"../chunks/7QFBZLAK.js";import"../chunks/ZXV3ZKVM.js";import"../chunks/FT7G3QQ4.js";import"../chunks/VQXYHAU4.js";import"../chunks/6IMY2J5W.js";import"../chunks/T2O6XEQO.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
2
- import{ha as w,la as h}from"../chunks/KBO5NELQ.js";import"../chunks/O6LRXDFY.js";import"../chunks/IG2INK7Z.js";import"../chunks/GL5Y2PAS.js";import"../chunks/MI5QEZ7Y.js";import"../chunks/ENZI5RN5.js";import"../chunks/XAHQAK65.js";import"../chunks/WW4HVDSO.js";import"../chunks/K3KCYVMN.js";import"../chunks/V72PBUK4.js";import"../chunks/HPQSHDEH.js";import"../chunks/25FDQIKY.js";import"../chunks/K2CN4CGB.js";import"../chunks/CPQR6PSB.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
2
+ import{ha as w,la as h}from"../chunks/32XY6IBN.js";import"../chunks/PMQOJ7FF.js";import"../chunks/JKA2W4E5.js";import"../chunks/ART5HP5M.js";import"../chunks/4HFD24QY.js";import"../chunks/7R4WTDHI.js";import"../chunks/3GWBIPGH.js";import"../chunks/XHNZDLR4.js";import"../chunks/7QFBZLAK.js";import"../chunks/ZXV3ZKVM.js";import"../chunks/FT7G3QQ4.js";import"../chunks/VQXYHAU4.js";import"../chunks/6IMY2J5W.js";import"../chunks/T2O6XEQO.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
@@ -1 +1 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
@@ -1,5 +1,5 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
2
- import{$ as It,A as F,B as dt,C as ut,D as ht,E as ft,F as gt,G as bt,H as mt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as _t,S as xt,T as Rt,U as Ot,V as Ct,W as Bt,X as re,Y as Ft,Z as Mt,_ as $t,a as Q,aa as Lt,b as X,ba as Ut,c as Z,ca as Dt,d as Ne,da as jt,e as qe,ea as Nt,f as We,fa as M,g as Ke,ga as Vt,h as Ve,ha as $,i as Ge,ia as V,j as ze,ja as Gt,k as He,ka as zt,l as Ye,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as rt,t as st,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/KBO5NELQ.js";import{a as ne}from"../chunks/KUTBWXNL.js";import{a as x,b as ee,c as te,f as b,g as pt,h as d,j as se,k as Kt}from"../chunks/O6LRXDFY.js";import{a as qt,b as Wt}from"../chunks/IG2INK7Z.js";import{d as _,j as De,k as je,l as H,m as B,t as Y,u as J}from"../chunks/GL5Y2PAS.js";import"../chunks/MI5QEZ7Y.js";import"../chunks/ENZI5RN5.js";import"../chunks/XAHQAK65.js";import"../chunks/WW4HVDSO.js";import"../chunks/K3KCYVMN.js";import{m as Ue}from"../chunks/V72PBUK4.js";import"../chunks/HPQSHDEH.js";import{b as A,c as K}from"../chunks/25FDQIKY.js";import"../chunks/K2CN4CGB.js";import"../chunks/CPQR6PSB.js";import"reflect-metadata";import{existsSync as G,writeFileSync as _r,writeSync as xr}from"node:fs";import{createServer as Rr}from"node:http";import{dirname as k,join as z,resolve as xe}from"node:path";import{Readable as Or}from"node:stream";var Ht=2e3,Yt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Qt=512,I=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Yt,this.shutdownMs=r.shutdownMs??Ht,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Qt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Xt}from"node:crypto";import{bind as Zt,bunDriver as er,createDatabase as tr,envBlock as rr,createSearchWorker as sr,cutOff as nr,forgetUser as ar,MigrationOpen as or,MigrationRefused as ir,Migrator as ce,renewingBunPool as ae,VersionNotMigrated as lr}from"palgres";import{toModel as de}from"palgres/dsl";var cr=["start","complete","rollback","plan","status","types"],dr=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!cr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function U(t){return de(pe(t))}function ur(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function pr(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var oe=5;function fe(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=ae(()=>new r.SQL({url:n,prepare:!1,max:s})),i=ae(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:er(a,i),poolSize:s,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await R(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await R("types",rr(r,{module:"palbase/backend/env"}),e),0}async function me(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!dr.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=fe(t,he(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=U(t),u=new ce(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let g=new URL(s);g.pathname=`/${f}`;let y=a(g.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>hr(e)});if(r==="plan"){let f=await u.plan(l);return await R(r,f),f.refusals.length>0?1:0}if(r==="status")return await R(r,await u.status()),0;let h=r==="start"?await fr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await R(r,h),0}catch(l){return l instanceof ir?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):nr(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??ie(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function hr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=_({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function fr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof or)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function R(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
2
+ import{$ as It,A as F,B as dt,C as ut,D as ht,E as ft,F as gt,G as bt,H as mt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as _t,S as xt,T as Rt,U as Ot,V as Ct,W as Bt,X as re,Y as Ft,Z as Mt,_ as $t,a as Q,aa as Lt,b as X,ba as Ut,c as Z,ca as Dt,d as Ne,da as jt,e as qe,ea as Nt,f as We,fa as M,g as Ke,ga as Vt,h as Ve,ha as $,i as Ge,ia as V,j as ze,ja as Gt,k as He,ka as zt,l as Ye,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as rt,t as st,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/32XY6IBN.js";import{a as ne}from"../chunks/BW5DFI3C.js";import{a as x,b as ee,c as te,f as b,g as pt,h as d,j as se,k as Kt}from"../chunks/PMQOJ7FF.js";import{a as qt,b as Wt}from"../chunks/JKA2W4E5.js";import{d as _,j as De,k as je,l as H,m as B,t as Y,u as J}from"../chunks/ART5HP5M.js";import"../chunks/4HFD24QY.js";import"../chunks/7R4WTDHI.js";import"../chunks/3GWBIPGH.js";import"../chunks/XHNZDLR4.js";import"../chunks/7QFBZLAK.js";import{n as Ue}from"../chunks/ZXV3ZKVM.js";import"../chunks/FT7G3QQ4.js";import{b as A,c as K}from"../chunks/VQXYHAU4.js";import"../chunks/6IMY2J5W.js";import"../chunks/T2O6XEQO.js";import"reflect-metadata";import{existsSync as G,writeFileSync as _r,writeSync as xr}from"node:fs";import{createServer as Rr}from"node:http";import{dirname as k,join as z,resolve as xe}from"node:path";import{Readable as Or}from"node:stream";var Ht=2e3,Yt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Qt=512,I=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Yt,this.shutdownMs=r.shutdownMs??Ht,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Qt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Xt}from"node:crypto";import{bind as Zt,bunDriver as er,createDatabase as tr,envBlock as rr,createSearchWorker as sr,cutOff as nr,forgetUser as ar,MigrationOpen as or,MigrationRefused as ir,Migrator as ce,renewingBunPool as ae,VersionNotMigrated as lr}from"palgres";import{toModel as de}from"palgres/dsl";var cr=["start","complete","rollback","plan","status","types"],dr=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!cr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function U(t){return de(pe(t))}function ur(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function pr(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var oe=5;function fe(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=ae(()=>new r.SQL({url:n,prepare:!1,max:s})),i=ae(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:er(a,i),poolSize:s,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await R(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await R("types",rr(r,{module:"palbase/backend/env"}),e),0}async function me(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!dr.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=fe(t,he(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=U(t),u=new ce(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let g=new URL(s);g.pathname=`/${f}`;let y=a(g.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>hr(e)});if(r==="plan"){let f=await u.plan(l);return await R(r,f),f.refusals.length>0?1:0}if(r==="status")return await R(r,await u.status()),0;let h=r==="start"?await fr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await R(r,h),0}catch(l){return l instanceof ir?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):nr(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??ie(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function hr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=_({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function fr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof or)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function R(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
3
3
  `,s))}function ie(t){return(t instanceof Error?t.message:String(t)).split(`
4
4
  `)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function br(t,e){try{return await new ce(t).plan(e)}catch{return}}var le="palbase.idempotency_keys.response_body";function mr(t,e){let r=null,s=!1,n=async()=>{let o=e.currentKey();if(!(s||o===r)){s=!0;try{let c=await t.reseal();r=o;let l=c.reduce((u,h)=>u+h.resealed,0);l>0&&d.info(`[palbase] fields: ${l} value(s) sealed again with key ${o}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${o} stopped; tried again in a minute`,{error:c})}finally{s=!1}}},a=setTimeout(n,1e4),i=setInterval(n,6e4);for(let o of[a,i])o.unref?.();return()=>{clearTimeout(a),clearInterval(i)}}var L=class extends Error{digest;plan;constructor(e,r){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...r?yr(r):[" palbase db:plan says what it would change"]].join(`
5
5
  `)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function yr(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let r of t.changes)e.push(` + ${r}`);for(let r of t.refusals)e.push(` \u2717 ${r}`);return e}var wr=8e4;async function ye(t,e,r,s){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=pe(t),i=de(a),o=fe(t,he(e))(n);try{let c=!1,l=p=>{c||(c=!0,d.warn(`[palbase] database: not answering yet (${p instanceof Error?p.message:String(p)}) \u2014 waiting for it, as one waking does`))},u=await Zt(o.engine,i,{waitMs:s.onPlatform?wr:0,onUnreachable:l}).catch(async p=>{throw s.onPlatform||!(p instanceof lr)?p:new L(p.digest,await br(o.pool,i))}),h=Xt("sha256",r).update("palgres page cursor").digest("hex"),f=t.embed??s.embed,g=s.fields,y=await tr({sql:o.engine,schemas:a,binding:u,cursorSecret:h,admission:pr(o.poolSize),embed:f,log:p=>d.warn(`[palbase] ${p}`),fields:async()=>(await g.load(),g)}),S=g.loaded?mr(y,g):()=>{},m=ur(i)?sr({sql:o.engine,embed:f,log:p=>d.info(`[palbase] ${p}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:p=>ar(o.engine,u,i,p),...m?{search:m}:{},keptAnswers:{seal:p=>g.loaded?g.encrypt(le,p):p,open:async p=>g.isEncrypted(p)?(g.loaded||await g.load(),g.decrypt(le,p)):p},close:async()=>{S(),g.close(),await o.close()}}}catch(c){throw await o.close(),c}}function Pr(t){let e=Buffer.from(t,"base64"),r=new Array(e.byteLength/4);for(let s=0;s<r.length;s++)r[s]=e.readFloatLE(s*4);return r}function we(t){return async({texts:e,model:r,dimensions:s})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:r,dimensions:s}});return{model:n.model,vectors:n.vectors.map(Pr)}}}var Sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Pe(t,e,r){let s=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&s.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&s.push("palbase.url / PALBASE_URL is the project origin alone")}catch{s.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let i=t.projectId??e.PALBASE_PROJECT_ID??"";Sr.test(i)||s.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&s.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let l=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(c!==void 0||l!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(l??"")&&s.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),s.length>0)throw new Error(`[palbase] the app cannot start:
@@ -9,4 +9,4 @@ ${s.join(`
9
9
  `)}
10
10
  `}function Ae(t,e,r=Ar){let s=Buffer.from(e,"utf8"),n=new Int32Array(new SharedArrayBuffer(4));for(let a=0;a<s.length;)try{a+=r(t,s,a,s.length-a)}catch(i){if(i.code!=="EAGAIN")throw i;Atomics.wait(n,0,0,5)}}var ke=2e4,Ee=5e3,Cr=15e3,Br="/_palbase/health";function Fr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=F(s,Q);return n?n.providers.some(a=>F(a,X)!==void 0&&F(a,Z)===void 0)||n.imports.some(r):!1};return t.some(r)}var Mr={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=ue(s);if(n!==void 0){let w=n==="types"?await be(e.db):e.db?await me(e.db,s,n):await ge(n);throw process.exit(w),new j(w)}let a=s.PALBASE_CONTRACT_OUT;if(a){let w;try{await _e(Te(s)),w=await $r(r,e,s)}catch(v){throw xr(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
11
11
  `),process.exit(1),new O}throw a==="/dev/stdout"?Ae(1,ve(w)):_r(a,`${w}
12
- `),process.exit(0),new O}let i=Te(s),o=await _e(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),se(o?void 0:i);let c=e.db?U(e.db):void 0,l=await J({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Fr(r)||c!==void 0&&D(c),h=Pe(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=_({url:h.url,secretKey:h.secretKey}),g=e.port??Number(s.PORT??"8080");if(!Number.isInteger(g)||g<0||g>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await ye(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&D(y.model)?{"user.deleted":[w=>Ir(y,w)]}:void 0,m=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new I(f.analytics),C=()=>$({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:H({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Dr(e.cors,s.PALBASE_WEB_ORIGINS),platform:m,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),T=C(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await T.start();break}catch(v){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:v}),await new Promise(Le=>setTimeout(Le,W)),W*=2,T=C()}return Lr(T,f,g,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Te(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=k(xe(e));for(;!G(z(r,"package.json"))&&k(r)!==r;)r=k(r);return G(z(r,"package.json"))?r:process.cwd()}async function _e(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=xe(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(s);for(;!G(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/FQLY6TBH.js"),{routeContracts:i}=await import("../chunks/45DR7TF6.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=$({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:_({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:re()},events:e.db&&D(U(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Ir(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r);d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Lr(t,e,r,s,n,a){let i,o={on:!1},c=(m,p)=>new URL(m.url).pathname===Br&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,p),l=Rr((m,p)=>{Ur(c,m,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,p)=>{l.once("error",p),l.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=m=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(T=>l.close(()=>T()));l.closeIdleConnections();let C=setTimeout(()=>l.closeAllConnections(),m);await p,clearTimeout(C),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(ke),g=!1,y=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let m=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Cr);m.unref(),f().then(()=>{clearTimeout(m),process.exit(0)},p=>{clearTimeout(m),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=m=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let p=setTimeout(()=>process.exit(1),Ee+1e3);h(Ee).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let g of f)i.append(h,g);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Or.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function Dr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>V(o)),a=s.filter(o=>!V(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Ys,boolean as Js,check as Qs,date as Xs,defineSchema as Zs,defineTable as en,enumType as tn,foreignKey as rn,index as sn,integer as nn,jsonb as an,numeric as on,ownedByUser as ln,policy as cn,raw as dn,sqlType as un,text as pn,timestamp as hn,userRef as fn,uuid as gn}from"palgres/dsl";import{increment as mn,now as yn}from"palgres";function E(t){if(t instanceof A)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return E(r)}}var jr=x("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Nr=100,qr=1e3,Wr=168*3600,Kr={s:1,m:60,h:3600,d:86400};function Vr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Kr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${b.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Re(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function Gr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:E(a)}},async download(e){try{let r=await b.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return E(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Vr(r?.expiresIn);return s===void 0||s<1||s>Wr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??Nr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(qr,n+s-a.length)),l=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Re(u));if(i=l.data.next_cursor,!i)break}}catch(c){return E(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await b.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return E(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var zr={bucket:Gr},Oe=t=>ee("Storage",t,zr),Hr={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},Yr=x("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>b.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>b.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await b.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return E(c)}return{data:{message_ids:a},error:null,status:i}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,Jr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return te.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return P(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),r=>r.values??{})}var Me={setOverrideForUser:(t,e,r)=>P(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),setOverridesForUser:(t,e)=>P(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),clearAllOverridesForUser:t=>P(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Qr=x("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Ce(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Be(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Be(s);return{name:r,enabled:Ce(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Jr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Ie();return r?Me.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Me}}),Xr=x("Realtime",{broadcast(t,e,r){return P(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as Tn}from"zod";export{je as AuthUnavailable,vt as Authorize,Mt as BadRequest,He as Body,Gt as CACHE_MAX_TTL,zt as Cache,wt as ChatPart,st as Client,$t as Conflict,O as ContractRunEnded,Ne as Controller,lt as Cron,pt as Database,It as DeadlockDetected,Ge as Delete,Rt as DiError,Ue as EVENT_TYPES,Qr as Flags,Bt as Forbidden,St as Gateway,Pt as GatewayRefusal,qe as Get,Je as Headers,Lt as HttpError,at as Injectable,d as Log,Vt as MAX_BODY_BYTES,j as MigrationRunEnded,ot as Module,Ut as NotFound,Yr as Notifications,it as On,kt as OnConnect,Et as OnDisconnect,Tt as OnEmpty,At as OnFirst,Ze as OptionalUser,Ot as PalError,b as Palbase,A as PalbaseError,Mr as PalbaseFactory,Qe as Param,Ve as Patch,We as Post,Ke as Put,ze as Query,Ye as QueryParams,Xr as Realtime,et as Req,tt as RequestId,nt as Resolve,L as SchemaNotPushed,jr as Secrets,Dt as SerializationFailure,Hr as Storage,_t as Subscribe,ft as Task,ht as TaskFailure,gt as Tasks,bt as TestUserTemplate,De as TokenError,B as TokenVerifier,jt as TooManyRequests,rt as TraceId,Ct as Unauthorized,Nt as UniqueViolation,mt as Upload,yt as UploadedObject,Xe as User,ct as Webhook,Ys as bigint,Js as boolean,Qs as check,$ as createApp,Xs as date,Ft as defineError,Zs as defineSchema,en as defineTable,Wt as encrypt,qt as encrypted,tn as enumType,rn as foreignKey,dt as getRegisteredControllers,ut as getRoutes,xt as getWebhookManifest,mn as increment,sn as index,nn as integer,an as jsonb,yn as now,on as numeric,ln as ownedByUser,cn as policy,dn as raw,un as sqlType,Kt as t,pn as text,hn as timestamp,fn as userRef,gn as uuid,Tn as z};
12
+ `),process.exit(0),new O}let i=Te(s),o=await _e(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),se(o?void 0:i);let c=e.db?U(e.db):void 0,l=await J({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Fr(r)||c!==void 0&&D(c),h=Pe(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=_({url:h.url,secretKey:h.secretKey}),g=e.port??Number(s.PORT??"8080");if(!Number.isInteger(g)||g<0||g>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await ye(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&D(y.model)?{"user.deleted":[w=>Ir(y,w)]}:void 0,m=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new I(f.analytics),C=()=>$({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:H({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Dr(e.cors,s.PALBASE_WEB_ORIGINS),platform:m,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),T=C(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await T.start();break}catch(v){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:v}),await new Promise(Le=>setTimeout(Le,W)),W*=2,T=C()}return Lr(T,f,g,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Te(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=k(xe(e));for(;!G(z(r,"package.json"))&&k(r)!==r;)r=k(r);return G(z(r,"package.json"))?r:process.cwd()}async function _e(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=xe(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(s);for(;!G(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/4S4ODZVM.js"),{routeContracts:i}=await import("../chunks/KRQZOF2L.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=$({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:_({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:re()},events:e.db&&D(U(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Ir(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r);d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Lr(t,e,r,s,n,a){let i,o={on:!1},c=(m,p)=>new URL(m.url).pathname===Br&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,p),l=Rr((m,p)=>{Ur(c,m,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,p)=>{l.once("error",p),l.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=m=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(T=>l.close(()=>T()));l.closeIdleConnections();let C=setTimeout(()=>l.closeAllConnections(),m);await p,clearTimeout(C),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(ke),g=!1,y=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let m=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Cr);m.unref(),f().then(()=>{clearTimeout(m),process.exit(0)},p=>{clearTimeout(m),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=m=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let p=setTimeout(()=>process.exit(1),Ee+1e3);h(Ee).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let g of f)i.append(h,g);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Or.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function Dr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>V(o)),a=s.filter(o=>!V(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Ys,boolean as Js,check as Qs,date as Xs,defineSchema as Zs,defineTable as en,enumType as tn,foreignKey as rn,index as sn,integer as nn,jsonb as an,numeric as on,ownedByUser as ln,policy as cn,raw as dn,sqlType as un,text as pn,timestamp as hn,userRef as fn,uuid as gn}from"palgres/dsl";import{increment as mn,now as yn}from"palgres";function E(t){if(t instanceof A)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return E(r)}}var jr=x("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Nr=100,qr=1e3,Wr=168*3600,Kr={s:1,m:60,h:3600,d:86400};function Vr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Kr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${b.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Re(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function Gr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:E(a)}},async download(e){try{let r=await b.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return E(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Vr(r?.expiresIn);return s===void 0||s<1||s>Wr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??Nr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(qr,n+s-a.length)),l=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Re(u));if(i=l.data.next_cursor,!i)break}}catch(c){return E(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await b.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return E(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var zr={bucket:Gr},Oe=t=>ee("Storage",t,zr),Hr={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},Yr=x("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>b.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>b.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await b.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return E(c)}return{data:{message_ids:a},error:null,status:i}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,Jr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return te.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return P(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),r=>r.values??{})}var Me={setOverrideForUser:(t,e,r)=>P(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),setOverridesForUser:(t,e)=>P(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),clearAllOverridesForUser:t=>P(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Qr=x("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Ce(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Be(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Be(s);return{name:r,enabled:Ce(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Jr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Ie();return r?Me.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Me}}),Xr=x("Realtime",{broadcast(t,e,r){return P(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as Tn}from"zod";export{je as AuthUnavailable,vt as Authorize,Mt as BadRequest,He as Body,Gt as CACHE_MAX_TTL,zt as Cache,wt as ChatPart,st as Client,$t as Conflict,O as ContractRunEnded,Ne as Controller,lt as Cron,pt as Database,It as DeadlockDetected,Ge as Delete,Rt as DiError,Ue as EVENT_TYPES,Qr as Flags,Bt as Forbidden,St as Gateway,Pt as GatewayRefusal,qe as Get,Je as Headers,Lt as HttpError,at as Injectable,d as Log,Vt as MAX_BODY_BYTES,j as MigrationRunEnded,ot as Module,Ut as NotFound,Yr as Notifications,it as On,kt as OnConnect,Et as OnDisconnect,Tt as OnEmpty,At as OnFirst,Ze as OptionalUser,Ot as PalError,b as Palbase,A as PalbaseError,Mr as PalbaseFactory,Qe as Param,Ve as Patch,We as Post,Ke as Put,ze as Query,Ye as QueryParams,Xr as Realtime,et as Req,tt as RequestId,nt as Resolve,L as SchemaNotPushed,jr as Secrets,Dt as SerializationFailure,Hr as Storage,_t as Subscribe,ft as Task,ht as TaskFailure,gt as Tasks,bt as TestUserTemplate,De as TokenError,B as TokenVerifier,jt as TooManyRequests,rt as TraceId,Ct as Unauthorized,Nt as UniqueViolation,mt as Upload,yt as UploadedObject,Xe as User,ct as Webhook,Ys as bigint,Js as boolean,Qs as check,$ as createApp,Xs as date,Ft as defineError,Zs as defineSchema,en as defineTable,Wt as encrypt,qt as encrypted,tn as enumType,rn as foreignKey,dt as getRegisteredControllers,ut as getRoutes,xt as getWebhookManifest,mn as increment,sn as index,nn as integer,an as jsonb,yn as now,on as numeric,ln as ownedByUser,cn as policy,dn as raw,un as sqlType,Kt as t,pn as text,hn as timestamp,fn as userRef,gn as uuid,Tn as z};
@@ -1 +1 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
@@ -1,2 +1,2 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
2
- import{a as u}from"../chunks/KUTBWXNL.js";import{c as p,i as c}from"../chunks/O6LRXDFY.js";import{b as l,c as g,d as f,e as y}from"../chunks/55C2GHGA.js";import"../chunks/MI5QEZ7Y.js";import"../chunks/XAHQAK65.js";import"../chunks/WW4HVDSO.js";import"../chunks/K3KCYVMN.js";import"../chunks/V72PBUK4.js";import"../chunks/HPQSHDEH.js";import"../chunks/25FDQIKY.js";import"../chunks/K2CN4CGB.js";import"../chunks/CPQR6PSB.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as u}from"../chunks/BW5DFI3C.js";import{c as p,i as c}from"../chunks/PMQOJ7FF.js";import{b as l,c as g,d as f,e as y}from"../chunks/BKGX3AZA.js";import"../chunks/4HFD24QY.js";import"../chunks/3GWBIPGH.js";import"../chunks/XHNZDLR4.js";import"../chunks/7QFBZLAK.js";import"../chunks/ZXV3ZKVM.js";import"../chunks/FT7G3QQ4.js";import"../chunks/VQXYHAU4.js";import"../chunks/6IMY2J5W.js";import"../chunks/T2O6XEQO.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
2
- import{a as xt,c as re,d as dr,e as cr,f as we,h as $,i as mr}from"./O6LRXDFY.js";import{c as ur,d as lr,e as en,f as fr,g as pr}from"./IG2INK7Z.js";import{a as rr,e as at,g as Et,h as sr,i as ar,j as St,k as At,n as or,t as ir}from"./GL5Y2PAS.js";import{a as _t,b as tr,n as nr}from"./ENZI5RN5.js";import{b as ie}from"./25FDQIKY.js";import"reflect-metadata";var tn=[{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}],hr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Rt=/^\d+$/;function pa(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),i=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Rt.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let l=t,h=n;if(i!=="*")if(i.includes("-")){let y=i.indexOf("-"),k=i.slice(0,y),S=i.slice(y+1);if(!Rt.test(k)||!Rt.test(S)||Number(k)<t||Number(S)>n||Number(k)>Number(S))return;l=Number(k),h=Number(S)}else{if(!Rt.test(i)||Number(i)<t||Number(i)>n)return;l=Number(i),h=a===-1?l:n}for(let y=l;y<=h;y+=d)r.add(y)}return r}function gr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${hr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=pa(t[h],tn[h].lo,tn[h].hi);if(!y)return`${hr}; its ${tn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let i=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 y=r.has(l.getUTCDate()),k=a.has(l.getUTCDay());if(i||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var Ue=Symbol.for("palbase.backend.controller"),Le=Symbol.for("palbase.backend.routes"),rn=Symbol.for("palbase.backend.params"),sn=Symbol.for("palbase.backend.injectable"),an=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),Ie=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=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 nn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[nn]instanceof Set||(e[nn]=new Set),e[nn]}var qe=new Set(["webhooks","_palbase"]);function id(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&&qe.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,Ue,()=>({basePath:e,options:t})),se().add(n)}}function He(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,Le,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var dd=He("GET"),cd=He("POST"),ud=He("PUT"),ld=He("PATCH"),fd=He("DELETE"),pd=He("QUERY");function le(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,rn,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function on(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 md=e=>le("body",{schema:on("Body",e)}),hd=e=>le("query",{schema:on("QueryParams",e)}),gd=e=>le("headers",e===void 0?{}:{schema:on("Headers",e)}),yd=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return le("param",{name:e})},wd=()=>le("user"),bd=()=>le("optionalUser"),kd=()=>le("req"),vd=()=>le("requestId"),Td=()=>le("requestId"),$d=()=>le("client");function _d(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 le("resolve",{resolver:e,options:t[0]})}function Ed(){return e=>{de(e,sn,()=>!0),se().add(e)}}function Sd(e){return t=>{de(t,an,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var br=/^[a-z]+(\.[a-z_]+)+$/,ma=/^[a-z][a-z0-9-]{1,62}$/,dn=e=>e.startsWith("file.");function Ad(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"||!ma.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(!dn(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,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var cn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ha=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function yr(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(!ha.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 xd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!cn.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=gr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||yr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${yr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var wr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ga=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Rd(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(!ga.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&&!wr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${wr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&ya(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,Ce)??[];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:i,bucket:d}of s){if(a.has(i))throw new TypeError(`${n}: @On("${i}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${i}", { 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(i)}de(t,Ie,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:i,fn:d})=>({event:i,fn:d}))})),se().add(t)}}function ya(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 Od(){return[...se()].filter(e=>D(e,Ue)!==void 0)}function Pd(e){return(D(e,Le)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Ot=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Nd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!cn.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,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var fn;function vr(e){fn=e}function un(){if(!fn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return fn}var wa=720*3600;function ba(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>wa))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 ka(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Ud=xt("Tasks",{async enqueue(e,t,n={}){return ba(n),un().enqueue(ka(e),t===void 0?null:t,n)},async cancel(e,t={}){return un().cancel(e,t.machine)},async get(e,t={}){return un().get(e,t.machine)}}),ln=(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 Tr(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 we.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 ln(a.data,a.status===200)},async cancel(n,r){return ln((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return ln((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var va=1e4,Ta=36e5,kr=24*36e5,Pt=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<kr))return this.view(l,!0)}let a=this.now(),i=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:i,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 i=`${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: ${i}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${i}`):(t.state="waiting",t.reason=`the app answered ${i}`,t.runAt=this.now()+Math.min(va*2**Math.min(t.attempt-1,16),Ta),$.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>=kr&&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 Ct="/_palbase/test-user-templates",$a=/^[a-z][a-z0-9_-]{0,63}$/;function Hd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!$a.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function $r(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 _r(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 _a="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 Er(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,_a),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var pn="/_palbase/storage/upload/authorize",Sr="/_palbase/storage/upload/complete",mn="/_palbase/realtime/rooms";var Ea=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ze(e){if(!Ea(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 Ar(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function xr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Mt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Sa=/^[a-z][a-z0-9-]{1,62}$/,Rr=1024,Aa=new Set(["userId","uploadId","filename"]);function Kd(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Sa.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=xa(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(i,d,l)=>{if(typeof d!="string"||l===void 0||typeof l.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(i.constructor,Le,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function Jd(){return le("uploadedObject")}function xa(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Aa.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(!Or(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Or(e){if(e===""||new TextEncoder().encode(e).byteLength>Rr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Ra(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Oa(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Oa(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 Pr(e,t){let n=Ra(e,t);return Or(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Rr} bytes)`}}function Cr(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 hn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Mr(e,t){if(!hn(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 i=ze(t.user);if(!i)return"user is { id?, session?, role }";let d=Ar(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:i,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=Pa(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:i,...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 Pa(e){if(!hn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:i,width:d,height:l,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof i!="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")&&!(!hn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:i,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Ca}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),Be=Symbol.for("palbase.backend.gatewayHooks"),jr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ma={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(jr),output:()=>structuredClone(jr)}}},Hr=Symbol.for("palbase.backend.gatewayRefusal"),Dr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Hr,{value:!0})}},ja=e=>typeof e=="object"&&e!==null&&e[Hr]===!0&&typeof e.reason=="string",Fe=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Da=6e4,Na=86400,Nr=604800,Ur=65536,$e=255,Ua=["roles:","flags:","messaging:","debug:"],La=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ge=e=>new TextEncoder().encode(e).byteLength,gn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",bn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ia(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ge(e)>$e)return`a channel is ${$e} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=Ua.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 zr(e){if(typeof e!="string"||e==="")return"is a name";if(Ge(e)>$e)return`is ${$e} bytes at most`}function Xd(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ia(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&bn(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=qa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let i=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(i)||La.has(i))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(i)} \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 ${i}: 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 ${i}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let S=zr(y);if(S)throw new TypeError(`@Gateway("${e}") on ${i}: event "${y}" ${S}`);if(!gn(k))throw new TypeError(`@Gateway("${e}") on ${i}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Be,kn),h={name:i,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ma}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Da,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 ${i}: 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 ${i}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Fe(h))throw new TypeError(`@Gateway("${e}") on ${i}: 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 ${i}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Fe(h))throw new TypeError(`@Gateway("${e}") on ${i}: 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,Me,()=>h),se().add(a)}}function qa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Na;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Nr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Nr} (a week)`);return n}var kn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ha={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ot(e){let t=Ha[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,Be,kn),i=a.hooks[e];if(i!==void 0&&i!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${i} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var ec=ot("authorize"),tc=ot("first"),nc=ot("connect"),rc=ot("disconnect"),sc=ot("empty");function ac(e,t,n={}){let r=zr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!gn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!gn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,i)=>{if(typeof a!="string"||i===void 0||typeof i.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,Be,kn),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 za(e){return D(e,Me)}function Fa(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 i=n[a];if(i.length>=2&&i.startsWith("{")&&i.endsWith("}")){if(r[a]==="")return;s.push([i.slice(1,-1),r[a]])}else if(i!==r[a])return}return Object.fromEntries(s)}function Fr(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),i=Object.hasOwn(t,a)?t[a]:void 0;if(typeof i!="string"||i===""||i.includes(":")||/[\x00-\x1F\x7F]/.test(i))return{problem:`{${a}} is a non-empty string with no ':' (got ${i===void 0?"nothing":typeof i})`};n.push(i)}let r=n.join(":");return Ge(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Ga(e,t,n){let r=bn(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))?Fr(e,t):Ba(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let i=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(i.user=s),n.end===!0){if(i.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"};i.end=!0}return i}function Ba(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 Ka=1e4,Ja=1e3,Wa=100,vn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Lr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Ir=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Gr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let m=za(b),v=a.get(m.name);if(v!==void 0&&v!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let C=s.get(Ir(m.pattern));if(C!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(C)?.cls.name}'s "${C}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Ir(m.pattern),m.pattern);for(let[V,Z]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof E[Z]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${V} is ${Z}, which is no method of it`);let U={cls:b,instance:E,g:m};n.set(m.pattern,U),r.set(b,U)}let i=new Map,d=new Set,l=new Set,h=new wn(t.broadcast),y=b=>{let E=i.get(b);return E||(E=new AbortController,i.set(b,E)),E},k=(b,E)=>{E?.abort(),i.get(b)===E&&i.delete(b)},S=(b,E,m,v,C,U)=>{if(!Object.hasOwn(b.g.events,m)){$.warn(`[palbase] ${C}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){$.warn(`[palbase] ${C}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:m,payload:v??{},...U!==void 0?{conn_id:U}:{}},C)},z=async(b,E,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(E)};function N(b,E,m,v,C,U,V){let Z=v?.signal??AbortSignal.abort(),L=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...m}),signal:Z,count:C,user:U,emit:(I,G)=>S(b,E,I,G,L,V),pipe:I=>z(I,E,L),owner:{hold(I){re.exit(async()=>{try{await I(Z)}catch(G){Z.aborted||$.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(E,v)}}}function H(b){let{room:E,channel:m}=b;if(typeof E!="string"||typeof m!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let v=n.get(E);return!v||!Fe(v.g)?he(404,"not_found",`This app serves no gateway "${E}"`):{entry:v,channel:m,params:Fa(E,m)}}let J=(b,E)=>he(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function F(b,E){let m=H(b);if("status"in m)return m;let{entry:v,channel:C,params:U}=m,V={status:200,body:{subscribe:!1,publish:!1}};if(!U)return $.warn(`[palbase] ${v.cls.name}: realtime asked about "${C}", which is not a channel of the gateway "${v.g.pattern}"; the join is refused`),V;let Z=ze(b.user),L=Z?.id;if(!L)return V;if(v.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}};if(v.g.access==="owner")return U[bn(v.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}}:V;let I=v.g.hooks.authorize;if(!I)return V;let G,B;try{G=await t.run(Z,`${v.cls.name}.${I}`,E,async()=>v.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Va(G)}catch(ne){if(t.isOutage(ne)||E?.aborted)throw ne;return $.error(`[palbase] ${v.cls.name}.${I} (@Authorize of ${C}) failed; the join is refused`,{error:ne}),V}return B==="malformed"?($.warn(`[palbase] ${v.cls.name}.${I} (@Authorize of ${C}) answered ${Za(G)}, which is no grant (true, { read, write } or null); the join is refused`),V):{status:200,body:B}}async function oe(b,E){let m=H(b);if("status"in m)return m;if(!m.params)return J(m.entry.g.pattern,m.channel);let v=ze(b.user);if(!v?.id||typeof b.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let C=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!C)return{status:200,body:{ok:!1,reason:yn(`gateway "${m.channel}" takes no message "${b.event}"`,jt)}};let U=await C.schema["~standard"].validate(Ca(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:qr(U.issues)}};let V=y(m.channel),Z={...N(m.entry,m.channel,m.params,V,0,{id:v.id}),payload:U.value},L=`${m.entry.cls.name}.${C.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run(v,`${m.entry.cls.name}.${C.fn}`,E,async()=>m.entry.instance[C.fn](Z))}catch(B){if(t.isOutage(B))throw B;return ja(B)?{status:200,body:{ok:!1,reason:yn(B.reason,jt)}}:(E?.aborted||$.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(C.reply){let B=await C.reply["~standard"].validate(I);if(B.issues)return $.error(`[palbase] ${L} returned an ack its reply schema refuses (${qr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return $.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Ge(G)>Ur?($.error(`[palbase] ${L} returned an ack of ${Ge(G)} bytes, past ${Ur}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function me(b,E){let m=H(b);if("status"in m)return m;if(!m.params)return J(m.entry.g.pattern,m.channel);let v=b.event;if(typeof v!="string"||!Object.hasOwn(Lr,v))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let C=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(C===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let U=v==="join"||v==="leave",V=U?ze(b.user):void 0,Z=U?b.connId:void 0;if(U&&(!V?.id||typeof Z!="string"||Z===""))return he(400,"bad_request",`A ${v} names its member: user and connId`);let L=`${v}\0${m.channel}\0${typeof Z=="string"?Z:""}`;if(U&&d.has(L))return{status:204};if(l.has(L))return he(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let I=m.entry.g.hooks[Lr[v]],G;if(v==="empty"?(G=i.get(m.channel),k(m.channel,G)):G=v==="leave"?i.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,C,{id:V?.id??""},v==="join"?Z:void 0);try{await t.run(V,`${m.entry.cls.name}.${I}`,E,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return E?.aborted||$.error(`[palbase] ${m.entry.cls.name}.${I} (${v} of ${m.channel}) failed; realtime tells it again`,{error:ne}),he(500,"handler_failed",`The gateway's ${v} could not be handled`)}}return U&&(d.add(L),d.size>Ka&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function Se(b,E){let m=r.get(b),v=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${v}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let C=Fr(m.g.pattern,E??{});if(typeof C!="string")throw new TypeError(`${v}: ${C.problem}`);return{entry:m,channel:C,where:v}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,m){return vn(E)?b==="authorize"?F(E,m):b==="message"?oe(E,m):b==="lifecycle"?me(E,m):he(404,"not_found",`No gateway call ${JSON.stringify(b)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,m,v){let{entry:C,channel:U,where:V}=Se(b,E);S(C,U,m,v,V)},async pipe(b,E,m){let{channel:v,where:C}=Se(b,E);await z(m,v,C)},async revalidate(b,E,m={}){let v=r.get(b),C=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!v)throw new TypeError(`${C}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Ga(v.g.pattern,E??{},m);if("problem"in U)throw new TypeError(`${C}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of i.values())b.abort();i.clear()}}}function Va(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!vn(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function Za(e){return Array.isArray(e)?"an array":vn(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 Ya=20,jt=256;function qr(e){let t="";for(let n of e.slice(0,Ya)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=jt)break}return yn(t,jt)}function yn(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 wn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ge(t.event)>$e){$.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){$.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ja?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),re.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,Wa);try{await this.broadcast(s)}catch(i){$.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:i})}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 Tn,createHmac as Qa,createPublicKey as Wr,timingSafeEqual as Xa,verify as Vr}from"node:crypto";function cc(e){let t=D(e,Ie);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function Zr(e,t,n,r={}){let s=new Map,a=[];for(let i of e){let d=D(i,Ie),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${i.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${i.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=eo(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let S=t(i),z=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${i.name}.${H}`,call:(J,F)=>S[H](J,F)}]));s.set(d.name,{name:d.name,cls:i,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:z})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as xt,c as re,d as dr,e as cr,f as we,h as $,i as mr}from"./PMQOJ7FF.js";import{c as ur,d as lr,e as en,f as fr,g as pr}from"./JKA2W4E5.js";import{a as rr,e as at,g as Et,h as sr,i as ar,j as St,k as At,n as or,t as ir}from"./ART5HP5M.js";import{a as _t,b as tr,n as nr}from"./7R4WTDHI.js";import{b as ie}from"./VQXYHAU4.js";import"reflect-metadata";var tn=[{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}],hr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Rt=/^\d+$/;function pa(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),i=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Rt.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let l=t,h=n;if(i!=="*")if(i.includes("-")){let y=i.indexOf("-"),k=i.slice(0,y),S=i.slice(y+1);if(!Rt.test(k)||!Rt.test(S)||Number(k)<t||Number(S)>n||Number(k)>Number(S))return;l=Number(k),h=Number(S)}else{if(!Rt.test(i)||Number(i)<t||Number(i)>n)return;l=Number(i),h=a===-1?l:n}for(let y=l;y<=h;y+=d)r.add(y)}return r}function gr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${hr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=pa(t[h],tn[h].lo,tn[h].hi);if(!y)return`${hr}; its ${tn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let i=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 y=r.has(l.getUTCDate()),k=a.has(l.getUTCDay());if(i||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var Ue=Symbol.for("palbase.backend.controller"),Le=Symbol.for("palbase.backend.routes"),rn=Symbol.for("palbase.backend.params"),sn=Symbol.for("palbase.backend.injectable"),an=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),Ie=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=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 nn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[nn]instanceof Set||(e[nn]=new Set),e[nn]}var qe=new Set(["webhooks","_palbase"]);function id(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&&qe.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,Ue,()=>({basePath:e,options:t})),se().add(n)}}function He(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,Le,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var dd=He("GET"),cd=He("POST"),ud=He("PUT"),ld=He("PATCH"),fd=He("DELETE"),pd=He("QUERY");function le(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,rn,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function on(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 md=e=>le("body",{schema:on("Body",e)}),hd=e=>le("query",{schema:on("QueryParams",e)}),gd=e=>le("headers",e===void 0?{}:{schema:on("Headers",e)}),yd=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return le("param",{name:e})},wd=()=>le("user"),bd=()=>le("optionalUser"),kd=()=>le("req"),vd=()=>le("requestId"),Td=()=>le("requestId"),$d=()=>le("client");function _d(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 le("resolve",{resolver:e,options:t[0]})}function Ed(){return e=>{de(e,sn,()=>!0),se().add(e)}}function Sd(e){return t=>{de(t,an,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var br=/^[a-z]+(\.[a-z_]+)+$/,ma=/^[a-z][a-z0-9-]{1,62}$/,dn=e=>e.startsWith("file.");function Ad(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"||!ma.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(!dn(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,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var cn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ha=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function yr(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(!ha.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 xd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!cn.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=gr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||yr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${yr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var wr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ga=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Rd(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(!ga.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&&!wr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${wr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&ya(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,Ce)??[];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:i,bucket:d}of s){if(a.has(i))throw new TypeError(`${n}: @On("${i}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${i}", { 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(i)}de(t,Ie,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:i,fn:d})=>({event:i,fn:d}))})),se().add(t)}}function ya(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 Od(){return[...se()].filter(e=>D(e,Ue)!==void 0)}function Pd(e){return(D(e,Le)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Ot=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Nd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!cn.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,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var fn;function vr(e){fn=e}function un(){if(!fn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return fn}var wa=720*3600;function ba(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>wa))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 ka(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Ud=xt("Tasks",{async enqueue(e,t,n={}){return ba(n),un().enqueue(ka(e),t===void 0?null:t,n)},async cancel(e,t={}){return un().cancel(e,t.machine)},async get(e,t={}){return un().get(e,t.machine)}}),ln=(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 Tr(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 we.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 ln(a.data,a.status===200)},async cancel(n,r){return ln((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return ln((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var va=1e4,Ta=36e5,kr=24*36e5,Pt=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<kr))return this.view(l,!0)}let a=this.now(),i=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:i,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 i=`${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: ${i}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${i}`):(t.state="waiting",t.reason=`the app answered ${i}`,t.runAt=this.now()+Math.min(va*2**Math.min(t.attempt-1,16),Ta),$.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>=kr&&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 Ct="/_palbase/test-user-templates",$a=/^[a-z][a-z0-9_-]{0,63}$/;function Hd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!$a.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function $r(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 _r(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 _a="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 Er(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,_a),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var pn="/_palbase/storage/upload/authorize",Sr="/_palbase/storage/upload/complete",mn="/_palbase/realtime/rooms";var Ea=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ze(e){if(!Ea(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 Ar(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function xr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Mt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Sa=/^[a-z][a-z0-9-]{1,62}$/,Rr=1024,Aa=new Set(["userId","uploadId","filename"]);function Kd(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Sa.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=xa(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(i,d,l)=>{if(typeof d!="string"||l===void 0||typeof l.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(i.constructor,Le,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function Jd(){return le("uploadedObject")}function xa(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Aa.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(!Or(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Or(e){if(e===""||new TextEncoder().encode(e).byteLength>Rr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Ra(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Oa(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Oa(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 Pr(e,t){let n=Ra(e,t);return Or(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Rr} bytes)`}}function Cr(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 hn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Mr(e,t){if(!hn(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 i=ze(t.user);if(!i)return"user is { id?, session?, role }";let d=Ar(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:i,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=Pa(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:i,...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 Pa(e){if(!hn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:i,width:d,height:l,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof i!="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")&&!(!hn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:i,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Ca}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),Be=Symbol.for("palbase.backend.gatewayHooks"),jr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ma={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(jr),output:()=>structuredClone(jr)}}},Hr=Symbol.for("palbase.backend.gatewayRefusal"),Dr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Hr,{value:!0})}},ja=e=>typeof e=="object"&&e!==null&&e[Hr]===!0&&typeof e.reason=="string",Fe=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Da=6e4,Na=86400,Nr=604800,Ur=65536,$e=255,Ua=["roles:","flags:","messaging:","debug:"],La=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ge=e=>new TextEncoder().encode(e).byteLength,gn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",bn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ia(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ge(e)>$e)return`a channel is ${$e} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=Ua.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 zr(e){if(typeof e!="string"||e==="")return"is a name";if(Ge(e)>$e)return`is ${$e} bytes at most`}function Xd(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ia(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&bn(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=qa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let i=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(i)||La.has(i))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(i)} \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 ${i}: 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 ${i}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let S=zr(y);if(S)throw new TypeError(`@Gateway("${e}") on ${i}: event "${y}" ${S}`);if(!gn(k))throw new TypeError(`@Gateway("${e}") on ${i}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Be,kn),h={name:i,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ma}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Da,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 ${i}: 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 ${i}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Fe(h))throw new TypeError(`@Gateway("${e}") on ${i}: 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 ${i}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Fe(h))throw new TypeError(`@Gateway("${e}") on ${i}: 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,Me,()=>h),se().add(a)}}function qa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Na;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Nr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Nr} (a week)`);return n}var kn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ha={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ot(e){let t=Ha[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,Be,kn),i=a.hooks[e];if(i!==void 0&&i!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${i} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var ec=ot("authorize"),tc=ot("first"),nc=ot("connect"),rc=ot("disconnect"),sc=ot("empty");function ac(e,t,n={}){let r=zr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!gn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!gn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,i)=>{if(typeof a!="string"||i===void 0||typeof i.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,Be,kn),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 za(e){return D(e,Me)}function Fa(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 i=n[a];if(i.length>=2&&i.startsWith("{")&&i.endsWith("}")){if(r[a]==="")return;s.push([i.slice(1,-1),r[a]])}else if(i!==r[a])return}return Object.fromEntries(s)}function Fr(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),i=Object.hasOwn(t,a)?t[a]:void 0;if(typeof i!="string"||i===""||i.includes(":")||/[\x00-\x1F\x7F]/.test(i))return{problem:`{${a}} is a non-empty string with no ':' (got ${i===void 0?"nothing":typeof i})`};n.push(i)}let r=n.join(":");return Ge(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Ga(e,t,n){let r=bn(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))?Fr(e,t):Ba(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let i=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(i.user=s),n.end===!0){if(i.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"};i.end=!0}return i}function Ba(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 Ka=1e4,Ja=1e3,Wa=100,vn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Lr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Ir=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Gr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let m=za(b),v=a.get(m.name);if(v!==void 0&&v!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let C=s.get(Ir(m.pattern));if(C!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(C)?.cls.name}'s "${C}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Ir(m.pattern),m.pattern);for(let[V,Z]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof E[Z]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${V} is ${Z}, which is no method of it`);let U={cls:b,instance:E,g:m};n.set(m.pattern,U),r.set(b,U)}let i=new Map,d=new Set,l=new Set,h=new wn(t.broadcast),y=b=>{let E=i.get(b);return E||(E=new AbortController,i.set(b,E)),E},k=(b,E)=>{E?.abort(),i.get(b)===E&&i.delete(b)},S=(b,E,m,v,C,U)=>{if(!Object.hasOwn(b.g.events,m)){$.warn(`[palbase] ${C}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){$.warn(`[palbase] ${C}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:m,payload:v??{},...U!==void 0?{conn_id:U}:{}},C)},z=async(b,E,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(E)};function N(b,E,m,v,C,U,V){let Z=v?.signal??AbortSignal.abort(),L=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...m}),signal:Z,count:C,user:U,emit:(I,G)=>S(b,E,I,G,L,V),pipe:I=>z(I,E,L),owner:{hold(I){re.exit(async()=>{try{await I(Z)}catch(G){Z.aborted||$.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(E,v)}}}function H(b){let{room:E,channel:m}=b;if(typeof E!="string"||typeof m!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let v=n.get(E);return!v||!Fe(v.g)?he(404,"not_found",`This app serves no gateway "${E}"`):{entry:v,channel:m,params:Fa(E,m)}}let J=(b,E)=>he(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function F(b,E){let m=H(b);if("status"in m)return m;let{entry:v,channel:C,params:U}=m,V={status:200,body:{subscribe:!1,publish:!1}};if(!U)return $.warn(`[palbase] ${v.cls.name}: realtime asked about "${C}", which is not a channel of the gateway "${v.g.pattern}"; the join is refused`),V;let Z=ze(b.user),L=Z?.id;if(!L)return V;if(v.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}};if(v.g.access==="owner")return U[bn(v.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}}:V;let I=v.g.hooks.authorize;if(!I)return V;let G,B;try{G=await t.run(Z,`${v.cls.name}.${I}`,E,async()=>v.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Va(G)}catch(ne){if(t.isOutage(ne)||E?.aborted)throw ne;return $.error(`[palbase] ${v.cls.name}.${I} (@Authorize of ${C}) failed; the join is refused`,{error:ne}),V}return B==="malformed"?($.warn(`[palbase] ${v.cls.name}.${I} (@Authorize of ${C}) answered ${Za(G)}, which is no grant (true, { read, write } or null); the join is refused`),V):{status:200,body:B}}async function oe(b,E){let m=H(b);if("status"in m)return m;if(!m.params)return J(m.entry.g.pattern,m.channel);let v=ze(b.user);if(!v?.id||typeof b.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let C=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!C)return{status:200,body:{ok:!1,reason:yn(`gateway "${m.channel}" takes no message "${b.event}"`,jt)}};let U=await C.schema["~standard"].validate(Ca(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:qr(U.issues)}};let V=y(m.channel),Z={...N(m.entry,m.channel,m.params,V,0,{id:v.id}),payload:U.value},L=`${m.entry.cls.name}.${C.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run(v,`${m.entry.cls.name}.${C.fn}`,E,async()=>m.entry.instance[C.fn](Z))}catch(B){if(t.isOutage(B))throw B;return ja(B)?{status:200,body:{ok:!1,reason:yn(B.reason,jt)}}:(E?.aborted||$.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(C.reply){let B=await C.reply["~standard"].validate(I);if(B.issues)return $.error(`[palbase] ${L} returned an ack its reply schema refuses (${qr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return $.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Ge(G)>Ur?($.error(`[palbase] ${L} returned an ack of ${Ge(G)} bytes, past ${Ur}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function me(b,E){let m=H(b);if("status"in m)return m;if(!m.params)return J(m.entry.g.pattern,m.channel);let v=b.event;if(typeof v!="string"||!Object.hasOwn(Lr,v))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let C=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(C===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let U=v==="join"||v==="leave",V=U?ze(b.user):void 0,Z=U?b.connId:void 0;if(U&&(!V?.id||typeof Z!="string"||Z===""))return he(400,"bad_request",`A ${v} names its member: user and connId`);let L=`${v}\0${m.channel}\0${typeof Z=="string"?Z:""}`;if(U&&d.has(L))return{status:204};if(l.has(L))return he(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let I=m.entry.g.hooks[Lr[v]],G;if(v==="empty"?(G=i.get(m.channel),k(m.channel,G)):G=v==="leave"?i.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,C,{id:V?.id??""},v==="join"?Z:void 0);try{await t.run(V,`${m.entry.cls.name}.${I}`,E,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return E?.aborted||$.error(`[palbase] ${m.entry.cls.name}.${I} (${v} of ${m.channel}) failed; realtime tells it again`,{error:ne}),he(500,"handler_failed",`The gateway's ${v} could not be handled`)}}return U&&(d.add(L),d.size>Ka&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function Se(b,E){let m=r.get(b),v=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${v}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let C=Fr(m.g.pattern,E??{});if(typeof C!="string")throw new TypeError(`${v}: ${C.problem}`);return{entry:m,channel:C,where:v}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,m){return vn(E)?b==="authorize"?F(E,m):b==="message"?oe(E,m):b==="lifecycle"?me(E,m):he(404,"not_found",`No gateway call ${JSON.stringify(b)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,m,v){let{entry:C,channel:U,where:V}=Se(b,E);S(C,U,m,v,V)},async pipe(b,E,m){let{channel:v,where:C}=Se(b,E);await z(m,v,C)},async revalidate(b,E,m={}){let v=r.get(b),C=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!v)throw new TypeError(`${C}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Ga(v.g.pattern,E??{},m);if("problem"in U)throw new TypeError(`${C}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of i.values())b.abort();i.clear()}}}function Va(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!vn(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function Za(e){return Array.isArray(e)?"an array":vn(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 Ya=20,jt=256;function qr(e){let t="";for(let n of e.slice(0,Ya)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=jt)break}return yn(t,jt)}function yn(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 wn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ge(t.event)>$e){$.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){$.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ja?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),re.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,Wa);try{await this.broadcast(s)}catch(i){$.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:i})}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 Tn,createHmac as Qa,createPublicKey as Wr,timingSafeEqual as Xa,verify as Vr}from"node:crypto";function cc(e){let t=D(e,Ie);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function Zr(e,t,n,r={}){let s=new Map,a=[];for(let i of e){let d=D(i,Ie),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${i.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${i.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=eo(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let S=t(i),z=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${i.name}.${H}`,call:(J,F)=>S[H](J,F)}]));s.set(d.name,{name:d.name,cls:i,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:z})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
3
  - ${a.join(`
4
4
  - `)}`);return s}function Yr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ke=1024,Br=1024*Ke;function eo(e,t){if(e.signature)return je(void 0,e.signature.header,1/0,fo(e.signature,t));switch(e.provider){case"stripe":return je("stripe","stripe-signature",512*Ke,ro(t));case"github":return je("github","x-hub-signature-256",25*Br,so(t));case"slack":return je("slack","x-slack-signature",64*Ke,ao(t));case"discord":return je("discord","x-signature-ed25519",64*Ke,oo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ke),check:co(t)};case"sendgrid":return je("sendgrid","x-twilio-email-event-webhook-signature",Br,uo(t));case"livekit":return je("livekit","authorization",512*Ke,lo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function je(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??Qr(e,s)}}function Qr(e,t){let n=$n(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:Xr(e,t.headers,r),event:r,...to(e,t,r)}}function Xr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=De(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=ns(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 De(n,"EventType");case"livekit":return De(n,"event");default:return De(n,"type")}}function to(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(De(n,"id"));case"slack":return r(De(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${es(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>De(s,"sg_event_id")||void 0)}:{};default:return{}}}var no=300;function ro(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 y=l.slice(0,h).trim(),k=l.slice(h+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(y==="v1"){let S=fe(k,"hex");if(!S)return"malformed_signature";a.push(S)}}let i=it(s);if(i===void 0||a.length===0)return"malformed_signature";if(dt(i,n))return"stale_timestamp";let d=Je("sha256",e,`${s}.`,t.body);return a.some(l=>_e(l,d))?void 0:"signature_mismatch"}}function so(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?fe(n.slice(7),"hex"):void 0;return r?_e(r,Je("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function ao(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=it(s),i=r.startsWith("v0=")?fe(r.slice(3),"hex"):void 0;return a===void 0||!i?"malformed_signature":dt(a,n)?"stale_timestamp":_e(i,Je("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function oo(e){let t=fe(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=Wr({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 i=r.headers.get("x-signature-timestamp")??void 0,d=it(i),l=fe(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":dt(d,s)?"stale_timestamp":Vr(null,ts(i,r.body),n,l)?void 0:"signature_mismatch"}}var io=1e3;function co(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=fe(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"),i="",d;if(a!==null){if(!_e(Buffer.from(a.toLowerCase()),Buffer.from(Tn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let z=1;for(let J of t.body)if(J===38&&++z>io)return"malformed_signature";let N=new Map;for(let[J,F]of new URLSearchParams($n(t.body))){let oe=N.get(J);oe||N.set(J,oe=new Set),oe.add(F)}let H=[];for(let J of[...N.keys()].sort()){let F=[...N.get(J)].sort();for(let oe of F)i+=J+oe;H.push([J,F.length===1?F[0]:F])}d=Object.fromEntries(H)}let l=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![h,y].some(z=>_e(r,Je("sha1",e,z,i))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),S=k?{id:`${k}:${es(`${h}
5
5
  ${i}`)}`}:{};return d?{type:Xr("twilio",t.headers,d),event:d,...S}:{...Qr("twilio",t),...S}}}function uo(e){let t;try{let n=fe(e,"base64");if(!n)throw new Error;t=Wr({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(),i=it(a),d=fe(s.trim(),"base64");return i===void 0||!d?"malformed_signature":dt(i,r)?"stale_timestamp":Vr("sha256",ts(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Kr=60;function lo(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=Jr(fe(s[0],"base64url")),i=fe(s[2],"base64url");if(a?.alg!=="HS256"||!i)return"malformed_signature";if(!_e(i,Je("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Jr(fe(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Kr||typeof d.nbf=="number"&&n<d.nbf-Kr)return"stale_timestamp";let l=typeof d.sha256=="string"?fe(d.sha256,"base64"):void 0;return l&&_e(l,Tn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function fo(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let i=s.headers.get(e.header);if(!i)return"missing_signature";if(e.prefix){if(!i.startsWith(e.prefix))return"malformed_signature";i=i.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=it(d);if(h===void 0)return"malformed_signature";if(dt(h,a))return"stale_timestamp"}let l=fe(i.trim(),e.encoding);return l?_e(l,Je(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var po=new TextEncoder;function Je(e,t,...n){let r=Qa(e,t);for(let s of n)r.update(s);return r.digest()}function es(e){return Tn("sha256").update(e).digest("hex")}function ts(e,t){return Buffer.concat([po.encode(e),t])}function _e(e,t){return e.byteLength===t.byteLength&&Xa(e,t)}var mo={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 fe(e,t){return mo[t].test(e)?Buffer.from(e,t):void 0}function it(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function dt(e,t){return Math.abs(t-e)>no}function $n(e){return new TextDecoder().decode(e)}function Jr(e){if(e)try{return JSON.parse($n(e))}catch{return}}function ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(e,t){let n=ns(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var W=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
@@ -1,5 +1,5 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
2
- import{a as M,c as he,d as ye,e as be}from"./WW4HVDSO.js";import{a as we}from"./K3KCYVMN.js";import{a as pe}from"./V72PBUK4.js";import{a as ge,b as fe,c as me}from"./HPQSHDEH.js";import{b as $,d as ue}from"./25FDQIKY.js";async function*ke(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",l="",u=[],h,r=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(s,{stream:!0});for(let d=i.indexOf(`
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as M,c as he,d as ye,e as be}from"./XHNZDLR4.js";import{a as we}from"./7QFBZLAK.js";import{a as pe}from"./ZXV3ZKVM.js";import{a as ge,b as fe,c as me}from"./FT7G3QQ4.js";import{b as $,d as ue}from"./VQXYHAU4.js";async function*ke(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",l="",u=[],h,r=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(s,{stream:!0});for(let d=i.indexOf(`
3
3
  `);d>=0;d=i.indexOf(`
4
4
  `)){let p=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),p===""?(l!==""&&(yield h===void 0?{event:l,data:u.join(`
5
5
  `)}:{event:l,data:u.join(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.17.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.18.0 — Palbase SDK License (see LICENSE) */
2
2
  var s=class extends Error{code;constructor(t,e){super(e),this.name="FieldError",this.code=t}},f="pbe1.",g="pbl1.",k=6e4,p="[A-Za-z_][A-Za-z0-9_$]{0,62}",w=new RegExp(`^${p}\\.${p}(\\.${p})?$`);function v(o){return w.test(o)}var h=class{crypto;keys=new Map;lookupKey;timer;opts;now;constructor(t){this.opts=t,this.now=t.now??Date.now}get loaded(){return this.lookupKey!==void 0}async load(t){this.crypto??=await import("node:crypto"),this.take(await this.opts.fetch(t)),this.timer===void 0&&(this.timer=setInterval(()=>{this.opts.fetch().then(e=>this.take(e),()=>{})},k),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}take(t){let e=new Map;for(let r of t.keys)e.set(r.id,{id:r.id,key:Buffer.from(r.key,"base64url"),activatesAt:Date.parse(r.activates_at)});this.keys=e,this.lookupKey=Buffer.from(t.lookup,"base64url")}ready(){if(this.crypto===void 0||this.lookupKey===void 0)throw new s("not_loaded","the project's field keys are not loaded: await palbase.fields.load() at startup");return this.crypto}currentKey(){this.ready();let t;for(let e of this.keys.values())e.activatesAt<=this.now()&&(t===void 0||e.activatesAt>=t.activatesAt)&&(t=e);if(t===void 0)throw new s("unknown_key","the project has no field key in force");return t.id}encrypt(t,e){let r=this.ready();l(t);let n=this.currentKey(),i=r.randomBytes(12);return b(r,this.keys.get(n).key,i,n,t,e)}decrypt(t,e){let r=this.ready();if(l(t),!e.startsWith(f))throw new s("not_encrypted",`${t} holds a value that is not encrypted`);let n=e.slice(f.length),i=n.indexOf("."),a=i<0?n:n.slice(0,i),u=this.keys.get(a);if(u===void 0)throw new s("unknown_key",`${t} was sealed with field key ${a}, which this project does not hold`);let c=Buffer.from(n.slice(i+1),"base64url");if(i<0||c.length<28||c.toString("base64url")!==n.slice(i+1))throw new s("unopenable",`${t} holds a value that does not open here`);try{let d=r.createDecipheriv("aes-256-gcm",u.key,c.subarray(0,12));return d.setAAD(y(t)),d.setAuthTag(c.subarray(c.length-16)),Buffer.concat([d.update(c.subarray(12,c.length-16)),d.final()]).toString("utf8")}catch{throw new s("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(f)}lookup(t,e){let r=this.ready();return l(t),m(r,this.lookupKey,t,e)}};function l(o){if(!v(o))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(o)}`)}function y(o){return Buffer.from(`pbe1\0${o}`,"utf8")}function b(o,t,e,r,n,i){let a=o.createCipheriv("aes-256-gcm",t,e);a.setAAD(y(n));let u=Buffer.concat([e,a.update(i,"utf8"),a.final(),a.getAuthTag()]);return`${f}${r}.${u.toString("base64url")}`}function m(o,t,e,r){let n=o.createHmac("sha256",t);return n.update(`pbl1\0${e}\0`,"utf8"),n.update(r,"utf8"),`${g}${n.digest("base64url")}`}export{s as a,h as b};