palbase 0.18.4 → 0.18.5

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 (49) 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/{MAYJWEPM.js → 2CZIJUEA.js} +1 -1
  8. package/dist/chunks/{GLPFMTZP.js → 3JSH2MUE.js} +2 -2
  9. package/dist/chunks/{W65B2VZ3.js → 5FJ5HY4N.js} +2 -2
  10. package/dist/chunks/{V4TFN353.js → 5W3LOKAA.js} +2 -2
  11. package/dist/chunks/{KPTP2RTE.js → 7YDYPPAK.js} +1 -1
  12. package/dist/chunks/{GF42QGWO.js → DSRFESUP.js} +2 -2
  13. package/dist/chunks/{PIWNLITG.js → EJCZSU6N.js} +2 -2
  14. package/dist/chunks/{6CJHLHPT.js → GEKPVLFJ.js} +2 -2
  15. package/dist/chunks/{RKPLX5YV.js → IB2CXDQX.js} +1 -1
  16. package/dist/chunks/ICDIBK5M.js +21 -0
  17. package/dist/chunks/{VUXQEYPQ.js → ITJURBMS.js} +2 -2
  18. package/dist/chunks/{6RKQ5ANL.js → J3MZRKKM.js} +2 -2
  19. package/dist/chunks/{HKOGKWNU.js → JHK7EIQJ.js} +3 -3
  20. package/dist/chunks/{NEBALOPJ.js → JXS4PFKE.js} +1 -1
  21. package/dist/chunks/{CHDD73OG.js → LVWFOKBJ.js} +2 -2
  22. package/dist/chunks/{SSL3F7OB.js → P7K2DF3E.js} +2 -2
  23. package/dist/chunks/RYK2ZLYB.js +2 -0
  24. package/dist/chunks/{Q33BWD44.js → T4R24MAP.js} +2 -2
  25. package/dist/chunks/{XE6LFBDN.js → TKFOVBGN.js} +2 -2
  26. package/dist/chunks/{KMA7REYL.js → UILOHBBQ.js} +1 -1
  27. package/dist/chunks/{7CTORXHD.js → VTEQCSQV.js} +1 -1
  28. package/dist/chunks/{5BTTH7AT.js → WBFCNBXY.js} +1 -1
  29. package/dist/chunks/{N5WYA3DM.js → YYDJXLXP.js} +2 -2
  30. package/dist/cli.js +3 -3
  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/backend/src/decorators.d.ts +10 -0
  45. package/types/backend/src/openapi.d.ts +1 -0
  46. package/types/internal/src/modules/auth.d.ts +26 -4
  47. package/types/web/src/auth.d.ts +8 -0
  48. package/dist/chunks/HHYRMVWF.js +0 -2
  49. package/dist/chunks/UPS6BGJD.js +0 -21
