palbase 0.21.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +11 -11
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{6B2JVMVC.js → 2TXIGYOJ.js} +1 -1
- package/dist/chunks/{BC7DKAEV.js → 4HAHFRWH.js} +2 -2
- package/dist/chunks/5Q3GX7V7.js +22 -0
- package/dist/chunks/{LHLXKWXT.js → ASHJUFAR.js} +2 -2
- package/dist/chunks/{UTZFJM2O.js → BUZEU3KO.js} +2 -2
- package/dist/chunks/{LHC3VBGV.js → CNM6KHAV.js} +1 -1
- package/dist/chunks/{3MPGMDIO.js → CYQ5IWPO.js} +1 -1
- package/dist/chunks/{Y3KNVE2U.js → EPLCUBM7.js} +1 -1
- package/dist/chunks/{XZY2DTL7.js → GRMAYURX.js} +2 -2
- package/dist/chunks/{5BNYK6GP.js → GUJW2U4D.js} +1 -1
- package/dist/chunks/GXOAVCC5.js +21 -0
- package/dist/chunks/{RTL4OAKC.js → IPHVAOYL.js} +1 -1
- package/dist/chunks/{BQTZYHJN.js → JEBQEIT2.js} +2 -2
- package/dist/chunks/{BYKIJBPE.js → KSRQ5B2V.js} +2 -2
- package/dist/chunks/{PI2NU4TV.js → MQJN2IGB.js} +2 -2
- package/dist/chunks/{PKYERPHS.js → QRRNK56K.js} +2 -2
- package/dist/chunks/{YALT2FTV.js → RRS3QIHN.js} +2 -2
- package/dist/chunks/{23M37HPW.js → RZE7ZGC5.js} +2 -2
- package/dist/chunks/{TUJQKUDT.js → SI3QKQTV.js} +2 -2
- package/dist/chunks/U7YF4HAG.js +18 -0
- package/dist/chunks/{7LCTRRHG.js → X2IT755X.js} +1 -1
- package/dist/chunks/{SIIBIKCD.js → YCVPM3S4.js} +2 -2
- package/dist/chunks/{QZMFPTXQ.js → ZWM2JBGV.js} +2 -2
- package/dist/cli.js +130 -126
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/chats.d.ts +20 -1
- package/types/ai/src/index.d.ts +2 -2
- package/types/ai/src/tools.d.ts +20 -0
- package/types/backend/src/attest.d.ts +18 -2
- package/types/backend/src/bootstrap.d.ts +2 -4
- package/types/backend/src/database.d.ts +12 -2
- package/types/backend/src/engine.d.ts +10 -3
- package/types/backend/src/index.d.ts +1 -1
- package/types/internal/src/modules/ai.d.ts +46 -2
- package/types/web/src/notify.d.ts +44 -2
- package/dist/chunks/DEMLN2MO.js +0 -18
- package/dist/chunks/PJLACUYP.js +0 -22
- package/dist/chunks/TACI6JAQ.js +0 -21
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as u,b as d}from"./
|
|
1
|
+
/*! palbase 0.23.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u,b as d}from"./GRMAYURX.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project's account has no balance to pay for Palbase's models: top it up (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof d)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new d({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=u(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.23.0 — 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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.23.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.23.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var K="pbt1.",E="Palbase-Encryption";var z="x-palbase-encrypted",o=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},h=new TextEncoder,P=new TextDecoder("utf-8",{fatal:!0}),l=()=>{let e=globalThis.crypto?.subtle;if(!e)throw new Error("encrypted fields need WebCrypto (crypto.subtle): a secure context \u2014 https, or localhost");return e};function y(e){return new Uint8Array(new ArrayBuffer(e))}function f(...e){let t=y(e.reduce((r,i)=>r+i.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function d(e){return f(e)}function m(e,t){let n=y(t);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return n}function x(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new o("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),r=y(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}var S=f(h.encode("KEM"),m(32,2)),g=f(h.encode("HPKE"),m(32,2),m(1,2),m(1,2)),v=h.encode("HPKE-v1"),X=16,H=12,T=32,$=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function N(e,t){let n=await l().importKey("raw",e.length===0?y(32):d(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await l().sign("HMAC",n,d(t)))}async function k(e,t,n,r){return N(t,f(v,e,h.encode(n),r))}async function U(e,t,n,r,i){let a=f(m(i,2),v,e,h.encode(n),r),s=y(i),c=y(0);for(let u=1,p=0;p<i;u++)c=await N(t,f(c,a,Uint8Array.of(u))),s.set(c.subarray(0,Math.min(c.length,i-p)),p),p+=c.length;return s}async function j(e){if(e.length!==32)throw new o("malformed","an X25519 private key is 32 bytes");return l().importKey("pkcs8",f($,e),{name:"X25519"},!1,["deriveBits"])}async function C(e){if(e.length!==32)throw new o("malformed","an X25519 public key is 32 bytes");return l().importKey("raw",d(e),{name:"X25519"},!1,[])}async function O(e,t){return new Uint8Array(await l().deriveBits({name:"X25519",public:t},e,256))}async function R(e,t,n){let r=await k(S,y(0),"eae_prk",e);return U(S,r,"shared_secret",f(t,n),T)}async function _(e,t){let n=await k(g,y(0),"psk_id_hash",y(0)),r=await k(g,y(0),"info_hash",t),i=f(Uint8Array.of(0),n,r),a=await k(g,e,"secret",y(0));return{key:await U(g,a,"key",i,X),nonce:await U(g,a,"base_nonce",i,H)}}async function b(e,t,n,r,i){let a=await l().importKey("raw",d(t),"AES-GCM",!1,[e]);return new Uint8Array(await l()[e]({name:"AES-GCM",iv:d(n),additionalData:d(r)},a,d(i)))}async function V(e,t,n,r=y(0),i){let a,s;if(i)a=await j(i.privateKey),s=d(i.publicKey);else{let B=await l().generateKey({name:"X25519"},!0,["deriveBits"]);a=B.privateKey,s=new Uint8Array(await l().exportKey("raw",B.publicKey))}let c=await R(await O(a,await C(e)),s,e),{key:u,nonce:p}=await _(c,t);return{enc:s,ct:await b("encrypt",u,p,r,n)}}async function q(e,t,n,r,i,a=y(0)){if(n.length!==32)throw new o("malformed","an encapsulated X25519 key is 32 bytes");try{let s=await R(await O(await j(e),await C(n)),n,t),{key:c,nonce:u}=await _(s,r);return await b("decrypt",c,u,a,i)}catch{throw new o("unopenable","the request's key does not open with the project's key it names")}}async function Z(e){let t=await l().importKey("pkcs8",f($,e),{name:"X25519"},!0,["deriveBits"]),n=await l().exportKey("jwk",t);return w(n.x)}function Q(e,t,n,r=[]){if(r.some(i=>i.includes("\0")))throw new o("malformed","a path's value holds no NUL");return h.encode(["palbase-encryption","1",e,t.toUpperCase(),L(n),...r].join("\0"))}function L(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function Y(e,t,n,r={}){let i=r.key?d(r.key):crypto.getRandomValues(y(32)),{enc:a,ct:s}=await V(t,n,i,y(0),r.ephemeral);return{kid:e,key:i,header:`1.${e}.${x(a)}.${x(s)}`}}function J(e){let t=e.trim().split(".");if(t.length!==4||t[0]!=="1"||!/^t[1-9][0-9]{0,5}$/.test(t[1]))throw new o("malformed",`${E} is 1.<key id>.<enc>.<ct>`);let n=w(t[2]),r=w(t[3]);if(n.length!==32||r.length!==48)throw new o("malformed",`${E} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:r}}async function ee(e,t,n,r){let{enc:i,ct:a}=J(e),s=await q(t,n,i,r,a);if(s.length!==32)throw new o("unopenable","the request's key is not 32 bytes");return s}function I(e){return h.encode(`pbt1\0${e}`)}async function te(e,t,n,r){let i=r?d(r):crypto.getRandomValues(y(12)),a=JSON.stringify(n);if(a===void 0)throw new o("malformed",`${t}: an encrypted field holds a JSON value`);let s=await b("encrypt",e,i,I(t),h.encode(a));return K+x(f(i,s))}function F(e){return typeof e=="string"&&e.startsWith(K)}async function ne(e,t,n){if(!F(n))throw new o("unopenable",`${t} is not an encrypted field`);let r;try{r=w(n.slice(K.length))}catch{throw new o("unopenable",`${t} is not an encrypted field`)}if(r.length<28)throw new o("unopenable",`${t} is too short to be an encrypted field`);let i;try{i=await b("decrypt",e,r.subarray(0,12),I(t),r.subarray(12))}catch{throw new o("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(P.decode(i))}catch{throw new o("unopenable",`${t} opens to no JSON value`)}}function D(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function G(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var M=Symbol("items");function W(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?M:G(n))}async function re(e,t,n,r){let i=e;for(let a of n){let s=W(a,t);s!==void 0&&(i=await A(i,s,t,r))}return i}async function A(e,t,n,r){if(t.length===0)return e===void 0?void 0:r(n,e);let[i,...a]=t;if(i===M){if(!Array.isArray(e))return e;let c=[];for(let[u,p]of e.entries())c.push(await A(p,a,`${n}/${u}`,r));return c}if(Array.isArray(e)){if(!/^(0|[1-9][0-9]*)$/.test(i)||Number(i)>=e.length)return e;let c=[...e];return c[Number(i)]=await A(c[Number(i)],a,`${n}/${i}`,r),c}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,i))return e;let s={...e};return s[i]=await A(s[i],a,`${n}/${D(i)}`,r),s}function ie(){return x(crypto.getRandomValues(y(16)))}async function se(e,t,n,r){let i,a=!1;try{i=w(e.payload);let u=await l().importKey("raw",w(t),{name:"Ed25519"},!1,["verify"]);a=await l().verify({name:"Ed25519"},u,w(e.signature),i)}catch{throw new o("unverified","the project's key list does not verify")}if(!a)throw new o("unverified","the project's key list is not signed with the project's key");let s;try{s=JSON.parse(P.decode(i))}catch{throw new o("unverified","the project's key list is no JSON")}if(s.v!==1||s.project!==n||typeof s.issued_at!="string"||!Array.isArray(s.keys)||s.keys.length===0)throw new o("unverified","the key list is not this project's, or holds no key");if(s.nonce!==r)throw new o("unverified","the key list was not asked for just now: its nonce is not the one sent");let c=s.keys.map(u=>{if(typeof u.kid!="string"||!/^t[1-9][0-9]{0,5}$/.test(u.kid)||typeof u.key!="string")throw new o("unverified","a key of the list is malformed");let p=w(u.key);if(p.length!==32)throw new o("unverified","a key of the list is not an X25519 public key");return{kid:u.kid,key:p}});return{project:s.project,issuedAt:s.issued_at,keys:c}}export{E as a,z as b,o as c,w as d,Z as e,Q as f,Y as g,J as h,ee as i,te as j,F as k,ne as l,D as m,G as n,re as o,ie as p,se as q};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as g,b}from"./
|
|
1
|
+
/*! palbase 0.23.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,b}from"./CYQ5IWPO.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.23.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/*! palbase 0.23.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as pr,d as mr,e as rn,f as hr,g as gr}from"./SI3QKQTV.js";import{a as Pt,c as re,d as lr,e as fr,f as we,h as _,i as yr}from"./ZWM2JBGV.js";import{a as or,e as dt,g as xt,h as ir,i as dr,j as Rt,k as Ot,n as cr,t as ur}from"./4HAHFRWH.js";import{a as At,b as sr,n as ar}from"./EPLCUBM7.js";import{b as de}from"./GRMAYURX.js";import"reflect-metadata";var sn=[{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}],wr="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)",Ct=/^\d+$/;function ya(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Ct.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let f=t,h=n;if(o!=="*")if(o.includes("-")){let y=o.indexOf("-"),k=o.slice(0,y),T=o.slice(y+1);if(!Ct.test(k)||!Ct.test(T)||Number(k)<t||Number(T)>n||Number(k)>Number(T))return;f=Number(k),h=Number(T)}else{if(!Ct.test(o)||Number(o)<t||Number(o)>n)return;f=Number(o),h=a===-1?f:n}for(let y=f;y<=h;y+=d)r.add(y)}return r}function br(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${wr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=ya(t[h],sn[h].lo,sn[h].hi);if(!y)return`${wr}; its ${sn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=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()),k=a.has(f.getUTCDay());if(o||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var He=Symbol.for("palbase.backend.controller"),qe=Symbol.for("palbase.backend.routes"),on=Symbol.for("palbase.backend.params"),dn=Symbol.for("palbase.backend.injectable"),cn=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),ze=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ce(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var an=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[an]instanceof Set||(e[an]=new Set),e[an]}var Ge=new Set(["webhooks","_palbase"]);function md(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ce(n,He,()=>({basePath:e,options:t})),se().add(n)}}function Fe(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`);ce(r.constructor,qe,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var hd=Fe("GET"),gd=Fe("POST"),yd=Fe("PUT"),wd=Fe("PATCH"),bd=Fe("DELETE"),kd=Fe("QUERY");function ue(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ce(n.constructor,on,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function un(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 vd=e=>ue("body",{schema:un("Body",e)}),Td=e=>ue("query",{schema:un("QueryParams",e)}),$d=e=>ue("headers",e===void 0?{}:{schema:un("Headers",e)}),_d=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},Ed=()=>ue("user"),Sd=()=>ue("optionalUser"),Ad=()=>ue("req"),xd=()=>ue("requestId"),Rd=()=>ue("requestId"),Od=()=>ue("client"),Pd=()=>ue("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return ue("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{ce(e,dn,()=>!0),se().add(e)}}function jd(e){return t=>{ce(t,cn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Tr=/^[a-z]+(\.[a-z_]+)+$/,wa=/^[a-z][a-z0-9-]{1,62}$/,ln=e=>e.startsWith("file.");function Dd(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"||!wa.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(!ln(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`);ce(r.constructor,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var fn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ba=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function kr(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(!ba.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 Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.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=br(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||kr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${kr(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 vr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ka=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(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(!ka.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&&!vr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${vr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&va(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Ce)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ce(t,ze,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function va(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 Ld(){return[...se()].filter(e=>D(e,He)!==void 0)}function Id(e){return(D(e,qe)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Mt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.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 hn;function _r(e){hn=e}function pn(){if(!hn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return hn}var Ta=720*3600;function $a(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ta))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 Bd=Pt("Tasks",{async enqueue(e,t,n={}){return $a(n),pn().enqueue(_a(e),t===void 0?null:t,n)},async cancel(e,t={}){return pn().cancel(e,t.machine)},async get(e,t={}){return pn().get(e,t.machine)}}),mn=(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 Er(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 mn(a.data,a.status===200)},async cancel(n,r){return mn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return mn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ea=1e4,Sa=36e5,$r=24*36e5,jt=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 de({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 de({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 de({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<$r))return this.view(f,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new de({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 de({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ea*2**Math.min(t.attempt-1,16),Sa),_.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>=$r&&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 Dt="/_palbase/test-user-templates",Aa=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Aa.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 Sr(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 Ar(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof de&&n.status===404)return!1;throw n}}var xa="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 xr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,xa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var gn="/_palbase/storage/upload/authorize",Rr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Be(e){if(!Ra(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 Or(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Pr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Nt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Oa=/^[a-z][a-z0-9-]{1,62}$/,Cr=1024,Pa=new Set(["userId","uploadId","filename"]);function ec(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(!Oa.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=Ca(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,f)=>{if(typeof d!="string"||f===void 0||typeof f.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ce(o.constructor,qe,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function tc(){return ue("uploadedObject")}function Ca(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Pa.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(!Mr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Mr(e){if(e===""||new TextEncoder().encode(e).byteLength>Cr)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 Ma(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ja(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ja(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 jr(e,t){let n=Ma(e,t);return Mr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Cr} bytes)`}}function Dr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Nr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Be(t.user);if(!o)return"user is { id?, session?, role }";let d=Or(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let f=Da(t.uploadedObject);return f?f.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...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 Da(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:f,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||f!==void 0&&typeof f!="number"||h!==void 0&&typeof h!="string")&&!(!wn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...f!==void 0?{height:f}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Na}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),We=Symbol.for("palbase.backend.gatewayHooks"),Ur={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"]},Ua={"~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(Ur),output:()=>structuredClone(Ur)}}},Fr=Symbol.for("palbase.backend.gatewayRefusal"),Lr=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})}},La=e=>typeof e=="object"&&e!==null&&e[Fr]===!0&&typeof e.reason=="string",Ke=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ia=6e4,Ha=86400,Ir=604800,Hr=65536,$e=255,qa=["roles:","flags:","messaging:","debug:"],za=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(" ")),Je=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ga(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(Je(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 Br(e){if(typeof e!="string"||e==="")return"is a name";if(Je(e)>$e)return`is ${$e} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ga(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"&&Tn(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 o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||za.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let T=Br(y);if(T)throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" ${T}`);if(!bn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let f=ce(a,We,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ua}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ia,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 ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ce(a,Me,()=>h),se().add(a)}}function Fa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ha;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Ir)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Ir} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ba={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ba[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=ce(n.constructor,We,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Br(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=ce(s.constructor,We,$n),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 Ka(e){return D(e,Me)}function Ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Kr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Je(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Wa(e,t,n){let r=Tn(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))?Kr(e,t):Va(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Va(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 Za=1e4,Ya=1e3,Qa=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ye=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),qr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},zr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Jr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:S}of e){let m=Ka(b),$=a.get(m.name);if($!==void 0&&$!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let M=s.get(zr(m.pattern));if(M!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(zr(m.pattern),m.pattern);for(let[Z,Y]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof S[Y]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${Z} is ${Y}, which is no method of it`);let U={cls:b,instance:S,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,f=new Set,h=new vn(t.broadcast),y=b=>{let S=o.get(b);return S||(S=new AbortController,o.set(b,S)),S},k=(b,S)=>{S?.abort(),o.get(b)===S&&o.delete(b)},T=(b,S,m,$,M,U)=>{if(!Object.hasOwn(b.g.events,m)){_.warn(`[palbase] ${M}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){_.warn(`[palbase] ${M}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:S,event:m,payload:$??{},...U!==void 0?{conn_id:U}:{}},M)},F=async(b,S,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(S)};function N(b,S,m,$,M,U,Z){let Y=$?.signal??AbortSignal.abort(),L=`${b.cls.name} (${S})`;return{channel:S,params:Object.freeze({...m}),signal:Y,count:M,user:U,emit:(I,G)=>T(b,S,I,G,L,Z),pipe:I=>F(I,S,L),owner:{hold(I){re.exit(async()=>{try{await I(Y)}catch(G){Y.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(S,$)}}}function H(b){let{room:S,channel:m}=b;if(typeof S!="string"||typeof m!="string")return ye(400,"bad_request","A gateway's call names its pattern (room) and its channel");let $=n.get(S);return!$||!Ke($.g)?ye(404,"not_found",`This app serves no gateway "${S}"`):{entry:$,channel:m,params:Ja(S,m)}}let W=(b,S)=>ye(400,"bad_request",`"${S}" is not a channel of the gateway "${b}"`);async function z(b,S){let m=H(b);if("status"in m)return m;let{entry:$,channel:M,params:U}=m,Z={status:200,body:{subscribe:!1,publish:!1}};if(!U)return _.warn(`[palbase] ${$.cls.name}: realtime asked about "${M}", which is not a channel of the gateway "${$.g.pattern}"; the join is refused`),Z;let Y=Be(b.user),L=Y?.id;if(!L)return Z;if($.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}};if($.g.access==="owner")return U[Tn($.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}}:Z;let I=$.g.hooks.authorize;if(!I)return Z;let G,B;try{G=await t.run(Y,`${$.cls.name}.${I}`,S,async()=>$.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Xa(G)}catch(ne){if(t.isOutage(ne)||S?.aborted)throw ne;return _.error(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) failed; the join is refused`,{error:ne}),Z}return B==="malformed"?(_.warn(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) answered ${eo(G)}, which is no grant (true, { read, write } or null); the join is refused`),Z):{status:200,body:B}}async function ie(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=Be(b.user);if(!$?.id||typeof b.event!="string")return ye(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:kn(`gateway "${m.channel}" takes no message "${b.event}"`,Ut)}};let U=await M.schema["~standard"].validate(Na(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Gr(U.issues)}};let Z=y(m.channel),Y={...N(m.entry,m.channel,m.params,Z,0,{id:$.id}),payload:U.value},L=`${m.entry.cls.name}.${M.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run($,`${m.entry.cls.name}.${M.fn}`,S,async()=>m.entry.instance[M.fn](Y))}catch(B){if(t.isOutage(B))throw B;return La(B)?{status:200,body:{ok:!1,reason:kn(B.reason,Ut)}}:(S?.aborted||_.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(M.reply){let B=await M.reply["~standard"].validate(I);if(B.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Gr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Je(G)>Hr?(_.error(`[palbase] ${L} returned an ack of ${Je(G)} bytes, past ${Hr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function ge(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=b.event;if(typeof $!="string"||!Object.hasOwn(qr,$))return ye(400,"bad_request","A gateway's moment is first, join, leave or empty");let M=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(M===void 0)return ye(400,"bad_request","A gateway's moment says its count of members");let U=$==="join"||$==="leave",Z=U?Be(b.user):void 0,Y=U?b.connId:void 0;if(U&&(!Z?.id||typeof Y!="string"||Y===""))return ye(400,"bad_request",`A ${$} names its member: user and connId`);let L=`${$}\0${m.channel}\0${typeof Y=="string"?Y:""}`;if(U&&d.has(L))return{status:204};if(f.has(L))return ye(503,"in_progress","This moment of the gateway is being handled",5);f.add(L);try{let I=m.entry.g.hooks[qr[$]],G;if($==="empty"?(G=o.get(m.channel),k(m.channel,G)):G=$==="leave"?o.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,M,{id:Z?.id??""},$==="join"?Y:void 0);try{await t.run(Z,`${m.entry.cls.name}.${I}`,S,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return S?.aborted||_.error(`[palbase] ${m.entry.cls.name}.${I} (${$} of ${m.channel}) failed; realtime tells it again`,{error:ne}),ye(500,"handler_failed",`The gateway's ${$} could not be handled`)}}return U&&(d.add(L),d.size>Za&&d.delete(d.values().next().value)),{status:204}}finally{f.delete(L)}}function Se(b,S){let m=r.get(b),$=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${$}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let M=Kr(m.g.pattern,S??{});if(typeof M!="string")throw new TypeError(`${$}: ${M.problem}`);return{entry:m,channel:M,where:$}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,S,m){return _n(S)?b==="authorize"?z(S,m):b==="message"?ie(S,m):b==="lifecycle"?ge(S,m):ye(404,"not_found",`No gateway call ${JSON.stringify(b)}`):ye(400,"bad_request","A gateway's call is a JSON object")},emit(b,S,m,$){let{entry:M,channel:U,where:Z}=Se(b,S);T(M,U,m,$,Z)},async pipe(b,S,m){let{channel:$,where:M}=Se(b,S);await F(m,$,M)},async revalidate(b,S,m={}){let $=r.get(b),M=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!$)throw new TypeError(`${M}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Wa($.g.pattern,S??{},m);if("problem"in U)throw new TypeError(`${M}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Xa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(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 eo(e){return Array.isArray(e)?"an array":_n(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 to=20,Ut=256;function Gr(e){let t="";for(let n of e.slice(0,to)){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)>=Ut)break}return kn(t,Ut)}function kn(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 vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Je(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>=Ya?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,Qa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as no,createPublicKey as Yr,timingSafeEqual as ro,verify as Qr}from"node:crypto";function yc(e){let t=D(e,ze);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 Xr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,ze),f=s.get(d.name);if(f)throw new TypeError(`@Webhook "${d.name}" is declared by ${f.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=so(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let T=t(o),F=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${o.name}.${H}`,call:(W,z)=>T[H](W,z)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:F})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
|
+
- ${a.join(`
|
|
4
|
+
- `)}`);return s}function es(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Wr=1024*Ve;function so(e,t){if(e.signature)return je(void 0,e.signature.header,1/0,go(e.signature,t));switch(e.provider){case"stripe":return je("stripe","stripe-signature",512*Ve,io(t));case"github":return je("github","x-hub-signature-256",25*Wr,co(t));case"slack":return je("slack","x-slack-signature",64*Ve,uo(t));case"discord":return je("discord","x-signature-ed25519",64*Ve,lo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:po(t)};case"sendgrid":return je("sendgrid","x-twilio-email-event-webhook-signature",Wr,mo(t));case"livekit":return je("livekit","authorization",512*Ve,ho(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function je(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??ts(e,s)}}function ts(e,t){let n=Sn(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:ns(e,t.headers,r),event:r,...ao(e,t,r)}}function ns(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=De(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=as(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return De(n,"EventType");case"livekit":return De(n,"event");default:return De(n,"type")}}function ao(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(De(n,"id"));case"slack":return r(De(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${rs(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>De(s,"sg_event_id")||void 0)}:{};default:return{}}}var oo=300;function io(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(),k=f.slice(h+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(y==="v1"){let T=me(k,"hex");if(!T)return"malformed_signature";a.push(T)}}let o=ut(s);if(o===void 0||a.length===0)return"malformed_signature";if(lt(o,n))return"stale_timestamp";let d=Ze("sha256",e,`${s}.`,t.body);return a.some(f=>_e(f,d))?void 0:"signature_mismatch"}}function co(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?_e(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function uo(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ut(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":lt(a,n)?"stale_timestamp":_e(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function lo(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=Yr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ut(o),f=me(a,"hex");return d===void 0||!f||f.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":Qr(null,ss(o,r.body),n,f)?void 0:"signature_mismatch"}}var fo=1e3;function po(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!_e(Buffer.from(a.toLowerCase()),Buffer.from(En("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let F=1;for(let W of t.body)if(W===38&&++F>fo)return"malformed_signature";let N=new Map;for(let[W,z]of new URLSearchParams(Sn(t.body))){let ie=N.get(W);ie||N.set(W,ie=new Set),ie.add(z)}let H=[];for(let W of[...N.keys()].sort()){let z=[...N.get(W)].sort();for(let ie of z)o+=W+ie;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(F=>_e(r,Ze("sha1",e,F,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),T=k?{id:`${k}:${rs(`${h}
|
|
5
|
+
${o}`)}`}:{};return d?{type:ns("twilio",t.headers,d),event:d,...T}:{...ts("twilio",t),...T}}}function mo(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=Yr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=ut(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":lt(o,r)?"stale_timestamp":Qr("sha256",ss(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Vr=60;function ho(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=Zr(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!_e(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Zr(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Vr||typeof d.nbf=="number"&&n<d.nbf-Vr)return"stale_timestamp";let f=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return f&&_e(f,En("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function go(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ut(d);if(h===void 0)return"malformed_signature";if(lt(h,a))return"stale_timestamp"}let f=me(o.trim(),e.encoding);return f?_e(f,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var yo=new TextEncoder;function Ze(e,t,...n){let r=no(e,t);for(let s of n)r.update(s);return r.digest()}function rs(e){return En("sha256").update(e).digest("hex")}function ss(e,t){return Buffer.concat([yo.encode(e),t])}function _e(e,t){return e.byteLength===t.byteLength&&ro(e,t)}var wo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return wo[t].test(e)?Buffer.from(e,t):void 0}function ut(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function lt(e,t){return Math.abs(t-e)>oo}function Sn(e){return new TextDecoder().decode(e)}function Zr(e){if(e)try{return JSON.parse(Sn(e))}catch{return}}function as(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(e,t){let n=as(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(o=>` - ${o}`).join(`
|
|
13
|
+
`)}`),this.name="DiError",this.kind=t,this.path=n}},bo=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],ko=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),Lt=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,cn);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 o of a.imports){if(o===r)throw new V("unknown import",[r.name],r.name,`${r.name} imports itself`,["remove it from its own imports"]);n(o,[...s,r.name])}};for(let r of t)n(r,[]);for(let[r,s]of this.defs){for(let a of[...s.controllers,...s.providers]){let o=this.owner.get(a);if(o&&o!==r)throw new V("duplicate ownership",[o.name,a.name,r.name],a.name,`${a.name} is listed by ${o.name} and by ${r.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(a,r)}for(let a of s.providers)this.providers.add(a);for(let a of s.controllers){if(!D(a,He))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,Me)||D(a,We))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,We)&&!D(r,Me))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,dn)&&!D(r,Ce)&&!D(r,Me)&&!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,Me)&&this.gateways.push(r),D(r,ze)?this.webhooks.push(r):D(r,Ce)&&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 bo)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,o=Reflect.getMetadata("design:paramtypes",t)??[];if(a>0&&o.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=[];o.slice(0,a).forEach((h,y)=>{if(ko.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),o=this.owner.get(a);if(o!==s){if(!this.defs.get(s).imports.includes(o))throw new V("missing import",[...r,a.name],`${s.name}`,`${t.name} (in ${s.name}) needs ${a.name}, owned by ${o.name}, which ${s.name} does not import`,[`add ${o.name} to ${s.name}'s imports (imports are not transitive)`]);if(!this.defs.get(o).exports.includes(a))throw new V("private dependency",[...r,a.name],`${o.name}`,`${a.name} is ${o.name}'s own: it is not in its exports`,[`add ${a.name} to ${o.name}'s exports`])}return a}target(t,n){if(this.owner.has(t))return t;let r=[...this.owner.keys()].filter(s=>s.prototype instanceof t);if(r.length===1)return r[0];throw r.length>1?new 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 vo,HttpError as ft}from"palgres";import{z as Ee}from"zod";import{BadRequest as xc,Conflict as Rc,DeadlockDetected as Oc,HttpError as Pc,NotFound as Cc,SerializationFailure as Mc,TooManyRequests as jc,UniqueViolation as Dc}from"palgres";function pt(e){if(typeof e!="object"||e===null||e[vo]!==!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 os=class extends ft{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},is=class extends ft{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},ds=class extends ft{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function us(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 To=Symbol.for("palbase.backend.errorRegistry"),$o={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 Eo(){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=$o[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function So(){let e=globalThis;return e[To]??=Eo()}var Ao=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function Ec(e,t,n){if(typeof e!="string"||e.length>100||!Ao.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=So(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&cs(s.data)!==cs(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(T=>T.split(/(?=[A-Z])/)),o=a.map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join(""),d=a.map(T=>T.toLowerCase()).join(" "),f=d.charAt(0).toUpperCase()+d.slice(1),k=n?(T=>class extends ft{static code=e;static status=t;constructor(F,N){let H=xo(e,T,F);super(t,e,N??(typeof H=="string"?H:f),H),this.name=o}})(n):class extends ft{static code=e;static status=t;constructor(T){super(t,e,T??f),this.name=o}};return Object.defineProperty(k,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),k}function xo(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 cs(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as Ro}from"palgres";var ls="/_palbase/ai/tools",fs="/_palbase/ai/agents",ps="/_palbase/ai/repos",Qe=4<<20,Oo=Symbol.for("palbase.ai.tool_error");function ms(e){return e instanceof Error&&e[Oo]===!0}var Po=Symbol.for("palbase.ai.declared");function hs(){let e=globalThis[Po];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 Ye=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function gs(e){let t={};if(e==null)return t;if(Ye(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 ys(e){if(!Ye(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(!Ye(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=gs(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 ws(e){let t=ys(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 bs(e){let t=ys(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=Ye(a)?gs(a.metadata):void 0;if(!Ye(a)||typeof a.id!="string"||typeof a.client_id!="string"||a.author!==null&&typeof a.author!="string"||typeof a.author_name!="string"||typeof a.text!="string"||typeof a.delivery!="string"||o===void 0)return"message is {id, client_id, author, author_name, text, delivery, metadata}, or null";r={id:a.id,clientId:a.client_id,author:a.author,authorName:a.author_name,text:a.text,delivery:a.delivery,metadata:Ro(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!Ye(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 Co=1e4,Mo=10*6e4,It=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<=Mo&&this.seen.size<=Co)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},jo=1e3,Do=256*1024,Ht=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>Do)&&(this.answers.set(t,n),this.answers.size>jo&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as ea,isEngineRaised as Gn,markData as fe}from"palgres";import{createHash as ta}from"node:crypto";import{createHash as No,randomInt as Uo}from"node:crypto";import{ago as An,isRetryable as Lo,now as ks}from"palgres";import{defineSchema as Io,defineTable as Ho,index as qo,integer as zo,jsonb as Go,raw as Fo,text as xn,timestamp as vs}from"palgres/dsl";var xs=new Set(["POST","PUT","PATCH","DELETE"]),Ts=255,$s=35,_s=24,Bo=65536,Es=1e3,Ko=64,On={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"}},Jo=Ho("idempotency_keys",{columns:{key:xn().primaryKey(),fingerprint:xn(),started_at:vs().defaultNow(),completed_at:vs().nullable(),status_code:zo().nullable(),response_headers:Go().nullable(),response_body:xn().nullable()},indexes:e=>[qo("idempotency_keys_started").on(e.col("started_at"))]}),Fc=Io("palbase",{tables:[Jo],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)"})]}),Wo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Vo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},Zo={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},Ss={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},zt=class extends Error{};function mt(e){return xs.has(e.method)&&e.meta.upload===void 0}function Rs(e,t){if(!xs.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Yo(e,t){return Os([e.role,e.uid,t]).digest("hex")}function Qo(e){return Os([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Os(e){let t=No("sha256");for(let n of e)t.update(n).update("\0");return t}function Xo(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function Rn(e){return e<500&&e!==429&&e!==499}function ei(e,t){return t&&Rn(e)}function Ps(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 ti={role:"service",claims:{}},ni={seal:e=>e,open:async e=>e},Gt=class{db;answers;constructor(t,n=ni){this.db=t,this.answers=n}async serve(t,n,r){if(t.key.length>Ts)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Ts} characters`});let s;try{s=await this.begin(Yo(t.caller,t.key),Qo(t))}catch(d){return _.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:d}),r.refusal(Ss)}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(Ss)}return ri({...s.kept,body:d},r.requestId)}if("refused"in s)return r.refusal(s.refused==="reused"?Wo:Vo);let a=s.claim,o;try{o=await n(d=>this.record(a,d))}catch(d){if(d instanceof zt)return r.refusal(Zo);let f=r.failure(d);return ei(f.status,r.ran())&&!Lo(d)?this.keep(a,f):(await this.release(a),f)}return Rn(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:An({hours:_s})}}}))}async begin(t,n){return Uo(Ko)===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:An({hours:_s})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let d=Xo(o,n);if(d==="reused")return{refused:"reused"};if(d==="replay")return{kept:{status:o.status_code,headers:o.response_headers??[],body:o.response_body}};let[f]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:An({seconds:$s})}},set:{started_at:ks()}});return f?{claim:{key:t,started:f.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!Rn(n.status))return n;let{response:r,kept:s}=await As(n),a=re.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let o=s.body===null?null:this.answers.seal(s.body),[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),o]);if(d?.answered!==!0)throw new zt;return r}async keep(t,n){let{response:r,kept:s}=await As(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:ks(),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()+$s*1e3,r=()=>{Date.now()+Es>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},Es).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(ti),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 ri(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 qt=Symbol("waits");function si(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(qt));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function As(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 si(d);if(f!==qt&&f.done)break;if(f!==qt&&(s.push(f.value),a+=f.value.byteLength,a<=Bo))continue;let h=f===qt?d:void 0,y=new ReadableStream({start(k){for(let T of s)k.enqueue(T)},async pull(k){let T=await(h??r.read());h=void 0,T.done?k.close():k.enqueue(T.value)},cancel:k=>r.cancel(k)});return{response:n(y),kept:{status:e.status,headers:t.filter(([k])=>k!=="content-length"&&k!=="content-encoding"),body:null}}}let o=Buffer.concat(s);return{response:n(o),kept:{status:e.status,headers:t,body:o.byteLength===0?null:o.toString("base64")}}}import{createHash as ai}from"node:crypto";var Pn="/webhooks/palbase",Us="PalbaseErrorEnvelope",Cs="PalbaseBearer",oi={$ref:`#/components/schemas/${Us}`},ii={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"]},Ms={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Xe={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Ls(e,t,n){let r={[Us]:ii},s={},a=[],o=[],d=new Set,f=new Map;for(let m of e){let $=o.find(K=>fi(K,m));if($){a.push({route:m.id,handler:js(m),answeredBy:$.id});continue}o.push(m);let M=m.segments.map(K=>typeof K=="string"?K:"{}").join("/");f.has(M)||f.set(M,mi(m.segments.flatMap(K=>typeof K=="string"?[]:[K.param])));let U=f.get(M),Z=0,Y=`/${m.segments.map(K=>typeof K=="string"?K:`{${U[Z++]}}`).join("/")}`,L=t(m),I=Ft(pi(m),d),G=m.method!=="GET"&&m.method!=="HEAD",B=K=>{let xe=m.params.filter(Ue=>Ue.kind===K&&Ue.schema).map((Ue,_t)=>Jt(Ue.schema,`${I}.${K}${_t===0?"":`.${_t+1}`}`,r));return xe.length===0?void 0:xe.length===1?xe[0]:{allOf:xe}},ne=U.map(K=>({name:K,in:"path",required:!0,schema:{type:"string"}})),Ae=B("query");Ae&&ne.push(...Ns(Ae,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:Ae}]);let vt=B("headers");vt&&ne.push(...Ns(vt,"header")??[]);let Tt=n.idempotency===!0&&mt(m);Tt&&ne.push({...On,schema:{...On.schema}});let he=G?B("body"):void 0,X={operationId:I};m.controller.name!==""&&(X.tags=[m.controller.name]),ne.length>0&&(X.parameters=ne),he&&(X.requestBody={required:!bi(he),content:{"application/json":{schema:he}}});let at=m.params.some(K=>K.schema!==void 0),$t=n.routes?.(m),ot=vi(I,$t?.throws??[],n.errors);X.responses={...ki($t,I,r),..._i(L,{validates:at,hasPathParams:U.length>0,readsBody:G,keyed:Tt}),...$i(ot,I,r)},ot.length>0&&(X["x-palbase-errors"]=Ti(I,ot)),L.auth.required&&(X.security=[{[Cs]:[]}]),X["x-palbase-handler"]=js(m);let Xt=m.params.some(K=>K.kind==="optionalUser")||n.databaseSeesCaller;X["x-palbase-auth"]=L.auth.required?"required":Xt?"optional":"public",X["x-palbase-verified-email"]=L.auth.verifiedEmail,L.auth.aal!=="aal1"&&(X["x-palbase-aal"]=L.auth.aal),L.auth.maxAge!==null&&(X["x-palbase-max-age"]=L.auth.maxAge),L.attest&&(X["x-palbase-attest"]=!0);let Ne=L.limit===!1?!1:L.limit.map(K=>({max:K.max,window:K.window}));X["x-palbase-rate-limit"]=Ne===!1?!1:Ne.length===1?Ne[0]:Ne,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 $={operationId:Ft(`webhooks.${m.name}`,d)};m.cls!==""&&($.tags=[m.cls]),$.description=m.provider?`${Ms[m.provider]??m.provider}'s deliveries: verified with ${Ms[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.`,$.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",Xe),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",Xe)},$["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:$}}let h=[...new Set(n.platformEvents??[])].sort();if(h.length>0){let m={operationId:Ft("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",Xe),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 $=[...new Set(n.platformEventBuckets??[])].sort();m["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:h,...$.length>0?{buckets:$}:{}},s[Pn]={post:m}}let y=n.gateways??[],k=ui(y,r),T=y.length>0,F=Object.fromEntries(y.filter(Ke).map(m=>[m.pattern,{events:k[m.name].events,messages:Object.fromEntries(Object.entries(k[m.name].messages).map(([$,M])=>[$,M.payload])),graceMs:m.graceMs,...m.logKeepSeconds>0?{logKeepSeconds:m.logKeepSeconds}:{}}])),N=Object.keys(F).length>0,H=y.filter(m=>!Ke(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=di(n.ai?.agents??[]),ie=Object.keys(z).length>0,ge=ci(n.ai?.tools??[]),Se=Object.keys(ge).length>0,b={schemas:r,securitySchemes:{[Cs]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},S={openapi:"3.2.0",info:{title:"Palbase backend",version:ai("sha256").update(JSON.stringify({paths:s,components:b,unreachable:a,...T?{gateways:k}:{},...N?{rooms:F}:{},...W?{channels:H}:{},...ie?{agents:z}:{},...Se?{aiTools:ge}:{}})).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:b};return a.length>0&&(S["x-palbase-unreachable"]=a),T&&(S["x-palbase-gateways"]=k),N&&(S["x-palbase-room"]=F),W&&(S["x-palbase-channels"]=H),ie&&(S["x-palbase-agents"]=z),Se&&(S["x-palbase-ai-tools"]=ge),S}function di(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 ci(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 ui(e,t){let n=[];for(let r of e){let s=(d,f,h,y)=>{let k=Kt(`${r.name}_${d}_${f}`),T={},F=Jt(h,k,T,y);F.$ref===void 0&&(T[k]=F),li(r.pattern,d,f,T[k]);for(let[N,H]of Object.entries(T)){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/${k}`}},a=Object.fromEntries(Object.entries(r.events).map(([d,f])=>[d,s("event",d,f,"answered")])),o=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:o}])}return Object.fromEntries(n)}function li(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 fi(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 js(e){return`${e.controller.name}.${e.fn}`}function pi(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 Ft(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function mi(e){let t=new Set;return e.map(n=>Ft(n,t))}function Jt(e,t,n,r="sent"){let s=e["~standard"],a=s.jsonSchema?.input;if(typeof a!="function")return{};let o;try{o=a({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...s.vendor==="zod"?{override:hi}:{}}})}catch{return{}}let d=Kt(t);for(;Object.keys(n).some(f=>f===d||f.startsWith(`${d}.`));)d=`${d}_`;return gi(o,d,n,r)}function hi(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function gi(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=h=>h==="#"?(a=!0,`#/components/schemas/${t}`):h.startsWith("#/$defs/")?`#/components/schemas/${t}.${Kt(wi(h.slice(8)))}`:h,d="all";if(r==="sent"){let h=new Set;for(let y of[e,...Object.values(s)])Bt(y,h);d=h}for(let[h,y]of Object.entries(s))n[`${t}.${Kt(h)}`]=gt(ht(y,o,d));let f=gt(ht(e,o,d));return a?(n[t]=f,{$ref:`#/components/schemas/${t}`}):f}var yi=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",sr]),Cn=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),Mn=new Set(["anyOf","oneOf","allOf","prefixItems"]),jn=new Set(["properties","patternProperties","dependentSchemas"]),ae=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ht(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):yi.has(s)?r[s]=a:Cn.has(s)?r[s]=ht(a,t,n):Mn.has(s)&&Array.isArray(a)?r[s]=a.map(o=>ht(o,t,n)):jn.has(s)&&ae(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,d])=>[o,ht(d,t,n)])));return r}var Ds=Number.MAX_SAFE_INTEGER;function gt(e){if(!ae(e))return e;let t={};for(let[r,s]of Object.entries(e))Cn.has(r)?t[r]=gt(s):Mn.has(r)&&Array.isArray(s)?t[r]=s.map(gt):jn.has(r)&&ae(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,gt(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Ds&&delete t.minimum,t.maximum===Ds&&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 Bt(e,t){if(ae(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(ae))continue;if(r.every(a=>"const"in a||Array.isArray(a.enum)))for(let a of r)t.add(a);let s=r.map(a=>ae(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(o=>ae(o[a])&&"const"in o[a]))for(let o of s)t.add(o[a])}for(let[n,r]of Object.entries(e))if(Cn.has(n))Bt(r,t);else if(Mn.has(n)&&Array.isArray(r))for(let s of r)Bt(s,t);else if(jn.has(n)&&ae(r))for(let s of Object.values(r))Bt(s,t)}}function wi(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Kt(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function Ns(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 bi(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:oi}}}}function ki(e,t,n){if(!e)return{200:{description:"The handler's answer, as JSON",content:{"application/json":{}}},204:{description:"The handler answered nothing (undefined or null)"}};if(e.returns.kind==="void")return{204:{description:"No Content"}};if(e.returns.kind==="raw")return{default:{description:"The handler's own Response, as it built it"}};let r=Jt(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function vi(e,t,n){let r=new Set,s=[];for(let a of t){if(r.has(a.code))continue;r.add(a.code);let o=n?.get(a.code);if(o&&a.status!==o.status)throw new Error(`${e} throws "${a.code}" with status ${a.status}, but the code is defined with status ${o.status} \u2014 a client matches an error by its code, so one code carries one status`);s.push({...a,...o?.data?{data:o.data}:{}})}return s}function Ti(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 $i(e,t,n){let r=new Map;for(let a of e)r.set(a.status,[...r.get(a.status)??[],a]);let s={};for(let a of[...r.keys()].sort((o,d)=>o-d)){let o=r.get(a),d=o.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=Jt(f.data,`${t}.${f.code}.data`,n,"answered"),y.push("data")),{type:"object",properties:h,required:y}});s[String(a)]={description:o.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",Xe)),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)",Xe)),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":""}`,Xe),n}var Wt=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,o)=>{let d=this.reserve(`${t}\0${o}`,a);"wait"in d?r=Math.max(r??0,d.wait):s.push([`${t}\0${o}`,d.window])}),r!==void 0)for(let[a,o]of s)this.give(a,o);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 yt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return Ei(r??t??"unknown")}function Ei(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(n)return n[1];let[r,s=""]=t.split("::"),a=r?r.split(":"):[],o=s?s.split(":"):[],d=t.includes("::")?[...a,...Array(8-a.length-o.length).fill("0"),...o]: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 Dn="/.well-known/palbase/attest-challenge",oe={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"},Si=25e3,Vt=3e3,Ai=1e4,Is=()=>({capable:0,incapable:0,unknown:0,no_sdk:0,verified:0,refused:0}),Zt=class{constructor(t,n=Date.now){this.auth=t;this.now=n}auth;now;mode;readAt=-1/0;reading;counts=Is();timer;shipping=Promise.resolve();async modeNow(){return this.now()-this.readAt>=Si&&(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(Vt)})).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,s){let a=await this.modeNow();if(a===void 0)return{unavailable:!0,pass:!1};if(a==="off")return{pass:!0};let o=t.headers,d=o.get(oe.deviceId)??"",f=o.get(oe.payload)??"",h=o.get(oe.signature)??"",y=d!==""&&f!==""&&h!=="",k=y&&Hs(f)&&Hs(h);this.declared(o,y);let T;try{T=(await this.auth.adminVerifyDeviceAssertion({body:{installation_id:o.get(oe.anchor)??"",device_id:k?d:"",challenge:o.get(oe.challenge)??"",payload:k?f:"",signature:k?h:"",method:t.method,path:s??xi(n),body_sha256:r&&r.byteLength>0?await Ri(r):""},signal:AbortSignal.timeout(Vt)})).data}catch(H){return _.warn(`[palbase] attest: auth could not verify ${t.method} ${n.pathname}`,{error:H}),a==="enforce"?{unavailable:!0,pass:!1}:{pass:!0}}y&&this.outcome(k&&T.ok);let F=a==="enforce"&&T.ok&&T.device_id&&T.platform?{id:T.device_id,platform:T.platform}:void 0;return T.ok||a==="monitor"?{pass:!0,challenge:T.next_challenge||void 0,device:F}:{pass:!1,reason:y?k?T.reason==="assertion_stale"||T.reason==="device_unknown"||T.reason==="assertion_invalid"?T.reason:"app_attest_required":"assertion_invalid":"app_attest_required",challenge:T.next_challenge}}async challengeFor(t){let n=await this.modeNow();if(n===void 0)return{unavailable:!0};if(n==="off")return{};try{let r=await this.auth.adminVerifyDeviceAssertion({body:{installation_id:t,device_id:"",challenge:"",payload:"",signature:"",method:"GET",path:Dn,body_sha256:""},signal:AbortSignal.timeout(Vt)});return r.data.next_challenge?{challenge:r.data.next_challenge}:{unavailable:!0}}catch(r){return _.warn("[palbase] attest: auth could not mint a challenge",{error:r}),{unavailable:!0}}}declared(t,n){let r=t.get(oe.capable);n||r==="yes"?this.counts.capable++:r==="no"?this.counts.incapable++:t.get(oe.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()},Ai),this.timer.unref?.())}async flush(){let t=this.counts;Object.values(t).every(n=>n===0)||(this.counts=Is(),this.shipping=this.shipping.then(async()=>{try{await this.auth.adminRecordAttestObservations({body:t,signal:AbortSignal.timeout(Vt)})}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 Hs(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 xi(e){let t=e.href,n=t.indexOf("#");return(n===-1?t:t.slice(0,n)).slice(e.origin.length)}async function Ri(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,He),s=D(n,qe)??[];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,on)??new Map;for(let o of s){let d=`${r.basePath}${o.subpath}`||"/",f=d.split("/").filter(Boolean).map(y=>{let k=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(y)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(y);return k?{param:k[1]}:y});if(typeof f[0]=="string"&&Ge.has(f[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${d} \u2014 /${f[0]} is the platform's; a route is served elsewhere`);let h=[...a.get(o.fn)??[]].sort((y,k)=>y.index-k.index);for(let y of h)if(y.kind==="param"&&!f.some(k=>typeof k!="string"&&k.param===y.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${y.name}") names no {${y.name}} in ${o.method} ${d}`);t.push({id:`${o.method} ${d}`,method:o.method,segments:f,controller:n,fn:o.fn,params:h,meta:o,controllerAuth:r.options.auth,controllerAttest:r.options.attest})}}return Dr(t),t}function Nn(e,t,n){let r=n.split("/").filter(Boolean);for(let s of e){if(s.method!==t||s.segments.length!==r.length)continue;let a={},o=!0;for(let d=0;d<r.length&&o;d++){let f=s.segments[d];if(typeof f=="string")o=f===r[d];else try{a[f.param]=decodeURIComponent(r[d])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function In(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function et(e,t,n,r,s){return st(e,e?In(e.requests,t):void 0,n,r,s)}var wt={role:"service",claims:{}};async function st(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}),o=e.app.request(t,{signal:n,heldIdle:a}),d=re.getStore();d&&(d.database=o.database);let f;try{f=await s()}catch(h){throw await o.rollback(h).catch(y=>_.error("[palbase] the request's transaction could not be rolled back",{error:y})),h}try{await o.commit()}catch(h){throw await o.rollback(h).catch(y=>_.error("[palbase] the request's transaction could not be rolled back",{error:y})),h}return f}var Pi=1024*1024,Ci=20,Mi={max:300,window:60},ji={max:60,window:60},Di=/^ins_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,tt="/_palbase/crons",nt="/_palbase/tasks",zs=50,Gs=50,Ni=4096,Ui=69632,Fs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,rt=1e4,Li=6e4;function Ii(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 Bs(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 Ks(e){return{...e.aal!=="aal1"?{acr_values:e.aal}:{},...e.maxAge!==null?{max_age:e.maxAge}:{}}}var Hi=60;function qi(e,t,n){if(e===null)return!1;let r=n/1e3-e;return r>=-Hi&&r<=t}var ee=class extends Error{constructor(n,r,s,a,o,d,f){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=o;this.challenge=d;this.headers=f}status;code;data;retryAfter;challenge;headers};function zi(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 Gi=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Fi(e,t){let n=new Headers(e.headers);for(let r of Gi)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 Js(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Yt(e.headers,"Accept-Language")),e}function Yt(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 le(e,t,n,r={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}})}function v(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),le(e.status,n,t,r)}function Ws(e,t){if(t===void 0)return e;try{return e.headers.set(oe.challenge,t),e}catch{let n=new Headers(e.headers);return n.set(oe.challenge,t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}}var na=new Set([0,429,502,503,504]);function Vs(e,t,n,r){if(r?.aborted)return _.info(`[palbase] ${n}: the client left before its answer`),v({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof ee)return v({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge,headers:e.headers},t);if(pt(e)){let a=e;return a.status>=500&&_.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),le(a.status,us(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Qt(e,n);return s?v(s,t):(e instanceof de?_.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}),v({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Qt(e,t){if(e instanceof Ot)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 de&&na.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=ea(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 Bi(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return ms(e)?t(e.message):pt(e)&&!Gn(e)&&!Hn(e)?t(e.errorDescription):Hn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function Hn(e){return e instanceof Ot||e instanceof de&&na.has(e.status)||ea(e)!==void 0||pt(e)&&e.status===503&&Gn(e)}async function Un(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,Ci).map(o=>({field:(o.path??[]).map(d=>String(typeof d=="object"&&d!==null&&"key"in d?d.key:d)).join("."),message:o.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 bt(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 o=new Uint8Array(a),d=0;for(let f of s)o.set(f,d),d+=f.byteLength;return o}function Ki(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return fe(t)}function Ji(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:Wi(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 Wi(e){return e==="aal1"||e==="aal2"||e==="aal3"?e:null}function Zs(e){return e==="aal3"?3:e==="aal2"?2:1}function Vi(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 Zi=/^[A-Za-z0-9._:-]{8,128}$/,Yi=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Qi={max:20,window:60},Xi=10*6e4,ed=1e4,kt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},qn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=ta("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,d;if(!a){let h=this.limiter.reserve(o,Qi);if("wait"in h)throw new kt(h.wait);d=h}let f=await r();if(!f)throw this.known.delete(s),new Rt("unknown_token","The token is not one of the app's");return d&&this.limiter.give(o,d.window),this.known.delete(s),this.known.set(s,this.now()+Xi),this.known.size>ed&&this.known.delete(this.known.keys().next().value),f}};function Au(e){let t=new Lt(e.modules),n=qs(t.controllers.map(i=>i.cls)),r=new Map(n.map(i=>[i,Ii(i,e.auth)])),s=i=>i.meta.options.attest??i.controllerAttest??!1,a=n.some(s)?new Zt(e.server.auth,e.now):void 0,o=new Map;for(let i of n){let c={body:[],query:[]};for(let l of i.params){if(!l.schema)continue;let u=hr(l.schema);if(l.kind==="body")c.body.push(...rn(u,"/body",i.id));else if(l.kind==="query"){let g=rn(u,"/query",i.id),p=g.find(w=>w.split("/").length!==3);if(p)throw new TypeError(`${i.id}: ${p} \u2014 an encrypted query field is one of the query's own names`);c.query.push(...g)}else if(gr(u))throw new TypeError(`${i.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(i.meta.upload)throw new TypeError(`${i.id}: an upload's body comes through storage, which seals nothing \u2014 it carries no encrypted field`);o.set(i,c)}}async function d(i,c,l,u){let g=e.server.transit;try{return g.loaded||await g.load(),await g.request({header:l,method:u,path:sd(i),params:i.segments.flatMap(p=>typeof p=="string"?[]:[c[p.param]??""])})}catch(p){throw Qs(p)}}for(let[i,c]of r){if(!c.required&&i.params.some(l=>l.kind==="user"))throw new TypeError(`${i.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(i.meta.upload&&c.verifiedEmail)throw new TypeError(`${i.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(i.meta.upload&&c.aal!=="aal1")throw new TypeError(`${i.id}: an @Upload route cannot ask for auth { aal } \u2014 storage names its caller by id and session, not by its token`);if(i.meta.upload&&c.maxAge!==null)throw new TypeError(`${i.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(i)&&i.params.some(l=>l.kind==="attestedDevice"))throw new TypeError(`${i.id}: @AttestedDevice() on a route that does not ask for device attestation \u2014 mark it attest: true`);if(i.meta.upload&&s(i))throw new TypeError(`${i.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 i of n)for(let c of i.params)c.kind==="resolve"&&f.set(c,t.dependencyOf(i.controller,c.resolver,`${i.id} @Resolve(${c.resolver?.name})`));let h=new Map;for(let i of t.cronProviders){let c=t.get(i),l=D(i,Te),u=h.get(l.name);if(u)throw new TypeError(`@Cron "${l.name}" is ${u.owner} and ${i.name}: a cron's name is its own \u2014 name one of them`);h.set(l.name,{declaration:l,owner:i.name,run:g=>c.run(g)})}let y=new Map;for(let i of t.taskProviders){let c=t.get(i),l=D(i,be),u=y.get(l.name);if(u)throw new TypeError(`@Task "${l.name}" is ${u.owner} and ${i.name}: a task type's name is its own \u2014 name one of them`);y.set(l.name,{declaration:l,owner:i.name,run:(g,p)=>c.run(g,p)})}let k=new Map;for(let i of t.templateProviders){let c=t.get(i),l=D(i,ke),u=k.get(l.name);if(u)throw new TypeError(`@TestUserTemplate "${l.name}" is ${u.owner} and ${i.name}: a template's name is its own \u2014 name one of them`);k.set(l.name,{owner:i.name,seed:(g,p)=>c.seed(g,p),...typeof c.undo=="function"?{undo:(g,p)=>c.undo(g,p)}:{}})}k.size>0&&!e.platform&&_.info(`[palbase] ${k.size} @TestUserTemplate(s): the platform calls a machine for its test users; nothing does here`);let T=new Map,F=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>zs)throw new TypeError(`${h.size} @Cron classes: a machine runs ${zs} crons at most`);if(y.size>Gs)throw new TypeError(`${y.size} @Task classes: a machine runs ${Gs} 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=Jr(t.gateways.map(i=>({cls:i,instance:t.get(i)})),{run:(i,c,l,u)=>re.run({requestId:re.getStore()?.requestId??"",...i?.id?{userId:i.id}:{}},()=>st(e.database,e.database?i?.id?In(e.database.requests,Nt(i)):wt: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:i=>e.server.realtime.broadcast({body:{messages:i}}),revalidate:i=>e.server.realtime.revalidate({body:i}),isOutage:Hn});W.declarations.length>0&&!e.platform&&_.info(`[palbase] ${W.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let z=hs();(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 ie=i=>c=>t.provider(c,`${i} ctx.inject(${typeof c=="function"?c.name:String(c)})`),ge=new Ht,Se=new It(e.now??Date.now),b=new Set,S=e.database!==void 0||e.contractOnly?.database===!0;if(S){for(let i of n)if(mt(i)&&i.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&Ps(c.schema)))throw new TypeError(`${i.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 Gt(e.database.app,e.database.keptAnswers):void 0,$=ud(e.cors),M=e.now??Date.now,U=new Wt(e.now),Z=new qn(U,e.now??Date.now),Y=e.maxBodyBytes??Pi,L=i=>{let c=i.meta.options.rateLimit??e.rateLimit??Mi;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,G=Xr(t.webhooks,i=>t.get(i),I,{secrets:e.contractOnly===void 0}),B=G.size===0&&h.size===0&&y.size===0&&k.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(I).filter(i=>typeof i[1]=="string"&&!ur(i[0])))),ne=new Map([...G.keys()].map(i=>[i,{seen:new Set,inflight:new Set}])),Ae=new Map([...G.keys()].map(i=>[i,{counts:new Map,at:void 0}])),vt,Tt=()=>vt??=Ls(n,i=>({auth:r.get(i),limit:L(i),attest:s(i)}),{databaseSeesCaller:S,idempotency:S,webhooks:[...G.values()].map(i=>({name:i.name,cls:i.cls.name,provider:i.provider,signatureHeader:i.signatureHeader,secretEnv:i.secretEnv,events:[...i.events.keys()]})),platformEvents:[...he.keys()],gateways:W.declarations,ai:{agents:[...z.agents.values()].map(i=>({name:i.name,...i.description!==void 0?{description:i.description}:{},...i.machine!==void 0?{machine:i.machine}:{}})),tools:[...[...z.tools.values()].map(i=>({name:i.name,kind:"backend",description:i.description,parameters:i.parameters,approval:i.approval,...i.machine!==void 0?{machine:i.machine}:{}})),...[...z.clientTools.values()].map(i=>({name:i.name,kind:"client",description:i.description,parameters:i.parameters,approval:i.approval}))]},platformEventBuckets:nd(he),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),he=new Map;for(let[i,c]of Object.entries(e.events??{}))he.set(i,c.map(l=>({name:`palbase(${i})`,call:u=>l(u)})));for(let i of t.eventProviders){let c=t.get(i);for(let{event:l,fn:u,bucket:g}of D(i,Ce)??[]){if(!Tr.test(l))throw new TypeError(`@On("${l}") on ${i.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`);he.has(l)||he.set(l,[]),he.get(l).push({name:`${i.name}.${u}`,bucket:g,call:async(p,w)=>c[u](p,w)})}}let X=new Set,at=new Set;lr(e.server),fr({to:(i,c)=>({emit:(l,u)=>W.emit(i,c,l,u),pipe:l=>W.pipe(i,c,l),revalidate:l=>W.revalidate(i,c,l)})}),_r(e.platform?Er(I.PALBASE_MACHINE):new jt(new Map([...y].map(([i,c])=>[i,c.declaration])),(i,c)=>Jn(i,c),e.now));async function $t(i,c){let l;try{l=await dr(i,e.webhookSecret,{now:e.now})}catch(u){if(u instanceof dt)return v({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${u.code}`},c);throw u}if(fe(l.data),X.has(l.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(at.has(l.id))return v({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);at.add(l.id);try{let u;try{await et(e.database,null,void 0,`event ${l.type}`,async()=>{for(let g of he.get(l.type)??[])if(!(g.bucket!==void 0&&td(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}),v({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return X.add(l.id),X.size>rt&&X.delete(X.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{at.delete(l.id)}}async function ot(i,c={}){let l=i.headers.get("origin");if($&&l!==null){let u=$.allows(l);if(i.method==="OPTIONS"&&i.headers.has("access-control-request-method"))return u?new Response(null,{status:204,headers:$.preflight(l,i.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let g=await Yn(i,c);if(u)for(let[p,w]of Object.entries($.headers(l)))p==="vary"?Yt(g.headers,w):g.headers.set(p,w);else Yt(g.headers,"Origin");return g}return Yn(i,c)}async function Xt(i,c,l,u){if(!i.headers.get(l.scheme.header))return K(l,"missing_signature",u);let g={headers:i.headers,body:await bt(i,l.scheme.maxBytes(Y)),url:es(i,c)},p;try{p=l.scheme.check(g,M()/1e3)}catch{return K(l,"signature_mismatch",u,"check_failed")}if(typeof p=="string")return K(l,p,u);let w=l.events.get(p.type);if(!w)return _.info(`[palbase] webhook ${l.name}: no @On takes "${p.type}"; acknowledged`),le(200,{ok:!0,handled:!1},u);let E=ne.get(l.name),R=p.event,O=[];if(p.id!==void 0){if(E.seen.has(p.id))return le(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||!E.seen.has(j));if(x.length===0)return le(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=>E.inflight.has(A)))return v({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},u);fe(R);for(let A of O)E.inflight.add(A);let P;try{P=await et(e.database,null,void 0,`webhook ${l.name}`,()=>w.call(R,{env:B,requestId:u,environmentId:e.projectId??""}))}catch(A){let x=Qt(A,`webhook ${l.name}`)??ad(A,l.name);return x?v(x,u):(_.error(`[palbase] ${w.name} failed on ${l.name} "${p.type}"; the sender delivers it again`,{error:A}),v({status:500,code:"handler_failed",message:"The event could not be handled"},u))}finally{for(let A of O)E.inflight.delete(A)}for(let A of O)E.seen.add(A),E.seen.size>rt&&E.seen.delete(E.seen.values().next().value);return Ne(P,l,u)}function Ne(i,c,l){if(i instanceof Response)return i;if(typeof i=="string"){let u=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(i,{status:200,headers:{"content-type":u,"x-request-id":l}})}return le(200,i??{ok:!0,handled:!0},l)}function K(i,c,l,u=c){let g=Ae.get(i.name);g.counts.set(u,(g.counts.get(u)??0)+1);let p=M();return(g.at===void 0||p-g.at>=Li)&&(xe(i.name),g.at=p),v({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},l)}function xe(i){let c=Ae.get(i).counts;if(c.size===0)return;let l=[...c.values()].reduce((u,g)=>u+g,0);_.warn(`[palbase] webhook ${i}: ${l} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function Ue(i){let c=i.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?G.get(c[1]):void 0}async function _t(i,c,l,u){let g=c.pathname===tt;if(i.method!==(g?"GET":"POST"))return v({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 bt(i,Ni);try{await xt({secret:l,signature:i.headers.get("palbase-signature"),body:p,now:e.now})}catch(q){if(q instanceof dt)return v({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:J})=>({name:J.name,schedule:J.schedule,time_zone:J.timeZone,timeout:J.timeout,retry:J.retries}));return le(200,{crons:q},u,{"cache-control":"no-store"})}let w=c.pathname.slice(tt.length+1),E=h.get(w);if(!E)return v({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 v({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 v({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 v({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);H.add(j);let Q={env:B,environmentId:e.projectId??"",cron:w,runId:P,scheduledAt:new Date(A),attempt:x};try{await st(e.database,e.database?wt:void 0,i.signal,`cron ${w}`,async()=>{if(await E.run(Q),i.signal.aborted)throw new Error(`the platform gave up on this attempt of ${w} before it ended`)})}catch(q){return i.signal.aborted||_.error(`[palbase] cron ${w} failed (run ${P}, attempt ${String(x)})`,{error:q}),v({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>rt&&N.delete(N.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}let Jn=async({task:i,id:c,attempt:l,payload:u,createdAt:g},p)=>{let w=y.get(i);if(!w)return{status:404,message:`this version has no task ${JSON.stringify(i)}`};let E=fe(u??null),R=w.declaration.payload;if(R){let P=await R["~standard"].validate(E);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 ${i} ${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 "${i}" takes: ${A}`}}E=P.value}let O={env:B,environmentId:e.projectId??"",task:i,id:c,attempt:l,createdAt:g};try{await st(e.database,e.database?wt:void 0,p,`task ${i}`,async()=>{if(await w.run(E,O),p.aborted)throw new Error(`the platform gave up on this attempt of ${i} before it ended`)})}catch(P){return P instanceof Mt?(_.error(`[palbase] task ${i} ${c} can never be done: ${P.message}`),{status:422,message:P.message}):(p.aborted||_.error(`[palbase] task ${i} failed (task ${c}, attempt ${String(l)})`,{error:P}),{status:500,message:`the task ${i} failed; it is tried again`})}return{status:204}};async function aa(i,c,l,u){let g=c.pathname===nt;if(i.method!==(g?"GET":"POST"))return v({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 bt(i,Ui);try{await xt({secret:l,signature:i.headers.get("palbase-signature"),body:p,now:e.now})}catch(q){if(q instanceof dt)return v({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:J})=>({name:J.name,timeout:J.timeout,retry:J.retries,concurrency:J.concurrency}));return le(200,{tasks:q},u,{"cache-control":"no-store"})}let w=c.pathname.slice(nt.length+1),E;try{E=JSON.parse(new TextDecoder().decode(p))}catch{return v({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}=E??{};if(R!==w||typeof O!="string"||O===""||typeof x!="string"||!Fs.test(x)||Number.isNaN(Date.parse(x))||!Number.isInteger(P)||P<1)return v({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 v({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);H.add(j);let Q;try{Q=await Jn({task:w,id:O,attempt:P,payload:A,createdAt:new Date(x)},i.signal)}finally{H.delete(j)}return Q.status===404?v({status:404,code:"task_not_found",message:Q.message??""},u):Q.status===422?v({status:422,code:"task_failure",message:Q.message??""},u):Q.status>=300?v({status:Q.status,code:"task_failed",message:Q.message??""},u):(N.add(j),N.size>rt&&N.delete(N.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}}))}async function Le(i,c,l,u){if(i.method!=="POST")return v({status:405,code:"method_not_allowed",message:`${u} is POSTed`},l);let g;try{ir({signature:i.headers.get("palbase-signature"),now:e.now}),g=await bt(i,1048576),await xt({secret:c,signature:i.headers.get("palbase-signature"),body:g,now:e.now})}catch(w){if(w instanceof dt)return v({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 v({status:400,code:"bad_request",message:`${u} is JSON`},l)}return typeof p!="object"||p===null||!Object.hasOwn(p,"call")||p.call!==new URL(i.url).pathname?v({status:401,code:"invalid_signature",message:`${u} is the platform's to call: signed_for_another_call`},l):{body:p}}async function oa(i,c,l,u,g){let p=await Le(c,l,u,`An upload's ${i}`);if(p instanceof Response)return p;let w=Nr(i,p.body);if(typeof w=="string")return v({status:400,code:"bad_request",message:`An upload's ${i}: ${w}`},u);if(i==="complete"){if(b.has(w.uploadId))return v({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},u);b.add(w.uploadId),b.size>rt&&b.delete(b.values().next().value)}let E=Nn(n,w.method,w.route);if(!E||"malformed"in E||!E.route.meta.upload)return v({status:404,code:"not_found",message:`No upload route for ${w.method} ${w.route}`},u);let{route:R,params:O}=E,P=E.route.meta.upload,A=Vi(w.user);if(A&&Qn(g,A.id),r.get(R).required&&!A)throw new ee(401,"unauthorized","This route needs a signed-in user");if(i==="authorize"){let Q=L(R);if(Q!==!1){let J=U.takeEach(`${R.id}\0${Pr(w.user,w.client)}`,Q);if(J!==void 0)throw new ee(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:J},J)}let q=jr(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 et(e.database,Nt(w.user),c.signal,R.id,async()=>{let J={request:c,query:new URLSearchParams(w.query),params:O,user:A,body:w.body===void 0||w.body===null?{}:fe(w.body),requestId:u};await Zn(R,J);for(let ve of R.params)(ve.kind==="query"||ve.kind==="body"&&w.body!==void 0)&&await Xs(ve,J)}),le(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?{}:fe(w.body);return Ln(await en(R,{request:c,query:x,params:O,user:A,body:j,requestId:u,uploadedObject:fe(w.uploadedObject)},Nt(w.user)),void 0,u)}async function ia(i,c,l,u){let g=c.pathname.slice(Dt.length+1),p=g.endsWith("/undo"),w=p?g.slice(0,-5):g,E=await Le(i,l,u,"A test user template");if(E instanceof Response)return E;let R=k.get(w);if(!R||p&&!R.undo)return v({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=Sr(w,E.body);if(typeof O=="string")return v({status:400,code:"bad_request",message:`A test user template's call: ${O}`},u);let P=fe(O.user),A;try{A=await Ar(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}),v({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`),v({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(F.has(x))return v({status:409,code:"in_progress",message:`The template ${w} is being written for this user`,retryAfter:5},u);if(!p&&T.has(x))return le(200,{rows:T.get(x)},u);F.add(x);let j={env:B,environmentId:e.projectId??"",template:w},Q=`test user template ${w}${p?" undo":""}`;try{let q={};return await st(e.database,e.database?wt:void 0,i.signal,Q,async()=>{if(p?await R.undo(P,j):(await R.seed(P,j),q=await xr(re.getStore()?.database)),i.signal.aborted)throw new Error(`the platform gave up on ${Q} before it ended`)}),p?(T.delete(x),new Response(null,{status:204,headers:{"x-request-id":u}})):(T.set(x,q),T.size>rt&&T.delete(T.keys().next().value),le(200,{rows:q},u))}catch(q){i.signal.aborted||_.error(`[palbase] ${Q} failed for ${P.id}: nothing of it was kept`,{error:q});let J=q instanceof Error&&q.message!==""?`: ${q.message.replace(/\s+/g," ").slice(0,300)}`:"";return v({status:500,code:p?"undo_failed":"template_failed",message:`${p?"The undo of":"The template"} ${w} failed${J}; nothing of it was kept`},u)}finally{F.delete(x)}}function Wn(i,c,l,u){let g=i?{sub:i.id,role:"authenticated"}:null;return re.run({requestId:re.getStore()?.requestId??"",...i?{userId:i.id}:{}},()=>et(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 Vn=(i,c)=>new Response(i,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function da(i,c,l){let u=await Le(i,c,l,"A tool call");if(u instanceof Response)return u;let g=u.body,p=g.tool;if(typeof p!="string"||p==="")return v({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 v({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(p.slice(0,64))}`},l);let E=g.call_id,R=ws(g.context);if(typeof E!="string"||E===""||E.length>256||typeof R=="string")return v({status:400,code:"bad_request",message:`A call of ${p} is {tool, call_id, input, context}${typeof R=="string"?`: ${R}`:""}`},l);let O=ta("sha256").update(JSON.stringify(g)).digest("hex"),P=ge.answered(E);if(P!==void 0)return P.digest!==O?v({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},l):Vn(P.answer,l);if(ge.isRunning(E))return v({status:409,code:"in_progress",message:"This call is running",retryAfter:2},l);ge.start(E);let A;try{let x=await Wn(R.user,`ai.tool ${p}`,i.signal,()=>w.call(fe(g.input??{}),{...R,callId:E,signal:i.signal,inject:ie(`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>Qe&&(_.error(`[palbase] ai.tool ${p} answered ${j} bytes (call ${E}): a machine's answer is ${Qe} at most; the agent is told it failed`),A=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${Qe/(1<<20)} MiB it may be`}],is_error:!0}))}catch(x){if(i.signal.aborted)return ge.end(E,void 0),v({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);_.error(`[palbase] ai.tool ${p} failed (call ${E}, chat ${R.chatId}); the agent is told`,{error:x}),A=JSON.stringify({output:[{type:"text",text:Bi(x)}],is_error:!0})}return ge.end(E,{digest:O,answer:A}),Vn(A,l)}async function ca(i,c,l){let u=await Le(i,c,l,"An agent's turn");if(u instanceof Response)return u;let g=bs(u.body);if(typeof g=="string"||g.agent==="")return v({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 v({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(p.slice(0,64))}`},l);let E;try{E=await Wn(g.user,`ai.agent ${p}`,i.signal,()=>w.resolve({...g,signal:i.signal,inject:ie(`ai.agent ${p}`)}))}catch(P){if(i.signal.aborted)return v({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let A=Qt(P,`ai.agent ${p}`);return A?v(A,l):(_.error(`[palbase] ai.agent ${p} failed for chat ${g.chatId}; the turn is not started`,{error:P}),v({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},l))}let R=E.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`),v({status:500,code:"agent_failed",message:`The agent ${p} could not be defined for this turn`},l);let O=JSON.stringify(E.definition);return new TextEncoder().encode(O).byteLength>Qe?(_.error(`[palbase] ai.agent ${p}'s definition is larger than the ${Qe} bytes a machine's answer may be`),v({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 ua(i,c,l){let u=await Le(i,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 v({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 v({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 v({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 E;try{E=await st(e.database,e.database?wt:void 0,i.signal,`ai.repo ${g.repo}`,async()=>w({repo:g.repo,repository:g.repository,signal:i.signal,inject:ie(p?`ai.repo ${g.repo}`:`ai.repoTokens for ${g.repo}`)}))}catch(R){if(i.signal.aborted)return v({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let O=Qt(R,`ai.repo ${g.repo}`);return O?v(O,l):(_.error(`[palbase] ai.repo ${g.repo} gave no token; the workspace's clone or push is refused`,{error:R}),v({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},l))}return!p&&E==null?v({status:404,code:"repo_not_found",message:`ai.repoTokens gives no token for ${JSON.stringify(g.repo.slice(0,64))}`},l):typeof E!="string"||E.trim()===""?(_.error(`[palbase] ai.repo ${g.repo}'s token function answered no token`),v({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},l)):new Response(JSON.stringify({token:E}),{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function la(i,c,l,u){let g=await Le(c,l,u,`A gateway's ${i}`);if(g instanceof Response)return g;let p=await W.serve(i,g.body,c.signal);return"code"in p?v({status:p.status,code:p.code,message:p.message,retryAfter:p.retryAfter},u):"body"in p?le(200,p.body,u):new Response(null,{status:204,headers:{"x-request-id":u}})}async function Zn(i,c){let l=[],u={params:Object.freeze({...c.params}),user:fe(c.user),headers:i.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let g of i.params)g.kind==="resolve"&&(l[g.index]=await f.get(g).resolve(u,g.options));return l}async function en(i,c,l,u){let g=t.get(i.controller),p=await et(e.database,l,c.request.signal,i.id,async()=>{let w=await Zn(i,c);for(let R of i.params)R.kind!=="resolve"&&(w[R.index]=await Xs(R,c));u?.ran();let E=await g[i.fn](...w);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${i.id}'s upload before it was answered`);return u?u.record(Js(Ys(E,c.requestId),re.getStore()?.usedLocales)):E});return u?p:Js(Ys(p,c.requestId),re.getStore()?.usedLocales)}async function Yn(i,c){let l=i.headers.get("x-request-id")??"",u=Zi.test(l)?l:`req_${crypto.randomUUID()}`,g=performance.now(),p=new URL(i.url).pathname,w={endpoint:p},E=await fa(i,c,u,w);return e.telemetry?.record({requestId:u,method:i.method,endpoint:w.endpoint,path:p,status:E.status,durationMs:performance.now()-g,userId:w.userId}),E}function Qn(i,c){i.userId=c;let l=re.getStore();l&&(l.userId=c)}async function fa(i,c,l,u){let g=e.strings,p=g?{requestId:l,strings:g,locales:yr(i.headers.get("accept-language"),g.source),usedLocales:[]}:{requestId:l},w=await pa(p,i,c,l,u);return g&&Yt(w.headers,"Accept-Language"),w}async function pa(i,c,l,u,g){return re.run(i,async()=>{let p=new URL(c.url),w=`${c.method} ${p.pathname}`;try{if(p.pathname===Pn&&he.size>0)return c.method!=="POST"?v({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):e.webhookSecret?await $t(c,u):v({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},u);let E=Ue(p.pathname);if(E)return w=`webhook ${E.name}`,c.method!=="POST"?v({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):await Xt(c,p,E,u);if(e.platform&&(p.pathname===tt||p.pathname.startsWith(`${tt}/`)))return w=p.pathname===tt?"crons":`cron ${p.pathname.slice(tt.length+1)}`,await _t(c,p,e.platform.secret,u);if(e.platform&&(p.pathname===nt||p.pathname.startsWith(`${nt}/`)))return w=p.pathname===nt?"tasks":`task ${p.pathname.slice(nt.length+1)}`,await aa(c,p,e.platform.secret,u);if(e.platform&&(p.pathname===gn||p.pathname===Rr)){let C=p.pathname===gn?"authorize":"complete";return w=`upload ${C}`,await oa(C,c,e.platform.secret,u,g)}if(e.platform&&p.pathname.startsWith(`${yn}/`)){let C=p.pathname.slice(yn.length+1);return w=`gateway ${C}`,await la(C,c,e.platform.secret,u)}if(e.platform&&p.pathname===ls)return w="ai tool call",await da(c,e.platform.secret,u);if(e.platform&&p.pathname===fs)return w="ai agent's turn",await ca(c,e.platform.secret,u);if(e.platform&&p.pathname===ps)return w="ai repository's token",await ua(c,e.platform.secret,u);if(e.platform&&p.pathname.startsWith(`${Dt}/`))return w=`test user template ${p.pathname.slice(Dt.length+1)}`,await ia(c,p,e.platform.secret,u);if(a&&p.pathname===Dn){if(w="attest challenge",c.method!=="GET")return v({status:405,code:"method_not_allowed",message:"A challenge is asked for with GET"},u);let C=c.headers.get(oe.anchor)??"";if(C==="")return v({status:400,code:"installation_anchor_required",message:`A challenge is for an installation: send ${oe.anchor}`},u);if(!Di.test(C))return v({status:400,code:"invalid_installation_anchor",message:`${oe.anchor} is the installation anchor auth issued (ins_\u2026)`},u);let pe=U.takeEach(`attest challenge\0a:${yt(c.headers,l.remoteAddress)}`,[ji]);if(pe!==void 0)return v({status:429,code:"too_many_requests",message:"Too many challenges asked for from this address",retryAfter:pe},u);let Ie=await a.challengeFor(C);if("unavailable"in Ie)return v({status:503,code:"attest_unavailable",message:"The device's attestation cannot be checked right now",retryAfter:1},u);let Pe={"cache-control":"no-store","x-request-id":u};return Ie.challenge&&(Pe[oe.challenge]=Ie.challenge),new Response(null,{status:204,headers:Pe})}if(od(p.pathname))return v({status:404,code:"not_found",message:`No route for ${c.method} ${p.pathname}`},u);let R=Nn(n,c.method,p.pathname);if(R&&"malformed"in R)return v({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},u);if(!R)return v({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),J=q?.[2],ve=q?.[1].toLowerCase()==="dpop";if(J)try{let C=!ve&&e.tokens&&!Yi.test(J)&&e.tokens.accepts(J)?e.tokens:void 0,pe=C?await Z.ask(J,yt(c.headers,l.remoteAddress),()=>et(e.database,null,c.signal,"token",()=>C.resolve(J))):await e.verifier.verify(J,ve?{proof:c.headers.get("dpop"),method:c.method,url:cr(c.headers,p)}:void 0);x=Ji(pe),j=pe.claims}catch(C){if(!A.required&&(C instanceof Rt||C instanceof Ot||C instanceof kt))x=null;else throw C instanceof kt?new ee(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:C.wait},C.wait):C instanceof Rt?new ee(401,"invalid_token","The access token is not valid",{reason:C.reason},void 0,zi(C.reason)):C}else if(Q!==""&&A.required)throw new ee(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(x&&Qn(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&&Zs(x.acr)<Zs(A.aal))throw new ee(401,"insufficient_user_authentication",`This route needs a sign-in at ${A.aal}: step up and call again`,Ks(A),void 0,Bs(A,ve));if(x&&A.maxAge!==null&&!qi(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`,Ks(A),void 0,Bs(A,ve));let Xn=L(O);if(Xn!==!1){let C=x?`u:${x.id}`:`a:${yt(c.headers,l.remoteAddress)}`,pe=U.takeEach(`${O.id}\0${C}`,Xn);if(pe!==void 0)throw new ee(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:pe},pe)}let Re=c.method==="GET"||c.method==="HEAD"?void 0:await bt(c,Y),tn,er=null;if(a&&s(O)){let C=await a.check(c,p,Re,l.target);if("unavailable"in C)throw new ee(503,"attest_unavailable","The device's attestation cannot be checked right now",void 0,1);if(!C.pass)throw new ee(401,"app_attest_required","This route is called by the app on a device that attests",{reason:C.reason,challenge:C.challenge},void 0,void 0,{[oe.challenge]:C.challenge});tn=C.challenge,er=C.device??null}let Et=Re===void 0?void 0:Ki(Re),nn=p.searchParams,Oe=o.get(O),St=c.headers.get(At),it=Oe!==void 0||St!==null?await d(O,P,St,c.method):void 0;if(it&&Oe)try{if(Oe.body.length>0&&Et!==void 0&&(Et=await it.open(Et,"/body",Oe.body)),Oe.query.length>0){let C=await it.open(Object.fromEntries(p.searchParams),"/query",Oe.query);nn=new URLSearchParams(p.searchParams);for(let pe of Oe.query){let Ie=ar(pe.slice(7)),Pe=C[Ie];Pe!==void 0&&nn.set(Ie,typeof Pe=="string"?Pe:JSON.stringify(Pe))}}}catch(C){throw Qs(C)}let tr={request:c,query:nn,params:P,user:x,body:Et,raw:Re,requestId:u,attested:er},nr=m&&Re!==void 0&&mt(O)?Rs(c.method,c.headers):void 0;if(!m||nr===void 0)return Ws(await Ln(await en(O,tr,j),it,u),tn);let ma={role:In(e.database.requests,j).role,uid:x?.id??`a:${yt(c.headers,l.remoteAddress)}`},rr=!1,ha=St!==null?{uri:`${p.pathname}${p.search}`,body:rd(new TextEncoder().encode(`${St}
|
|
21
|
+
`),Re)}:{uri:`${p.pathname}${p.search}`,body:Re},ga=C=>async pe=>C(await Ln(pe,it,u));return Ws(await m.serve({key:nr,caller:ma,method:c.method,...ha},C=>en(O,tr,j,{record:ga(C),ran:()=>{rr=!0}}),{requestId:u,refusal:C=>v(C,u),failure:C=>Vs(C,u,w,c.signal),ran:()=>rr}),tn)}catch(E){return Vs(E,u,w,c.signal)}})}return{handle:ot,routes:n.map(i=>i.id),contract:Tt,start:()=>t.start(),stop:async()=>{W.close(),await a?.stop();for(let i of Ae.keys())xe(i);await t.shutdown(),await e.telemetry?.flush()}}}function td(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function nd(e){let t=new Set;for(let[n,r]of e)if(ln(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 Ys(e,t){if(e instanceof Response)return Fi(e,t);if(e==null)return new Response(null,{status:204,headers:{"x-request-id":t}});if(pr()===0)return le(200,e,t);let{value:n,pointers:r}=mr(e);return le(200,n,t,r.length>0?{[zn]:JSON.stringify(r)}:{})}var zn="x-palbase-answer-encrypted";async function Ln(e,t,n){let r=e.headers.get(zn);if(r===null)return e;if(!t)return await e.body?.cancel(),v({status:400,code:"encryption_required",message:`This route answers encrypted fields: the request names its key in ${At}`,data:{field:At}},n);let s=new Headers(e.headers);s.delete(zn),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 rd(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Qs(e){return e instanceof or?new ee(e.status,e.code,e.message,e.data):e}function sd(e){return`/${e.segments.map(t=>typeof t=="string"?t:"{}").join("/")}`}function ad(e,t){if(!(!pt(e)||e.status!==503||!Gn(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 od(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return Ge.has(decodeURIComponent(t))}catch{return Ge.has(t)}}var id="GET, POST, PUT, PATCH, DELETE, QUERY",dd=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function cd(e){return dd.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function ud(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!cd(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":id,"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 Xs(e,t){switch(e.kind){case"body":return Un(e.schema,t.body??{},"Request body");case"query":return Un(e.schema,fe(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),fe(n),e.schema?Un(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return fe(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"attestedDevice":return t.attested??null;case"client":{let n=t.request.headers;return fe({sdkVersion:n.get("x-palbase-sdk-version"),appVersion:n.get("x-palbase-client-version"),platform:n.get("x-platform"),osVersion:n.get("x-os-version")})}}}var Bn=720*3600;function Fn(e){return e instanceof de&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function ra(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),Bn)}function sa(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Kn=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(!Fn(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:sa(n),ttl:ra(r)}})}catch(s){if(!Fn(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 o;try{o=(await we.cache.getCacheEntry({query:{key:t}})).data}catch(f){if(!Fn(f))throw f;_.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:f.status})}if(o?.found)return o.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}},Pu=Pt("Cache",new Kn);function Cu(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},o=()=>{let h=n();for(let[k,T]of r)T.expiresAt<=h&&r.delete(k);if(r.size<t)return;let y=[...r.entries()].sort((k,T)=>k[1].expiresAt-T[1].expiresAt);for(let[k]of y.slice(0,Math.ceil(y.length/4)))r.delete(k)},d=async(h,y,k)=>{r.size>=t&&!r.has(h)&&o(),r.set(h,{value:sa(y),expiresAt:n()+(ra(k)??Bn)*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),k=(typeof y?.value=="number"&&Number.isInteger(y.value)?y.value:0)+1;return r.set(h,{value:k,expiresAt:y?.expiresAt??n()+Bn*1e3}),k},getOrSet(h,y,k){let T=a(h);if(T)return Promise.resolve(structuredClone(T.value));let F=s.get(h);if(F)return F;let N=(async()=>{try{let H=await k();return await d(h,H,y),H}finally{s.delete(h)}})();return s.set(h,N),N}}}export{cn as a,Ce as b,ze as c,md as d,hd as e,gd as f,yd as g,wd as h,bd as i,kd as j,vd as k,Td as l,$d as m,_d as n,Ed as o,Sd as p,Ad as q,xd as r,Rd as s,Od as t,Pd as u,Cd as v,Md as w,jd as x,Dd as y,Nd as z,Ud as A,D as B,Ld as C,Id as D,Mt as E,Fd as F,Bd as G,Vd as H,ec as I,tc as J,Ua as K,Lr as L,ic as M,dc as N,cc as O,uc as P,lc as Q,fc as R,pc as S,yc as T,V as U,os as V,is as W,ds as X,So as Y,Ec as Z,xc as _,Rc as $,Oc as aa,Pc as ba,Cc as ca,Mc as da,jc as ea,Dc as fa,Fc as ga,Pi as ha,Au as ia,cd as ja,Bn as ka,Pu as la,Cu as ma};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.23.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
|