palbase 0.37.1 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{LEBJY4WH.js → 2WLJWZTT.js} +3 -3
- package/dist/chunks/{NPJJBKWB.js → 4NXMQWCX.js} +2 -2
- package/dist/chunks/{GHUIGLRJ.js → 5DUY3VP2.js} +2 -2
- package/dist/chunks/{DQYLTIE5.js → 6SDU7XE2.js} +2 -2
- package/dist/chunks/{YT7ZMYMN.js → 6SKJE2BU.js} +2 -2
- package/dist/chunks/{I6H2425X.js → 7EDHWR5A.js} +2 -2
- package/dist/chunks/{TPQAYDWC.js → CL6S7PER.js} +1 -1
- package/dist/chunks/{YOR7K46P.js → F3D326PD.js} +1 -1
- package/dist/chunks/{H6LQPKWU.js → FM3BAHZZ.js} +1 -1
- package/dist/chunks/{UA3CCXS4.js → GZEEHPBE.js} +2 -2
- package/dist/chunks/{6FVAAS5I.js → IIZT54SQ.js} +2 -2
- package/dist/chunks/{MW7YMYNO.js → JFHJPS5G.js} +1 -1
- package/dist/chunks/{JEA6LCOK.js → JJ5KC2LB.js} +2 -2
- package/dist/chunks/{QA6474UP.js → JLRUWZ5F.js} +2 -2
- package/dist/chunks/{XYRYBY7I.js → JRTLS5CM.js} +2 -2
- package/dist/chunks/{IZ6RIKPB.js → KCKE34OI.js} +2 -2
- package/dist/chunks/{YO6MPQJ4.js → L5S55A54.js} +2 -2
- package/dist/chunks/{PMT4A5UW.js → LRXCOKXA.js} +2 -2
- package/dist/chunks/{AYPQOPOF.js → RSQV7RNP.js} +1 -1
- package/dist/chunks/{GCVJJS4Y.js → TGQPGUJJ.js} +1 -1
- package/dist/chunks/{SRDV2B4P.js → UDOERJLL.js} +2 -2
- package/dist/chunks/{VU2SS32B.js → WHJSFH5J.js} +2 -2
- package/dist/chunks/{RAPT7CYO.js → Z4ULG52U.js} +1 -1
- package/dist/cli.js +125 -125
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/cloud/src/generated/project.d.ts +1 -1
- package/types/internal/src/messaging/store.d.ts +2 -0
- package/types/internal/src/modules/machines.d.ts +73 -8
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as pr,d as mr,e as rn,f as hr,g as gr}from"./6FVAAS5I.js";import{a as Pt,c as re,d as lr,e as fr,f as we,h as _,i as yr}from"./YO6MPQJ4.js";import{a as or,e as dt,g as xt,h as ir,i as dr,j as Rt,k as Ot,n as cr,t as ur}from"./SRDV2B4P.js";import{a as At,b as sr,n as ar}from"./GCVJJS4Y.js";import{b as de}from"./IZ6RIKPB.js";import"reflect-metadata";var sn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],wr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ct=/^\d+$/;function ya(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Ct.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let f=t,h=n;if(o!=="*")if(o.includes("-")){let y=o.indexOf("-"),k=o.slice(0,y),T=o.slice(y+1);if(!Ct.test(k)||!Ct.test(T)||Number(k)<t||Number(T)>n||Number(k)>Number(T))return;f=Number(k),h=Number(T)}else{if(!Ct.test(o)||Number(o)<t||Number(o)>n)return;f=Number(o),h=a===-1?f:n}for(let y=f;y<=h;y+=d)r.add(y)}return r}function br(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${wr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=ya(t[h],sn[h].lo,sn[h].hi);if(!y)return`${wr}; its ${sn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),f=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,f.setUTCDate(f.getUTCDate()+1)){if(!s.has(f.getUTCMonth()+1))continue;let y=r.has(f.getUTCDate()),k=a.has(f.getUTCDay());if(o||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var He=Symbol.for("palbase.backend.controller"),qe=Symbol.for("palbase.backend.routes"),on=Symbol.for("palbase.backend.params"),dn=Symbol.for("palbase.backend.injectable"),cn=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),ze=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ce(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var an=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[an]instanceof Set||(e[an]=new Set),e[an]}var Ge=new Set(["webhooks","_palbase"]);function md(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ce(n,He,()=>({basePath:e,options:t})),se().add(n)}}function Fe(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ce(r.constructor,qe,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var hd=Fe("GET"),gd=Fe("POST"),yd=Fe("PUT"),wd=Fe("PATCH"),bd=Fe("DELETE"),kd=Fe("QUERY");function ue(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ce(n.constructor,on,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function un(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var vd=e=>ue("body",{schema:un("Body",e)}),Td=e=>ue("query",{schema:un("QueryParams",e)}),$d=e=>ue("headers",e===void 0?{}:{schema:un("Headers",e)}),_d=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},Ed=()=>ue("user"),Sd=()=>ue("optionalUser"),Ad=()=>ue("req"),xd=()=>ue("requestId"),Rd=()=>ue("requestId"),Od=()=>ue("client"),Pd=()=>ue("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return ue("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{ce(e,dn,()=>!0),se().add(e)}}function jd(e){return t=>{ce(t,cn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Tr=/^[a-z]+(\.[a-z_]+)+$/,wa=/^[a-z][a-z0-9-]{1,62}$/,ln=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!wa.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!ln(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ce(r.constructor,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var fn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ba=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function kr(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!ba.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=br(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||kr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${kr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var vr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ka=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!ka.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!vr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${vr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&va(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Ce)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ce(t,ze,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function va(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,He)!==void 0)}function Id(e){return(D(e,qe)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Mt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var hn;function _r(e){hn=e}function pn(){if(!hn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return hn}var Ta=720*3600;function $a(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ta))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function _a(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Bd=Pt("Tasks",{async enqueue(e,t,n={}){return $a(n),pn().enqueue(_a(e),t===void 0?null:t,n)},async cancel(e,t={}){return pn().cancel(e,t.machine)},async get(e,t={}){return pn().get(e,t.machine)}}),mn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Er(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await we.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return mn(a.data,a.status===200)},async cancel(n,r){return mn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return mn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ea=1e4,Sa=36e5,$r=24*36e5,jt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new de({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new de({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new de({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let f of this.tasks.values())if(f.task===t&&f.key===r.key&&(f.finishedAt===void 0||this.now()-f.finishedAt<$r))return this.view(f,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new de({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new de({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ea*2**Math.min(t.attempt-1,16),Sa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=$r&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Dt="/_palbase/test-user-templates",Aa=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Aa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function Sr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Ar(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof de&&n.status===404)return!1;throw n}}var xa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function xr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,xa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var gn="/_palbase/storage/upload/authorize",Rr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Be(e){if(!Ra(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Or(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Pr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Nt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Oa=/^[a-z][a-z0-9-]{1,62}$/,Cr=1024,Pa=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Oa.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=Ca(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,f)=>{if(typeof d!="string"||f===void 0||typeof f.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ce(o.constructor,qe,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function tc(){return ue("uploadedObject")}function Ca(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Pa.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Mr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Mr(e){if(e===""||new TextEncoder().encode(e).byteLength>Cr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Ma(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ja(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ja(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function jr(e,t){let n=Ma(e,t);return Mr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Cr} bytes)`}}function Dr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Nr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Be(t.user);if(!o)return"user is { id?, session?, role }";let d=Or(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let f=Da(t.uploadedObject);return f?f.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:f,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Da(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:f,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||f!==void 0&&typeof f!="number"||h!==void 0&&typeof h!="string")&&!(!wn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...f!==void 0?{height:f}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Na}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),We=Symbol.for("palbase.backend.gatewayHooks"),Ur={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ua={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Ur),output:()=>structuredClone(Ur)}}},Fr=Symbol.for("palbase.backend.gatewayRefusal"),Lr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Fr,{value:!0})}},La=e=>typeof e=="object"&&e!==null&&e[Fr]===!0&&typeof e.reason=="string",Ke=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ia=6e4,Ha=86400,Ir=604800,Hr=65536,$e=255,qa=["roles:","flags:","messaging:","calls:","debug:"],za=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Je=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ga(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Je(e)>$e)return`a channel is ${$e} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=qa.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Br(e){if(typeof e!="string"||e==="")return"is a name";if(Je(e)>$e)return`is ${$e} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ga(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Fa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||za.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let T=Br(y);if(T)throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" ${T}`);if(!bn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let f=ce(a,We,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ua}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ia,hooks:{...f.hooks},messages:Object.assign(Object.create(null),f.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ce(a,Me,()=>h),se().add(a)}}function Fa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ha;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Ir)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Ir} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ba={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ba[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ce(n.constructor,We,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Br(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=ce(s.constructor,We,$n),f=d.messages[e];if(f!==void 0&&f.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${f.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ka(e){return D(e,Me)}function Ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Kr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Je(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Wa(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Kr(e,t):Va(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Va(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Za=1e4,Ya=1e3,Qa=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ye=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),qr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},zr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Jr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:S}of e){let m=Ka(b),$=a.get(m.name);if($!==void 0&&$!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let M=s.get(zr(m.pattern));if(M!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(zr(m.pattern),m.pattern);for(let[Z,Y]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof S[Y]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${Z} is ${Y}, which is no method of it`);let U={cls:b,instance:S,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,f=new Set,h=new vn(t.broadcast),y=b=>{let S=o.get(b);return S||(S=new AbortController,o.set(b,S)),S},k=(b,S)=>{S?.abort(),o.get(b)===S&&o.delete(b)},T=(b,S,m,$,M,U)=>{if(!Object.hasOwn(b.g.events,m)){_.warn(`[palbase] ${M}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){_.warn(`[palbase] ${M}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:S,event:m,payload:$??{},...U!==void 0?{conn_id:U}:{}},M)},F=async(b,S,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(S)};function N(b,S,m,$,M,U,Z){let Y=$?.signal??AbortSignal.abort(),L=`${b.cls.name} (${S})`;return{channel:S,params:Object.freeze({...m}),signal:Y,count:M,user:U,emit:(I,G)=>T(b,S,I,G,L,Z),pipe:I=>F(I,S,L),owner:{hold(I){re.exit(async()=>{try{await I(Y)}catch(G){Y.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(S,$)}}}function H(b){let{room:S,channel:m}=b;if(typeof S!="string"||typeof m!="string")return ye(400,"bad_request","A gateway's call names its pattern (room) and its channel");let $=n.get(S);return!$||!Ke($.g)?ye(404,"not_found",`This app serves no gateway "${S}"`):{entry:$,channel:m,params:Ja(S,m)}}let W=(b,S)=>ye(400,"bad_request",`"${S}" is not a channel of the gateway "${b}"`);async function z(b,S){let m=H(b);if("status"in m)return m;let{entry:$,channel:M,params:U}=m,Z={status:200,body:{subscribe:!1,publish:!1}};if(!U)return _.warn(`[palbase] ${$.cls.name}: realtime asked about "${M}", which is not a channel of the gateway "${$.g.pattern}"; the join is refused`),Z;let Y=Be(b.user),L=Y?.id;if(!L)return Z;if($.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}};if($.g.access==="owner")return U[Tn($.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}}:Z;let I=$.g.hooks.authorize;if(!I)return Z;let G,B;try{G=await t.run(Y,`${$.cls.name}.${I}`,S,async()=>$.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Xa(G)}catch(ne){if(t.isOutage(ne)||S?.aborted)throw ne;return _.error(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) failed; the join is refused`,{error:ne}),Z}return B==="malformed"?(_.warn(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) answered ${eo(G)}, which is no grant (true, { read, write } or null); the join is refused`),Z):{status:200,body:B}}async function ie(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=Be(b.user);if(!$?.id||typeof b.event!="string")return ye(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:kn(`gateway "${m.channel}" takes no message "${b.event}"`,Ut)}};let U=await M.schema["~standard"].validate(Na(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Gr(U.issues)}};let Z=y(m.channel),Y={...N(m.entry,m.channel,m.params,Z,0,{id:$.id}),payload:U.value},L=`${m.entry.cls.name}.${M.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run($,`${m.entry.cls.name}.${M.fn}`,S,async()=>m.entry.instance[M.fn](Y))}catch(B){if(t.isOutage(B))throw B;return La(B)?{status:200,body:{ok:!1,reason:kn(B.reason,Ut)}}:(S?.aborted||_.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(M.reply){let B=await M.reply["~standard"].validate(I);if(B.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Gr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Je(G)>Hr?(_.error(`[palbase] ${L} returned an ack of ${Je(G)} bytes, past ${Hr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function ge(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=b.event;if(typeof $!="string"||!Object.hasOwn(qr,$))return ye(400,"bad_request","A gateway's moment is first, join, leave or empty");let M=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(M===void 0)return ye(400,"bad_request","A gateway's moment says its count of members");let U=$==="join"||$==="leave",Z=U?Be(b.user):void 0,Y=U?b.connId:void 0;if(U&&(!Z?.id||typeof Y!="string"||Y===""))return ye(400,"bad_request",`A ${$} names its member: user and connId`);let L=`${$}\0${m.channel}\0${typeof Y=="string"?Y:""}`;if(U&&d.has(L))return{status:204};if(f.has(L))return ye(503,"in_progress","This moment of the gateway is being handled",5);f.add(L);try{let I=m.entry.g.hooks[qr[$]],G;if($==="empty"?(G=o.get(m.channel),k(m.channel,G)):G=$==="leave"?o.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,M,{id:Z?.id??""},$==="join"?Y:void 0);try{await t.run(Z,`${m.entry.cls.name}.${I}`,S,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return S?.aborted||_.error(`[palbase] ${m.entry.cls.name}.${I} (${$} of ${m.channel}) failed; realtime tells it again`,{error:ne}),ye(500,"handler_failed",`The gateway's ${$} could not be handled`)}}return U&&(d.add(L),d.size>Za&&d.delete(d.values().next().value)),{status:204}}finally{f.delete(L)}}function Se(b,S){let m=r.get(b),$=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${$}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let M=Kr(m.g.pattern,S??{});if(typeof M!="string")throw new TypeError(`${$}: ${M.problem}`);return{entry:m,channel:M,where:$}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,S,m){return _n(S)?b==="authorize"?z(S,m):b==="message"?ie(S,m):b==="lifecycle"?ge(S,m):ye(404,"not_found",`No gateway call ${JSON.stringify(b)}`):ye(400,"bad_request","A gateway's call is a JSON object")},emit(b,S,m,$){let{entry:M,channel:U,where:Z}=Se(b,S);T(M,U,m,$,Z)},async pipe(b,S,m){let{channel:$,where:M}=Se(b,S);await F(m,$,M)},async revalidate(b,S,m={}){let $=r.get(b),M=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!$)throw new TypeError(`${M}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Wa($.g.pattern,S??{},m);if("problem"in U)throw new TypeError(`${M}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Xa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function eo(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var to=20,Ut=256;function Gr(e){let t="";for(let n of e.slice(0,to)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ut)break}return kn(t,Ut)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Je(t.event)>$e){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ya?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),re.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,Qa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as no,createPublicKey as Yr,timingSafeEqual as ro,verify as Qr}from"node:crypto";function yc(e){let t=D(e,ze);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function Xr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,ze),f=s.get(d.name);if(f)throw new TypeError(`@Webhook "${d.name}" is declared by ${f.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=so(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let T=t(o),F=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${o.name}.${H}`,call:(W,z)=>T[H](W,z)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:F})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
1
|
+
/*! palbase 0.38.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as pr,d as mr,e as rn,f as hr,g as gr}from"./IIZT54SQ.js";import{a as Pt,c as re,d as lr,e as fr,f as we,h as _,i as yr}from"./L5S55A54.js";import{a as or,e as dt,g as xt,h as ir,i as dr,j as Rt,k as Ot,n as cr,t as ur}from"./UDOERJLL.js";import{a as At,b as sr,n as ar}from"./TGQPGUJJ.js";import{b as de}from"./KCKE34OI.js";import"reflect-metadata";var sn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],wr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ct=/^\d+$/;function ya(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Ct.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let f=t,h=n;if(o!=="*")if(o.includes("-")){let y=o.indexOf("-"),k=o.slice(0,y),T=o.slice(y+1);if(!Ct.test(k)||!Ct.test(T)||Number(k)<t||Number(T)>n||Number(k)>Number(T))return;f=Number(k),h=Number(T)}else{if(!Ct.test(o)||Number(o)<t||Number(o)>n)return;f=Number(o),h=a===-1?f:n}for(let y=f;y<=h;y+=d)r.add(y)}return r}function br(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${wr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=ya(t[h],sn[h].lo,sn[h].hi);if(!y)return`${wr}; its ${sn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),f=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,f.setUTCDate(f.getUTCDate()+1)){if(!s.has(f.getUTCMonth()+1))continue;let y=r.has(f.getUTCDate()),k=a.has(f.getUTCDay());if(o||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var He=Symbol.for("palbase.backend.controller"),qe=Symbol.for("palbase.backend.routes"),on=Symbol.for("palbase.backend.params"),dn=Symbol.for("palbase.backend.injectable"),cn=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),ze=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ce(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var an=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[an]instanceof Set||(e[an]=new Set),e[an]}var Ge=new Set(["webhooks","_palbase"]);function md(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ce(n,He,()=>({basePath:e,options:t})),se().add(n)}}function Fe(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ce(r.constructor,qe,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var hd=Fe("GET"),gd=Fe("POST"),yd=Fe("PUT"),wd=Fe("PATCH"),bd=Fe("DELETE"),kd=Fe("QUERY");function ue(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ce(n.constructor,on,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function un(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var vd=e=>ue("body",{schema:un("Body",e)}),Td=e=>ue("query",{schema:un("QueryParams",e)}),$d=e=>ue("headers",e===void 0?{}:{schema:un("Headers",e)}),_d=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},Ed=()=>ue("user"),Sd=()=>ue("optionalUser"),Ad=()=>ue("req"),xd=()=>ue("requestId"),Rd=()=>ue("requestId"),Od=()=>ue("client"),Pd=()=>ue("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return ue("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{ce(e,dn,()=>!0),se().add(e)}}function jd(e){return t=>{ce(t,cn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Tr=/^[a-z]+(\.[a-z_]+)+$/,wa=/^[a-z][a-z0-9-]{1,62}$/,ln=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!wa.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!ln(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ce(r.constructor,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var fn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ba=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function kr(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!ba.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=br(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||kr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${kr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var vr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ka=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!ka.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!vr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${vr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&va(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Ce)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ce(t,ze,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function va(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,He)!==void 0)}function Id(e){return(D(e,qe)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Mt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var hn;function _r(e){hn=e}function pn(){if(!hn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return hn}var Ta=720*3600;function $a(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ta))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function _a(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Bd=Pt("Tasks",{async enqueue(e,t,n={}){return $a(n),pn().enqueue(_a(e),t===void 0?null:t,n)},async cancel(e,t={}){return pn().cancel(e,t.machine)},async get(e,t={}){return pn().get(e,t.machine)}}),mn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Er(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await we.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return mn(a.data,a.status===200)},async cancel(n,r){return mn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return mn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ea=1e4,Sa=36e5,$r=24*36e5,jt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new de({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new de({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new de({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let f of this.tasks.values())if(f.task===t&&f.key===r.key&&(f.finishedAt===void 0||this.now()-f.finishedAt<$r))return this.view(f,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new de({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new de({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ea*2**Math.min(t.attempt-1,16),Sa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=$r&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Dt="/_palbase/test-user-templates",Aa=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Aa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function Sr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Ar(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof de&&n.status===404)return!1;throw n}}var xa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function xr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,xa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var gn="/_palbase/storage/upload/authorize",Rr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Be(e){if(!Ra(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Or(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Pr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Nt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Oa=/^[a-z][a-z0-9-]{1,62}$/,Cr=1024,Pa=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Oa.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=Ca(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,f)=>{if(typeof d!="string"||f===void 0||typeof f.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ce(o.constructor,qe,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function tc(){return ue("uploadedObject")}function Ca(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Pa.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Mr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Mr(e){if(e===""||new TextEncoder().encode(e).byteLength>Cr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Ma(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ja(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ja(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function jr(e,t){let n=Ma(e,t);return Mr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Cr} bytes)`}}function Dr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Nr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Be(t.user);if(!o)return"user is { id?, session?, role }";let d=Or(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let f=Da(t.uploadedObject);return f?f.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:f,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Da(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:f,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||f!==void 0&&typeof f!="number"||h!==void 0&&typeof h!="string")&&!(!wn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...f!==void 0?{height:f}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Na}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),We=Symbol.for("palbase.backend.gatewayHooks"),Ur={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ua={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Ur),output:()=>structuredClone(Ur)}}},Fr=Symbol.for("palbase.backend.gatewayRefusal"),Lr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Fr,{value:!0})}},La=e=>typeof e=="object"&&e!==null&&e[Fr]===!0&&typeof e.reason=="string",Ke=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ia=6e4,Ha=86400,Ir=604800,Hr=65536,$e=255,qa=["roles:","flags:","messaging:","calls:","debug:"],za=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Je=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ga(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Je(e)>$e)return`a channel is ${$e} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=qa.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Br(e){if(typeof e!="string"||e==="")return"is a name";if(Je(e)>$e)return`is ${$e} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ga(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Fa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||za.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let T=Br(y);if(T)throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" ${T}`);if(!bn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let f=ce(a,We,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ua}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ia,hooks:{...f.hooks},messages:Object.assign(Object.create(null),f.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ce(a,Me,()=>h),se().add(a)}}function Fa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ha;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Ir)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Ir} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ba={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ba[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ce(n.constructor,We,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Br(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=ce(s.constructor,We,$n),f=d.messages[e];if(f!==void 0&&f.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${f.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ka(e){return D(e,Me)}function Ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Kr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Je(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Wa(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Kr(e,t):Va(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Va(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Za=1e4,Ya=1e3,Qa=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ye=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),qr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},zr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Jr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:S}of e){let m=Ka(b),$=a.get(m.name);if($!==void 0&&$!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let M=s.get(zr(m.pattern));if(M!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(zr(m.pattern),m.pattern);for(let[Z,Y]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof S[Y]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${Z} is ${Y}, which is no method of it`);let U={cls:b,instance:S,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,f=new Set,h=new vn(t.broadcast),y=b=>{let S=o.get(b);return S||(S=new AbortController,o.set(b,S)),S},k=(b,S)=>{S?.abort(),o.get(b)===S&&o.delete(b)},T=(b,S,m,$,M,U)=>{if(!Object.hasOwn(b.g.events,m)){_.warn(`[palbase] ${M}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){_.warn(`[palbase] ${M}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:S,event:m,payload:$??{},...U!==void 0?{conn_id:U}:{}},M)},F=async(b,S,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(S)};function N(b,S,m,$,M,U,Z){let Y=$?.signal??AbortSignal.abort(),L=`${b.cls.name} (${S})`;return{channel:S,params:Object.freeze({...m}),signal:Y,count:M,user:U,emit:(I,G)=>T(b,S,I,G,L,Z),pipe:I=>F(I,S,L),owner:{hold(I){re.exit(async()=>{try{await I(Y)}catch(G){Y.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(S,$)}}}function H(b){let{room:S,channel:m}=b;if(typeof S!="string"||typeof m!="string")return ye(400,"bad_request","A gateway's call names its pattern (room) and its channel");let $=n.get(S);return!$||!Ke($.g)?ye(404,"not_found",`This app serves no gateway "${S}"`):{entry:$,channel:m,params:Ja(S,m)}}let W=(b,S)=>ye(400,"bad_request",`"${S}" is not a channel of the gateway "${b}"`);async function z(b,S){let m=H(b);if("status"in m)return m;let{entry:$,channel:M,params:U}=m,Z={status:200,body:{subscribe:!1,publish:!1}};if(!U)return _.warn(`[palbase] ${$.cls.name}: realtime asked about "${M}", which is not a channel of the gateway "${$.g.pattern}"; the join is refused`),Z;let Y=Be(b.user),L=Y?.id;if(!L)return Z;if($.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}};if($.g.access==="owner")return U[Tn($.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}}:Z;let I=$.g.hooks.authorize;if(!I)return Z;let G,B;try{G=await t.run(Y,`${$.cls.name}.${I}`,S,async()=>$.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Xa(G)}catch(ne){if(t.isOutage(ne)||S?.aborted)throw ne;return _.error(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) failed; the join is refused`,{error:ne}),Z}return B==="malformed"?(_.warn(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) answered ${eo(G)}, which is no grant (true, { read, write } or null); the join is refused`),Z):{status:200,body:B}}async function ie(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=Be(b.user);if(!$?.id||typeof b.event!="string")return ye(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:kn(`gateway "${m.channel}" takes no message "${b.event}"`,Ut)}};let U=await M.schema["~standard"].validate(Na(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Gr(U.issues)}};let Z=y(m.channel),Y={...N(m.entry,m.channel,m.params,Z,0,{id:$.id}),payload:U.value},L=`${m.entry.cls.name}.${M.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run($,`${m.entry.cls.name}.${M.fn}`,S,async()=>m.entry.instance[M.fn](Y))}catch(B){if(t.isOutage(B))throw B;return La(B)?{status:200,body:{ok:!1,reason:kn(B.reason,Ut)}}:(S?.aborted||_.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(M.reply){let B=await M.reply["~standard"].validate(I);if(B.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Gr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Je(G)>Hr?(_.error(`[palbase] ${L} returned an ack of ${Je(G)} bytes, past ${Hr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function ge(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=b.event;if(typeof $!="string"||!Object.hasOwn(qr,$))return ye(400,"bad_request","A gateway's moment is first, join, leave or empty");let M=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(M===void 0)return ye(400,"bad_request","A gateway's moment says its count of members");let U=$==="join"||$==="leave",Z=U?Be(b.user):void 0,Y=U?b.connId:void 0;if(U&&(!Z?.id||typeof Y!="string"||Y===""))return ye(400,"bad_request",`A ${$} names its member: user and connId`);let L=`${$}\0${m.channel}\0${typeof Y=="string"?Y:""}`;if(U&&d.has(L))return{status:204};if(f.has(L))return ye(503,"in_progress","This moment of the gateway is being handled",5);f.add(L);try{let I=m.entry.g.hooks[qr[$]],G;if($==="empty"?(G=o.get(m.channel),k(m.channel,G)):G=$==="leave"?o.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,M,{id:Z?.id??""},$==="join"?Y:void 0);try{await t.run(Z,`${m.entry.cls.name}.${I}`,S,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return S?.aborted||_.error(`[palbase] ${m.entry.cls.name}.${I} (${$} of ${m.channel}) failed; realtime tells it again`,{error:ne}),ye(500,"handler_failed",`The gateway's ${$} could not be handled`)}}return U&&(d.add(L),d.size>Za&&d.delete(d.values().next().value)),{status:204}}finally{f.delete(L)}}function Se(b,S){let m=r.get(b),$=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${$}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let M=Kr(m.g.pattern,S??{});if(typeof M!="string")throw new TypeError(`${$}: ${M.problem}`);return{entry:m,channel:M,where:$}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,S,m){return _n(S)?b==="authorize"?z(S,m):b==="message"?ie(S,m):b==="lifecycle"?ge(S,m):ye(404,"not_found",`No gateway call ${JSON.stringify(b)}`):ye(400,"bad_request","A gateway's call is a JSON object")},emit(b,S,m,$){let{entry:M,channel:U,where:Z}=Se(b,S);T(M,U,m,$,Z)},async pipe(b,S,m){let{channel:$,where:M}=Se(b,S);await F(m,$,M)},async revalidate(b,S,m={}){let $=r.get(b),M=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!$)throw new TypeError(`${M}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Wa($.g.pattern,S??{},m);if("problem"in U)throw new TypeError(`${M}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Xa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function eo(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var to=20,Ut=256;function Gr(e){let t="";for(let n of e.slice(0,to)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ut)break}return kn(t,Ut)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Je(t.event)>$e){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ya?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),re.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,Qa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as no,createPublicKey as Yr,timingSafeEqual as ro,verify as Qr}from"node:crypto";function yc(e){let t=D(e,ze);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function Xr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,ze),f=s.get(d.name);if(f)throw new TypeError(`@Webhook "${d.name}" is declared by ${f.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=so(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let T=t(o),F=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${o.name}.${H}`,call:(W,z)=>T[H](W,z)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:F})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
3
|
- ${a.join(`
|
|
4
4
|
- `)}`);return s}function es(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Wr=1024*Ve;function so(e,t){if(e.signature)return je(void 0,e.signature.header,1/0,go(e.signature,t));switch(e.provider){case"stripe":return je("stripe","stripe-signature",512*Ve,io(t));case"github":return je("github","x-hub-signature-256",25*Wr,co(t));case"slack":return je("slack","x-slack-signature",64*Ve,uo(t));case"discord":return je("discord","x-signature-ed25519",64*Ve,lo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:po(t)};case"sendgrid":return je("sendgrid","x-twilio-email-event-webhook-signature",Wr,mo(t));case"livekit":return je("livekit","authorization",512*Ve,ho(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function je(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??ts(e,s)}}function ts(e,t){let n=Sn(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:ns(e,t.headers,r),event:r,...ao(e,t,r)}}function ns(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=De(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=as(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return De(n,"EventType");case"livekit":return De(n,"event");default:return De(n,"type")}}function ao(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(De(n,"id"));case"slack":return r(De(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${rs(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>De(s,"sg_event_id")||void 0)}:{};default:return{}}}var oo=300;function io(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let f of r.split(",")){let h=f.indexOf("=");if(h<=0)continue;let y=f.slice(0,h).trim(),k=f.slice(h+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(y==="v1"){let T=me(k,"hex");if(!T)return"malformed_signature";a.push(T)}}let o=ut(s);if(o===void 0||a.length===0)return"malformed_signature";if(lt(o,n))return"stale_timestamp";let d=Ze("sha256",e,`${s}.`,t.body);return a.some(f=>_e(f,d))?void 0:"signature_mismatch"}}function co(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?_e(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function uo(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ut(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":lt(a,n)?"stale_timestamp":_e(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function lo(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=Yr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ut(o),f=me(a,"hex");return d===void 0||!f||f.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":Qr(null,ss(o,r.body),n,f)?void 0:"signature_mismatch"}}var fo=1e3;function po(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!_e(Buffer.from(a.toLowerCase()),Buffer.from(En("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let F=1;for(let W of t.body)if(W===38&&++F>fo)return"malformed_signature";let N=new Map;for(let[W,z]of new URLSearchParams(Sn(t.body))){let ie=N.get(W);ie||N.set(W,ie=new Set),ie.add(z)}let H=[];for(let W of[...N.keys()].sort()){let z=[...N.get(W)].sort();for(let ie of z)o+=W+ie;H.push([W,z.length===1?z[0]:z])}d=Object.fromEntries(H)}let f=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||f}${s.pathname}${s.search}`;if(![h,y].some(F=>_e(r,Ze("sha1",e,F,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),T=k?{id:`${k}:${rs(`${h}
|
|
5
5
|
${o}`)}`}:{};return d?{type:ns("twilio",t.headers,d),event:d,...T}:{...ts("twilio",t),...T}}}function mo(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=Yr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=ut(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":lt(o,r)?"stale_timestamp":Qr("sha256",ss(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Vr=60;function ho(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=Zr(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!_e(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Zr(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Vr||typeof d.nbf=="number"&&n<d.nbf-Vr)return"stale_timestamp";let f=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return f&&_e(f,En("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function go(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ut(d);if(h===void 0)return"malformed_signature";if(lt(h,a))return"stale_timestamp"}let f=me(o.trim(),e.encoding);return f?_e(f,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var yo=new TextEncoder;function Ze(e,t,...n){let r=no(e,t);for(let s of n)r.update(s);return r.digest()}function rs(e){return En("sha256").update(e).digest("hex")}function ss(e,t){return Buffer.concat([yo.encode(e),t])}function _e(e,t){return e.byteLength===t.byteLength&&ro(e,t)}var wo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return wo[t].test(e)?Buffer.from(e,t):void 0}function ut(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function lt(e,t){return Math.abs(t-e)>oo}function Sn(e){return new TextDecoder().decode(e)}function Zr(e){if(e)try{return JSON.parse(Sn(e))}catch{return}}function as(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(e,t){let n=as(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var V=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as D,g as b,l as O,m as _,s as F}from"./TPQAYDWC.js";import{b as w}from"./IZ6RIKPB.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.37.1"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
|
|
1
|
+
/*! palbase 0.38.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as D,g as b,l as O,m as _,s as F}from"./CL6S7PER.js";import{b as w}from"./KCKE34OI.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.38.0"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as M,c as ye,d as be,e as we}from"./
|
|
1
|
+
/*! palbase 0.38.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as M,c as ye,d as be,e as we}from"./6SKJE2BU.js";import{a as ke}from"./FM3BAHZZ.js";import{a as ge}from"./7EDHWR5A.js";import{a as fe,b as me,c as he}from"./LRXCOKXA.js";import{b as $,d as pe}from"./KCKE34OI.js";async function*Te(e,t={}){let a=e.getReader(),o=new TextDecoder,i="",l="",u=[],h,r=()=>{a.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await a.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=o.decode(s,{stream:!0});for(let d=i.indexOf(`
|
|
3
3
|
`);d>=0;d=i.indexOf(`
|
|
4
4
|
`)){let p=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),p===""?(l!==""&&(yield h===void 0?{event:l,data:u.join(`
|
|
5
5
|
`)}:{event:l,data:u.join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as u,b as d}from"./
|
|
1
|
+
/*! palbase 0.38.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u,b as d}from"./KCKE34OI.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project has no paid rights now to pay for Palbase's models (it is on Free, at its month's limit, or its payment account has an unpaid charge): move it to Pay as you go (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof d)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new d({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=u(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
|