palbase 0.77.0 → 0.78.1
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/ai-sdk/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{34HGL5FX.js → 25KG2TVU.js} +1 -1
- package/dist/chunks/{GFBWGJW3.js → 2T3EX52E.js} +1 -1
- package/dist/chunks/{VOLGPAPR.js → 35KQJQ77.js} +2 -2
- package/dist/chunks/{ES24JS2D.js → 3TJFV35H.js} +2 -2
- package/dist/chunks/{FN5763FR.js → 3XF644A5.js} +2 -2
- package/dist/chunks/426QPZNS.js +13 -0
- package/dist/chunks/{U4VX7NKX.js → 4XE4HLPK.js} +2 -2
- package/dist/chunks/{WXT24CE5.js → 5KGMQFET.js} +1 -1
- package/dist/chunks/6Y4ICGZ7.js +2 -0
- package/dist/chunks/{G3PH5T6N.js → EUMY6SCM.js} +1 -1
- package/dist/chunks/{IZVBCAKH.js → FCCX2OTM.js} +2 -2
- package/dist/chunks/{RQJ4MX2H.js → IO5HB5B6.js} +2 -2
- package/dist/chunks/{AUOFL6RB.js → JY7YG3BO.js} +2 -2
- package/dist/chunks/{RRS7TQKX.js → L63FWRZX.js} +2 -2
- package/dist/chunks/{ONLXIZ6E.js → LONPNPNX.js} +2 -2
- package/dist/chunks/{DENZSXKJ.js → LXS7JHPJ.js} +2 -2
- package/dist/chunks/{QWXF6KWI.js → QWKOKJKM.js} +1 -1
- package/dist/chunks/{7RTPVUIH.js → RB4JQXKZ.js} +2 -2
- package/dist/chunks/{BDHVYVWT.js → ROV6TJZK.js} +1 -1
- package/dist/chunks/{KLK7HZZ7.js → TFPVJ3C3.js} +3 -3
- package/dist/chunks/{JOVXELK5.js → UUDOMSKW.js} +2 -2
- package/dist/chunks/{FE7ZBADH.js → VNUCKM7H.js} +1 -1
- package/dist/chunks/{ZZNNCI6A.js → WTFMJKDB.js} +2 -2
- package/dist/chunks/{F6OGRDZB.js → ZBTOHVML.js} +2 -2
- package/dist/chunks/{CYNLRAAW.js → ZIHVYOXE.js} +2 -2
- package/dist/cli.js +7 -3
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- 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/payments-ui.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 +7 -0
- package/types/backend/src/gateways.d.ts +2 -1
- package/types/cloud/src/generated/project.d.ts +1 -1
- package/types/internal/src/chat.d.ts +28 -0
- package/types/internal/src/modules/ai.d.ts +11 -7
- package/types/internal/src/modules/payments.d.ts +366 -24
- package/types/web/src/chat.d.ts +20 -0
- package/types/web/src/index.d.ts +1 -1
- package/dist/chunks/4M4GEXJS.js +0 -13
- package/dist/chunks/6WCN7VAZ.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as gr,d as yr,e as nn,f as wr,g as br}from"./JOVXELK5.js";import{a as Rt,c as ne,d as mr,e as hr,f as be,h as _,i as kr}from"./ONLXIZ6E.js";import{F as pr,a as cr,e as dt,g as St,h as ur,i as lr,j as At,k as xt,n as fr}from"./AUOFL6RB.js";import{a as Et,b as ir,n as dr}from"./34HGL5FX.js";import{b as ie}from"./VOLGPAPR.js";import"reflect-metadata";var rn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],vr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ot=/^\d+$/;function ka(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function Tr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${vr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ka(t[h],rn[h].lo,rn[h].hi);if(!g)return`${vr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var Ge=new Set(["webhooks","_palbase"]);function gd(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function ze(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var yd=ze("GET"),wd=ze("POST"),bd=ze("PUT"),kd=ze("PATCH"),vd=ze("DELETE"),Td=ze("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var $d=e=>pe("body",{schema:cn("Body",e)}),_d=e=>pe("query",{schema:cn("QueryParams",e)}),Ed=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Sd=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Ad=()=>pe("user"),xd=()=>pe("optionalUser"),Rd=()=>pe("req"),Od=()=>pe("requestId"),Pd=()=>pe("client"),Cd=()=>pe("attestedDevice");function Md(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function jd(){return e=>{de(e,on,()=>!0),se().add(e)}}function Dd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Er=/^[a-z]+(\.[a-z_]+)+$/,va=/^[a-z][a-z0-9-]{1,62}$/,un=e=>e.startsWith("file.");function Nd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!va.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!un(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ta=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function $r(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!Ta.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Ud(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=Tr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||$r(t.timeZone)!==void 0))throw new TypeError(`${n}: ${$r(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var _r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$a=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ld(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!$a.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!_r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${_r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&_a(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Me)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,Be,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function _a(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Id(){return[...se()].filter(e=>D(e,qe)!==void 0)}function qd(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Ar(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var Ea=720*3600;function Sa(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ea))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function Aa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Wd=Rt("Tasks",{async enqueue(e,t,n={}){return Sa(n),fn().enqueue(Aa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function xr(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await be.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var xa=1e4,Ra=36e5,Sr=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Sr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(xa*2**Math.min(t.attempt-1,16),Ra),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Sr&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Mt="/_palbase/test-user-templates",Oa=/^[a-z][a-z0-9_-]{0,63}$/;function Zd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Oa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function Rr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Or(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Pa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Pr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Pa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Cr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Mr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ca=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Ca(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function jr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Dr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ma=/^[a-z][a-z0-9-]{1,62}$/,Nr=1024,ja=new Set(["userId","uploadId","filename"]);function tc(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ma.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let s=Da(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function nc(){return pe("uploadedObject")}function Da(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ja.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Ur(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Ur(e){if(e===""||new TextEncoder().encode(e).byteLength>Nr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Na(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ua(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ua(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function Lr(e,t){let n=Na(e,t);return Ur(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Nr} bytes)`}}function Ir(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function qr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=jr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=La(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function La(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as Ia}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),Hr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},qa={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Hr),output:()=>structuredClone(Hr)}}},Jr=Symbol.for("palbase.backend.gatewayRefusal"),Br=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Jr,{value:!0})}},Ha=e=>typeof e=="object"&&e!==null&&e[Jr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,bn=e=>({id:e.id??"",...e.session?{session:e.session}:{}}),Ba=6e4,Ga=86400,Gr=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Fa=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ke=e=>new TextEncoder().encode(e).byteLength,kn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",$n=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Wa(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ke(e)>Se)return`a channel is ${Se} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=za.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Vr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} bytes at most`}function dc(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Wa(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&$n(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Ka(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||Fa.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,b]of Object.entries(d)){let k=Vr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!kn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,_n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:qa}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ba,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!We(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,je,()=>h),se().add(a)}}function Ka(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ga;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Gr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Gr} (a week)`);return n}var _n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ja={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ja[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Je,_n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var cc=ct("authorize"),uc=ct("first"),lc=ct("connect"),fc=ct("disconnect"),pc=ct("empty");function mc(e,t,n={}){let r=Vr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!kn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!kn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=de(s.constructor,Je,_n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Va(e){return D(e,je)}function Za(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Zr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Ya(e,t,n){let r=$n(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Zr(e,t):Qa(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Qa(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Xa=1e4,eo=1e3,to=100,En=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Wr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Yr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Va(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Wr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Wr(f.pattern),f.pattern);for(let[G,z]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([I,N])=>[`message ${I}`,N.fn])])if(typeof E[z]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${G} is ${z}, which is no method of it`);let L={cls:v,instance:E,g:f};n.set(f.pattern,L),r.set(v,L)}let o=new Map,d=new Set,l=new Set,h=new Tn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,L)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...L!==void 0?{conn_id:L}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,L,G){let z=T?.signal??AbortSignal.abort(),I=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:z,count:R,user:L,emit:(N,F)=>k(v,E,N,F,I,G),pipe:N=>B(N,E,I),owner:{hold(N){ne.exit(async()=>{try{await N(z)}catch(F){z.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:F})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Za(E,f)}}let K=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function J(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:L}=f,G={status:200,body:{subscribe:!1,publish:!1}};if(!L)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),G;let z=Fe(v.user);if(!z?.id)return G;let I=z.id;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return L[$n(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:G;let N=T.g.hooks.authorize;if(!N)return G;let F,Q;try{F=await t.run(z,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:bn(z),params:Object.freeze({...L})})),Q=no(F)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),G}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${ro(F)}, which is no grant (true, { read, write } or null); the join is refused`),G):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:vn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let L=await R.schema["~standard"].validate(Ia(v.payload??{}));if(L.issues)return{status:200,body:{ok:!1,reason:Kr(L.issues)}};let G=g(f.channel),z={...U(f.entry,f.channel,f.params,G,0,bn(T)),payload:L.value},I=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](z))}catch(Q){if(t.isOutage(Q))throw Q;return Ha(Q)?{status:200,body:{ok:!1,reason:vn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${Kr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let F;try{F=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return F===void 0?{status:200,body:{ok:!0}}:Ke(F)>zr?(_.error(`[palbase] ${I} returned an ack of ${Ke(F)} bytes, past ${zr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(F)}}}async function he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Fr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let L=T==="join"||T==="leave",G=L?Fe(v.user):void 0,z=L?v.connId:void 0;if(L&&(!G?.id||typeof z!="string"||z===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${f.channel}\0${typeof z=="string"?z:""}`;if(L&&d.has(I))return{status:204};if(l.has(I))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(I);try{let N=f.entry.g.hooks[Fr[T]],F;if(T==="empty"?(F=o.get(f.channel),b(f.channel,F)):F=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,F,R,G?bn(G):{id:""},T==="join"?z:void 0);try{await t.run(G,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return L&&(d.add(I),d.size>Xa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(I)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Zr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return En(E)?v==="authorize"?J(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:L,where:G}=ge(v,E);k(R,L,f,T,G)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let L=Ya(T.g.pattern,E??{},f);if("problem"in L)throw new TypeError(`${R}: ${L.problem}`);let G=ne.getStore()?.saying;if(G){G.push(()=>{t.revalidate(L).catch(z=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:z}))});return}await t.revalidate(L)},close(){for(let v of o.values())v.abort();o.clear()}}}function no(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!En(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function ro(e){return Array.isArray(e)?"an array":En(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var so=20,Dt=256;function Kr(e){let t="";for(let n of e.slice(0,so)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Dt)break}return vn(t,Dt)}function vn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var Tn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=eo?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,to);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Sn,createHmac as ao,createPublicKey as ts,timingSafeEqual as oo,verify as ns}from"node:crypto";function wc(e){let t=D(e,Be);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function rs(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=io(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(K,J)=>k[q](K,J)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
1
|
+
/*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as gr,d as yr,e as nn,f as wr,g as br}from"./UUDOMSKW.js";import{a as Rt,c as ne,d as mr,e as hr,f as be,h as _,i as kr}from"./LONPNPNX.js";import{F as pr,a as cr,e as dt,g as St,h as ur,i as lr,j as At,k as xt,n as fr}from"./JY7YG3BO.js";import{a as Et,b as ir,n as dr}from"./25KG2TVU.js";import{b as ie}from"./35KQJQ77.js";import"reflect-metadata";var rn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],vr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ot=/^\d+$/;function ka(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function Tr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${vr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ka(t[h],rn[h].lo,rn[h].hi);if(!g)return`${vr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var Ge=new Set(["webhooks","_palbase"]);function gd(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function ze(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var yd=ze("GET"),wd=ze("POST"),bd=ze("PUT"),kd=ze("PATCH"),vd=ze("DELETE"),Td=ze("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var $d=e=>pe("body",{schema:cn("Body",e)}),_d=e=>pe("query",{schema:cn("QueryParams",e)}),Ed=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Sd=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Ad=()=>pe("user"),xd=()=>pe("optionalUser"),Rd=()=>pe("req"),Od=()=>pe("requestId"),Pd=()=>pe("client"),Cd=()=>pe("attestedDevice");function Md(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function jd(){return e=>{de(e,on,()=>!0),se().add(e)}}function Dd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Er=/^[a-z]+(\.[a-z_]+)+$/,va=/^[a-z][a-z0-9-]{1,62}$/,un=e=>e.startsWith("file.");function Nd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!va.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!un(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ta=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function $r(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!Ta.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Ud(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=Tr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||$r(t.timeZone)!==void 0))throw new TypeError(`${n}: ${$r(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var _r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$a=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ld(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!$a.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!_r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${_r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&_a(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Me)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,Be,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function _a(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Id(){return[...se()].filter(e=>D(e,qe)!==void 0)}function qd(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Ar(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var Ea=720*3600;function Sa(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ea))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function Aa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Wd=Rt("Tasks",{async enqueue(e,t,n={}){return Sa(n),fn().enqueue(Aa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function xr(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await be.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var xa=1e4,Ra=36e5,Sr=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Sr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(xa*2**Math.min(t.attempt-1,16),Ra),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Sr&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Mt="/_palbase/test-user-templates",Oa=/^[a-z][a-z0-9_-]{0,63}$/;function Zd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Oa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function Rr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Or(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Pa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Pr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Pa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Cr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Mr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ca=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Ca(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function jr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Dr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ma=/^[a-z][a-z0-9-]{1,62}$/,Nr=1024,ja=new Set(["userId","uploadId","filename"]);function tc(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ma.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let s=Da(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function nc(){return pe("uploadedObject")}function Da(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ja.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Ur(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Ur(e){if(e===""||new TextEncoder().encode(e).byteLength>Nr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Na(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ua(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ua(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function Lr(e,t){let n=Na(e,t);return Ur(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Nr} bytes)`}}function Ir(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function qr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=jr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=La(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function La(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as Ia}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),Hr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},at:{type:"string",description:"When it happened, as the journal took it (a voice's end: when its record says it ended): RFC 3339 in UTC, to the microsecond, at a fixed width \u2014 2026-11-28T06:36:15.321369Z \u2014 so its text sorts as its time: kept as this text, never parsed and written again. Absent for text the channel tells ahead of the journal."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},qa={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, at?, data}"}]},jsonSchema:{input:()=>structuredClone(Hr),output:()=>structuredClone(Hr)}}},Jr=Symbol.for("palbase.backend.gatewayRefusal"),Br=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Jr,{value:!0})}},Ha=e=>typeof e=="object"&&e!==null&&e[Jr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,bn=e=>({id:e.id??"",...e.session?{session:e.session}:{}}),Ba=6e4,Ga=86400,Gr=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Fa=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ke=e=>new TextEncoder().encode(e).byteLength,kn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",$n=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Wa(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ke(e)>Se)return`a channel is ${Se} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=za.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Vr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} bytes at most`}function dc(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Wa(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&$n(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Ka(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||Fa.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,b]of Object.entries(d)){let k=Vr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!kn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,_n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:qa}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ba,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!We(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,je,()=>h),se().add(a)}}function Ka(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ga;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Gr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Gr} (a week)`);return n}var _n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ja={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ja[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Je,_n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var cc=ct("authorize"),uc=ct("first"),lc=ct("connect"),fc=ct("disconnect"),pc=ct("empty");function mc(e,t,n={}){let r=Vr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!kn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!kn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=de(s.constructor,Je,_n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Va(e){return D(e,je)}function Za(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Zr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Ya(e,t,n){let r=$n(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Zr(e,t):Qa(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Qa(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Xa=1e4,eo=1e3,to=100,En=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Wr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Yr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Va(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Wr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Wr(f.pattern),f.pattern);for(let[G,z]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([I,N])=>[`message ${I}`,N.fn])])if(typeof E[z]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${G} is ${z}, which is no method of it`);let L={cls:v,instance:E,g:f};n.set(f.pattern,L),r.set(v,L)}let o=new Map,d=new Set,l=new Set,h=new Tn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,L)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...L!==void 0?{conn_id:L}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,L,G){let z=T?.signal??AbortSignal.abort(),I=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:z,count:R,user:L,emit:(N,F)=>k(v,E,N,F,I,G),pipe:N=>B(N,E,I),owner:{hold(N){ne.exit(async()=>{try{await N(z)}catch(F){z.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:F})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Za(E,f)}}let K=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function J(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:L}=f,G={status:200,body:{subscribe:!1,publish:!1}};if(!L)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),G;let z=Fe(v.user);if(!z?.id)return G;let I=z.id;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return L[$n(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:G;let N=T.g.hooks.authorize;if(!N)return G;let F,Q;try{F=await t.run(z,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:bn(z),params:Object.freeze({...L})})),Q=no(F)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),G}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${ro(F)}, which is no grant (true, { read, write } or null); the join is refused`),G):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:vn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let L=await R.schema["~standard"].validate(Ia(v.payload??{}));if(L.issues)return{status:200,body:{ok:!1,reason:Kr(L.issues)}};let G=g(f.channel),z={...U(f.entry,f.channel,f.params,G,0,bn(T)),payload:L.value},I=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](z))}catch(Q){if(t.isOutage(Q))throw Q;return Ha(Q)?{status:200,body:{ok:!1,reason:vn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${Kr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let F;try{F=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return F===void 0?{status:200,body:{ok:!0}}:Ke(F)>zr?(_.error(`[palbase] ${I} returned an ack of ${Ke(F)} bytes, past ${zr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(F)}}}async function he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Fr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let L=T==="join"||T==="leave",G=L?Fe(v.user):void 0,z=L?v.connId:void 0;if(L&&(!G?.id||typeof z!="string"||z===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${f.channel}\0${typeof z=="string"?z:""}`;if(L&&d.has(I))return{status:204};if(l.has(I))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(I);try{let N=f.entry.g.hooks[Fr[T]],F;if(T==="empty"?(F=o.get(f.channel),b(f.channel,F)):F=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,F,R,G?bn(G):{id:""},T==="join"?z:void 0);try{await t.run(G,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return L&&(d.add(I),d.size>Xa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(I)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Zr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return En(E)?v==="authorize"?J(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:L,where:G}=ge(v,E);k(R,L,f,T,G)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let L=Ya(T.g.pattern,E??{},f);if("problem"in L)throw new TypeError(`${R}: ${L.problem}`);let G=ne.getStore()?.saying;if(G){G.push(()=>{t.revalidate(L).catch(z=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:z}))});return}await t.revalidate(L)},close(){for(let v of o.values())v.abort();o.clear()}}}function no(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!En(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function ro(e){return Array.isArray(e)?"an array":En(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var so=20,Dt=256;function Kr(e){let t="";for(let n of e.slice(0,so)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Dt)break}return vn(t,Dt)}function vn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var Tn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=eo?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,to);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Sn,createHmac as ao,createPublicKey as ts,timingSafeEqual as oo,verify as ns}from"node:crypto";function wc(e){let t=D(e,Be);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function rs(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=io(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(K,J)=>k[q](K,J)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
3
|
- ${a.join(`
|
|
4
4
|
- `)}`);return s}function ss(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Qr=1024*Ve;function io(e,t){if(e.signature)return De(void 0,e.signature.header,1/0,bo(e.signature,t));switch(e.provider){case"stripe":return De("stripe","stripe-signature",512*Ve,lo(t));case"github":return De("github","x-hub-signature-256",25*Qr,fo(t));case"slack":return De("slack","x-slack-signature",64*Ve,po(t));case"discord":return De("discord","x-signature-ed25519",64*Ve,mo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:go(t)};case"sendgrid":return De("sendgrid","x-twilio-email-event-webhook-signature",Qr,yo(t));case"livekit":return De("livekit","authorization",512*Ve,wo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function De(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??as(e,s)}}function as(e,t){let n=An(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:os(e,t.headers,r),event:r,...co(e,t,r)}}function os(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Ne(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=cs(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return Ne(n,"EventType");case"livekit":return Ne(n,"event");default:return Ne(n,"type")}}function co(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Ne(n,"id"));case"slack":return r(Ne(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${is(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Ne(s,"sg_event_id")||void 0)}:{};default:return{}}}var uo=300;function lo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let l of r.split(",")){let h=l.indexOf("=");if(h<=0)continue;let g=l.slice(0,h).trim(),b=l.slice(h+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=b}else if(g==="v1"){let k=me(b,"hex");if(!k)return"malformed_signature";a.push(k)}}let o=ut(s);if(o===void 0||a.length===0)return"malformed_signature";if(lt(o,n))return"stale_timestamp";let d=Ze("sha256",e,`${s}.`,t.body);return a.some(l=>Ae(l,d))?void 0:"signature_mismatch"}}function fo(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?Ae(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function po(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ut(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":lt(a,n)?"stale_timestamp":Ae(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function mo(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=ts({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ut(o),l=me(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":ns(null,ds(o,r.body),n,l)?void 0:"signature_mismatch"}}var ho=1e3;function go(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!Ae(Buffer.from(a.toLowerCase()),Buffer.from(Sn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let B=1;for(let K of t.body)if(K===38&&++B>ho)return"malformed_signature";let U=new Map;for(let[K,J]of new URLSearchParams(An(t.body))){let le=U.get(K);le||U.set(K,le=new Set),le.add(J)}let q=[];for(let K of[...U.keys()].sort()){let J=[...U.get(K)].sort();for(let le of J)o+=K+le;q.push([K,J.length===1?J[0]:J])}d=Object.fromEntries(q)}let l=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![h,g].some(B=>Ae(r,Ze("sha1",e,B,o))))return"signature_mismatch";let b=t.headers.get("i-twilio-idempotency-token"),k=b?{id:`${b}:${is(`${h}
|
|
5
5
|
${o}`)}`}:{};return d?{type:os("twilio",t.headers,d),event:d,...k}:{...as("twilio",t),...k}}}function yo(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=ts({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=ut(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":lt(o,r)?"stale_timestamp":ns("sha256",ds(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Xr=60;function wo(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=es(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Ae(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=es(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Xr||typeof d.nbf=="number"&&n<d.nbf-Xr)return"stale_timestamp";let l=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return l&&Ae(l,Sn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function bo(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ut(d);if(h===void 0)return"malformed_signature";if(lt(h,a))return"stale_timestamp"}let l=me(o.trim(),e.encoding);return l?Ae(l,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var ko=new TextEncoder;function Ze(e,t,...n){let r=ao(e,t);for(let s of n)r.update(s);return r.digest()}function is(e){return Sn("sha256").update(e).digest("hex")}function ds(e,t){return Buffer.concat([ko.encode(e),t])}function Ae(e,t){return e.byteLength===t.byteLength&&oo(e,t)}var vo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return vo[t].test(e)?Buffer.from(e,t):void 0}function ut(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function lt(e,t){return Math.abs(t-e)>uo}function An(e){return new TextDecoder().decode(e)}function es(e){if(e)try{return JSON.parse(An(e))}catch{return}}function cs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,t){let n=cs(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var Y=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as C}from"./QWXF6KWI.js";import{a as ue}from"./BDHVYVWT.js";import{a as D,b as j,c as U,d as I,e as K,f as q,g as F,h as $,i as N,j as V,k as J,l as z,m as Y,n as G,o as X,p as Z,q as Q,r as ee,s as te}from"./ES24JS2D.js";import{a as w,c as oe,d as se,e as ie,f as ae,h as ce,i as pe,j as M,k as le,l as de,o as A}from"./34HGL5FX.js";import{a as ne,b as re}from"./FN5763FR.js";import{b as T,d as b}from"./VOLGPAPR.js";var h=class extends Error{status=400;code;data;constructor(e,n,r={}){super(n),this.name="TransitRefusal",this.code=e,this.data=r}},Le=6e4,Be=1e3;function O(t){return/^t[1-9][0-9]{0,5}$/.test(t)?Number(t.slice(1)):0}var S=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(n=>new Promise(r=>setTimeout(r,n)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Le),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let n=this.now();try{let r=await this.opts.fetch(e),o=new Map;for(let s of r.keys){let i=se(s.key);o.set(s.id,{privateKey:i,publicKey:this.keys.get(s.id)?.publicKey??await ie(i)})}this.keys=o,this.order=r.keys.map(s=>s.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=n}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(O),...[...this.retired].map(O))}async key(e){let n=this.now();for(;O(e)>this.newest()&&this.heldFrom<n;){let s=this.fetchedAt+Be-this.now();if(s>0){await this.sleep(s);continue}await this.refresh()}let r=this.keys.get(e),o=this.current();if(this.retired.has(e))throw new h("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:o});if(r===void 0)throw new h("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:o});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new h("encryption_required",`this route carries encrypted fields: the request names its key in ${w}`,{field:w,current:this.current()});let n;try{n=ce(e.header).kid}catch{throw new h("encryption_unopenable",`${w} is not one`,{field:w})}let r=await this.key(n),o;try{o=ae(this.projectId,e.method,e.path,e.params??[])}catch{throw new h("encryption_unopenable","the request's path holds a value no key is sealed for",{field:w})}try{return new R(n,await pe(e.header,r.privateKey,r.publicKey,o))}catch(s){throw s instanceof oe?new h("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:w}):s}}},R=class{kid;key;constructor(e,n){this.kid=e,this.key=n}async open(e,n,r){return A(e,n,r,async(o,s)=>{if(!le(s))throw new h("encryption_required",`${o} is an encrypted field: it came plain`,{field:o});try{return await de(this.key,o,s)}catch{throw new h("encryption_unopenable",`${o} does not open: changed, moved from another field, or another request's`,{field:o})}})}async seal(e,n){return A(e,"/response",n,(r,o)=>M(this.key,r,o))}sealField(e,n){return M(this.key,e,n)}};var De=/^pb_[a-z0-9]+_s/;function H(t){if(ue())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof t.secretKey!="string"||!De.test(t.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=re(b({baseUrl:t.url,credentials:{secretKey:t.secretKey},fetch:t.fetch,solveProofOfWork:t.solveProofOfWork??!1}),t.retry??ne),n=Z.client(e);return{ai:D.client(e),analytics:j.client(e),auth:U.client(e),cache:I.client(e),calls:K.client(e),fields:new C({fetch:async r=>(await n.getFieldKeys({signal:r})).data}),flags:$.client(e),iap:N.client(e),machines:J.client(e),messaging:z.client(e),notify:Y.client(e),payments:G.client(e),campaigns:q.client(e),commerce:F.client(e),journeys:V.client(e),realtime:X.client(e),secrets:n,storage:Q.client(e),stores:ee.client(e),workspaces:te.client(e),transit:new S({fetch:async r=>(await n.getTransitKeys({signal:r})).data}),transport:e,url:new URL(t.url).origin}}var u=class extends Error{code;constructor(e,n){super(n),this.name="WebhookSignatureError",this.code=e}},Ue=300,Ie=/^[0-9]{1,12}$/,Ke=/^[0-9a-f]{64}$/,ye=8,qe=/^whsec_[0-9A-Za-z]{32,}$/,Fe=1024*1024;async function me(t){if(typeof t.secret!="string"||!qe.test(t.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await he(t);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(ge(t.body)))}catch{throw new u("invalid_body","the signed body is not JSON")}if(!Ye(e))throw new u("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function he(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the key the request was signed with");let e=ge(t.body),{t:n,v1:r}=fe(t),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=new Uint8Array(await crypto.subtle.sign("HMAC",o,ze(new TextEncoder().encode(`${n}.`),e))),i=!1;for(let p of r)Je(s,Ve(p))&&(i=!0);if(!i)throw new u("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function fe(t){let e=t.toleranceSeconds??Ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(t.toleranceSeconds)})`);let n=(t.now??Date.now)();if(!Number.isFinite(n))throw new TypeError(`now() returns epoch milliseconds (got ${String(n)})`);let r=t.signature;if(typeof r!="string"||r.trim()==="")throw new u("missing_signature","the request carries no Palbase-Signature header");let o,s=[];for(let i of r.split(",")){let p=i.indexOf("=");if(p<=0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=i.slice(0,p).trim(),a=i.slice(p+1).trim();if(c==="t"){if(o!==void 0||!Ie.test(a))throw new u("malformed_signature","Palbase-Signature carries one t, in unix seconds");o=a}else if(c==="v1"){if(!Ke.test(a))throw new u("malformed_signature","a v1 is 64 lowercase hex characters");if(s.length===ye)throw new u("malformed_signature",`Palbase-Signature carries at most ${ye} v1`);s.push(a)}}if(o===void 0||s.length===0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(n/1e3-Number(o))>e)throw new u("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:o,v1:s}}async function $e(t,e,n={}){let r=await Ne(t,n.maxBytes??Fe);return me({toleranceSeconds:n.toleranceSeconds,now:n.now,secret:e,signature:t.headers.get("palbase-signature"),body:r})}async function Ne(t,e){let n=()=>new u("body_too_large",`the body is larger than ${e} bytes`),r=Number(t.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw n();if(!t.body)return new Uint8Array(0);let o=t.body.getReader(),s=[],i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;if(i+=l.byteLength,i>e)throw await o.cancel().catch(()=>{}),n();s.push(l)}let p=new Uint8Array(i),c=0;for(let a of s)p.set(a,c),c+=a.byteLength;return p}function ge(t){if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Ve(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function Je(t,e){if(t.byteLength!==e.byteLength)return!1;let n=0;for(let r=0;r<t.byteLength;r++)n|=t[r]^e[r];return n===0}function ze(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}function Ye(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var we=60,Ge=60,Xe=8*1024,Ze=1e5;function W(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ve(t){let e=t.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let n=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function ke(t){let e=ve(t);if(e)try{let n=JSON.parse(new TextDecoder().decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}catch{return}}var x=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ze){this.max=e}spend(e,n){if(n>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,n);let o=r.get(e.jti);if(o!==void 0&&o>n)throw new d("proof","the DPoP proof is not taken: it was used before");o!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(n),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,n,r){for(let[o,s]of n){if(s>r)break;n.delete(o),this.held--}n.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,o]of this.byKey){for(let[s,i]of o)i>e||(o.delete(s),this.held--);o.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let n=[...this.byKey].sort((r,o)=>o[1].size-r[1].size);for(let[r,o]of n){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=o.size}}};async function Qe(t,e){let n=`{"crv":"P-256","kty":"EC","x":"${t}","y":"${e}"}`;return W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)))}function Se(t){try{let e=new URL(t);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function be(t,e,n,r){let o=We=>{throw new d("proof",`the DPoP proof is not taken: ${We}`)},s=n.proof;if(!s)return o("there is none (a DPoP-bound token comes with a DPoP header)");if(s.length>Xe)return o("it is too long");let i=s.split(".");if(i.length!==3)return o("it is not a JWS of three parts");let p=ke(i[0]),c=ke(i[1]);if(!p||!c)return o("its header or claims are not base64url JSON");if(p.typ!=="dpop+jwt")return o("its typ is not dpop+jwt");if(p.alg!=="ES256")return o(`it is signed with ${String(p.alg)}; only ES256 is taken`);let a=p.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return o("its header carries no P-256 public key");if("d"in a)return o("its header carries a private key");if(await Qe(a.x,a.y)!==e)return o("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return o("its key is not a P-256 point")}let y=ve(i[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${i[0]}.${i[1]}`)).catch(()=>!1))return o("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==n.method.toUpperCase())return o(`it is for ${String(c.htm)}, not ${n.method}`);let m=typeof c.htu=="string"?Se(c.htu):void 0,f=Se(n.url);if(!m||!f||m!==f)return o(`it is for ${String(c.htu)}, not ${f??n.url}`);let v=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-v)>we)return o("it was not made within a minute of now");let Oe=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)));if(c.ath!==Oe)return o("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return o("it has no jti (or one longer than 256)");let He=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:He,until:(c.iat+we+Ge)*1e3+1}}var d=class extends Error{reason;constructor(e,n){super(n),this.name="TokenError",this.reason=e}},k=class extends Error{constructor(e,n){super(e,n),this.name="AuthUnavailable"}},et=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function tt(t){return async e=>{let n=b({baseUrl:t.url,credentials:{secretKey:t.secretKey,accessToken:()=>e},fetch:t.fetch});try{return await n.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!et.has(r.code))return!1;throw new k("a session's standing could not be told",{cause:r})}}}var L={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},Re=60,nt=16*1024,rt=10*6e4,ot=5e4,xe=t=>typeof t=="string"&&Object.hasOwn(L,t),B=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new x;constructor(e){let n=new URL(e.issuer);if(n.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=n.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,n){if(typeof e!="string"||e.length===0||e.length>nt)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let o=Ee(r[0]),s=Ee(r[1]);if(!o||!s)throw new d("malformed","the token header or claims are not base64url JSON");let i=o.alg;if(!xe(i))throw new d("algorithm",`the token is signed with ${String(i)}; only ES256 and PS256 are taken`);let p=o.kid;if(typeof p!="string"||p==="")throw new d("malformed","the token header names no kid");let c=await this.key(p);if(!c)throw new d("unknown_key",`no key ${p} in the project's key set`);if(c.alg!==i)throw new d("algorithm",`key ${p} is ${c.alg}, the token says ${i}`);let a=Pe(r[2]);if(!a)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(L[c.alg].verify,c.key,a,l).catch(()=>!1))throw new d("signature","the signature does not verify");let g=this.check(s),m=s.cnf,f;if(m!==void 0){if(!n)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof m!="object"||m===null||typeof m.jkt!="string"||m.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");f=await be(e,m.jkt,n,this.now())}else if(n)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,g.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return f&&this.seenProofs.spend(f,this.now()),g}async verifyRequest(e){let n=e.headers instanceof Headers?e.headers:it(e.headers),r=n.get("authorization")??"";if(r==="")return null;let o=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!o)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let s=o[1].toLowerCase()==="dpop",i=new URL(e.url,`http://${n.get("host")??"localhost"}`);return this.verify(o[2],s?{proof:n.get("dpop"),method:e.method,url:_e(n,i)}:void 0)}async stands(e,n){let r=this.now(),o=this.standings.get(n);if(o&&r<o.until)return o.live;let s=this.asking.get(n);s||(s=this.standing(e,n).finally(()=>this.asking.delete(n)),this.asking.set(n,s));let i;try{i=await s}catch(c){let a=this.standings.get(n),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new k("a session's standing cannot be read now",{cause:c})}let p=this.now();return this.standings.delete(n),this.standings.set(n,{live:i,at:p,until:p+this.standingTtlMs}),this.standings.size>ot&&this.standings.delete(this.standings.keys().next().value),i}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+Re<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-Re>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let o=e.custom_claims;if(o!==void 0&&(typeof o!="object"||o===null||o.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let n=this.now();if(n>=this.keysUntil){let o=this.keys.size>0&&n<this.keysUntil+rt;if(this.lastFailure!==void 0&&n-this.lastFetch<this.refetchIntervalMs){if(!o)throw new k("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(s){if(!o)throw s}}let r=this.keys.get(e);return!r&&n-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,n;try{if(n=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!n.ok)throw new Error(`the project's key set answered ${n.status}`);e=await n.json()}catch(s){throw this.lastFailure=s,new k("the project's key set cannot be read now",{cause:s})}this.lastFailure=void 0;let r=new Map;for(let s of Array.isArray(e.keys)?e.keys:[]){let i=s.alg;if(typeof s.kid!="string"||!xe(i))continue;let p=L[i];if(s.kty!==p.kty||s.use!==void 0&&s.use!=="sig")continue;let{d:c,...a}=s;try{r.set(s.kid,{alg:i,key:await crypto.subtle.importKey("jwk",a,p.import,!1,["verify"])})}catch{}}this.keys=r;let o=at(n.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(o,this.refetchIntervalMs),this.maxKeyAgeMs)}};function _e(t,e){let n=t.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=n==="https"||n==="http"?n:e.protocol.slice(0,-1),o=t.get("host")??e.host;return st.test(o)?`${r}://${o}${e.pathname}`:""}var st=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function it(t){let e=new Headers;for(let[n,r]of Object.entries(t))if(r!==void 0)for(let o of Array.isArray(r)?r:[r])e.append(n,o);return e}function at(t){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(t??"");return e?Number(e[1])*1e3:void 0}function Pe(t){if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)return null;let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(t.length/4)*4,"=")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Ee(t){let e=Pe(t);if(!e)return null;try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}catch{return null}}function ct(t,e,n=Date.now()){let r=Object.hasOwn(t.entitlements,e)?t.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof n=="number"?n:n.getTime()):!1}var E=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function pt(t,e,n,r){let{idempotencyKey:o,amount:s,ttlSeconds:i,metadata:p}=n;if(typeof o!="string"||o==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:s,...n.credits!==void 0?{credits:n.credits}:{limit:n.limit},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{metadata:p}:{}},a=(await t.iap.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":o},body:c})).data;if(a.status!=="held")throw new E(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(g){throw await t.iap.releaseSpend({path:l}).catch(()=>{}),g}return await t.iap.commitSpend({path:l}),y}var lt=new Set(["provider_unavailable","authentication_required","three_ds_failed"]);function dt(t){return t!==void 0&<.has(t)}function ut(t,e){return{[Te]:!0,commitAmount:t,value:e}}var Te=Symbol("palbase.payments.settleWalletHold");function yt(t){return typeof t=="object"&&t!==null&&Te in t}var _=class extends Error{hold;constructor(e){super(`wallet hold ${JSON.stringify(e.id)} is already ${e.status}: the work is not run again (use a new Idempotency-Key for a new hold)`),this.name="WalletHoldSettled",this.hold=e}};async function mt(t,e,n){let{idempotencyKey:r,walletKey:o,amount:s,ttlSeconds:i,reference:p,metadata:c}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError("idempotencyKey is required for withWalletHold so retries never reserve funds twice");if(!Number.isInteger(s)||s<=0)throw new TypeError("amount must be a positive integer in minor units");let a={wallet_key:o,amount:s,...e.customerId!==void 0?{customer_id:e.customerId}:{spend_token:e.spendToken},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{reference:p}:{},...c!==void 0?{metadata:c}:{}},l=(await t.payments.createWalletHold({headers:{"Idempotency-Key":r},body:a})).data;if(l.status!=="held")throw new _(l);let y;try{y=await n(l)}catch(g){throw await t.payments.releaseWalletHold({path:{hold_id:l.id}}).catch(()=>{}),g}return yt(y)?(y.commitAmount<=0?await t.payments.releaseWalletHold({path:{hold_id:l.id}}):await t.payments.commitWalletHold({path:{hold_id:l.id},body:{amount:y.commitAmount}}),y.value):(await t.payments.commitWalletHold({path:{hold_id:l.id}}),y)}function ht(t){return t.type.startsWith("payments.")}function ft(t){return t.type.startsWith("commerce.")}function gt(t){return t.type.startsWith("promotions.")}var wt=300,kt=/^[0-9]{1,12}$/;function St(t){return typeof t=="string"?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function vt(t){if(t.startsWith("whsec_")){let e=t.slice(6);try{let n=atob(e),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}catch{}}return new TextEncoder().encode(t)}function bt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Rt(t){try{let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}catch{return null}}async function Me(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the commerce hook signing secret (whsec_\u2026)");let e=t.webhookId?.trim()??"",n=t.webhookTimestamp?.trim()??"",r=t.webhookSignature?.trim()??"";if(!e||!n||!r)throw new u("missing_signature","webhook-id, webhook-timestamp, and webhook-signature headers are required");if(!kt.test(n))throw new u("malformed_signature","webhook-timestamp must be unix seconds");let o=t.toleranceSeconds??wt,s=Math.floor((t.now?.()??Date.now())/1e3);if(Math.abs(s-Number(n))>o)throw new u("stale_timestamp",`webhook-timestamp ${n} is outside tolerance (${o}s)`);let i=St(t.body),p=new TextEncoder().encode(`${e}.${n}.`),c=new Uint8Array(p.length+i.length);c.set(p,0),c.set(i,p.length);let a=vt(t.secret),l=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),y=await crypto.subtle.importKey("raw",l,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),g=new Uint8Array(await crypto.subtle.sign("HMAC",y,c)),m=!1;for(let f of r.split(/\s+/)){if(!f.startsWith("v1,"))continue;let v=Rt(f.slice(3));if(v&&bt(g,v)){m=!0;break}}if(!m)throw new u("signature_mismatch","no v1 signature in webhook-signature matches the payload")}function Ae(t){return async e=>{let n=new Uint8Array(await e.arrayBuffer()),r=e.headers.get("webhook-id")??"";try{await Me({secret:t.secret,webhookId:r,webhookTimestamp:e.headers.get("webhook-timestamp"),webhookSignature:e.headers.get("webhook-signature"),body:n,toleranceSeconds:t.toleranceSeconds,now:t.now})}catch(i){let p=i instanceof u?i.code:"signature_mismatch",c=i instanceof Error?i.message:"invalid hook signature";return new Response(JSON.stringify({error:p,error_description:c}),{status:401,headers:{"content-type":"application/json"}})}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return new Response(JSON.stringify({error:"invalid_body",error_description:"hook body is not valid JSON"}),{status:400,headers:{"content-type":"application/json"}})}let s=await t.handle({hookPoint:e.headers.get("x-palbase-hook-point")??"",webhookId:r,payload:o,request:e});return new Response(JSON.stringify(s),{status:200,headers:{"content-type":"application/json"}})}}var P=class extends Error{hookPoint;constructor(e){super(`expected x-palbase-hook-point "discovery.rank", got "${e}"`),this.hookPoint=e}};function xt(t){let e=Ae({secret:t.secret,toleranceSeconds:t.toleranceSeconds,now:t.now,handle:n=>{if(n.hookPoint!==""&&n.hookPoint!=="discovery.rank")throw new P(n.hookPoint);return t.handle(n)}});return async n=>{try{return await e(n)}catch(r){if(r instanceof P)return new Response(JSON.stringify({error:"invalid_hook_point",error_description:r.message}),{status:400,headers:{"content-type":"application/json"}});throw r}}}function Et(t){return t.type.startsWith("campaigns.")}function _t(t){return t.type.startsWith("journey.")}async function*Pt(t){let e,n=new Set;do{let r=(await t(e)).data;yield r;let o=r.next_cursor??void 0;if(o!==void 0&&n.has(o))throw new Error(`the listing answered a cursor it had answered before (${o})`);o!==void 0&&n.add(o),e=o}while(e)}var Tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Mt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function Ce(t){return!Tt.test(t)||Mt.test(t)||/_PROXY$/i.test(t)}var At=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|CONTRACT_ENTRY|WEB_ORIGINS|SECRETS|DB_[A-Z0-9_]+))$/;function Ct(t){return At.test(t)}async function Ot(t={}){let e=t.env??process.env,n=e.PALBASE_SECRETS;if(n===void 0||n==="")return;if(n==="production")throw new TypeError("PALBASE_SECRETS=production: a production secret's value is never read back \u2014 only the machines that start with it are given it. Run here with PALBASE_SECRETS=development (palbase env:pull writes it), and set a value for this computer with palbase secrets:set NAME --dev");if(n!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${n}`);let r=t.url??e.PALBASE_URL??"",o=t.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||o==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let s=H({url:new URL(r).origin,secretKey:o,fetch:t.fetch}),{data:i}=await s.secrets.getEnvironmentValues({path:{environment:n}}),p=[],c=[],a=[];for(let[l,y]of Object.entries(i.values)){if(Ce(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,p.push(l)}return{set:n,loaded:p.sort(),kept:c.sort(),refused:a.sort()}}export{h as a,S as b,R as c,H as d,u as e,me as f,he as g,fe as h,$e as i,d as j,k,tt as l,B as m,_e as n,ct as o,E as p,pt as q,dt as r,ut as s,_ as t,mt as u,ht as v,ft as w,gt as x,Me as y,Ae as z,xt as A,Et as B,_t as C,Pt as D,Ce as E,Ct as F,Ot as G};
|
|
1
|
+
/*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as C}from"./QWKOKJKM.js";import{a as ue}from"./ROV6TJZK.js";import{a as D,b as j,c as U,d as I,e as K,f as q,g as F,h as $,i as N,j as V,k as J,l as z,m as Y,n as G,o as X,p as Z,q as Q,r as ee,s as te}from"./3TJFV35H.js";import{a as w,c as oe,d as se,e as ie,f as ae,h as ce,i as pe,j as M,k as le,l as de,o as A}from"./25KG2TVU.js";import{a as ne,b as re}from"./3XF644A5.js";import{b as T,d as b}from"./35KQJQ77.js";var h=class extends Error{status=400;code;data;constructor(e,n,r={}){super(n),this.name="TransitRefusal",this.code=e,this.data=r}},Le=6e4,Be=1e3;function O(t){return/^t[1-9][0-9]{0,5}$/.test(t)?Number(t.slice(1)):0}var S=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(n=>new Promise(r=>setTimeout(r,n)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Le),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let n=this.now();try{let r=await this.opts.fetch(e),o=new Map;for(let s of r.keys){let i=se(s.key);o.set(s.id,{privateKey:i,publicKey:this.keys.get(s.id)?.publicKey??await ie(i)})}this.keys=o,this.order=r.keys.map(s=>s.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=n}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(O),...[...this.retired].map(O))}async key(e){let n=this.now();for(;O(e)>this.newest()&&this.heldFrom<n;){let s=this.fetchedAt+Be-this.now();if(s>0){await this.sleep(s);continue}await this.refresh()}let r=this.keys.get(e),o=this.current();if(this.retired.has(e))throw new h("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:o});if(r===void 0)throw new h("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:o});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new h("encryption_required",`this route carries encrypted fields: the request names its key in ${w}`,{field:w,current:this.current()});let n;try{n=ce(e.header).kid}catch{throw new h("encryption_unopenable",`${w} is not one`,{field:w})}let r=await this.key(n),o;try{o=ae(this.projectId,e.method,e.path,e.params??[])}catch{throw new h("encryption_unopenable","the request's path holds a value no key is sealed for",{field:w})}try{return new R(n,await pe(e.header,r.privateKey,r.publicKey,o))}catch(s){throw s instanceof oe?new h("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:w}):s}}},R=class{kid;key;constructor(e,n){this.kid=e,this.key=n}async open(e,n,r){return A(e,n,r,async(o,s)=>{if(!le(s))throw new h("encryption_required",`${o} is an encrypted field: it came plain`,{field:o});try{return await de(this.key,o,s)}catch{throw new h("encryption_unopenable",`${o} does not open: changed, moved from another field, or another request's`,{field:o})}})}async seal(e,n){return A(e,"/response",n,(r,o)=>M(this.key,r,o))}sealField(e,n){return M(this.key,e,n)}};var De=/^pb_[a-z0-9]+_s/;function H(t){if(ue())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof t.secretKey!="string"||!De.test(t.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=re(b({baseUrl:t.url,credentials:{secretKey:t.secretKey},fetch:t.fetch,solveProofOfWork:t.solveProofOfWork??!1}),t.retry??ne),n=Z.client(e);return{ai:D.client(e),analytics:j.client(e),auth:U.client(e),cache:I.client(e),calls:K.client(e),fields:new C({fetch:async r=>(await n.getFieldKeys({signal:r})).data}),flags:$.client(e),iap:N.client(e),machines:J.client(e),messaging:z.client(e),notify:Y.client(e),payments:G.client(e),campaigns:q.client(e),commerce:F.client(e),journeys:V.client(e),realtime:X.client(e),secrets:n,storage:Q.client(e),stores:ee.client(e),workspaces:te.client(e),transit:new S({fetch:async r=>(await n.getTransitKeys({signal:r})).data}),transport:e,url:new URL(t.url).origin}}var u=class extends Error{code;constructor(e,n){super(n),this.name="WebhookSignatureError",this.code=e}},Ue=300,Ie=/^[0-9]{1,12}$/,Ke=/^[0-9a-f]{64}$/,ye=8,qe=/^whsec_[0-9A-Za-z]{32,}$/,Fe=1024*1024;async function me(t){if(typeof t.secret!="string"||!qe.test(t.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await he(t);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(ge(t.body)))}catch{throw new u("invalid_body","the signed body is not JSON")}if(!Ye(e))throw new u("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function he(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the key the request was signed with");let e=ge(t.body),{t:n,v1:r}=fe(t),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=new Uint8Array(await crypto.subtle.sign("HMAC",o,ze(new TextEncoder().encode(`${n}.`),e))),i=!1;for(let p of r)Je(s,Ve(p))&&(i=!0);if(!i)throw new u("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function fe(t){let e=t.toleranceSeconds??Ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(t.toleranceSeconds)})`);let n=(t.now??Date.now)();if(!Number.isFinite(n))throw new TypeError(`now() returns epoch milliseconds (got ${String(n)})`);let r=t.signature;if(typeof r!="string"||r.trim()==="")throw new u("missing_signature","the request carries no Palbase-Signature header");let o,s=[];for(let i of r.split(",")){let p=i.indexOf("=");if(p<=0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=i.slice(0,p).trim(),a=i.slice(p+1).trim();if(c==="t"){if(o!==void 0||!Ie.test(a))throw new u("malformed_signature","Palbase-Signature carries one t, in unix seconds");o=a}else if(c==="v1"){if(!Ke.test(a))throw new u("malformed_signature","a v1 is 64 lowercase hex characters");if(s.length===ye)throw new u("malformed_signature",`Palbase-Signature carries at most ${ye} v1`);s.push(a)}}if(o===void 0||s.length===0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(n/1e3-Number(o))>e)throw new u("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:o,v1:s}}async function $e(t,e,n={}){let r=await Ne(t,n.maxBytes??Fe);return me({toleranceSeconds:n.toleranceSeconds,now:n.now,secret:e,signature:t.headers.get("palbase-signature"),body:r})}async function Ne(t,e){let n=()=>new u("body_too_large",`the body is larger than ${e} bytes`),r=Number(t.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw n();if(!t.body)return new Uint8Array(0);let o=t.body.getReader(),s=[],i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;if(i+=l.byteLength,i>e)throw await o.cancel().catch(()=>{}),n();s.push(l)}let p=new Uint8Array(i),c=0;for(let a of s)p.set(a,c),c+=a.byteLength;return p}function ge(t){if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Ve(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function Je(t,e){if(t.byteLength!==e.byteLength)return!1;let n=0;for(let r=0;r<t.byteLength;r++)n|=t[r]^e[r];return n===0}function ze(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}function Ye(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var we=60,Ge=60,Xe=8*1024,Ze=1e5;function W(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ve(t){let e=t.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let n=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function ke(t){let e=ve(t);if(e)try{let n=JSON.parse(new TextDecoder().decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}catch{return}}var x=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ze){this.max=e}spend(e,n){if(n>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,n);let o=r.get(e.jti);if(o!==void 0&&o>n)throw new d("proof","the DPoP proof is not taken: it was used before");o!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(n),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,n,r){for(let[o,s]of n){if(s>r)break;n.delete(o),this.held--}n.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,o]of this.byKey){for(let[s,i]of o)i>e||(o.delete(s),this.held--);o.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let n=[...this.byKey].sort((r,o)=>o[1].size-r[1].size);for(let[r,o]of n){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=o.size}}};async function Qe(t,e){let n=`{"crv":"P-256","kty":"EC","x":"${t}","y":"${e}"}`;return W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)))}function Se(t){try{let e=new URL(t);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function be(t,e,n,r){let o=We=>{throw new d("proof",`the DPoP proof is not taken: ${We}`)},s=n.proof;if(!s)return o("there is none (a DPoP-bound token comes with a DPoP header)");if(s.length>Xe)return o("it is too long");let i=s.split(".");if(i.length!==3)return o("it is not a JWS of three parts");let p=ke(i[0]),c=ke(i[1]);if(!p||!c)return o("its header or claims are not base64url JSON");if(p.typ!=="dpop+jwt")return o("its typ is not dpop+jwt");if(p.alg!=="ES256")return o(`it is signed with ${String(p.alg)}; only ES256 is taken`);let a=p.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return o("its header carries no P-256 public key");if("d"in a)return o("its header carries a private key");if(await Qe(a.x,a.y)!==e)return o("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return o("its key is not a P-256 point")}let y=ve(i[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${i[0]}.${i[1]}`)).catch(()=>!1))return o("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==n.method.toUpperCase())return o(`it is for ${String(c.htm)}, not ${n.method}`);let m=typeof c.htu=="string"?Se(c.htu):void 0,f=Se(n.url);if(!m||!f||m!==f)return o(`it is for ${String(c.htu)}, not ${f??n.url}`);let v=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-v)>we)return o("it was not made within a minute of now");let Oe=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)));if(c.ath!==Oe)return o("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return o("it has no jti (or one longer than 256)");let He=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:He,until:(c.iat+we+Ge)*1e3+1}}var d=class extends Error{reason;constructor(e,n){super(n),this.name="TokenError",this.reason=e}},k=class extends Error{constructor(e,n){super(e,n),this.name="AuthUnavailable"}},et=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function tt(t){return async e=>{let n=b({baseUrl:t.url,credentials:{secretKey:t.secretKey,accessToken:()=>e},fetch:t.fetch});try{return await n.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!et.has(r.code))return!1;throw new k("a session's standing could not be told",{cause:r})}}}var L={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},Re=60,nt=16*1024,rt=10*6e4,ot=5e4,xe=t=>typeof t=="string"&&Object.hasOwn(L,t),B=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new x;constructor(e){let n=new URL(e.issuer);if(n.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=n.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,n){if(typeof e!="string"||e.length===0||e.length>nt)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let o=Ee(r[0]),s=Ee(r[1]);if(!o||!s)throw new d("malformed","the token header or claims are not base64url JSON");let i=o.alg;if(!xe(i))throw new d("algorithm",`the token is signed with ${String(i)}; only ES256 and PS256 are taken`);let p=o.kid;if(typeof p!="string"||p==="")throw new d("malformed","the token header names no kid");let c=await this.key(p);if(!c)throw new d("unknown_key",`no key ${p} in the project's key set`);if(c.alg!==i)throw new d("algorithm",`key ${p} is ${c.alg}, the token says ${i}`);let a=Pe(r[2]);if(!a)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(L[c.alg].verify,c.key,a,l).catch(()=>!1))throw new d("signature","the signature does not verify");let g=this.check(s),m=s.cnf,f;if(m!==void 0){if(!n)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof m!="object"||m===null||typeof m.jkt!="string"||m.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");f=await be(e,m.jkt,n,this.now())}else if(n)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,g.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return f&&this.seenProofs.spend(f,this.now()),g}async verifyRequest(e){let n=e.headers instanceof Headers?e.headers:it(e.headers),r=n.get("authorization")??"";if(r==="")return null;let o=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!o)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let s=o[1].toLowerCase()==="dpop",i=new URL(e.url,`http://${n.get("host")??"localhost"}`);return this.verify(o[2],s?{proof:n.get("dpop"),method:e.method,url:_e(n,i)}:void 0)}async stands(e,n){let r=this.now(),o=this.standings.get(n);if(o&&r<o.until)return o.live;let s=this.asking.get(n);s||(s=this.standing(e,n).finally(()=>this.asking.delete(n)),this.asking.set(n,s));let i;try{i=await s}catch(c){let a=this.standings.get(n),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new k("a session's standing cannot be read now",{cause:c})}let p=this.now();return this.standings.delete(n),this.standings.set(n,{live:i,at:p,until:p+this.standingTtlMs}),this.standings.size>ot&&this.standings.delete(this.standings.keys().next().value),i}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+Re<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-Re>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let o=e.custom_claims;if(o!==void 0&&(typeof o!="object"||o===null||o.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let n=this.now();if(n>=this.keysUntil){let o=this.keys.size>0&&n<this.keysUntil+rt;if(this.lastFailure!==void 0&&n-this.lastFetch<this.refetchIntervalMs){if(!o)throw new k("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(s){if(!o)throw s}}let r=this.keys.get(e);return!r&&n-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,n;try{if(n=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!n.ok)throw new Error(`the project's key set answered ${n.status}`);e=await n.json()}catch(s){throw this.lastFailure=s,new k("the project's key set cannot be read now",{cause:s})}this.lastFailure=void 0;let r=new Map;for(let s of Array.isArray(e.keys)?e.keys:[]){let i=s.alg;if(typeof s.kid!="string"||!xe(i))continue;let p=L[i];if(s.kty!==p.kty||s.use!==void 0&&s.use!=="sig")continue;let{d:c,...a}=s;try{r.set(s.kid,{alg:i,key:await crypto.subtle.importKey("jwk",a,p.import,!1,["verify"])})}catch{}}this.keys=r;let o=at(n.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(o,this.refetchIntervalMs),this.maxKeyAgeMs)}};function _e(t,e){let n=t.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=n==="https"||n==="http"?n:e.protocol.slice(0,-1),o=t.get("host")??e.host;return st.test(o)?`${r}://${o}${e.pathname}`:""}var st=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function it(t){let e=new Headers;for(let[n,r]of Object.entries(t))if(r!==void 0)for(let o of Array.isArray(r)?r:[r])e.append(n,o);return e}function at(t){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(t??"");return e?Number(e[1])*1e3:void 0}function Pe(t){if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)return null;let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(t.length/4)*4,"=")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Ee(t){let e=Pe(t);if(!e)return null;try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}catch{return null}}function ct(t,e,n=Date.now()){let r=Object.hasOwn(t.entitlements,e)?t.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof n=="number"?n:n.getTime()):!1}var E=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function pt(t,e,n,r){let{idempotencyKey:o,amount:s,ttlSeconds:i,metadata:p}=n;if(typeof o!="string"||o==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:s,...n.credits!==void 0?{credits:n.credits}:{limit:n.limit},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{metadata:p}:{}},a=(await t.iap.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":o},body:c})).data;if(a.status!=="held")throw new E(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(g){throw await t.iap.releaseSpend({path:l}).catch(()=>{}),g}return await t.iap.commitSpend({path:l}),y}var lt=new Set(["provider_unavailable","authentication_required","three_ds_failed"]);function dt(t){return t!==void 0&<.has(t)}function ut(t,e){return{[Te]:!0,commitAmount:t,value:e}}var Te=Symbol("palbase.payments.settleWalletHold");function yt(t){return typeof t=="object"&&t!==null&&Te in t}var _=class extends Error{hold;constructor(e){super(`wallet hold ${JSON.stringify(e.id)} is already ${e.status}: the work is not run again (use a new Idempotency-Key for a new hold)`),this.name="WalletHoldSettled",this.hold=e}};async function mt(t,e,n){let{idempotencyKey:r,walletKey:o,amount:s,ttlSeconds:i,reference:p,metadata:c}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError("idempotencyKey is required for withWalletHold so retries never reserve funds twice");if(!Number.isInteger(s)||s<=0)throw new TypeError("amount must be a positive integer in minor units");let a={wallet_key:o,amount:s,...e.customerId!==void 0?{customer_id:e.customerId}:{spend_token:e.spendToken},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{reference:p}:{},...c!==void 0?{metadata:c}:{}},l=(await t.payments.createWalletHold({headers:{"Idempotency-Key":r},body:a})).data;if(l.status!=="held")throw new _(l);let y;try{y=await n(l)}catch(g){throw await t.payments.releaseWalletHold({path:{hold_id:l.id}}).catch(()=>{}),g}return yt(y)?(y.commitAmount<=0?await t.payments.releaseWalletHold({path:{hold_id:l.id}}):await t.payments.commitWalletHold({path:{hold_id:l.id},body:{amount:y.commitAmount}}),y.value):(await t.payments.commitWalletHold({path:{hold_id:l.id}}),y)}function ht(t){return t.type.startsWith("payments.")}function ft(t){return t.type.startsWith("commerce.")}function gt(t){return t.type.startsWith("promotions.")}var wt=300,kt=/^[0-9]{1,12}$/;function St(t){return typeof t=="string"?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function vt(t){if(t.startsWith("whsec_")){let e=t.slice(6);try{let n=atob(e),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}catch{}}return new TextEncoder().encode(t)}function bt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Rt(t){try{let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}catch{return null}}async function Me(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the commerce hook signing secret (whsec_\u2026)");let e=t.webhookId?.trim()??"",n=t.webhookTimestamp?.trim()??"",r=t.webhookSignature?.trim()??"";if(!e||!n||!r)throw new u("missing_signature","webhook-id, webhook-timestamp, and webhook-signature headers are required");if(!kt.test(n))throw new u("malformed_signature","webhook-timestamp must be unix seconds");let o=t.toleranceSeconds??wt,s=Math.floor((t.now?.()??Date.now())/1e3);if(Math.abs(s-Number(n))>o)throw new u("stale_timestamp",`webhook-timestamp ${n} is outside tolerance (${o}s)`);let i=St(t.body),p=new TextEncoder().encode(`${e}.${n}.`),c=new Uint8Array(p.length+i.length);c.set(p,0),c.set(i,p.length);let a=vt(t.secret),l=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),y=await crypto.subtle.importKey("raw",l,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),g=new Uint8Array(await crypto.subtle.sign("HMAC",y,c)),m=!1;for(let f of r.split(/\s+/)){if(!f.startsWith("v1,"))continue;let v=Rt(f.slice(3));if(v&&bt(g,v)){m=!0;break}}if(!m)throw new u("signature_mismatch","no v1 signature in webhook-signature matches the payload")}function Ae(t){return async e=>{let n=new Uint8Array(await e.arrayBuffer()),r=e.headers.get("webhook-id")??"";try{await Me({secret:t.secret,webhookId:r,webhookTimestamp:e.headers.get("webhook-timestamp"),webhookSignature:e.headers.get("webhook-signature"),body:n,toleranceSeconds:t.toleranceSeconds,now:t.now})}catch(i){let p=i instanceof u?i.code:"signature_mismatch",c=i instanceof Error?i.message:"invalid hook signature";return new Response(JSON.stringify({error:p,error_description:c}),{status:401,headers:{"content-type":"application/json"}})}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return new Response(JSON.stringify({error:"invalid_body",error_description:"hook body is not valid JSON"}),{status:400,headers:{"content-type":"application/json"}})}let s=await t.handle({hookPoint:e.headers.get("x-palbase-hook-point")??"",webhookId:r,payload:o,request:e});return new Response(JSON.stringify(s),{status:200,headers:{"content-type":"application/json"}})}}var P=class extends Error{hookPoint;constructor(e){super(`expected x-palbase-hook-point "discovery.rank", got "${e}"`),this.hookPoint=e}};function xt(t){let e=Ae({secret:t.secret,toleranceSeconds:t.toleranceSeconds,now:t.now,handle:n=>{if(n.hookPoint!==""&&n.hookPoint!=="discovery.rank")throw new P(n.hookPoint);return t.handle(n)}});return async n=>{try{return await e(n)}catch(r){if(r instanceof P)return new Response(JSON.stringify({error:"invalid_hook_point",error_description:r.message}),{status:400,headers:{"content-type":"application/json"}});throw r}}}function Et(t){return t.type.startsWith("campaigns.")}function _t(t){return t.type.startsWith("journey.")}async function*Pt(t){let e,n=new Set;do{let r=(await t(e)).data;yield r;let o=r.next_cursor??void 0;if(o!==void 0&&n.has(o))throw new Error(`the listing answered a cursor it had answered before (${o})`);o!==void 0&&n.add(o),e=o}while(e)}var Tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Mt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function Ce(t){return!Tt.test(t)||Mt.test(t)||/_PROXY$/i.test(t)}var At=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|CONTRACT_ENTRY|WEB_ORIGINS|SECRETS|DB_[A-Z0-9_]+))$/;function Ct(t){return At.test(t)}async function Ot(t={}){let e=t.env??process.env,n=e.PALBASE_SECRETS;if(n===void 0||n==="")return;if(n==="production")throw new TypeError("PALBASE_SECRETS=production: a production secret's value is never read back \u2014 only the machines that start with it are given it. Run here with PALBASE_SECRETS=development (palbase env:pull writes it), and set a value for this computer with palbase secrets:set NAME --dev");if(n!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${n}`);let r=t.url??e.PALBASE_URL??"",o=t.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||o==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let s=H({url:new URL(r).origin,secretKey:o,fetch:t.fetch}),{data:i}=await s.secrets.getEnvironmentValues({path:{environment:n}}),p=[],c=[],a=[];for(let[l,y]of Object.entries(i.values)){if(Ce(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,p.push(l)}return{set:n,loaded:p.sort(),kept:c.sort(),refused:a.sort()}}export{h as a,S as b,R as c,H as d,u as e,me as f,he as g,fe as h,$e as i,d as j,k,tt as l,B as m,_e as n,ct as o,E as p,pt as q,dt as r,ut as s,_ as t,mt as u,ht as v,ft as w,gt as x,Me as y,Ae as z,xt as A,Et as B,_t as C,Pt as D,Ce as E,Ct as F,Ot as G};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"./
|
|
1
|
+
/*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"./VNUCKM7H.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
|
|
3
3
|
`)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Xe(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function Ee(e,t,n,r,s){we(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=xe(t);return!n.includes(`${ne}node_modules${ne}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+ne))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function Ce(e,t){let n=[],r=re(xe(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=G(r,"package.json");if(he(o)){try{let c=JSON.parse(be(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=re(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function se(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):Z.has(n)}function ie(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return Z.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${We(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function H(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=H(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ye(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&Z.has(ye(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&Z.has(ye(n,i)??""))return(i.propertyName||i.name).text;if(se(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function Te(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function X(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>Te(e,o)==="Controller"))continue;if(!s.name)throw new b(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Ge.has(Te(e,a)??""))){if(P(n,o.name)===null)throw new b(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var Ye=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function et(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ne(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=d=>{throw new b(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${d}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let d=[];for(let p of n.getSourceFiles()){if(d.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ie(e,p.fileName)||d.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!Ye.has(x.code)))}d.length&&u(t.formatDiagnostics(d.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
|
|
4
4
|
`})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(et(g))return{kind:"raw"};function y(d){let p=d.getSymbol();if(p?.getName()!=="Encrypted"||!(p.declarations??[]).some(S=>ie(e,S.getSourceFile().fileName)))return;let x=r.getTypeArguments(d);return x.length===1?x[0]:void 0}let f=new Set,V=0;function h(d,p){if(++V>2e3||f.size>24)return u(`${p}: contract is too large; name its schema`);let x=d.flags,S=t.TypeFlags;if(x&(S.Any|S.Unknown|S.Never|S.TypeParameter))return u(`${p}: ${r.typeToString(d)}`);let pe=y(d);if(pe)return`encrypted(${h(pe,p)})`;let Se=w=>{let k=r.getPropertiesOfType(w);if(!(w.flags&S.Object)||k.length!==1||k[0].name!=="__pg"||!(k[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(w).length)return!1;let N=r.getTypeOfSymbolAtLocation(k[0],o);return(N.isUnion()?N.types:[N]).every(E=>E.flags&(S.StringLiteral|S.Undefined))};if(d.isIntersection()){let w=d.types.filter(k=>!Se(k));if(w.length===1&&w.length<d.types.length)return h(w[0],p)}if(Se(d))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&S.StringLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.NumberLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.BooleanLiteral)return`z.literal(${r.typeToString(d)==="true"})`;if(x&S.String)return"z.string()";if(x&S.TemplateLiteral){let w=d;if(w.types.length>8||!w.types.every(E=>E.flags&S.String))return u(`${p}: template literal requires an explicit schema`);let k=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+k(w.texts[0]);for(let E of w.texts.slice(1,-1))if(E){let te=k(E);N+=`(?:(?!${te})[\\s\\S])*${te}`}return N+="[\\s\\S]*"+k(w.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&S.Number)return"z.number()";if(x&S.Boolean)return"z.boolean()";if(x&S.Null)return"z.null()";if(x&S.Undefined)return"z.undefined()";if(f.has(d))return u(`${p}: recursive response`);f.add(d);try{if(d.isUnion()){if(d.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=d.types.some(M=>M.flags&S.Null),W=d.types.some(M=>M.flags&S.Undefined),j=d.types.filter(M=>!(M.flags&(S.Null|S.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?h(j[0],p):`z.union([${j.map(M=>h(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(W?".optional()":"")}if(r.isTupleType(d))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(d)){let A=r.getTypeArguments(d)[0];return A.flags&S.Never?"z.array(z.string()).length(0)":`z.array(${h(A,`${p}[]`)})`}let w=d.isIntersection()&&d.types.every(A=>A.flags&S.Object);if(!(x&S.Object)&&!w||d.getCallSignatures().length||d.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(d)}`);let k=d.symbol?.declarations?.[0];if(k&&(t.isClassDeclaration(k)||t.isClassExpression(k)))return u(`${p}: class instance ${r.typeToString(d)}`);let N=r.getPropertiesOfType(d),E=r.getIndexInfosOfType(d);return E.length?E.length!==1||!(E[0].keyType.flags&S.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${h(E[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let W=A.getName(),j=h(r.getTypeOfSymbolAtLocation(A,o),`${p}.${W}`);return`${JSON.stringify(W)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{f.delete(d)}}return{kind:"expression",expression:h(g,"return")}}}import{resolve as tt}from"node:path";var oe=Symbol("not a named schema");function Ae(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=f=>new b(`${i.fileName} \u2014 ${n}.${o}: ${f}`);function c(f){if(s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Promise"&&f.typeArguments&&f.typeArguments.length===1)return c(f.typeArguments[0]);if(f.kind===s.SyntaxKind.VoidKeyword||f.kind===s.SyntaxKind.UndefinedKeyword)return null;let V=s.isArrayTypeNode(f)?f.elementType:s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Array"&&f.typeArguments&&f.typeArguments.length===1?f.typeArguments[0]:void 0,h=l(V??f);return h===oe?h:{...h,isArray:V!==void 0}}function l(f){if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName};if(s.isTypeReferenceNode(f)&&f.typeArguments&&f.typeArguments.length===1){let V=f.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(V)){let h=f.typeArguments[0];if(s.isTypeQueryNode(h))return{typeName:h.exprName.getText(i),node:h.exprName};if(s.isTypeReferenceNode(h)&&!h.typeArguments)return{typeName:h.typeName.getText(i),node:h.typeName}}}if(f.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return oe}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===oe)return u();let g=nt(e,m.node);if(!g)return u();let y=rt(e,g.symbol);return y?{kind:"schema",...y,array:m.isArray}:u()}function nt(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=H(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function rt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>H(e,i)===t).map(i=>i.name);return s.length===0?null:{file:tt(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ue={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},st=new Set(["HttpError","PalError"]),it=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],ot=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function $e(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=At(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function at(e,t,n){throw new b(`${O(e,t)} \u2014 ${n}`)}function q(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function de(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Fe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function Oe(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ct(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=Oe(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function J(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Re(e,t,n){for(let r=J(e,t);r;r=J(e,r))if(r===n)return!0;return!1}function U(e,t,n,r){let s=e.ts;for(let i=t;i;i=J(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||de(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function lt(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function ve(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Fe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function ze(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ut(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ae(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function Q(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)Q(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Fe(r,a)||n.add(a);for(let l of ve(e))Re(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of ve(e)){let u=ze(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function fe(e,t,n){let r=ut(e,t);if(r){let s=lt(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Re(e,o,r));if(i.length===1){n.add(i[0]);return}}Q(e,t,n)}function ft(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function je(e,t){return t.fn&&ft(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function C(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(C(e,t.whenTrue,n,r)),a(C(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(C(e,t.left,n,r)),a(C(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(C(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of ee(e,t,n))for(let l of Y(s,c.fn))a(C(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(C(e,c.initializer,je(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&Q(e,ae(e,c),i),i;if(c&&s.isParameter(c)){let l=ae(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?fe(e,l,i):Q(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(C(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):fe(e,ae(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of Y(s,c))a(C(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(C(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return Q(e,e.checker.getTypeAtLocation(t),i),i}function Y(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function Me(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function Ie(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function dt(e,t){let n=e.ts,r=Me(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(Ie(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!se(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of it)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function mt(e,t){let n=e.checker.getSymbolAtLocation(Ie(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Be(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=J(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||de(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function ee(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&J(e,n.owner);return c?Be(e,c,n.receiver):[]}let i=Me(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&J(e,n.owner),y=g&&U(e,g,i,!1);return y?[{fn:y.fn,ctx:{receiver:n.receiver,owner:y.owner,fn:y.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=U(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!mt(e,c))return[];let m=[];for(let g of C(e,l,n)){let y=U(e,g,i,!1);y&&m.push({fn:y.fn,ctx:{receiver:g,owner:y.owner,fn:y.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!de(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function De(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of C(e,s.expression,n)){let l=U(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function Le(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function gt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function Pe(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ke(e,t,n,r,s){if(st.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(Le(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:Pe(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ue,t)?ue[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!gt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return Le(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:Pe(c),code:c,status:i.status}))}function me(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function _e(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&at(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function pt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ve(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(f=>f.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(f=>s.isConstructorDeclaration(f)&&!!f.body),c=n,l=r;if(a){let f=pt(s,a);if(!f)return[];c=f.arguments,l=f}let u=ct(s,t),m=I(e,o);if(m)return Ke(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let f=me(e,g);return f?[{..._e(e,g,f),name:u||g.name.getText()}]:[]}let y=_(e,o);if(y){let f=Ve(e,y,c,l);return f.length===1&&u?[{...f[0],name:u}]:f}return[]}function St(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ke(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=me(e,o);if(c)return[_e(e,o,c)]}let a=Oe(n,o);return a&&v(e,a)?Ve(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,St(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of ee(e,t,n))for(let u of Y(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?je(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function ce(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r);return e.checker.getAwaitedType(s)!==s}function yt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function Tt(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function ht(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=yt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||Tt(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function bt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ue))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=me(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function xt(e,t){let n=bt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new b(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)xt(e,o);let i=ht(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function Ue(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function wt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?Ue(e,n.body,r.name.text):!1:!0:!1}return!0}function kt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function le(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,le(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?Ue(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(kt(e,o,"allSettled")){D(e,t.expression,n,r);let u=le(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=wt(s,t.arguments[a]);D(e,u.expression,n,le(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?ot.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=dt(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of ee(e,t,n))R(e,r,t,ce(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of De(e,u,n))R(e,r,u,ce(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Be(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of De(e,a,n))R(e,r,a,ce(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of C(e,t.expression,n)){let c=U(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function qe(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of ee(e,t,{receiver:null,owner:null,fn:null}))for(let o of Y(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...qe(e,a,n))}return s}function Et(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of qe(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;fe(e,ze(e,c),l);for(let u of l){let m=U(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function Ct(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Nt(e,t,n){let r=new Map;for(let i of Et(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=Ct(i.name),a=s.get(o);if(a)throw new b(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function At(e,t){let n=[];for(let{cls:r,routes:s}of X(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Nt(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Gt(e,t,n={}){let r=n.typescript??vt,s=Je(ge(e)),{options:i,ambient:o}=ke(r,s);return Dt(Ee(r,s,[Je(ge(t)),...o],i))}function Dt(e){let t=e.ts,n=Ne(e),r=$e(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=X(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ae(e,n,u.name.text,g))}catch(y){if(!(y instanceof b))throw y;o.push(y.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,y]of Object.entries(m))s.push({file:ge(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:y})}if(o.length===1)throw new b(o[0]);if(o.length>1)throw new b(`${o.length} routes have no contract:
|
|
5
5
|
${o.map(a=>`- ${a}`).join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{g as m}from"./
|
|
1
|
+
/*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{g as m}from"./TFPVJ3C3.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
|
|
3
3
|
`):process.stdout.write(`${o}
|
|
4
4
|
`)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
|