@@ -1,2 +1,2 @@
1
- /*! palbase 0.18.4 — Palbase SDK License (see LICENSE) */
2
- import{b as R}from"./KPTP2RTE.js";import{a as m,c as J,d as Y,e as G,f as X,h as Z,i as Q,j as A,k as ee,l as te,o as P}from"./7CTORXHD.js";import{a as ne}from"./5BTTH7AT.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q}from"./HHYRMVWF.js";import{a as z,b as V}from"./N5WYA3DM.js";import{b as T,d as v}from"./W65B2VZ3.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Ee=6e4,_e=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Ee),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=Y(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await G(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+_e-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=Z(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=X(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await Q(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof J?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ee(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await te(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Te=/^pb_[a-z0-9]+_s/;function O(n){if(ne())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!Te.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=V(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??z),t=B.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:N.client(e),machines:I.client(e),notify:F.client(e),purchases:D.client(e),realtime:W.client(e),secrets:t,storage:H.client(e),stores:q.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},Pe=300,Re=/^[0-9]{1,12}$/,xe=/^[0-9a-f]{64}$/,re=8,Oe=/^whsec_[0-9A-Za-z]{32,}$/,je=1024*1024;async function se(n){if(typeof n.secret!="string"||!Oe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ie(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(ae(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!$e(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ie(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=ae(n.body),{t,v1:r}=oe(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Le(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)Ce(i,Ue(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function oe(n){let e=n.toleranceSeconds??Pe;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Re.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!xe.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===re)throw new h("malformed_signature",`Palbase-Signature carries at most ${re} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:i}}async function Me(n,e,t={}){let r=await Ke(n,t.maxBytes??je);return se({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ke(n,e){let t=()=>new h("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),i=[],o=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(o+=l.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(l)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function ae(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Ue(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function Ce(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function Le(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function $e(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var ce=60,Ne=60,Ie=8*1024,Fe=1e5;function j(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function le(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function de(n){let e=le(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Fe){this.max=e}spend(e,t){if(t>=e.until)throw new u("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new u("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,i]of t){if(i>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[i,o]of s)o>e||(s.delete(i),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function De(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function ue(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function he(n,e,t,r){let s=Se=>{throw new u("proof",`the DPoP proof is not taken: ${Se}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>Ie)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=de(o[0]),c=de(o[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await De(a.x,a.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=le(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${o[0]}.${o[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let p=typeof c.htu=="string"?ue(c.htu):void 0,g=ue(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let be=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-be)>ce)return s("it was not made within a minute of now");let ke=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==ke)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let ve=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:ve,until:(c.iat+ce+Ne)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},We=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Be(n){return async e=>{let t=v({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!We.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},fe=60,He=16*1024,qe=10*6e4,ze=5e4,pe=n=>typeof n=="string"&&Object.hasOwn(M,n),K=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new E;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>He)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=ye(r[0]),i=ye(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!pe(o))throw new u("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==o)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=me(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,l).catch(()=>!1))throw new u("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await he(e,p.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,b.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Je(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:ge(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>ze&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new u("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+fe<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-fe>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new u("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+qe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!pe(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Ye(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ge(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Ve.test(s)?`${r}://${s}${e.pathname}`:""}var Ve=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Je(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Ye(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function me(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function ye(n){let e=me(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Ge(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var _=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Xe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),b}return await n.purchases.commitSpend({path:l}),y}async function*Ze(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Qe=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,et=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function we(n){return!Qe.test(n)||et.test(n)||/_PROXY$/i.test(n)}var tt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function nt(n){return tt.test(n)}async function rt(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[l,y]of Object.entries(o.values)){if(we(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,se as f,ie as g,oe as h,Me as i,u as j,w as k,Be as l,K as m,ge as n,Ge as o,_ as p,Xe as q,Ze as r,we as s,nt as t,rt as u};
1
+ /*! palbase 0.18.5 — Palbase SDK License (see LICENSE) */
2
+ import{b as R}from"./7YDYPPAK.js";import{a as m,c as J,d as Y,e as G,f as X,h as Z,i as Q,j as A,k as ee,l as te,o as P}from"./VTEQCSQV.js";import{a as ne}from"./WBFCNBXY.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q}from"./RYK2ZLYB.js";import{a as z,b as V}from"./YYDJXLXP.js";import{b as T,d as v}from"./5FJ5HY4N.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Ee=6e4,_e=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Ee),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=Y(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await G(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+_e-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=Z(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=X(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await Q(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof J?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ee(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await te(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Te=/^pb_[a-z0-9]+_s/;function O(n){if(ne())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!Te.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=V(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??z),t=B.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:N.client(e),machines:I.client(e),notify:F.client(e),purchases:D.client(e),realtime:W.client(e),secrets:t,storage:H.client(e),stores:q.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},Pe=300,Re=/^[0-9]{1,12}$/,xe=/^[0-9a-f]{64}$/,re=8,Oe=/^whsec_[0-9A-Za-z]{32,}$/,je=1024*1024;async function se(n){if(typeof n.secret!="string"||!Oe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ie(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(ae(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!$e(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ie(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=ae(n.body),{t,v1:r}=oe(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Le(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)Ce(i,Ue(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function oe(n){let e=n.toleranceSeconds??Pe;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Re.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!xe.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===re)throw new h("malformed_signature",`Palbase-Signature carries at most ${re} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:i}}async function Me(n,e,t={}){let r=await Ke(n,t.maxBytes??je);return se({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ke(n,e){let t=()=>new h("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),i=[],o=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(o+=l.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(l)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function ae(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Ue(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function Ce(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function Le(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function $e(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var ce=60,Ne=60,Ie=8*1024,Fe=1e5;function j(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function le(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function de(n){let e=le(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Fe){this.max=e}spend(e,t){if(t>=e.until)throw new u("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new u("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,i]of t){if(i>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[i,o]of s)o>e||(s.delete(i),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function De(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function ue(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function he(n,e,t,r){let s=Se=>{throw new u("proof",`the DPoP proof is not taken: ${Se}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>Ie)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=de(o[0]),c=de(o[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await De(a.x,a.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=le(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${o[0]}.${o[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let p=typeof c.htu=="string"?ue(c.htu):void 0,g=ue(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let be=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-be)>ce)return s("it was not made within a minute of now");let ke=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==ke)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let ve=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:ve,until:(c.iat+ce+Ne)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},We=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Be(n){return async e=>{let t=v({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!We.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},fe=60,He=16*1024,qe=10*6e4,ze=5e4,pe=n=>typeof n=="string"&&Object.hasOwn(M,n),K=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new E;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>He)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=ye(r[0]),i=ye(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!pe(o))throw new u("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==o)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=me(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,l).catch(()=>!1))throw new u("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await he(e,p.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,b.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Je(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:ge(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>ze&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new u("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+fe<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-fe>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new u("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+qe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!pe(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Ye(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ge(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Ve.test(s)?`${r}://${s}${e.pathname}`:""}var Ve=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Je(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Ye(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function me(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function ye(n){let e=me(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Ge(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var _=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Xe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),b}return await n.purchases.commitSpend({path:l}),y}async function*Ze(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Qe=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,et=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function we(n){return!Qe.test(n)||et.test(n)||/_PROXY$/i.test(n)}var tt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function nt(n){return tt.test(n)}async function rt(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[l,y]of Object.entries(o.values)){if(we(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,se as f,ie as g,oe as h,Me as i,u as j,w as k,Be as l,K as m,ge as n,Ge as o,_ as p,Xe as q,Ze as r,we as s,nt as t,rt as u};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.18.4 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.18.5 — Palbase SDK License (see LICENSE) */
2
2
  import{lstat as j,mkdir as F,readdir as M,readFile as N,rename as J,rm as T,writeFile as v}from"node:fs/promises";import{join as E}from"node:path";var o="palbase/strings",f="_meta.json",p=3,y=2,$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function m(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function b(r,n){try{return JSON.parse(r)}catch(t){throw new Error(`${n} is not JSON: ${t.message}`)}}async function x(r){let n=E(r,o);try{if(!(await j(n)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let t=new Map;for(let e of await M(n,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);t.set(e.name,await N(E(n,e.name),"utf8"))}return t.size===0?void 0:t}async function R(r,n=[p,y]){let t=await x(r);if(t===void 0)return;let e=t.get(f);if(e===void 0)throw new Error(`${o}/${f} is missing: it names the source language, and without it the language files are not a table`);let u=b(e,`${o}/${f}`);if(!$(u))throw new Error(`${o}/${f}: not a JSON object`);let s=u.version;if(s===y&&!n.includes(y))throw new Error(`${o}/${f}: version 2 is the earlier format ({"value", "state"} for each sentence) \u2014 run \`npx palbase strings\` once, and it writes the table as version ${p}`);if(typeof s!="number"||!n.includes(s))throw new Error(`${o}/${f}: version ${JSON.stringify(s)} is not one this reads (${n.join(" or ")})`);let a=u.source;if(typeof a!="string"||m(a)!==a)throw new Error(`${o}/${f}: source ${JSON.stringify(a)} is not a language tag as it is written (${m(String(a))??"en, en-US, zh-Hans"})`);let S=new Map;for(let w of[...t.keys()].sort()){if(w===f)continue;let i=w.slice(0,-5),g=`${o}/${w}`,d=m(i);if(d===void 0)throw new Error(`${g}: ${JSON.stringify(i)} is not a language tag`);if(d!==i)throw new Error(`${g}: the language is written ${d} \u2014 name the file ${d}.json`);if(i===a)throw new Error(`${g}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${g}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let O=b(t.get(w),g);if(!$(O))throw new Error(`${g}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[l,c]of Object.entries(O))if(s===p){if(typeof c!="string")throw new Error(`${g}: the translation of ${JSON.stringify(l)} is not a string`);h.set(l,c)}else if(typeof c=="string")h.set(l,c);else{if(!$(c)||typeof c.value!="string")throw new Error(`${g}: key ${JSON.stringify(l)} is not {"value": string, "state": string}`);h.set(l,c.state==="missing"?"":c.value)}S.set(i,h)}return{format:s,source:a,languages:S}}async function A(r){let n=await R(r,[p]);if(n===void 0)return;let t={};Object.setPrototypeOf(t,null);for(let[e,u]of n.languages)for(let[s,a]of u)Object.hasOwn(t,s)||(t[s]={},Object.setPrototypeOf(t[s],null)),t[s][e]=a;return{source:n.source,locales:[n.source,...n.languages.keys()],strings:t}}export{A as a};
@@ -0,0 +1,21 @@
1
+ /*! palbase 0.18.5 — Palbase SDK License (see LICENSE) */
2
+ import{a as Rt,c as re,d as ur,e as lr,f as we,h as $,i as gr}from"./T4R24MAP.js";import{c as fr,d as pr,e as tn,f as mr,g as hr}from"./J3MZRKKM.js";import{a as ar,e as ot,g as St,h as or,i as ir,j as At,k as xt,n as dr,t as cr}from"./GEKPVLFJ.js";import{a as Et,b as rr,n as sr}from"./VTEQCSQV.js";import{b as ie}from"./5FJ5HY4N.js";import"reflect-metadata";var nn=[{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}],yr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ot=/^\d+$/;function ga(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(!Ot.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let f=t,h=n;if(i!=="*")if(i.includes("-")){let y=i.indexOf("-"),b=i.slice(0,y),S=i.slice(y+1);if(!Ot.test(b)||!Ot.test(S)||Number(b)<t||Number(S)>n||Number(b)>Number(S))return;f=Number(b),h=Number(S)}else{if(!Ot.test(i)||Number(i)<t||Number(i)>n)return;f=Number(i),h=a===-1?f:n}for(let y=f;y<=h;y+=d)r.add(y)}return r}function wr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${yr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=ga(t[h],nn[h].lo,nn[h].hi);if(!y)return`${yr}; its ${nn[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("*"),f=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,f.setUTCDate(f.getUTCDate()+1)){if(!s.has(f.getUTCMonth()+1))continue;let y=r.has(f.getUTCDate()),b=a.has(f.getUTCDay());if(i||d?y&&b:y||b)return}return`"${e}" is never due: no date has that day in that month`}var Le=Symbol.for("palbase.backend.controller"),Ie=Symbol.for("palbase.backend.routes"),sn=Symbol.for("palbase.backend.params"),an=Symbol.for("palbase.backend.injectable"),on=Symbol.for("palbase.backend.module"),Pe=Symbol.for("palbase.backend.events"),qe=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 rn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[rn]instanceof Set||(e[rn]=new Set),e[rn]}var He=new Set(["webhooks","_palbase"]);function ld(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&&He.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,Le,()=>({basePath:e,options:t})),se().add(n)}}function ze(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,Ie,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var fd=ze("GET"),pd=ze("POST"),md=ze("PUT"),hd=ze("PATCH"),gd=ze("DELETE"),yd=ze("QUERY");function ce(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,sn,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function dn(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 wd=e=>ce("body",{schema:dn("Body",e)}),bd=e=>ce("query",{schema:dn("QueryParams",e)}),kd=e=>ce("headers",e===void 0?{}:{schema:dn("Headers",e)}),vd=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ce("param",{name:e})},Td=()=>ce("user"),$d=()=>ce("optionalUser"),_d=()=>ce("req"),Ed=()=>ce("requestId"),Sd=()=>ce("requestId"),Ad=()=>ce("client"),xd=()=>ce("attestedDevice");function Rd(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 ce("resolve",{resolver:e,options:t[0]})}function Od(){return e=>{de(e,an,()=>!0),se().add(e)}}function Pd(e){return t=>{de(t,on,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var vr=/^[a-z]+(\.[a-z_]+)+$/,ya=/^[a-z][a-z0-9-]{1,62}$/,cn=e=>e.startsWith("file.");function Cd(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"||!ya.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(!cn(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,Pe,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var un=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,wa=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function br(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(!wa.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 Md(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!un.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=wr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||br(t.timeZone)!==void 0))throw new TypeError(`${n}: ${br(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 kr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ba=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function jd(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(!ba.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&&!kr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${kr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&ka(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,Pe)??[];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,qe,()=>({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 ka(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 Dd(){return[...se()].filter(e=>D(e,Le)!==void 0)}function Nd(e){return(D(e,Ie)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Hd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!un.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 pn;function $r(e){pn=e}function ln(){if(!pn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return pn}var va=720*3600;function Ta(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>va))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 $a(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 zd=Rt("Tasks",{async enqueue(e,t,n={}){return Ta(n),ln().enqueue($a(e),t===void 0?null:t,n)},async cancel(e,t={}){return ln().cancel(e,t.machine)},async get(e,t={}){return ln().get(e,t.machine)}}),fn=(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 _r(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 fn(a.data,a.status===200)},async cancel(n,r){return fn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return fn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var _a=1e4,Ea=36e5,Tr=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let f of this.tasks.values())if(f.task===t&&f.key===r.key&&(f.finishedAt===void 0||this.now()-f.finishedAt<Tr))return this.view(f,!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(_a*2**Math.min(t.attempt-1,16),Ea),$.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>=Tr&&this.tasks.delete(s);n==="failed"&&$.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Mt="/_palbase/test-user-templates",Sa=/^[a-z][a-z0-9_-]{0,63}$/;function Kd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Sa.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 Er(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 Sr(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 Aa="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 Ar(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Aa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var mn="/_palbase/storage/upload/authorize",xr="/_palbase/storage/upload/complete",hn="/_palbase/realtime/rooms";var xa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!xa(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 Rr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Or(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ra=/^[a-z][a-z0-9-]{1,62}$/,Pr=1024,Oa=new Set(["userId","uploadId","filename"]);function Yd(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(!Ra.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=Pa(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,f)=>{if(typeof d!="string"||f===void 0||typeof f.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(i.constructor,Ie,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function Qd(){return ce("uploadedObject")}function Pa(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Oa.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(!Cr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Cr(e){if(e===""||new TextEncoder().encode(e).byteLength>Pr)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 Ca(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ma(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ma(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 Mr(e,t){let n=Ca(e,t);return Cr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Pr} bytes)`}}function jr(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 gn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Dr(e,t){if(!gn(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=Fe(t.user);if(!i)return"user is { id?, session?, role }";let d=Rr(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 f=ja(t.uploadedObject);return f?f.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:i,...d?{client:d}:{},filename:"",uploadedObject:f,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function ja(e){if(!gn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:i,width:d,height:f,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"||f!==void 0&&typeof f!="number"||h!==void 0&&typeof h!="string")&&!(!gn(y)||!Object.values(y).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:i,...d!==void 0?{width:d}:{},...f!==void 0?{height:f}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Da}from"palgres";var Ce=Symbol.for("palbase.backend.gateway"),Ke=Symbol.for("palbase.backend.gatewayHooks"),Nr={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"]},Na={"~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(Nr),output:()=>structuredClone(Nr)}}},Fr=Symbol.for("palbase.backend.gatewayRefusal"),Ur=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,Fr,{value:!0})}},Ua=e=>typeof e=="object"&&e!==null&&e[Fr]===!0&&typeof e.reason=="string",Ge=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,La=6e4,Ia=86400,Lr=604800,Ir=65536,$e=255,qa=["roles:","flags:","messaging:","debug:"],Ha=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(" ")),Be=e=>new TextEncoder().encode(e).byteLength,yn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",kn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function za(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(Be(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=qa.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Gr(e){if(typeof e!="string"||e==="")return"is a name";if(Be(e)>$e)return`is ${$e} bytes at most`}function sc(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=za(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"&&kn(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=Fa(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)||Ha.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,b]of Object.entries(d)){let S=Gr(y);if(S)throw new TypeError(`@Gateway("${e}") on ${i}: event "${y}" ${S}`);if(!yn(b))throw new TypeError(`@Gateway("${e}") on ${i}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let f=de(a,Ke,vn),h={name:i,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Na}:{...d},chat:r.chat===!0,graceMs:r.graceMs??La,hooks:{...f.hooks},messages:Object.assign(Object.create(null),f.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&&Ge(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&&!Ge(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,Ce,()=>h),se().add(a)}}function Fa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ia;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Lr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Lr} (a week)`);return n}var vn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ga={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function it(e){let t=Ga[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,Ke,vn),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 ac=it("authorize"),oc=it("first"),ic=it("connect"),dc=it("disconnect"),cc=it("empty");function uc(e,t,n={}){let r=Gr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!yn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!yn(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,Ke,vn),f=d.messages[e];if(f!==void 0&&f.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${f.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ba(e){return D(e,Ce)}function Ka(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 Br(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 Be(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Ja(e,t,n){let r=kn(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))?Br(e,t):Wa(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 Wa(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 Va=1e4,Za=1e3,Ya=100,Tn=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}:{}}),qr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Hr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Kr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:k,instance:E}of e){let m=Ba(k),v=a.get(m.name);if(v!==void 0&&v!==k)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,k);let C=s.get(Hr(m.pattern));if(C!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${k.name}: ${n.get(C)?.cls.name}'s "${C}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Hr(m.pattern),m.pattern);for(let[Z,Y]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([U,I])=>[`message ${U}`,I.fn])])if(typeof E[Y]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${k.name}: its ${Z} is ${Y}, which is no method of it`);let L={cls:k,instance:E,g:m};n.set(m.pattern,L),r.set(k,L)}let i=new Map,d=new Set,f=new Set,h=new bn(t.broadcast),y=k=>{let E=i.get(k);return E||(E=new AbortController,i.set(k,E)),E},b=(k,E)=>{E?.abort(),i.get(k)===E&&i.delete(k)},S=(k,E,m,v,C,L)=>{if(!Object.hasOwn(k.g.events,m)){$.warn(`[palbase] ${C}: emit("${m}") is not sent \u2014 ${k.cls.name} declares no event "${m}" (static events)`);return}if(k.g.chat&&m==="chat"){$.warn(`[palbase] ${C}: emit("chat") is not sent \u2014 ${k.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??{},...L!==void 0?{conn_id:L}:{}},C)},J=async(k,E,m)=>{if(typeof k!="object"||k===null||typeof k.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await k.pipe(E)};function N(k,E,m,v,C,L,Z){let Y=v?.signal??AbortSignal.abort(),U=`${k.cls.name} (${E})`;return{channel:E,params:Object.freeze({...m}),signal:Y,count:C,user:L,emit:(I,F)=>S(k,E,I,F,U,Z),pipe:I=>J(I,E,U),owner:{hold(I){re.exit(async()=>{try{await I(Y)}catch(F){Y.aborted||$.error(`[palbase] ${U}: a task owner.hold ran failed`,{error:F})}}).catch(()=>{})},release:()=>b(E,v)}}}function H(k){let{room:E,channel:m}=k;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||!Ge(v.g)?he(404,"not_found",`This app serves no gateway "${E}"`):{entry:v,channel:m,params:Ka(E,m)}}let W=(k,E)=>he(400,"bad_request",`"${E}" is not a channel of the gateway "${k}"`);async function z(k,E){let m=H(k);if("status"in m)return m;let{entry:v,channel:C,params:L}=m,Z={status:200,body:{subscribe:!1,publish:!1}};if(!L)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`),Z;let Y=Fe(k.user),U=Y?.id;if(!U)return Z;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 L[kn(v.g.pattern)[0].slice(1,-1)]===U?{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}}:Z;let I=v.g.hooks.authorize;if(!I)return Z;let F,G;try{F=await t.run(Y,`${v.cls.name}.${I}`,E,async()=>v.instance[I]({user:{id:U},params:Object.freeze({...L})})),G=Qa(F)}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}),Z}return G==="malformed"?($.warn(`[palbase] ${v.cls.name}.${I} (@Authorize of ${C}) answered ${Xa(F)}, which is no grant (true, { read, write } or null); the join is refused`),Z):{status:200,body:G}}async function oe(k,E){let m=H(k);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let v=Fe(k.user);if(!v?.id||typeof k.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let C=Object.hasOwn(m.entry.g.messages,k.event)?m.entry.g.messages[k.event]:void 0;if(!C)return{status:200,body:{ok:!1,reason:wn(`gateway "${m.channel}" takes no message "${k.event}"`,Dt)}};let L=await C.schema["~standard"].validate(Da(k.payload??{}));if(L.issues)return{status:200,body:{ok:!1,reason:zr(L.issues)}};let Z=y(m.channel),Y={...N(m.entry,m.channel,m.params,Z,0,{id:v.id}),payload:L.value},U=`${m.entry.cls.name}.${C.fn} (@Subscribe "${k.event}" of ${m.channel})`,I;try{I=await t.run(v,`${m.entry.cls.name}.${C.fn}`,E,async()=>m.entry.instance[C.fn](Y))}catch(G){if(t.isOutage(G))throw G;return Ua(G)?{status:200,body:{ok:!1,reason:wn(G.reason,Dt)}}:(E?.aborted||$.error(`[palbase] ${U} failed`,{error:G}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(C.reply){let G=await C.reply["~standard"].validate(I);if(G.issues)return $.error(`[palbase] ${U} returned an ack its reply schema refuses (${zr(G.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=G.value}let F;try{F=JSON.stringify(I)}catch(G){return $.error(`[palbase] ${U} returned an ack that is not JSON; the member is told it failed`,{error:G}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return F===void 0?{status:200,body:{ok:!0}}:Be(F)>Ir?($.error(`[palbase] ${U} returned an ack of ${Be(F)} bytes, past ${Ir}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(F)}}}async function me(k,E){let m=H(k);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let v=k.event;if(typeof v!="string"||!Object.hasOwn(qr,v))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let C=typeof k.count=="number"&&Number.isInteger(k.count)&&k.count>=0?k.count:void 0;if(C===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let L=v==="join"||v==="leave",Z=L?Fe(k.user):void 0,Y=L?k.connId:void 0;if(L&&(!Z?.id||typeof Y!="string"||Y===""))return he(400,"bad_request",`A ${v} names its member: user and connId`);let U=`${v}\0${m.channel}\0${typeof Y=="string"?Y:""}`;if(L&&d.has(U))return{status:204};if(f.has(U))return he(503,"in_progress","This moment of the gateway is being handled",5);f.add(U);try{let I=m.entry.g.hooks[qr[v]],F;if(v==="empty"?(F=i.get(m.channel),b(m.channel,F)):F=v==="leave"?i.get(m.channel):y(m.channel),I){let G=N(m.entry,m.channel,m.params,F,C,{id:Z?.id??""},v==="join"?Y:void 0);try{await t.run(Z,`${m.entry.cls.name}.${I}`,E,async()=>m.entry.instance[I](G))}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 L&&(d.add(U),d.size>Va&&d.delete(d.values().next().value)),{status:204}}finally{f.delete(U)}}function Se(k,E){let m=r.get(k),v=`Palbase.gateways.to(${k?.name??String(k)})`;if(!m)throw new TypeError(`${v}: ${k?.name??String(k)} is no @Gateway this app serves \u2014 list it in a module's providers`);let C=Br(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(k=>k.g),async serve(k,E,m){return Tn(E)?k==="authorize"?z(E,m):k==="message"?oe(E,m):k==="lifecycle"?me(E,m):he(404,"not_found",`No gateway call ${JSON.stringify(k)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(k,E,m,v){let{entry:C,channel:L,where:Z}=Se(k,E);S(C,L,m,v,Z)},async pipe(k,E,m){let{channel:v,where:C}=Se(k,E);await J(m,v,C)},async revalidate(k,E,m={}){let v=r.get(k),C=`Palbase.gateways.to(${k?.name??String(k)}).revalidate`;if(!v)throw new TypeError(`${C}: ${k?.name??String(k)} is no @Gateway this app serves \u2014 list it in a module's providers`);let L=Ja(v.g.pattern,E??{},m);if("problem"in L)throw new TypeError(`${C}: ${L.problem}`);await t.revalidate(L)},close(){for(let k of i.values())k.abort();i.clear()}}}function Qa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!Tn(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 Xa(e){return Array.isArray(e)?"an array":Tn(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 eo=20,Dt=256;function zr(e){let t="";for(let n of e.slice(0,eo)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Dt)break}return wn(t,Dt)}function wn(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 bn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Be(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>=Za?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,Ya);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 $n,createHmac as to,createPublicKey as Zr,timingSafeEqual as no,verify as Yr}from"node:crypto";function mc(e){let t=D(e,qe);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 Qr(e,t,n,r={}){let s=new Map,a=[];for(let i of e){let d=D(i,qe),f=s.get(d.name);if(f)throw new TypeError(`@Webhook "${d.name}" is declared by ${f.cls.name} and by ${i.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${i.name})`,y=n[d.secret.env],b;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{b=ro(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let S=t(i),J=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${i.name}.${H}`,call:(W,z)=>S[H](W,z)}]));s.set(d.name,{name:d.name,cls:i,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:J})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
+ - ${a.join(`
4
+ - `)}`);return s}function Xr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Je=1024,Jr=1024*Je;function ro(e,t){if(e.signature)return Me(void 0,e.signature.header,1/0,ho(e.signature,t));switch(e.provider){case"stripe":return Me("stripe","stripe-signature",512*Je,oo(t));case"github":return Me("github","x-hub-signature-256",25*Jr,io(t));case"slack":return Me("slack","x-slack-signature",64*Je,co(t));case"discord":return Me("discord","x-signature-ed25519",64*Je,uo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Je),check:fo(t)};case"sendgrid":return Me("sendgrid","x-twilio-email-event-webhook-signature",Jr,po(t));case"livekit":return Me("livekit","authorization",512*Je,mo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function Me(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??es(e,s)}}function es(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:ts(e,t.headers,r),event:r,...so(e,t,r)}}function ts(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=je(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=ss(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 je(n,"EventType");case"livekit":return je(n,"event");default:return je(n,"type")}}function so(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(je(n,"id"));case"slack":return r(je(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${ns(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>je(s,"sg_event_id")||void 0)}:{};default:return{}}}var ao=300;function oo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let f of r.split(",")){let h=f.indexOf("=");if(h<=0)continue;let y=f.slice(0,h).trim(),b=f.slice(h+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=b}else if(y==="v1"){let S=fe(b,"hex");if(!S)return"malformed_signature";a.push(S)}}let i=dt(s);if(i===void 0||a.length===0)return"malformed_signature";if(ct(i,n))return"stale_timestamp";let d=We("sha256",e,`${s}.`,t.body);return a.some(f=>_e(f,d))?void 0:"signature_mismatch"}}function io(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,We("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function co(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=dt(s),i=r.startsWith("v0=")?fe(r.slice(3),"hex"):void 0;return a===void 0||!i?"malformed_signature":ct(a,n)?"stale_timestamp":_e(i,We("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function uo(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=Zr({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=dt(i),f=fe(a,"hex");return d===void 0||!f||f.byteLength!==64?"malformed_signature":ct(d,s)?"stale_timestamp":Yr(null,rs(i,r.body),n,f)?void 0:"signature_mismatch"}}var lo=1e3;function fo(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($n("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let J=1;for(let W of t.body)if(W===38&&++J>lo)return"malformed_signature";let N=new Map;for(let[W,z]of new URLSearchParams(_n(t.body))){let oe=N.get(W);oe||N.set(W,oe=new Set),oe.add(z)}let H=[];for(let W of[...N.keys()].sort()){let z=[...N.get(W)].sort();for(let oe of z)i+=W+oe;H.push([W,z.length===1?z[0]:z])}d=Object.fromEntries(H)}let f=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||f}${s.pathname}${s.search}`;if(![h,y].some(J=>_e(r,We("sha1",e,J,i))))return"signature_mismatch";let b=t.headers.get("i-twilio-idempotency-token"),S=b?{id:`${b}:${ns(`${h}
5
+ ${i}`)}`}:{};return d?{type:ts("twilio",t.headers,d),event:d,...S}:{...es("twilio",t),...S}}}function po(e){let t;try{let n=fe(e,"base64");if(!n)throw new Error;t=Zr({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=dt(a),d=fe(s.trim(),"base64");return i===void 0||!d?"malformed_signature":ct(i,r)?"stale_timestamp":Yr("sha256",rs(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Wr=60;function mo(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=Vr(fe(s[0],"base64url")),i=fe(s[2],"base64url");if(a?.alg!=="HS256"||!i)return"malformed_signature";if(!_e(i,We("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Vr(fe(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Wr||typeof d.nbf=="number"&&n<d.nbf-Wr)return"stale_timestamp";let f=typeof d.sha256=="string"?fe(d.sha256,"base64"):void 0;return f&&_e(f,$n("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function ho(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=dt(d);if(h===void 0)return"malformed_signature";if(ct(h,a))return"stale_timestamp"}let f=fe(i.trim(),e.encoding);return f?_e(f,We(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var go=new TextEncoder;function We(e,t,...n){let r=to(e,t);for(let s of n)r.update(s);return r.digest()}function ns(e){return $n("sha256").update(e).digest("hex")}function rs(e,t){return Buffer.concat([go.encode(e),t])}function _e(e,t){return e.byteLength===t.byteLength&&no(e,t)}var yo={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 yo[t].test(e)?Buffer.from(e,t):void 0}function dt(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function ct(e,t){return Math.abs(t-e)>ao}function _n(e){return new TextDecoder().decode(e)}function Vr(e){if(e)try{return JSON.parse(_n(e))}catch{return}}function ss(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function je(e,t){let n=ss(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var V=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
6
+ Kind: ${t}
7
+ Path: ${n.join(" -> ")}
8
+ At: ${r}
9
+ ${s}
10
+
11
+ Potential solutions:
12
+ ${a.map(i=>` - ${i}`).join(`
13
+ `)}`),this.name="DiError",this.kind=t,this.path=n}},wo=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],bo=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),Nt=class{owner=new Map;defs=new Map;instances=new Map;providers=new Set;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];templateProviders=[];gateways=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let a=D(r,on);if(!a)throw new V("unknown import",[...s,r.name],r.name,`${r.name} is not a @Module`,["decorate it with @Module({ \u2026 })","or list the module itself, not one of its classes"]);this.defs.set(r,a);for(let i of a.imports){if(i===r)throw new V("unknown import",[r.name],r.name,`${r.name} imports itself`,["remove it from its own imports"]);n(i,[...s,r.name])}};for(let r of t)n(r,[]);for(let[r,s]of this.defs){for(let a of[...s.controllers,...s.providers]){let i=this.owner.get(a);if(i&&i!==r)throw new V("duplicate ownership",[i.name,a.name,r.name],a.name,`${a.name} is listed by ${i.name} and by ${r.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(a,r)}for(let a of s.providers)this.providers.add(a);for(let a of s.controllers){if(!D(a,Le))throw new V("undeclared provider",[r.name,a.name],a.name,`${a.name} is in ${r.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(D(a,Te))throw new V("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Cron: a cron is a provider's`,["give the cron a class of its own \u2014 @Cron({ name, schedule }) with run(meta) \u2014 listed in the module's providers"]);if(D(a,be))throw new V("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Task: a task is a provider's`,["give the task a class of its own \u2014 @Task({ name }) with run(payload, meta) \u2014 listed in the module's providers"]);if(D(a,ke))throw new V("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @TestUserTemplate: a template is a provider's`,["give the template a class of its own \u2014 @TestUserTemplate({ name }) with seed(user, meta) \u2014 listed in the module's providers"]);if(D(a,Ce)||D(a,Ke))throw new V("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Gateway: a gateway is a provider's`,["give the gateway a class of its own, listed in the module's providers"]);this.controllers.push({cls:a,module:r})}}}validate(){for(let t of se())if(!this.owner.has(t))throw new V("unowned class",[t.name],t.name,`${t.name} is declared but no module lists it: it would never be built`,["list it in a module's controllers or providers","or delete it"]);for(let[t,n]of this.defs){for(let r of n.exports)if(this.owner.get(r)!==t)throw new V("unknown export",[t.name,r.name],t.name,`${t.name} exports ${r.name}, which it does not own`,[`list ${r.name} in ${t.name}'s providers`,"or export it from the module that owns it"]);for(let r of n.providers){if(D(r,Ke)&&!D(r,Ce))throw new V("undeclared provider",[t.name,r.name],r.name,`${r.name} has a gateway's methods (@Authorize, @OnFirst, @Subscribe\u2026) but is no @Gateway`,["decorate it with @Gateway(pattern, options)"]);if(!D(r,an)&&!D(r,Pe)&&!D(r,Ce)&&!D(r,Te)&&!D(r,be)&&!D(r,ke)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new V("metadata missing",[t.name,r.name],r.name,`${r.name} has constructor parameters but no emitted types`,["decorate it with @Injectable()","enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json"]):new V("undeclared provider",[t.name,r.name],r.name,`${r.name} is in ${t.name}'s providers but is not @Injectable() (nor an @On handler, a @Gateway, a @Cron, a @Task or a @TestUserTemplate)`,["decorate it with @Injectable()"])}D(r,Ce)&&this.gateways.push(r),D(r,qe)?this.webhooks.push(r):D(r,Pe)&&this.eventProviders.push(r),D(r,Te)&&this.cronProviders.push(r),D(r,be)&&this.taskProviders.push(r),D(r,ke)&&this.templateProviders.push(r)}}for(let t of this.owner.keys())for(let n of wo)if(typeof t.prototype[n]=="function")throw new V("nest lifecycle name",[t.name],`${t.name}.${n}`,`${n} is NestJS's; it is never called here`,["use onStart() and onShutdown()"]);for(let t of this.owner.keys())this.resolve(t,[])}get(t){let n=this.instances.get(t);if(!n)throw new Error(`${t.name} is not built by this app`);return n}resolve(t,n){let r=this.instances.get(t);if(r)return r;if(n.includes(t.name))throw new V("dependency cycle",[...n,t.name],t.name,`${[...n,t.name].join(" -> ")} goes round`,["move the shared part into a third class both depend on"]);let s=[...n,t.name],a=t.length,i=Reflect.getMetadata("design:paramtypes",t)??[];if(a>0&&i.length===0)throw new V("metadata missing",s,t.name,`${t.name} takes ${a} constructor parameter(s) but no types were emitted`,["enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json","build with tsc, Bun or SWC (esbuild does not emit them)"]);let d=[];i.slice(0,a).forEach((h,y)=>{if(bo.has(h)||typeof h!="function")throw new V("unresolvable dependency",s,`${t.name} constructor parameter ${y}`,`parameter ${y} of ${t.name} is typed as ${h===void 0?"something with no runtime class":h.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);d.push(this.resolve(this.reachable(t,h,s),s))});let f=new t(...d);return this.instances.set(t,f),this.order.push(f),f}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}provider(t,n){if(typeof t!="function")throw new TypeError(`${n}: inject takes a provider's class \u2014 it was given ${t===null?"null":typeof t}`);let r=t;if(!this.owner.has(r)&&![...this.owner.keys()].some(a=>a.prototype instanceof r))throw new V("unowned class",[n,r.name],r.name,`${n} asks for ${r.name}, which no module provides: the app built none`,[`list ${r.name} in a module's providers`]);let s=this.target(r,[n]);if(!this.providers.has(s))throw new V("undeclared provider",[n,s.name],s.name,`${s.name} is a controller: only a module's providers are given`,[`move what ${n} needs into a provider, listed in a module's providers`]);return this.get(s)}reachable(t,n,r){let s=this.owner.get(t),a=this.target(n,r),i=this.owner.get(a);if(i!==s){if(!this.defs.get(s).imports.includes(i))throw new V("missing import",[...r,a.name],`${s.name}`,`${t.name} (in ${s.name}) needs ${a.name}, owned by ${i.name}, which ${s.name} does not import`,[`add ${i.name} to ${s.name}'s imports (imports are not transitive)`]);if(!this.defs.get(i).exports.includes(a))throw new V("private dependency",[...r,a.name],`${i.name}`,`${a.name} is ${i.name}'s own: it is not in its exports`,[`add ${a.name} to ${i.name}'s exports`])}return a}target(t,n){if(this.owner.has(t))return t;let r=[...this.owner.keys()].filter(s=>s.prototype instanceof t);if(r.length===1)return r[0];throw r.length>1?new V("duplicate ownership",[...n,t.name],t.name,`${t.name} has ${r.length} owned subclasses (${r.map(s=>s.name).join(", ")}): which one is meant cannot be told`,["ask for the subclass itself"]):new V("unowned class",[...n,t.name],t.name,`${t.name} is needed but no module lists it`,[`list ${t.name} in a module's providers (and export it if another module needs it)`])}async start(){let t=[];for(let n of this.order){let r=n.onStart;if(typeof r=="function")try{await r.call(n)}catch(s){throw await this.shutdown(t),new Error(`[palbase] ${n.constructor.name}.onStart() failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}t.push(n)}}async shutdown(t=this.order){for(let n of[...t].reverse()){let r=n.onShutdown;if(typeof r=="function")try{await r.call(n)}catch(s){console.error(`[palbase] ${n.constructor.name}.onShutdown() failed`,s)}}}};import{HTTP_ERROR_BRAND as ko,HttpError as ut}from"palgres";import{z as Ee}from"zod";import{BadRequest as Ec,Conflict as Sc,DeadlockDetected as Ac,HttpError as xc,NotFound as Rc,SerializationFailure as Oc,TooManyRequests as Pc,UniqueViolation as Cc}from"palgres";function lt(e){if(typeof e!="object"||e===null||e[ko]!==!0)return!1;let t=e;return Number.isInteger(t.status)&&t.status>=400&&t.status<=599&&typeof t.error=="string"&&typeof t.errorDescription=="string"}var as=class extends ut{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},os=class extends ut{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},is=class extends ut{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function cs(e,t){let n={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(n.data=e.data),n}var vo=Symbol.for("palbase.backend.errorRegistry"),To={bad_request:Ee.object({fields:Ee.array(Ee.object({field:Ee.string(),message:Ee.string()})),more:Ee.number().int().optional()}),too_many_requests:Ee.object({retryAfter:Ee.number().int()})},$o=new Set(["auth_unavailable","check_failed","client_closed_request","database_unavailable","duplicate_upload","email_not_verified","handler_failed","idempotency_key_in_use","idempotency_key_reused","in_progress","internal_error","invalid_idempotency_key","invalid_signature","invalid_token","job_failed","job_not_found","method_not_allowed","missing_signature","payload_too_large","service_unavailable","signature_mismatch","temporarily_unavailable","unknown_token","upload_required","webhook_secret_missing"]);function _o(){let e=new Map;for(let[t,n,r]of[["bad_request",400,"BadRequest"],["unauthorized",401,"Unauthorized"],["forbidden",403,"Forbidden"],["not_found",404,"NotFound"],["conflict",409,"Conflict"],["unique_violation",409,"UniqueViolation"],["too_many_requests",429,"TooManyRequests"]]){let s=To[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function Eo(){let e=globalThis;return e[vo]??=_o()}var So=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function Tc(e,t,n){if(typeof e!="string"||e.length>100||!So.test(e))throw new TypeError(`defineError(code, status): code is a wire code like room_locked or invite.notFound \u2014 a letter, then letters and digits in parts joined by . _ or - \u2014 not ${JSON.stringify(e)}`);if(!Number.isInteger(t)||t<400||t>599)throw new TypeError(`defineError("${e}", status): status is a 4xx or 5xx integer, not ${String(t)} \u2014 an error is never a success`);if(n!==void 0&&typeof n?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if($o.has(e))throw new TypeError(`defineError("${e}", ${t}): "${e}" is the framework's own answer \u2014 a client would read the framework's refusal as the project's error; give the project's its own code`);let r=Eo(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&ds(s.data)!==ds(n)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${s.builtin?`the built-in ${s.className}`:`defined with status ${s.status}${s.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let a=e.split(/[._-]/).flatMap(S=>S.split(/(?=[A-Z])/)),i=a.map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(""),d=a.map(S=>S.toLowerCase()).join(" "),f=d.charAt(0).toUpperCase()+d.slice(1),b=n?(S=>class extends ut{static code=e;static status=t;constructor(J,N){let H=Ao(e,S,J);super(t,e,N??(typeof H=="string"?H:f),H),this.name=i}})(n):class extends ut{static code=e;static status=t;constructor(S){super(t,e,S??f),this.name=i}};return Object.defineProperty(b,"name",{value:i}),r.set(e,{code:e,status:t,className:i,builtin:!1,...n?{data:n}:{}}),b}function Ao(e,t,n){let r=t["~standard"].validate(n);if(r instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(r.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${r.issues.map(s=>s.message).join("; ")}`);return r.value}function ds(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as xo}from"palgres";var us="/_palbase/ai/tools",ls="/_palbase/ai/agents",fs="/_palbase/ai/repos",Ze=4<<20,Ro=Symbol.for("palbase.ai.tool_error");function ps(e){return e instanceof Error&&e[Ro]===!0}var Oo=Symbol.for("palbase.ai.declared");function ms(){let e=globalThis[Oo];if(!e)return{tools:new Map,clientTools:new Map,agents:new Map,repos:new Map,repoTokens:void 0};let t=new Set(e.twice);for(let n of e.clientTools?.keys()??[])e.tools.has(n)&&t.add(`tool:${n}`);if(t.size>0){let n=[...t].map(r=>r.replace(":"," "));throw new TypeError(`[palbase] ${n.join(", ")}: declared twice with different values \u2014 an ai.tool's, an ai.clientTool's and an ai.agent's name is its own (an agent is given one tool of a name, and the build's contract names it once), and ai.repoTokens is given once; make each once, at a module's top level`)}return{tools:new Map(e.tools),clientTools:new Map(e.clientTools??[]),agents:new Map(e.agents),repos:new Map(e.repos??[]),repoTokens:e.repoTokens}}var Ve=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function hs(e){let t={};if(e==null)return t;if(Ve(e)){for(let[n,r]of Object.entries(e)){if(typeof r!="string")return;Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0})}return t}}function gs(e){if(!Ve(e))return"context is {chat_id, agent, user, metadata}";if(typeof e.chat_id!="string")return"context.chat_id is the chat (empty for a one-shot answer's call)";if(typeof e.agent!="string")return"context.agent is the agent's name";let t=null;if(e.user!==null&&e.user!==void 0){if(!Ve(e.user)||typeof e.user.id!="string"||e.user.id===""||e.user.name!==void 0&&typeof e.user.name!="string")return"context.user is {id, name}, or null";t={id:e.user.id,name:typeof e.user.name=="string"?e.user.name:""}}let n=hs(e.metadata);return n===void 0?"context.metadata is an object of strings":{chatId:e.chat_id,agent:e.agent,user:t,metadata:n}}function ys(e){let t=gs(e);if(typeof t=="string")return t;let n=e;return typeof n.turn_id!="string"||typeof n.run_id!="string"?"context.turn_id and context.run_id are the turn the call is made in and the run that made it":n.subagent!==null&&typeof n.subagent!="string"?"context.subagent is the subagent that made the call, or null":{...t,turnId:n.turn_id,runId:n.run_id,subagent:n.subagent}}function ws(e){let t=gs(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,i=Ve(a)?hs(a.metadata):void 0;if(!Ve(a)||typeof a.id!="string"||typeof a.client_id!="string"||a.author!==null&&typeof a.author!="string"||typeof a.author_name!="string"||typeof a.text!="string"||typeof a.delivery!="string"||i===void 0)return"message is {id, client_id, author, author_name, text, delivery, metadata}, or null";r={id:a.id,clientId:a.client_id,author:a.author,authorName:a.author_name,text:a.text,delivery:a.delivery,metadata:xo(i)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!Ve(n.goal)||typeof n.goal.objective!="string"||typeof n.goal.rubric!="string")return"goal is {objective, rubric}";s={objective:n.goal.objective,rubric:n.goal.rubric}}return{...t,message:r,goal:s}}var Po=1e4,Co=10*6e4,Ut=class{constructor(t=Date.now){this.now=t}now;seen=new Map;take(t){let n=this.now();for(let[r,s]of this.seen){if(n-s<=Co&&this.seen.size<=Po)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},Mo=1e3,jo=256*1024,Lt=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,n){this.running.delete(t),!(n===void 0||n.answer.length>jo)&&(this.answers.set(t,n),this.answers.size>Mo&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as Xs,isEngineRaised as Hn,markData as le}from"palgres";import{createHash as ea}from"node:crypto";import{createHash as Do,randomInt as No}from"node:crypto";import{ago as En,isRetryable as Uo,now as bs}from"palgres";import{defineSchema as Lo,defineTable as Io,index as qo,integer as Ho,jsonb as zo,raw as Fo,text as Sn,timestamp as ks}from"palgres/dsl";var As=new Set(["POST","PUT","PATCH","DELETE"]),vs=255,Ts=35,$s=24,Go=65536,_s=1e3,Bo=64,xn={description:"Makes the write safe to send again (at most 255 characters). A retry with the same key and the same request gets the first answer back, marked `Idempotent-Replayed: true`, and changes nothing; the same key with a different request is refused with 422, and while the first request still runs a retry gets 409 with Retry-After. Answers are kept for 24 hours.",in:"header",name:"Idempotency-Key",required:!1,schema:{maxLength:255,type:"string"}},Ko=Io("idempotency_keys",{columns:{key:Sn().primaryKey(),fingerprint:Sn(),started_at:ks().defaultNow(),completed_at:ks().nullable(),status_code:Ho().nullable(),response_headers:zo().nullable(),response_body:Sn().nullable()},indexes:e=>[qo("idempotency_keys_started").on(e.col("started_at"))]}),Hc=Lo("palbase",{tables:[Ko],raw:[Fo("idempotency_answer",`CREATE OR REPLACE FUNCTION palbase.idempotency_answer(record_key text, claimed_at timestamptz, answer_status integer, answer_headers jsonb, answer_body text) RETURNS boolean
14
+ LANGUAGE sql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp
15
+ AS $answer$
16
+ UPDATE palbase.idempotency_keys
17
+ SET completed_at = now(), status_code = answer_status, response_headers = answer_headers, response_body = answer_body
18
+ WHERE key = record_key AND started_at = claimed_at AND completed_at IS NULL
19
+ RETURNING true
20
+ $answer$`,{drop:"DROP FUNCTION IF EXISTS palbase.idempotency_answer(text, timestamptz, integer, jsonb, text)"})]}),Jo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Wo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},Vo={status:409,code:"idempotency_key_in_use",message:"This request's Idempotency-Key was taken over by a retry; what it did is not kept",retryAfter:1},Es={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},qt=class extends Error{};function ft(e){return As.has(e.method)&&e.meta.upload===void 0}function xs(e,t){if(!As.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Zo(e,t){return Rs([e.role,e.uid,t]).digest("hex")}function Yo(e){return Rs([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Rs(e){let t=Do("sha256");for(let n of e)t.update(n).update("\0");return t}function Qo(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function An(e){return e<500&&e!==429&&e!==499}function Xo(e,t){return t&&An(e)}function Os(e){let t=e["~standard"].jsonSchema?.input,n;try{n=t?.({target:"draft-2020-12"})}catch{return!1}let r=n?.properties;return typeof r=="object"&&r!==null&&Object.keys(r).some(s=>s.toLowerCase()==="idempotency-key")}var ei={role:"service",claims:{}},ti={seal:e=>e,open:async e=>e},Ht=class{db;answers;constructor(t,n=ti){this.db=t,this.answers=n}async serve(t,n,r){if(t.key.length>vs)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${vs} characters`});let s;try{s=await this.begin(Zo(t.caller,t.key),Yo(t))}catch(d){return $.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:d}),r.refusal(Es)}if("kept"in s){let d;try{d=s.kept.body===null?null:await this.answers.open(s.kept.body)}catch(f){return $.warn("[palbase] the answer kept against an Idempotency-Key could not be opened; the write is not run again",{error:f}),r.refusal(Es)}return ni({...s.kept,body:d},r.requestId)}if("refused"in s)return r.refusal(s.refused==="reused"?Jo:Wo);let a=s.claim,i;try{i=await n(d=>this.record(a,d))}catch(d){if(d instanceof qt)return r.refusal(Vo);let f=r.failure(d);return Xo(f.status,r.ran())&&!Uo(d)?this.keep(a,f):(await this.release(a),f)}return An(i.status)||await this.release(a),i}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:En({hours:$s})}}}))}async begin(t,n){return No(Bo)===0&&await this.sweep().catch(r=>$.warn("[palbase] the expired Idempotency-Keys could not be taken away; the next sweep tries again",{error:r})),this.asService(async r=>{for(let s=0;s<3;s++){let[a]=await r.insertMany([{key:t,fingerprint:n}],{onConflict:["key"],action:"ignore"});if(a)return{claim:{key:t,started:a.started_at}};if(await r.deleteMany({where:{key:t,started_at:{lt:En({hours:$s})}}})>0)continue;let i=await r.findUnique({where:{key:t}});if(i===null)continue;let d=Qo(i,n);if(d==="reused")return{refused:"reused"};if(d==="replay")return{kept:{status:i.status_code,headers:i.response_headers??[],body:i.response_body}};let[f]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:En({seconds:Ts})}},set:{started_at:bs()}});return f?{claim:{key:t,started:f.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!An(n.status))return n;let{response:r,kept:s}=await Ss(n),a=re.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let i=s.body===null?null:this.answers.seal(s.body),[d]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),i]);if(d?.answered!==!0)throw new qt;return r}async keep(t,n){let{response:r,kept:s}=await Ss(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:bs(),status_code:s.status,response_headers:s.headers,response_body:s.body===null?null:this.answers.seal(s.body)}}))}catch(a){$.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:a})}return r}async release(t){if(await this.releaseOnce(t))return;let n=Date.now()+Ts*1e3,r=()=>{Date.now()+_s>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},_s).unref()};r()}async releaseOnce(t){try{return await this.asService(n=>n.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let n=this.db.request(ei),r;try{r=await t(n.database.palbase.idempotency_keys)}catch(s){throw await n.rollback(s).catch(()=>{}),s}try{await n.commit()}catch(s){throw await n.rollback(s).catch(()=>{}),s}return r}};function ni(e,t){let n=new Headers(e.headers);return n.set("x-request-id",t),n.set("idempotent-replayed","true"),new Response(e.body===null?null:Buffer.from(e.body,"base64"),{status:e.status,headers:n})}var It=Symbol("waits");function ri(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(It));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function Ss(e){let t=[];e.headers.forEach((d,f)=>{f!=="x-request-id"&&t.push([f,d])});let n=d=>new Response(d,{status:e.status,statusText:e.statusText,headers:e.headers});if(e.body===null)return{response:n(null),kept:{status:e.status,headers:t,body:null}};let r=e.body.getReader(),s=[],a=0;for(;;){let d=r.read(),f=await ri(d);if(f!==It&&f.done)break;if(f!==It&&(s.push(f.value),a+=f.value.byteLength,a<=Go))continue;let h=f===It?d:void 0,y=new ReadableStream({start(b){for(let S of s)b.enqueue(S)},async pull(b){let S=await(h??r.read());h=void 0,S.done?b.close():b.enqueue(S.value)},cancel:b=>r.cancel(b)});return{response:n(y),kept:{status:e.status,headers:t.filter(([b])=>b!=="content-length"&&b!=="content-encoding"),body:null}}}let i=Buffer.concat(s);return{response:n(i),kept:{status:e.status,headers:t,body:i.byteLength===0?null:i.toString("base64")}}}import{createHash as si}from"node:crypto";var Rn="/webhooks/palbase",Ns="PalbaseErrorEnvelope",Ps="PalbaseBearer",ai={$ref:`#/components/schemas/${Ns}`},oi={type:"object",description:"Every refusal: the framework's, a handler's HttpError, the database's.",properties:{error:{type:"string",description:"A stable code, like bad_request"},error_description:{type:"string",description:"What went wrong, for a person"},status:{type:"integer",description:"The HTTP status"},request_id:{type:"string",description:"The request's id, as the app's log has it"},data:{description:"Details, when the refusal has them: a validation's fields, a token's reason, a limit's retryAfter"}},required:["error","error_description","status","request_id"]},Cs={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Ye={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Us(e,t,n){let r={[Ns]:oi},s={},a=[],i=[],d=new Set,f=new Map;for(let m of e){let v=i.find(B=>li(B,m));if(v){a.push({route:m.id,handler:Ms(m),answeredBy:v.id});continue}i.push(m);let C=m.segments.map(B=>typeof B=="string"?B:"{}").join("/");f.has(C)||f.set(C,pi(m.segments.flatMap(B=>typeof B=="string"?[]:[B.param])));let L=f.get(C),Z=0,Y=`/${m.segments.map(B=>typeof B=="string"?B:`{${L[Z++]}}`).join("/")}`,U=t(m),I=zt(fi(m),d),F=m.method!=="GET"&&m.method!=="HEAD",G=B=>{let xe=m.params.filter(Ne=>Ne.kind===B&&Ne.schema).map((Ne,vt)=>Bt(Ne.schema,`${I}.${B}${vt===0?"":`.${vt+1}`}`,r));return xe.length===0?void 0:xe.length===1?xe[0]:{allOf:xe}},ne=L.map(B=>({name:B,in:"path",required:!0,schema:{type:"string"}})),Ae=G("query");Ae&&ne.push(...Ds(Ae,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:Ae}]);let wt=G("headers");wt&&ne.push(...Ds(wt,"header")??[]);let bt=n.idempotency===!0&&ft(m);bt&&ne.push({...xn,schema:{...xn.schema}});let pe=F?G("body"):void 0,X={operationId:I};m.controller.name!==""&&(X.tags=[m.controller.name]),ne.length>0&&(X.parameters=ne),pe&&(X.requestBody={required:!wi(pe),content:{"application/json":{schema:pe}}});let rt=m.params.some(B=>B.schema!==void 0),kt=n.routes?.(m),st=ki(I,kt?.throws??[],n.errors);X.responses={...bi(kt,I,r),...$i(U,{validates:rt,hasPathParams:L.length>0,readsBody:F,keyed:bt}),...Ti(st,I,r)},st.length>0&&(X["x-palbase-errors"]=vi(I,st)),U.auth.required&&(X.security=[{[Ps]:[]}]),X["x-palbase-handler"]=Ms(m);let Yt=m.params.some(B=>B.kind==="optionalUser")||n.databaseSeesCaller;X["x-palbase-auth"]=U.auth.required?"required":Yt?"optional":"public",X["x-palbase-verified-email"]=U.auth.verifiedEmail,U.auth.aal!=="aal1"&&(X["x-palbase-aal"]=U.auth.aal),U.auth.maxAge!==null&&(X["x-palbase-max-age"]=U.auth.maxAge),U.attest&&(X["x-palbase-attest"]=!0);let De=U.limit===!1?!1:U.limit.map(B=>({max:B.max,window:B.window}));X["x-palbase-rate-limit"]=De===!1?!1:De.length===1?De[0]:De,m.meta.upload&&(X["x-palbase-upload"]={bucket:m.meta.upload.bucket,pathTemplate:m.meta.upload.pathTemplate}),(s[Y]??={})[m.method.toLowerCase()]=X}for(let m of n.webhooks??[]){let v={operationId:zt(`webhooks.${m.name}`,d)};m.cls!==""&&(v.tags=[m.cls]),v.description=m.provider?`${Cs[m.provider]??m.provider}'s deliveries: verified with ${Cs[m.provider]??m.provider}'s signature scheme under the secret in ${m.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${m.signatureHeader} header: verified under the secret in ${m.secretEnv}, then handed to the @On of their event type.`,v.responses={200:{description:"Taken: { ok: true, handled } \u2014 handled is false when no @On takes the event's type, and duplicate is true for a delivery already run; or the handler's answer: a Response as it is, text as text, anything else as JSON",content:{"application/json":{},[m.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:te("invalid_signature: the delivery is not signed with the secret \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:te("in_progress: the same delivery is being handled; the sender delivers it again",Ye),413:te("payload_too_large: the body is over what this sender sends"),500:te("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:te("service_unavailable, auth_unavailable or database_unavailable: what the handler needs of the platform did not answer \u2014 the sender delivers it again after Retry-After",Ye)},v["x-palbase-webhook"]=m.provider?{provider:m.provider,secretEnv:m.secretEnv,events:m.events}:{signatureHeader:m.signatureHeader,secretEnv:m.secretEnv,events:m.events},s[`/webhooks/${m.name}`]={post:v}}let h=[...new Set(n.platformEvents??[])].sort();if(h.length>0){let m={operationId:zt("webhooks.palbase",d)};m.description="The project's events, delivered by the platform to the app's machine: verified under the secret in PALBASE_WEBHOOK_SECRET, then handed to the @On of their type \u2014 user.deleted first to forgetting the rows the app keeps of that user.",m.responses={204:{description:"Taken: handled, or a delivery already run"},401:te("invalid_signature: the delivery is not the platform's \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:te("in_progress: the same event is being handled; the platform delivers it again",Ye),500:te("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:te("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let v=[...new Set(n.platformEventBuckets??[])].sort();m["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:h,...v.length>0?{buckets:v}:{}},s[Rn]={post:m}}let y=n.gateways??[],b=ci(y,r),S=y.length>0,J=Object.fromEntries(y.filter(Ge).map(m=>[m.pattern,{events:b[m.name].events,messages:Object.fromEntries(Object.entries(b[m.name].messages).map(([v,C])=>[v,C.payload])),graceMs:m.graceMs,...m.logKeepSeconds>0?{logKeepSeconds:m.logKeepSeconds}:{}}])),N=Object.keys(J).length>0,H=y.filter(m=>!Ge(m)).map(m=>({pattern:m.pattern,kind:m.access,publish:m.publish,state_read:!1,state_write:!1,...m.logKeepSeconds>0?{log_keep_seconds:m.logKeepSeconds}:{}})),W=H.length>0,z=ii(n.ai?.agents??[]),oe=Object.keys(z).length>0,me=di(n.ai?.tools??[]),Se=Object.keys(me).length>0,k={schemas:r,securitySchemes:{[Ps]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},E={openapi:"3.2.0",info:{title:"Palbase backend",version:si("sha256").update(JSON.stringify({paths:s,components:k,unreachable:a,...S?{gateways:b}:{},...N?{rooms:J}:{},...W?{channels:H}:{},...oe?{agents:z}:{},...Se?{aiTools:me}:{}})).digest("hex").slice(0,12),description:"The routes this app serves, as its decorators declare them, and \u2014 when its source was read as the contract was written \u2014 what each answers and the errors it throws (x-palbase-errors). Every refusal is the PalbaseErrorEnvelope; a declared error's carries its code and its data."},paths:s,components:k};return a.length>0&&(E["x-palbase-unreachable"]=a),S&&(E["x-palbase-gateways"]=b),N&&(E["x-palbase-room"]=J),W&&(E["x-palbase-channels"]=H),oe&&(E["x-palbase-agents"]=z),Se&&(E["x-palbase-ai-tools"]=me),E}function ii(e){let t=new Map;for(let n of e){if(t.has(n.name))throw new Error(`ai.agent "${n.name}" is declared twice: an agent's name is its own \u2014 make each once, at a module's top level`);t.set(n.name,{...n.description!==void 0?{description:n.description}:{},...n.machine!==void 0?{machine:n.machine}:{}})}return Object.fromEntries([...t].sort(([n],[r])=>n<r?-1:n>r?1:0))}function di(e){let t=new Map;for(let n of e){let r=t.get(n.name);if(r)throw new Error(`ai tool "${n.name}" is declared twice (${r.kind===n.kind?`two ai.${n.kind==="backend"?"tool":"clientTool"}s`:"an ai.tool and an ai.clientTool"}): an agent is given one tool of a name \u2014 rename one of them`);t.set(n.name,{kind:n.kind,description:n.description,parameters:n.parameters,...n.approval?{approval:!0}:{},...n.kind==="backend"&&n.machine!==void 0?{machine:n.machine}:{}})}return Object.fromEntries([...t].sort(([n],[r])=>n<r?-1:n>r?1:0))}function ci(e,t){let n=[];for(let r of e){let s=(d,f,h,y)=>{let b=Gt(`${r.name}_${d}_${f}`),S={},J=Bt(h,b,S,y);J.$ref===void 0&&(S[b]=J),ui(r.pattern,d,f,S[b]);for(let[N,H]of Object.entries(S)){if(Object.hasOwn(t,N)&&JSON.stringify(t[N])!==JSON.stringify(H))throw new Error(`@Gateway("${r.pattern}") ${d} "${f}": its schema is the component ${N}, which another gateway's names with another schema \u2014 rename one of them`);t[N]=H}return{$ref:`#/components/schemas/${b}`}},a=Object.fromEntries(Object.entries(r.events).map(([d,f])=>[d,s("event",d,f,"answered")])),i=Object.fromEntries(Object.entries(r.messages).map(([d,f])=>[d,{payload:s("message",d,f.schema,"sent"),...f.reply?{reply:s("reply",d,f.reply,"answered")}:{}}]));n.push([r.name,{pattern:r.pattern,...r.access?{access:r.access}:{},...r.logKeepSeconds>0?{durable:r.logKeepSeconds}:{},...r.chat?{chat:!0}:{},events:a,messages:i}])}return Object.fromEntries(n)}function ui(e,t,n,r){if(!(!ae(r)||!ae(r.properties))){for(let[s,a]of Object.entries(r.properties))if(a===!0||ae(a)&&Object.keys(a).length===0)throw new Error(t==="message"?`@Gateway("${e}") message "${n}" has an untyped field "${s}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`:`@Gateway("${e}") ${t} "${n}" has an untyped field "${s}". An untyped payload makes every generated client opaque \u2014 declare its shape.`)}}function li(e,t){return e.method===t.method&&e.segments.length===t.segments.length&&e.segments.every((n,r)=>typeof n!="string"||n===t.segments[r])}function Ms(e){return`${e.controller.name}.${e.fn}`}function fi(e){let t=e.controller.name;if(t.endsWith("Controller")&&(t=t.slice(0,-10)),t!=="")return`${t[0].toLowerCase()}${t.slice(1)}.${e.fn}`;let n=r=>r.charAt(0).toUpperCase()+r.slice(1);return e.method.toLowerCase()+e.segments.map(r=>typeof r=="string"?n(r):`By${n(r.param)}`).join("")}function zt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function pi(e){let t=new Set;return e.map(n=>zt(n,t))}function Bt(e,t,n,r="sent"){let s=e["~standard"],a=s.jsonSchema?.input;if(typeof a!="function")return{};let i;try{i=a({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...s.vendor==="zod"?{override:mi}:{}}})}catch{return{}}let d=Gt(t);for(;Object.keys(n).some(f=>f===d||f.startsWith(`${d}.`));)d=`${d}_`;return hi(i,d,n,r)}function mi(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function hi(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,i=h=>h==="#"?(a=!0,`#/components/schemas/${t}`):h.startsWith("#/$defs/")?`#/components/schemas/${t}.${Gt(yi(h.slice(8)))}`:h,d="all";if(r==="sent"){let h=new Set;for(let y of[e,...Object.values(s)])Ft(y,h);d=h}for(let[h,y]of Object.entries(s))n[`${t}.${Gt(h)}`]=mt(pt(y,i,d));let f=mt(pt(e,i,d));return a?(n[t]=f,{$ref:`#/components/schemas/${t}`}):f}var gi=new Set(["type","enum","required","dependentRequired","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","contentEncoding","contentMediaType","minItems","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties","readOnly","writeOnly","deprecated",rr]),On=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),Pn=new Set(["anyOf","oneOf","allOf","prefixItems"]),Cn=new Set(["properties","patternProperties","dependentSchemas"]),ae=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pt(e,t,n){if(!ae(e))return typeof e=="boolean"?e:{};let r={};for(let[s,a]of Object.entries(e))s==="$ref"&&typeof a=="string"?r.$ref=t(a):s==="const"?(n==="all"||n.has(e))&&(r.const=a):gi.has(s)?r[s]=a:On.has(s)?r[s]=pt(a,t,n):Pn.has(s)&&Array.isArray(a)?r[s]=a.map(i=>pt(i,t,n)):Cn.has(s)&&ae(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([i,d])=>[i,pt(d,t,n)])));return r}var js=Number.MAX_SAFE_INTEGER;function mt(e){if(!ae(e))return e;let t={};for(let[r,s]of Object.entries(e))On.has(r)?t[r]=mt(s):Pn.has(r)&&Array.isArray(s)?t[r]=s.map(mt):Cn.has(r)&&ae(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,i])=>[a,mt(i)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-js&&delete t.minimum,t.maximum===js&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,ae(t.propertyNames)&&Object.keys(t.propertyNames).length===1&&t.propertyNames.type==="string"&&delete t.propertyNames,Array.isArray(t.type)&&t.type.filter(r=>r!=="null").length>1&&Object.keys(t).length===1)return{anyOf:t.type.map(r=>({type:r}))};let n=t.anyOf;if(Array.isArray(n)&&n.length===2&&Object.keys(t).length===1){let r=n.findIndex(a=>ae(a)&&Object.keys(a).length===1&&a.type==="null"),s=n[1-r];if(r!==-1&&ae(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function Ft(e,t){if(ae(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(ae))continue;if(r.every(a=>"const"in a||Array.isArray(a.enum)))for(let a of r)t.add(a);let s=r.map(a=>ae(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(i=>ae(i[a])&&"const"in i[a]))for(let i of s)t.add(i[a])}for(let[n,r]of Object.entries(e))if(On.has(n))Ft(r,t);else if(Pn.has(n)&&Array.isArray(r))for(let s of r)Ft(s,t);else if(Cn.has(n)&&ae(r))for(let s of Object.values(r))Ft(s,t)}}function yi(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Gt(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function Ds(e,t){if(e.type!=="object"||typeof e.properties!="object"||e.properties===null)return;let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([r,s])=>({name:r,in:t,required:n.has(r),schema:s}))}function wi(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function te(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:ai}}}}function bi(e,t,n){if(!e)return{200:{description:"The handler's answer, as JSON",content:{"application/json":{}}},204:{description:"The handler answered nothing (undefined or null)"}};if(e.returns.kind==="void")return{204:{description:"No Content"}};if(e.returns.kind==="raw")return{default:{description:"The handler's own Response, as it built it"}};let r=Bt(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function ki(e,t,n){let r=new Set,s=[];for(let a of t){if(r.has(a.code))continue;r.add(a.code);let i=n?.get(a.code);if(i&&a.status!==i.status)throw new Error(`${e} throws "${a.code}" with status ${a.status}, but the code is defined with status ${i.status} \u2014 a client matches an error by its code, so one code carries one status`);s.push({...a,...i?.data?{data:i.data}:{}})}return s}function vi(e,t){let n=Object.create(null);for(let r of t){let s=r.name.charAt(0).toLowerCase()+r.name.slice(1),a=Object.hasOwn(n,s)?n[s]:void 0;if(a)throw new Error(`${e} throws "${a.code}" and "${r.code}" under one name, "${r.name}" \u2014 every client names an error case after it; give one of them its own defineError`);n[s]={status:r.status,code:r.code,hasData:r.data!==void 0,description:""}}return n}function Ti(e,t,n){let r=new Map;for(let a of e)r.set(a.status,[...r.get(a.status)??[],a]);let s={};for(let a of[...r.keys()].sort((i,d)=>i-d)){let i=r.get(a),d=i.map(f=>{let h={error:{type:"string",const:f.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},y=["error","error_description","status","request_id"];return f.data&&(h.data=Bt(f.data,`${t}.${f.code}.data`,n,"answered"),y.push("data")),{type:"object",properties:h,required:y}});s[String(a)]={description:i.map(f=>f.code).join(" | "),content:{"application/json":{schema:d.length===1?d[0]:{oneOf:d}}}}}return s}function $i(e,t){let n={},r=[t.validates&&"a parameter failed its schema (data.fields names each field, data.more how many more)",t.hasPathParams&&"the path is not valid percent-encoding"].filter(Boolean),s=[r.length>0&&`bad_request: ${r.join("; or ")}`,t.keyed&&"invalid_idempotency_key: the Idempotency-Key is over 255 characters"].filter(Boolean);s.length>0&&(n[400]=te(s.join("; ")));let a=[e.auth.required&&"unauthorized: no access token was sent; invalid_token: the token is not valid (data.reason says why), or the Authorization header is not a Bearer token",e.auth.aal!=="aal1"&&`insufficient_user_authentication: the user signed in below ${e.auth.aal} \u2014 step up and call again (WWW-Authenticate acr_values; data.acr_values)`,e.auth.maxAge!==null&&`insufficient_user_authentication: the user last signed in or stepped up more than ${e.auth.maxAge} seconds ago \u2014 step up and call again (WWW-Authenticate max_age; data.max_age)`,e.attest&&"app_attest_required: the environment asks for the device's attestation and the call's proof is missing or does not verify (data.reason: app_attest_required, assertion_invalid, assertion_stale, device_unknown; data.challenge and X-Palbase-Attest-Challenge to attest with)"].filter(Boolean);return a.length>0&&(n[401]=te(a.join("; "))),e.auth.verifiedEmail&&(n[403]=te("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=te("idempotency_key_in_use: a request with this Idempotency-Key is still running",Ye)),t.readsBody&&(n[413]=te("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=te("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=te("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Ye)),n[500]=te("internal_error: the handler failed; the app's log has it under the request id"),n[503]=te(`${e.auth.required?"auth_unavailable: sign-ins cannot be checked right now; ":""}${e.attest?"attest_unavailable: the device's attestation cannot be checked right now; ":""}service_unavailable: a platform service the request needs did not answer${t.keyed?"; temporarily_unavailable: the Idempotency-Key could not be recorded":""}`,Ye),n}var Kt=class{windows=new Map;now;maxKeys;constructor(t=Date.now,n=1e5){this.now=t,this.maxKeys=n}take(t,n){let r=this.now(),s=this.windows.get(t);if((!s||r>=s.resetAt)&&(s={count:0,resetAt:r+n.window*1e3}),this.windows.delete(t),this.windows.set(t,s),this.windows.size>this.maxKeys&&this.windows.delete(this.windows.keys().next().value),s.count++,s.count>n.max)return Math.max(1,Math.ceil((s.resetAt-r)/1e3))}takeEach(t,n){if(n.length===1)return this.take(t,n[0]);let r,s=[];if(n.forEach((a,i)=>{let d=this.reserve(`${t}\0${i}`,a);"wait"in d?r=Math.max(r??0,d.wait):s.push([`${t}\0${i}`,d.window])}),r!==void 0)for(let[a,i]of s)this.give(a,i);return r}reserve(t,n){let r=this.take(t,n);return r!==void 0?{wait:r}:{window:this.windows.get(t).resetAt}}give(t,n){let r=this.windows.get(t);r&&r.resetAt===n&&r.count>0&&r.count--}};function Jt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return _i(r??t??"unknown")}function _i(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(n)return n[1];let[r,s=""]=t.split("::"),a=r?r.split(":"):[],i=s?s.split(":"):[],d=t.includes("::")?[...a,...Array(8-a.length-i.length).fill("0"),...i]:a;return d.length!==8||d.some(f=>!/^[0-9a-f]{1,4}$/i.test(f))?t:`${d.slice(0,4).map(f=>parseInt(f,16).toString(16)).join(":")}::/64`}var ge={deviceId:"x-palbase-device-id",anchor:"x-palbase-installation-anchor",challenge:"x-palbase-attest-challenge",payload:"x-palbase-attest-payload",signature:"x-palbase-attest-signature",capable:"x-palbase-attest-capable",sdkVersion:"x-palbase-sdk-version"},Ei=25e3,Mn=3e3,Si=1e4,Ls=()=>({capable:0,incapable:0,unknown:0,no_sdk:0,verified:0,refused:0}),Wt=class{constructor(t,n=Date.now){this.auth=t;this.now=n}auth;now;mode;readAt=-1/0;reading;counts=Ls();timer;shipping=Promise.resolve();async modeNow(){return this.now()-this.readAt>=Ei&&(this.reading??=this.readMode().finally(()=>{this.reading=void 0}),await this.reading),this.mode}async readMode(){try{let n=(await this.auth.adminGetAttestPolicy({signal:AbortSignal.timeout(Mn)})).data.mode;if(n!=="off"&&n!=="monitor"&&n!=="enforce")throw new Error(`auth answered an App Attest mode this version does not know: ${JSON.stringify(n)}`);this.mode=n,this.readAt=this.now()}catch(t){$.warn(`[palbase] attest: the environment's App Attest mode could not be read${this.mode?`; keeping ${this.mode}`:""}`,{error:t})}}async check(t,n,r){let s=await this.modeNow();if(s===void 0)return{unavailable:!0,pass:!1};if(s==="off")return{pass:!0};let a=t.headers,i=a.get(ge.deviceId)??"",d=a.get(ge.payload)??"",f=a.get(ge.signature)??"",h=i!==""&&d!==""&&f!=="",y=h&&Is(d)&&Is(f);this.declared(a,h);let b;try{b=(await this.auth.adminVerifyDeviceAssertion({body:{installation_id:a.get(ge.anchor)??"",device_id:y?i:"",challenge:a.get(ge.challenge)??"",payload:y?d:"",signature:y?f:"",method:t.method,path:Ai(n),body_sha256:r&&r.byteLength>0?await xi(r):""},signal:AbortSignal.timeout(Mn)})).data}catch(N){return $.warn(`[palbase] attest: auth could not verify ${t.method} ${n.pathname}`,{error:N}),s==="enforce"?{unavailable:!0,pass:!1}:{pass:!0}}h&&this.outcome(y&&b.ok);let S=s==="enforce"&&b.ok&&b.device_id&&b.platform?{id:b.device_id,platform:b.platform}:void 0;return b.ok||s==="monitor"?{pass:!0,challenge:b.next_challenge||void 0,device:S}:{pass:!1,reason:h?y?b.reason==="assertion_stale"||b.reason==="device_unknown"||b.reason==="assertion_invalid"?b.reason:"app_attest_required":"assertion_invalid":"app_attest_required",challenge:b.next_challenge}}declared(t,n){let r=t.get(ge.capable);n||r==="yes"?this.counts.capable++:r==="no"?this.counts.incapable++:t.get(ge.sdkVersion)?this.counts.unknown++:this.counts.no_sdk++,this.schedule()}outcome(t){t?this.counts.verified++:this.counts.refused++}schedule(){this.timer||(this.timer=setInterval(()=>{this.flush()},Si),this.timer.unref?.())}async flush(){let t=this.counts;Object.values(t).every(n=>n===0)||(this.counts=Ls(),this.shipping=this.shipping.then(async()=>{try{await this.auth.adminRecordAttestObservations({body:t,signal:AbortSignal.timeout(Mn)})}catch(n){$.warn("[palbase] attest: a batch of App Attest counts was not recorded",{error:n})}}),await this.shipping)}async stop(){this.timer&&clearInterval(this.timer),this.timer=void 0,await this.flush()}};function Is(e){return e.length===0||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)?!1:Buffer.from(e,"base64").toString("base64")===e}function Ai(e){let t=e.href,n=t.indexOf("#");return(n===-1?t:t.slice(0,n)).slice(e.origin.length)}async function xi(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Buffer.from(n).toString("base64")}function qs(e){let t=[];for(let n of e){let r=D(n,Le),s=D(n,Ie)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=D(n,sn)??new Map;for(let i of s){let d=`${r.basePath}${i.subpath}`||"/",f=d.split("/").filter(Boolean).map(y=>{let b=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(y)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(y);return b?{param:b[1]}:y});if(typeof f[0]=="string"&&He.has(f[0]))throw new TypeError(`${n.name}.${i.fn}: ${i.method} ${d} \u2014 /${f[0]} is the platform's; a route is served elsewhere`);let h=[...a.get(i.fn)??[]].sort((y,b)=>y.index-b.index);for(let y of h)if(y.kind==="param"&&!f.some(b=>typeof b!="string"&&b.param===y.name))throw new TypeError(`${n.name}.${i.fn}: @Param("${y.name}") names no {${y.name}} in ${i.method} ${d}`);t.push({id:`${i.method} ${d}`,method:i.method,segments:f,controller:n,fn:i.fn,params:h,meta:i,controllerAuth:r.options.auth,controllerAttest:r.options.attest})}}return jr(t),t}function jn(e,t,n){let r=n.split("/").filter(Boolean);for(let s of e){if(s.method!==t||s.segments.length!==r.length)continue;let a={},i=!0;for(let d=0;d<r.length&&i;d++){let f=s.segments[d];if(typeof f=="string")i=f===r[d];else try{a[f.param]=decodeURIComponent(r[d])}catch{return{malformed:!0}}}if(i)return{route:s,params:a}}return null}function Un(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Qe(e,t,n,r,s){return nt(e,e?Un(e.requests,t):void 0,n,r,s)}var ht={role:"service",claims:{}};async function nt(e,t,n,r,s){if(!e||!t)return s();let a=h=>$.warn(`[palbase] ${r}: a transaction of the request could not be given back \u2014 it wrote, locked, is an $atomic or an $attempt, ran SQL of its own, or the database keeps one snapshot for it \u2014 and sat ${h} ms with no statement running: the handler waited on something else, and a database connection waited with it. Make the outside call before the first write, or outside $atomic.`,{waitedMs:h}),i=e.app.request(t,{signal:n,heldIdle:a}),d=re.getStore();d&&(d.database=i.database);let f;try{f=await s()}catch(h){throw await i.rollback(h).catch(y=>$.error("[palbase] the request's transaction could not be rolled back",{error:y})),h}try{await i.commit()}catch(h){throw await i.rollback(h).catch(y=>$.error("[palbase] the request's transaction could not be rolled back",{error:y})),h}return f}var Oi=1024*1024,Pi=20,Ci={max:300,window:60},Xe="/_palbase/crons",et="/_palbase/tasks",Hs=50,zs=50,Mi=4096,ji=69632,Fs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,tt=1e4,Di=6e4;function Ni(e,t){let n=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof n=="boolean")return{required:n,verifiedEmail:!1,aal:"aal1",maxAge:null};if((n.role??"").trim()!==""||(n.permission??"").trim()!=="")throw new TypeError(`${e.id}: auth { role, permission } is not checked by Palbase \u2014 check the role in the service`);let r=n.aal??"aal1";if(r!=="aal1"&&r!=="aal2"&&r!=="aal3")throw new TypeError(`${e.id}: auth { aal } is 'aal1', 'aal2' or 'aal3', not ${JSON.stringify(r)}`);if(r!=="aal1"&&n.required===!1)throw new TypeError(`${e.id}: auth { aal: '${r}' } asks how the user signed in \u2014 the route needs a signed-in user (required: true)`);let s=n.maxAge??null;if(s!==null&&!(Number.isInteger(s)&&s>0))throw new TypeError(`${e.id}: auth { maxAge } is a whole number of seconds above 0, not ${JSON.stringify(s)}`);if(s!==null&&n.required===!1)throw new TypeError(`${e.id}: auth { maxAge } asks when the user last signed in \u2014 the route needs a signed-in user (required: true)`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0,aal:r,maxAge:s}}function Gs(e,t){let n=['error="insufficient_user_authentication"'];return e.aal!=="aal1"&&n.push(`acr_values="urn:nist:800-63:${e.aal}"`),e.maxAge!==null&&n.push(`max_age=${e.maxAge}`),`${t?"DPoP":"Bearer"} ${n.join(", ")}`}function Bs(e){return{...e.aal!=="aal1"?{acr_values:e.aal}:{},...e.maxAge!==null?{max_age:e.maxAge}:{}}}var Ui=60;function Li(e,t,n){if(e===null)return!1;let r=n/1e3-e;return r>=-Ui&&r<=t}var ee=class extends Error{constructor(n,r,s,a,i,d,f){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=i;this.challenge=d;this.headers=f}status;code;data;retryAfter;challenge;headers};function Ii(e){if(e==="proof")return'DPoP error="invalid_dpop_proof", algs="ES256"';if(e==="bound"||e==="not_bound")return'DPoP error="invalid_token", algs="ES256"'}var qi=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Hi(e,t){let n=new Headers(e.headers);for(let r of qi)n.delete(r);return e.url!==""&&(n.delete("content-encoding"),n.delete("content-length")),n.set("x-request-id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function Ks(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Vt(e.headers,"Accept-Language")),e}function Vt(e,t){let n=(e.get("vary")??"").split(",").map(r=>r.trim()).filter(Boolean);n.includes("*")||n.some(r=>r.toLowerCase()===t.toLowerCase())||e.set("vary",[...n,t].join(", "))}function ue(e,t,n,r={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}})}function T(e,t){let n={error:e.code,error_description:e.message,status:e.status,request_id:t};e.data!==void 0&&(n.data=e.data);let r={...e.headers};return e.retryAfter!==void 0&&(r["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(r["www-authenticate"]=e.challenge),ue(e.status,n,t,r)}function Js(e,t){if(t===void 0)return e;try{return e.headers.set(ge.challenge,t),e}catch{let n=new Headers(e.headers);return n.set(ge.challenge,t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}}var ta=new Set([0,429,502,503,504]);function Ws(e,t,n,r){if(r?.aborted)return $.info(`[palbase] ${n}: the client left before its answer`),T({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof ee)return T({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge,headers:e.headers},t);if(lt(e)){let a=e;return a.status>=500&&$.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),ue(a.status,cs(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Zt(e,n);return s?T(s,t):(e instanceof ie?$.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):$.error(`[palbase] unhandled error in ${n}`,{error:e}),T({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Zt(e,t){if(e instanceof xt)return $.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ie&&ta.has(e.status))return $.warn(`[palbase] ${t}: a platform service did not answer (${e.op}: ${e.status} ${e.code})`,{error:e}),{status:503,code:"service_unavailable",message:"A service this request needs did not answer; try again shortly",retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))};let n=Xs(e);if(n!==void 0)return $.warn(`[palbase] ${t}: the database connection ${n==="lost"?"was lost":"could not be opened"}`,{error:e}),{status:503,code:"database_unavailable",message:"The database is temporarily unavailable",data:{retrySafe:n==="never"},retryAfter:1}}function zi(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return ps(e)?t(e.message):lt(e)&&!Hn(e)&&!Ln(e)?t(e.errorDescription):Ln(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function Ln(e){return e instanceof xt||e instanceof ie&&ta.has(e.status)||Xs(e)!==void 0||lt(e)&&e.status===503&&Hn(e)}async function Dn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,Pi).map(i=>({field:(i.path??[]).map(d=>String(typeof d=="object"&&d!==null&&"key"in d?d.key:d)).join("."),message:i.message})),a=r.issues.length-s.length;throw new ee(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function gt(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new ee(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let r=e.body.getReader(),s=[],a=0;for(;;){let{done:f,value:h}=await r.read();if(f)break;if(a+=h.byteLength,a>t)throw await r.cancel().catch(()=>{}),new ee(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(h)}let i=new Uint8Array(a),d=0;for(let f of s)i.set(f,d),d+=f.byteLength;return i}function Fi(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return le(t)}function Gi(e){let t=e.claims.custom_claims;return{id:e.id,email:e.email,role:e.role,emailVerified:e.emailVerified,metadata:typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},sessionId:e.sessionId,test:e.claims.test===!0,acr:Bi(e.claims.acr),amr:Array.isArray(e.claims.amr)?e.claims.amr.filter(n=>typeof n=="string"):[],authTime:typeof e.claims.auth_time=="number"&&e.claims.auth_time>0?e.claims.auth_time:null}}function Bi(e){return e==="aal1"||e==="aal2"||e==="aal3"?e:null}function Vs(e){return e==="aal3"?3:e==="aal2"?2:1}function Ki(e){return e.id?{id:e.id,email:e.email??null,role:e.role,emailVerified:e.emailVerified??!1,metadata:{},sessionId:e.session??null,test:!1,acr:null,amr:[],authTime:null}:null}var Ji=/^[A-Za-z0-9._:-]{8,128}$/,Wi=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Vi={max:20,window:60},Zi=10*6e4,Yi=1e4,yt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},In=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=ea("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),i=`token-misses\0a:${n}`,d;if(!a){let h=this.limiter.reserve(i,Vi);if("wait"in h)throw new yt(h.wait);d=h}let f=await r();if(!f)throw this.known.delete(s),new At("unknown_token","The token is not one of the app's");return d&&this.limiter.give(i,d.window),this.known.delete(s),this.known.set(s,this.now()+Zi),this.known.size>Yi&&this.known.delete(this.known.keys().next().value),f}};function _u(e){let t=new Nt(e.modules),n=qs(t.controllers.map(o=>o.cls)),r=new Map(n.map(o=>[o,Ni(o,e.auth)])),s=o=>o.meta.options.attest??o.controllerAttest??!1,a=n.some(s)?new Wt(e.server.auth,e.now):void 0,i=new Map;for(let o of n){let c={body:[],query:[]};for(let l of o.params){if(!l.schema)continue;let u=mr(l.schema);if(l.kind==="body")c.body.push(...tn(u,"/body",o.id));else if(l.kind==="query"){let g=tn(u,"/query",o.id),p=g.find(w=>w.split("/").length!==3);if(p)throw new TypeError(`${o.id}: ${p} \u2014 an encrypted query field is one of the query's own names`);c.query.push(...g)}else if(hr(u))throw new TypeError(`${o.id}: its ${l.kind} carry no encrypted field \u2014 its body's or its query's do`)}if(c.body.length+c.query.length!==0){if(o.meta.upload)throw new TypeError(`${o.id}: an upload's body comes through storage, which seals nothing \u2014 it carries no encrypted field`);i.set(o,c)}}async function d(o,c,l,u){let g=e.server.transit;try{return g.loaded||await g.load(),await g.request({header:l,method:u,path:td(o),params:o.segments.flatMap(p=>typeof p=="string"?[]:[c[p.param]??""])})}catch(p){throw Ys(p)}}for(let[o,c]of r){if(!c.required&&o.params.some(l=>l.kind==="user"))throw new TypeError(`${o.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(o.meta.upload&&c.verifiedEmail)throw new TypeError(`${o.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`);if(o.meta.upload&&c.aal!=="aal1")throw new TypeError(`${o.id}: an @Upload route cannot ask for auth { aal } \u2014 storage names its caller by id and session, not by its token`);if(o.meta.upload&&c.maxAge!==null)throw new TypeError(`${o.id}: an @Upload route cannot ask for auth { maxAge } \u2014 storage names its caller by id and session, not by its token's auth_time`);if(!s(o)&&o.params.some(l=>l.kind==="attestedDevice"))throw new TypeError(`${o.id}: @AttestedDevice() on a route that does not ask for device attestation \u2014 mark it attest: true`);if(o.meta.upload&&s(o))throw new TypeError(`${o.id}: an @Upload route cannot ask for device attestation \u2014 storage calls it, not the app's client; attest the route the app calls before the upload`)}let f=new Map;for(let o of n)for(let c of o.params)c.kind==="resolve"&&f.set(c,t.dependencyOf(o.controller,c.resolver,`${o.id} @Resolve(${c.resolver?.name})`));let h=new Map;for(let o of t.cronProviders){let c=t.get(o),l=D(o,Te),u=h.get(l.name);if(u)throw new TypeError(`@Cron "${l.name}" is ${u.owner} and ${o.name}: a cron's name is its own \u2014 name one of them`);h.set(l.name,{declaration:l,owner:o.name,run:g=>c.run(g)})}let y=new Map;for(let o of t.taskProviders){let c=t.get(o),l=D(o,be),u=y.get(l.name);if(u)throw new TypeError(`@Task "${l.name}" is ${u.owner} and ${o.name}: a task type's name is its own \u2014 name one of them`);y.set(l.name,{declaration:l,owner:o.name,run:(g,p)=>c.run(g,p)})}let b=new Map;for(let o of t.templateProviders){let c=t.get(o),l=D(o,ke),u=b.get(l.name);if(u)throw new TypeError(`@TestUserTemplate "${l.name}" is ${u.owner} and ${o.name}: a template's name is its own \u2014 name one of them`);b.set(l.name,{owner:o.name,seed:(g,p)=>c.seed(g,p),...typeof c.undo=="function"?{undo:(g,p)=>c.undo(g,p)}:{}})}b.size>0&&!e.platform&&$.info(`[palbase] ${b.size} @TestUserTemplate(s): the platform calls a machine for its test users; nothing does here`);let S=new Map,J=new Set,N=new Set,H=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(h.size>Hs)throw new TypeError(`${h.size} @Cron classes: a machine runs ${Hs} crons at most`);if(y.size>zs)throw new TypeError(`${y.size} @Task classes: a machine runs ${zs} task types at most`);h.size>0&&!e.platform&&$.info(`[palbase] ${h.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let W=Kr(t.gateways.map(o=>({cls:o,instance:t.get(o)})),{run:(o,c,l,u)=>re.run({requestId:re.getStore()?.requestId??"",...o?.id?{userId:o.id}:{}},()=>nt(e.database,e.database?o?.id?Un(e.database.requests,jt(o)):ht:void 0,l,c,async()=>{let g=await u();if(l?.aborted)throw new Error(`realtime gave up on ${c} before it ended`);return g})),broadcast:o=>e.server.realtime.broadcast({body:{messages:o}}),revalidate:o=>e.server.realtime.revalidate({body:o}),isOutage:Ln});W.declarations.length>0&&!e.platform&&$.info(`[palbase] ${W.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let z=ms();(z.tools.size>0||z.agents.size>0)&&!e.platform&&$.info(`[palbase] ${z.tools.size} ai.tool(s) and ${z.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let oe=o=>c=>t.provider(c,`${o} ctx.inject(${typeof c=="function"?c.name:String(c)})`),me=new Lt,Se=new Ut(e.now??Date.now),k=new Set,E=e.database!==void 0||e.contractOnly?.database===!0;if(E){for(let o of n)if(ft(o)&&o.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&Os(c.schema)))throw new TypeError(`${o.id}: its @Headers schema declares Idempotency-Key \u2014 the framework takes that header on every write of an app with a database and answers a retry from it; a handler reads it with @Headers() (no schema)`)}let m=e.database?new Ht(e.database.app,e.database.keptAnswers):void 0,v=id(e.cors),C=e.now??Date.now,L=new Kt(e.now),Z=new In(L,e.now??Date.now),Y=e.maxBodyBytes??Oi,U=o=>{let c=o.meta.options.rateLimit??e.rateLimit??Ci;if(c===!1)return!1;let l=(Array.isArray(c)?c:[c]).filter(u=>u.max>0&&u.window>0);return l.length>0?l:!1},I=e.env??process.env,F=Qr(t.webhooks,o=>t.get(o),I,{secrets:e.contractOnly===void 0}),G=F.size===0&&h.size===0&&y.size===0&&b.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(I).filter(o=>typeof o[1]=="string"&&!cr(o[0])))),ne=new Map([...F.keys()].map(o=>[o,{seen:new Set,inflight:new Set}])),Ae=new Map([...F.keys()].map(o=>[o,{counts:new Map,at:void 0}])),wt,bt=()=>wt??=Us(n,o=>({auth:r.get(o),limit:U(o),attest:s(o)}),{databaseSeesCaller:E,idempotency:E,webhooks:[...F.values()].map(o=>({name:o.name,cls:o.cls.name,provider:o.provider,signatureHeader:o.signatureHeader,secretEnv:o.secretEnv,events:[...o.events.keys()]})),platformEvents:[...pe.keys()],gateways:W.declarations,ai:{agents:[...z.agents.values()].map(o=>({name:o.name,...o.description!==void 0?{description:o.description}:{},...o.machine!==void 0?{machine:o.machine}:{}})),tools:[...[...z.tools.values()].map(o=>({name:o.name,kind:"backend",description:o.description,parameters:o.parameters,approval:o.approval,...o.machine!==void 0?{machine:o.machine}:{}})),...[...z.clientTools.values()].map(o=>({name:o.name,kind:"client",description:o.description,parameters:o.parameters,approval:o.approval}))]},platformEventBuckets:Xi(pe),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),pe=new Map;for(let[o,c]of Object.entries(e.events??{}))pe.set(o,c.map(l=>({name:`palbase(${o})`,call:u=>l(u)})));for(let o of t.eventProviders){let c=t.get(o);for(let{event:l,fn:u,bucket:g}of D(o,Pe)??[]){if(!vr.test(l))throw new TypeError(`@On("${l}") on ${o.name}.${u}: a platform event's type is dotted lowercase words, like user.deleted \u2014 a third party's event is taken by an @On in its @Webhook class`);pe.has(l)||pe.set(l,[]),pe.get(l).push({name:`${o.name}.${u}`,bucket:g,call:async(p,w)=>c[u](p,w)})}}let X=new Set,rt=new Set;ur(e.server),lr({to:(o,c)=>({emit:(l,u)=>W.emit(o,c,l,u),pipe:l=>W.pipe(o,c,l),revalidate:l=>W.revalidate(o,c,l)})}),$r(e.platform?_r(I.PALBASE_MACHINE):new Ct(new Map([...y].map(([o,c])=>[o,c.declaration])),(o,c)=>Bn(o,c),e.now));async function kt(o,c){let l;try{l=await ir(o,e.webhookSecret,{now:e.now})}catch(u){if(u instanceof ot)return T({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${u.code}`},c);throw u}if(le(l.data),X.has(l.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(rt.has(l.id))return T({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);rt.add(l.id);try{let u;try{await Qe(e.database,null,void 0,`event ${l.type}`,async()=>{for(let g of pe.get(l.type)??[])if(!(g.bucket!==void 0&&Qi(l)!==g.bucket))try{await g.call(l,{requestId:c})}catch(p){throw u=g.name,p}})}catch(g){return $.error(`[palbase] ${u??"the delivery"} failed on ${l.type} ${l.id}; the platform delivers it again`,{error:g}),T({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return X.add(l.id),X.size>tt&&X.delete(X.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{rt.delete(l.id)}}async function st(o,c={}){let l=o.headers.get("origin");if(v&&l!==null){let u=v.allows(l);if(o.method==="OPTIONS"&&o.headers.has("access-control-request-method"))return u?new Response(null,{status:204,headers:v.preflight(l,o.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let g=await Vn(o,c);if(u)for(let[p,w]of Object.entries(v.headers(l)))p==="vary"?Vt(g.headers,w):g.headers.set(p,w);else Vt(g.headers,"Origin");return g}return Vn(o,c)}async function Yt(o,c,l,u){if(!o.headers.get(l.scheme.header))return B(l,"missing_signature",u);let g={headers:o.headers,body:await gt(o,l.scheme.maxBytes(Y)),url:Xr(o,c)},p;try{p=l.scheme.check(g,C()/1e3)}catch{return B(l,"signature_mismatch",u,"check_failed")}if(typeof p=="string")return B(l,p,u);let w=l.events.get(p.type);if(!w)return $.info(`[palbase] webhook ${l.name}: no @On takes "${p.type}"; acknowledged`),ue(200,{ok:!0,handled:!1},u);let _=ne.get(l.name),R=p.event,O=[];if(p.id!==void 0){if(_.seen.has(p.id))return ue(200,{ok:!0,handled:!1,duplicate:!0},u);O=[p.id]}else if(p.ids&&Array.isArray(R)){let A=p.ids,x=R.map((j,Q)=>[j,A[Q]]).filter(([,j])=>j===void 0||!_.seen.has(j));if(x.length===0)return ue(200,{ok:!0,handled:!1,duplicate:!0},u);R=x.map(([j])=>j),O=x.flatMap(([,j])=>j===void 0?[]:[j])}if(O.some(A=>_.inflight.has(A)))return T({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},u);le(R);for(let A of O)_.inflight.add(A);let P;try{P=await Qe(e.database,null,void 0,`webhook ${l.name}`,()=>w.call(R,{env:G,requestId:u,environmentId:e.projectId??""}))}catch(A){let x=Zt(A,`webhook ${l.name}`)??nd(A,l.name);return x?T(x,u):($.error(`[palbase] ${w.name} failed on ${l.name} "${p.type}"; the sender delivers it again`,{error:A}),T({status:500,code:"handler_failed",message:"The event could not be handled"},u))}finally{for(let A of O)_.inflight.delete(A)}for(let A of O)_.seen.add(A),_.seen.size>tt&&_.seen.delete(_.seen.values().next().value);return De(P,l,u)}function De(o,c,l){if(o instanceof Response)return o;if(typeof o=="string"){let u=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(o,{status:200,headers:{"content-type":u,"x-request-id":l}})}return ue(200,o??{ok:!0,handled:!0},l)}function B(o,c,l,u=c){let g=Ae.get(o.name);g.counts.set(u,(g.counts.get(u)??0)+1);let p=C();return(g.at===void 0||p-g.at>=Di)&&(xe(o.name),g.at=p),T({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},l)}function xe(o){let c=Ae.get(o).counts;if(c.size===0)return;let l=[...c.values()].reduce((u,g)=>u+g,0);$.warn(`[palbase] webhook ${o}: ${l} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function Ne(o){let c=o.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?F.get(c[1]):void 0}async function vt(o,c,l,u){let g=c.pathname===Xe;if(o.method!==(g?"GET":"POST"))return T({status:405,code:"method_not_allowed",message:g?"The crons are listed with GET":"A cron is run with POST"},u);let p=g?new Uint8Array(0):await gt(o,Mi);try{await St({secret:l,signature:o.headers.get("palbase-signature"),body:p,now:e.now})}catch(q){if(q instanceof ot)return T({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${q.code}`},u);throw q}if(g){let q=[...h.values()].map(({declaration:K})=>({name:K.name,schedule:K.schedule,time_zone:K.timeZone,timeout:K.timeout,retry:K.retries}));return ue(200,{crons:q},u,{"cache-control":"no-store"})}let w=c.pathname.slice(Xe.length+1),_=h.get(w);if(!_)return T({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(w)}`},u);let R;try{R=JSON.parse(new TextDecoder().decode(p))}catch{return T({status:400,code:"bad_request",message:"A run is the JSON {cron, run_id, scheduled_at, attempt}"},u)}let{cron:O,run_id:P,scheduled_at:A,attempt:x}=R??{};if(O!==w||typeof P!="string"||P===""||typeof A!="string"||!Fs.test(A)||Number.isNaN(Date.parse(A))||!Number.isInteger(x)||x<1)return T({status:400,code:"bad_request",message:`A run of ${w} is the JSON {cron: "${w}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},u);let j=`${P}#${String(x)}`;if(N.has(j))return new Response(null,{status:204,headers:{"x-request-id":u}});if(H.has(j))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);H.add(j);let Q={env:G,environmentId:e.projectId??"",cron:w,runId:P,scheduledAt:new Date(A),attempt:x};try{await nt(e.database,e.database?ht:void 0,o.signal,`cron ${w}`,async()=>{if(await _.run(Q),o.signal.aborted)throw new Error(`the platform gave up on this attempt of ${w} before it ended`)})}catch(q){return o.signal.aborted||$.error(`[palbase] cron ${w} failed (run ${P}, attempt ${String(x)})`,{error:q}),T({status:500,code:"cron_failed",message:`The cron ${w} failed; the platform tries it again`},u)}finally{H.delete(j)}return N.add(j),N.size>tt&&N.delete(N.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}let Bn=async({task:o,id:c,attempt:l,payload:u,createdAt:g},p)=>{let w=y.get(o);if(!w)return{status:404,message:`this version has no task ${JSON.stringify(o)}`};let _=le(u??null),R=w.declaration.payload;if(R){let P=await R["~standard"].validate(_);if(P.issues){let A=P.issues.slice(0,5).map(x=>`${(x.path??[]).map(j=>String(typeof j=="object"&&j!==null&&"key"in j?j.key:j)).join(".")||"(payload)"}: ${x.message}`).join("; ");return $.error(`[palbase] task ${o} ${c}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${A}`),{status:422,message:`what it carries is not what @Task "${o}" takes: ${A}`}}_=P.value}let O={env:G,environmentId:e.projectId??"",task:o,id:c,attempt:l,createdAt:g};try{await nt(e.database,e.database?ht:void 0,p,`task ${o}`,async()=>{if(await w.run(_,O),p.aborted)throw new Error(`the platform gave up on this attempt of ${o} before it ended`)})}catch(P){return P instanceof Pt?($.error(`[palbase] task ${o} ${c} can never be done: ${P.message}`),{status:422,message:P.message}):(p.aborted||$.error(`[palbase] task ${o} failed (task ${c}, attempt ${String(l)})`,{error:P}),{status:500,message:`the task ${o} failed; it is tried again`})}return{status:204}};async function sa(o,c,l,u){let g=c.pathname===et;if(o.method!==(g?"GET":"POST"))return T({status:405,code:"method_not_allowed",message:g?"The task types are listed with GET":"A task is run with POST"},u);let p=g?new Uint8Array(0):await gt(o,ji);try{await St({secret:l,signature:o.headers.get("palbase-signature"),body:p,now:e.now})}catch(q){if(q instanceof ot)return T({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${q.code}`},u);throw q}if(g){let q=[...y.values()].map(({declaration:K})=>({name:K.name,timeout:K.timeout,retry:K.retries,concurrency:K.concurrency}));return ue(200,{tasks:q},u,{"cache-control":"no-store"})}let w=c.pathname.slice(et.length+1),_;try{_=JSON.parse(new TextDecoder().decode(p))}catch{return T({status:400,code:"bad_request",message:"A task is the JSON {task, id, attempt, payload, created_at}"},u)}let{task:R,id:O,attempt:P,payload:A,created_at:x}=_??{};if(R!==w||typeof O!="string"||O===""||typeof x!="string"||!Fs.test(x)||Number.isNaN(Date.parse(x))||!Number.isInteger(P)||P<1)return T({status:400,code:"bad_request",message:`A task of ${w} is the JSON {task: "${w}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},u);let j=`task:${O}#${String(P)}`;if(N.has(j))return new Response(null,{status:204,headers:{"x-request-id":u}});if(H.has(j))return T({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);H.add(j);let Q;try{Q=await Bn({task:w,id:O,attempt:P,payload:A,createdAt:new Date(x)},o.signal)}finally{H.delete(j)}return Q.status===404?T({status:404,code:"task_not_found",message:Q.message??""},u):Q.status===422?T({status:422,code:"task_failure",message:Q.message??""},u):Q.status>=300?T({status:Q.status,code:"task_failed",message:Q.message??""},u):(N.add(j),N.size>tt&&N.delete(N.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}}))}async function Ue(o,c,l,u){if(o.method!=="POST")return T({status:405,code:"method_not_allowed",message:`${u} is POSTed`},l);let g;try{or({signature:o.headers.get("palbase-signature"),now:e.now}),g=await gt(o,1048576),await St({secret:c,signature:o.headers.get("palbase-signature"),body:g,now:e.now})}catch(w){if(w instanceof ot)return T({status:401,code:"invalid_signature",message:`${u} is the platform's to call: ${w.code}`},l);throw w}let p;try{p=JSON.parse(new TextDecoder().decode(g))}catch{return T({status:400,code:"bad_request",message:`${u} is JSON`},l)}return typeof p!="object"||p===null||!Object.hasOwn(p,"call")||p.call!==new URL(o.url).pathname?T({status:401,code:"invalid_signature",message:`${u} is the platform's to call: signed_for_another_call`},l):{body:p}}async function aa(o,c,l,u,g){let p=await Ue(c,l,u,`An upload's ${o}`);if(p instanceof Response)return p;let w=Dr(o,p.body);if(typeof w=="string")return T({status:400,code:"bad_request",message:`An upload's ${o}: ${w}`},u);if(o==="complete"){if(k.has(w.uploadId))return T({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},u);k.add(w.uploadId),k.size>tt&&k.delete(k.values().next().value)}let _=jn(n,w.method,w.route);if(!_||"malformed"in _||!_.route.meta.upload)return T({status:404,code:"not_found",message:`No upload route for ${w.method} ${w.route}`},u);let{route:R,params:O}=_,P=_.route.meta.upload,A=Ki(w.user);if(A&&Zn(g,A.id),r.get(R).required&&!A)throw new ee(401,"unauthorized","This route needs a signed-in user");if(o==="authorize"){let Q=U(R);if(Q!==!1){let K=L.takeEach(`${R.id}\0${Or(w.user,w.client)}`,Q);if(K!==void 0)throw new ee(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:K},K)}let q=Mr(P.pathTemplate,{userId:A?.id??null,uploadId:w.uploadId,filename:w.filename});if("problem"in q)throw new ee(400,"bad_request",q.problem);return await Qe(e.database,jt(w.user),c.signal,R.id,async()=>{let K={request:c,query:new URLSearchParams(w.query),params:O,user:A,body:w.body===void 0||w.body===null?{}:le(w.body),requestId:u};await Wn(R,K);for(let ve of R.params)(ve.kind==="query"||ve.kind==="body"&&w.body!==void 0)&&await Qs(ve,K)}),ue(200,{bucket:P.bucket,path:q.path},u)}g.endpoint=R.id.slice(R.id.indexOf(" ")+1);let x=new URLSearchParams(w.query),j=w.body===null||w.body===void 0?{}:le(w.body);return Nn(await Qt(R,{request:c,query:x,params:O,user:A,body:j,requestId:u,uploadedObject:le(w.uploadedObject)},jt(w.user)),void 0,u)}async function oa(o,c,l,u){let g=c.pathname.slice(Mt.length+1),p=g.endsWith("/undo"),w=p?g.slice(0,-5):g,_=await Ue(o,l,u,"A test user template");if(_ instanceof Response)return _;let R=b.get(w);if(!R||p&&!R.undo)return T({status:404,code:"template_not_found",message:R?`@TestUserTemplate "${w}" has no undo: the user's deletion cleans up after it`:`This version has no test user template ${JSON.stringify(w)}`},u);let O=Er(w,_.body);if(typeof O=="string")return T({status:400,code:"bad_request",message:`A test user template's call: ${O}`},u);let P=le(O.user),A;try{A=await Sr(e.server,P.id)}catch(q){return $.error(`[palbase] test user template ${w}: auth could not say whether ${P.id} is a test user; nothing was written`,{error:q}),T({status:503,code:"auth_unavailable",message:"Auth could not say whether the user is a test user: the template did not run",retryAfter:5},u)}if(!A)return $.warn(`[palbase] test user template ${w}${p?" undo":""}: auth does not say ${P.id} is a test user \u2014 nothing was run`),T({status:403,code:"not_a_test_user",message:"Auth does not say this user is a test user: a template writes for test users alone"},u);let x=`${P.id}\0${w}`;if(J.has(x))return T({status:409,code:"in_progress",message:`The template ${w} is being written for this user`,retryAfter:5},u);if(!p&&S.has(x))return ue(200,{rows:S.get(x)},u);J.add(x);let j={env:G,environmentId:e.projectId??"",template:w},Q=`test user template ${w}${p?" undo":""}`;try{let q={};return await nt(e.database,e.database?ht:void 0,o.signal,Q,async()=>{if(p?await R.undo(P,j):(await R.seed(P,j),q=await Ar(re.getStore()?.database)),o.signal.aborted)throw new Error(`the platform gave up on ${Q} before it ended`)}),p?(S.delete(x),new Response(null,{status:204,headers:{"x-request-id":u}})):(S.set(x,q),S.size>tt&&S.delete(S.keys().next().value),ue(200,{rows:q},u))}catch(q){o.signal.aborted||$.error(`[palbase] ${Q} failed for ${P.id}: nothing of it was kept`,{error:q});let K=q instanceof Error&&q.message!==""?`: ${q.message.replace(/\s+/g," ").slice(0,300)}`:"";return T({status:500,code:p?"undo_failed":"template_failed",message:`${p?"The undo of":"The template"} ${w} failed${K}; nothing of it was kept`},u)}finally{J.delete(x)}}function Kn(o,c,l,u){let g=o?{sub:o.id,role:"authenticated"}:null;return re.run({requestId:re.getStore()?.requestId??"",...o?{userId:o.id}:{}},()=>Qe(e.database,g,l,c,async()=>{let p=await u();if(l.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return p}))}let Jn=(o,c)=>new Response(o,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function ia(o,c,l){let u=await Ue(o,c,l,"A tool call");if(u instanceof Response)return u;let g=u.body,p=g.tool;if(typeof p!="string"||p==="")return T({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},l);let w=z.tools.get(p);if(!w)return T({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(p.slice(0,64))}`},l);let _=g.call_id,R=ys(g.context);if(typeof _!="string"||_===""||_.length>256||typeof R=="string")return T({status:400,code:"bad_request",message:`A call of ${p} is {tool, call_id, input, context}${typeof R=="string"?`: ${R}`:""}`},l);let O=ea("sha256").update(JSON.stringify(g)).digest("hex"),P=me.answered(_);if(P!==void 0)return P.digest!==O?T({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},l):Jn(P.answer,l);if(me.isRunning(_))return T({status:409,code:"in_progress",message:"This call is running",retryAfter:2},l);me.start(_);let A;try{let x=await Kn(R.user,`ai.tool ${p}`,o.signal,()=>w.call(le(g.input??{}),{...R,callId:_,signal:o.signal,inject:oe(`ai.tool ${p}`)}));A="deferred"in x?JSON.stringify({deferred:!0,...x.expires_in_seconds!==void 0?{expires_in_seconds:x.expires_in_seconds}:{}}):JSON.stringify({output:x.output,is_error:x.is_error});let j=new TextEncoder().encode(A).byteLength;j>Ze&&($.error(`[palbase] ai.tool ${p} answered ${j} bytes (call ${_}): a machine's answer is ${Ze} at most; the agent is told it failed`),A=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${Ze/(1<<20)} MiB it may be`}],is_error:!0}))}catch(x){if(o.signal.aborted)return me.end(_,void 0),T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);$.error(`[palbase] ai.tool ${p} failed (call ${_}, chat ${R.chatId}); the agent is told`,{error:x}),A=JSON.stringify({output:[{type:"text",text:zi(x)}],is_error:!0})}return me.end(_,{digest:O,answer:A}),Jn(A,l)}async function da(o,c,l){let u=await Ue(o,c,l,"An agent's turn");if(u instanceof Response)return u;let g=ws(u.body);if(typeof g=="string"||g.agent==="")return T({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata, message}${typeof g=="string"?`: ${g}`:": agent names it"}`},l);let p=g.agent,w=z.agents.get(p);if(!w)return T({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(p.slice(0,64))}`},l);let _;try{_=await Kn(g.user,`ai.agent ${p}`,o.signal,()=>w.resolve({...g,signal:o.signal,inject:oe(`ai.agent ${p}`)}))}catch(P){if(o.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let A=Zt(P,`ai.agent ${p}`);return A?T(A,l):($.error(`[palbase] ai.agent ${p} failed for chat ${g.chatId}; the turn is not started`,{error:P}),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},l))}let R=_.tools.find(P=>z.tools.get(P.name)!==P);if(R)return $.error(`[palbase] ai.agent ${p} handed out ai.tool ${JSON.stringify(R.name)}, which this app did not declare when it was made \u2014 make each ai.tool once, at a module's top level, and hand that one out`),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},l);let O=JSON.stringify(_.definition);return new TextEncoder().encode(O).byteLength>Ze?($.error(`[palbase] ai.agent ${p}'s definition is larger than the ${Ze} bytes a machine's answer may be`),T({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},l)):new Response(O,{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function ca(o,c,l){let u=await Ue(o,c,l,"A repository's token");if(u instanceof Response)return u;let g=u.body;if(typeof g.repo!="string"||g.repo===""||typeof g.repository!="string"||typeof g.call_id!="string"||g.call_id===""||g.call_id.length>256)return T({status:400,code:"bad_request",message:"A repository's token is asked as {call_id, repo, repository}"},l);if(!Se.take(g.call_id))return T({status:409,code:"call_id_reused",message:"This token ask was answered already"},l);let p=z.repos.get(g.repo),w=p?R=>p.token(R):z.repoTokens;if(!w)return T({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(g.repo.slice(0,64))}, and no ai.repoTokens`},l);let _;try{_=await nt(e.database,e.database?ht:void 0,o.signal,`ai.repo ${g.repo}`,async()=>w({repo:g.repo,repository:g.repository,signal:o.signal,inject:oe(p?`ai.repo ${g.repo}`:`ai.repoTokens for ${g.repo}`)}))}catch(R){if(o.signal.aborted)return T({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let O=Zt(R,`ai.repo ${g.repo}`);return O?T(O,l):($.error(`[palbase] ai.repo ${g.repo} gave no token; the workspace's clone or push is refused`,{error:R}),T({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},l))}return!p&&_==null?T({status:404,code:"repo_not_found",message:`ai.repoTokens gives no token for ${JSON.stringify(g.repo.slice(0,64))}`},l):typeof _!="string"||_.trim()===""?($.error(`[palbase] ai.repo ${g.repo}'s token function answered no token`),T({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},l)):new Response(JSON.stringify({token:_}),{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function ua(o,c,l,u){let g=await Ue(c,l,u,`A gateway's ${o}`);if(g instanceof Response)return g;let p=await W.serve(o,g.body,c.signal);return"code"in p?T({status:p.status,code:p.code,message:p.message,retryAfter:p.retryAfter},u):"body"in p?ue(200,p.body,u):new Response(null,{status:204,headers:{"x-request-id":u}})}async function Wn(o,c){let l=[],u={params:Object.freeze({...c.params}),user:le(c.user),headers:o.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let g of o.params)g.kind==="resolve"&&(l[g.index]=await f.get(g).resolve(u,g.options));return l}async function Qt(o,c,l,u){let g=t.get(o.controller),p=await Qe(e.database,l,c.request.signal,o.id,async()=>{let w=await Wn(o,c);for(let R of o.params)R.kind!=="resolve"&&(w[R.index]=await Qs(R,c));u?.ran();let _=await g[o.fn](...w);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${o.id}'s upload before it was answered`);return u?u.record(Ks(Zs(_,c.requestId),re.getStore()?.usedLocales)):_});return u?p:Ks(Zs(p,c.requestId),re.getStore()?.usedLocales)}async function Vn(o,c){let l=o.headers.get("x-request-id")??"",u=Ji.test(l)?l:`req_${crypto.randomUUID()}`,g=performance.now(),p=new URL(o.url).pathname,w={endpoint:p},_=await la(o,c,u,w);return e.telemetry?.record({requestId:u,method:o.method,endpoint:w.endpoint,path:p,status:_.status,durationMs:performance.now()-g,userId:w.userId}),_}function Zn(o,c){o.userId=c;let l=re.getStore();l&&(l.userId=c)}async function la(o,c,l,u){let g=e.strings,p=g?{requestId:l,strings:g,locales:gr(o.headers.get("accept-language"),g.source),usedLocales:[]}:{requestId:l},w=await fa(p,o,c,l,u);return g&&Vt(w.headers,"Accept-Language"),w}async function fa(o,c,l,u,g){return re.run(o,async()=>{let p=new URL(c.url),w=`${c.method} ${p.pathname}`;try{if(p.pathname===Rn&&pe.size>0)return c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):e.webhookSecret?await kt(c,u):T({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},u);let _=Ne(p.pathname);if(_)return w=`webhook ${_.name}`,c.method!=="POST"?T({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):await Yt(c,p,_,u);if(e.platform&&(p.pathname===Xe||p.pathname.startsWith(`${Xe}/`)))return w=p.pathname===Xe?"crons":`cron ${p.pathname.slice(Xe.length+1)}`,await vt(c,p,e.platform.secret,u);if(e.platform&&(p.pathname===et||p.pathname.startsWith(`${et}/`)))return w=p.pathname===et?"tasks":`task ${p.pathname.slice(et.length+1)}`,await sa(c,p,e.platform.secret,u);if(e.platform&&(p.pathname===mn||p.pathname===xr)){let M=p.pathname===mn?"authorize":"complete";return w=`upload ${M}`,await aa(M,c,e.platform.secret,u,g)}if(e.platform&&p.pathname.startsWith(`${hn}/`)){let M=p.pathname.slice(hn.length+1);return w=`gateway ${M}`,await ua(M,c,e.platform.secret,u)}if(e.platform&&p.pathname===us)return w="ai tool call",await ia(c,e.platform.secret,u);if(e.platform&&p.pathname===ls)return w="ai agent's turn",await da(c,e.platform.secret,u);if(e.platform&&p.pathname===fs)return w="ai repository's token",await ca(c,e.platform.secret,u);if(e.platform&&p.pathname.startsWith(`${Mt}/`))return w=`test user template ${p.pathname.slice(Mt.length+1)}`,await oa(c,p,e.platform.secret,u);if(rd(p.pathname))return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},u);let R=jn(n,c.method,p.pathname);if(R&&"malformed"in R)return T({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},u);if(!R)return T({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},u);let{route:O,params:P}=R;if(w=O.id,g.endpoint=O.id.slice(O.id.indexOf(" ")+1),O.meta.upload)throw new ee(400,"upload_required",`${O.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let A=r.get(O),x=null,j=null,Q=c.headers.get("authorization")??"",q=/^(bearer|dpop)\s+(\S+)$/i.exec(Q),K=q?.[2],ve=q?.[1].toLowerCase()==="dpop";if(K)try{let M=!ve&&e.tokens&&!Wi.test(K)&&e.tokens.accepts(K)?e.tokens:void 0,ye=M?await Z.ask(K,Jt(c.headers,l.remoteAddress),()=>Qe(e.database,null,c.signal,"token",()=>M.resolve(K))):await e.verifier.verify(K,ve?{proof:c.headers.get("dpop"),method:c.method,url:dr(c.headers,p)}:void 0);x=Gi(ye),j=ye.claims}catch(M){if(!A.required&&(M instanceof At||M instanceof xt||M instanceof yt))x=null;else throw M instanceof yt?new ee(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:M.wait},M.wait):M instanceof At?new ee(401,"invalid_token","The access token is not valid",{reason:M.reason},void 0,Ii(M.reason)):M}else if(Q!==""&&A.required)throw new ee(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(x&&Zn(g,x.id),A.required&&!x)throw new ee(401,"unauthorized","This route needs a signed-in user");if(A.verifiedEmail&&!x?.emailVerified)throw new ee(403,"email_not_verified","This route needs a verified email address");if(x&&Vs(x.acr)<Vs(A.aal))throw new ee(401,"insufficient_user_authentication",`This route needs a sign-in at ${A.aal}: step up and call again`,Bs(A),void 0,Gs(A,ve));if(x&&A.maxAge!==null&&!Li(x.authTime,A.maxAge,Date.now()))throw new ee(401,"insufficient_user_authentication",`This route needs the user to have signed in or stepped up within the last ${A.maxAge} seconds: step up and call again`,Bs(A),void 0,Gs(A,ve));let Yn=U(O);if(Yn!==!1){let M=x?`u:${x.id}`:`a:${Jt(c.headers,l.remoteAddress)}`,ye=L.takeEach(`${O.id}\0${M}`,Yn);if(ye!==void 0)throw new ee(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:ye},ye)}let Re=c.method==="GET"||c.method==="HEAD"?void 0:await gt(c,Y),Xt,Qn=null;if(a&&s(O)){let M=await a.check(c,p,Re);if("unavailable"in M)throw new ee(503,"attest_unavailable","The device's attestation cannot be checked right now",void 0,1);if(!M.pass)throw new ee(401,"app_attest_required","This route is called by the app on a device that attests",{reason:M.reason,challenge:M.challenge},void 0,void 0,{[ge.challenge]:M.challenge});Xt=M.challenge,Qn=M.device??null}let Tt=Re===void 0?void 0:Fi(Re),en=p.searchParams,Oe=i.get(O),$t=c.headers.get(Et),at=Oe!==void 0||$t!==null?await d(O,P,$t,c.method):void 0;if(at&&Oe)try{if(Oe.body.length>0&&Tt!==void 0&&(Tt=await at.open(Tt,"/body",Oe.body)),Oe.query.length>0){let M=await at.open(Object.fromEntries(p.searchParams),"/query",Oe.query);en=new URLSearchParams(p.searchParams);for(let ye of Oe.query){let nr=sr(ye.slice(7)),_t=M[nr];_t!==void 0&&en.set(nr,typeof _t=="string"?_t:JSON.stringify(_t))}}}catch(M){throw Ys(M)}let Xn={request:c,query:en,params:P,user:x,body:Tt,raw:Re,requestId:u,attested:Qn},er=m&&Re!==void 0&&ft(O)?xs(c.method,c.headers):void 0;if(!m||er===void 0)return Js(await Nn(await Qt(O,Xn,j),at,u),Xt);let pa={role:Un(e.database.requests,j).role,uid:x?.id??`a:${Jt(c.headers,l.remoteAddress)}`},tr=!1,ma=$t!==null?{uri:`${p.pathname}${p.search}`,body:ed(new TextEncoder().encode(`${$t}
21
+ `),Re)}:{uri:`${p.pathname}${p.search}`,body:Re},ha=M=>async ye=>M(await Nn(ye,at,u));return Js(await m.serve({key:er,caller:pa,method:c.method,...ma},M=>Qt(O,Xn,j,{record:ha(M),ran:()=>{tr=!0}}),{requestId:u,refusal:M=>T(M,u),failure:M=>Ws(M,u,w,c.signal),ran:()=>tr}),Xt)}catch(_){return Ws(_,u,w,c.signal)}})}return{handle:st,routes:n.map(o=>o.id),contract:bt,start:()=>t.start(),stop:async()=>{W.close(),await a?.stop();for(let o of Ae.keys())xe(o);await t.shutdown(),await e.telemetry?.flush()}}}function Qi(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Xi(e){let t=new Set;for(let[n,r]of e)if(cn(n))for(let s of r){if(s.bucket===void 0)return;t.add(s.bucket)}return t.size===0?void 0:[...t].sort()}function Zs(e,t){if(e instanceof Response)return Hi(e,t);if(e==null)return new Response(null,{status:204,headers:{"x-request-id":t}});if(fr()===0)return ue(200,e,t);let{value:n,pointers:r}=pr(e);return ue(200,n,t,r.length>0?{[qn]:JSON.stringify(r)}:{})}var qn="x-palbase-answer-encrypted";async function Nn(e,t,n){let r=e.headers.get(qn);if(r===null)return e;if(!t)return await e.body?.cancel(),T({status:400,code:"encryption_required",message:`This route answers encrypted fields: the request names its key in ${Et}`,data:{field:Et}},n);let s=new Headers(e.headers);s.delete(qn),s.delete("content-length");let a=await t.seal(await e.json(),JSON.parse(r));return new Response(JSON.stringify(a),{status:e.status,statusText:e.statusText,headers:s})}function ed(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Ys(e){return e instanceof ar?new ee(e.status,e.code,e.message,e.data):e}function td(e){return`/${e.segments.map(t=>typeof t=="string"?t:"{}").join("/")}`}function nd(e,t){if(!(!lt(e)||e.status!==503||!Hn(e)))return $.warn(`[palbase] webhook ${t}: the database did not answer (${e.error})`,{error:e}),{status:503,code:e.error,message:e.errorDescription,data:e.data,retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))}}function rd(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return He.has(decodeURIComponent(t))}catch{return He.has(t)}}var sd="GET, POST, PUT, PATCH, DELETE, QUERY",ad=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function od(e){return ad.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function id(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!od(r))throw new TypeError(`cors origin ${JSON.stringify(r)} is https://host[:port] (http only for localhost), with no path`)}let t=e.origins==="*"?null:new Set(e.origins),n=String(e.maxAge??600);return{allows:r=>t===null||t.has(r),headers:r=>({"access-control-allow-origin":t===null?"*":r,"access-control-expose-headers":"idempotent-replayed, retry-after, x-request-id",vary:"Origin"}),preflight:(r,s)=>({"access-control-allow-origin":t===null?"*":r,"access-control-allow-methods":sd,"access-control-allow-headers":s&&/^[A-Za-z0-9-]+(\s*,\s*[A-Za-z0-9-]+)*$/.test(s)?s:"authorization, content-type","access-control-max-age":n,vary:"Origin"})}}async function Qs(e,t){switch(e.kind){case"body":return Dn(e.schema,t.body??{},"Request body");case"query":return Dn(e.schema,le(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),le(n),e.schema?Dn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return le(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"attestedDevice":return t.attested??null;case"client":{let n=t.request.headers;return le({sdkVersion:n.get("x-palbase-sdk-version"),appVersion:n.get("x-palbase-client-version"),platform:n.get("x-platform"),osVersion:n.get("x-os-version")})}}}var Fn=720*3600;function zn(e){return e instanceof ie&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function na(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),Fn)}function ra(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Gn=class{filling=new Map;async get(t){try{let n=await we.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!zn(n))throw n;return $.warn("cache: a read could not reach the cache; it is a miss",{key:t,status:n.status}),null}}async set(t,n,r){try{await we.cache.putCacheEntry({query:{key:t},body:{value:ra(n),ttl:na(r)}})}catch(s){if(!zn(s))throw s;$.warn("cache: a write could not reach the cache; it is let go",{key:t,status:s.status})}}async del(t){await we.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await we.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,n,r){let s=this.filling.get(t);if(s)return s;let a=(async()=>{try{let i;try{i=(await we.cache.getCacheEntry({query:{key:t}})).data}catch(f){if(!zn(f))throw f;$.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:f.status})}if(i?.found)return i.value??null;let d=await r();return await this.set(t,d,n),d}finally{this.filling.delete(t)}})();return this.filling.set(t,a),a}},xu=Rt("Cache",new Gn);function Ru(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=h=>{let y=r.get(h);if(y&&y.expiresAt<=n()){r.delete(h);return}return y},i=()=>{let h=n();for(let[b,S]of r)S.expiresAt<=h&&r.delete(b);if(r.size<t)return;let y=[...r.entries()].sort((b,S)=>b[1].expiresAt-S[1].expiresAt);for(let[b]of y.slice(0,Math.ceil(y.length/4)))r.delete(b)},d=async(h,y,b)=>{r.size>=t&&!r.has(h)&&i(),r.set(h,{value:ra(y),expiresAt:n()+(na(b)??Fn)*1e3})};return{get:async h=>{let y=a(h);return y?structuredClone(y.value):null},set:d,async del(h){r.delete(h)},async incr(h){let y=a(h),b=(typeof y?.value=="number"&&Number.isInteger(y.value)?y.value:0)+1;return r.set(h,{value:b,expiresAt:y?.expiresAt??n()+Fn*1e3}),b},getOrSet(h,y,b){let S=a(h);if(S)return Promise.resolve(structuredClone(S.value));let J=s.get(h);if(J)return J;let N=(async()=>{try{let H=await b();return await d(h,H,y),H}finally{s.delete(h)}})();return s.set(h,N),N}}}export{on as a,Pe as b,qe as c,ld as d,fd as e,pd as f,md as g,hd as h,gd as i,yd as j,wd as k,bd as l,kd as m,vd as n,Td as o,$d as p,_d as q,Ed as r,Sd as s,Ad as t,xd as u,Rd as v,Od as w,Pd as x,Cd as y,Md as z,jd as A,D as B,Dd as C,Nd as D,Pt as E,Hd as F,zd as G,Kd as H,Yd as I,Qd as J,Na as K,Ur as L,sc as M,ac as N,oc as O,ic as P,dc as Q,cc as R,uc as S,mc as T,V as U,as as V,os as W,is as X,Eo as Y,Tc as Z,Ec as _,Sc as $,Ac as aa,xc as ba,Rc as ca,Oc as da,Pc as ea,Cc as fa,Hc as ga,Oi as ha,_u as ia,od as ja,Fn as ka,xu as la,Ru as ma};