palbase 0.8.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/2DWAHEYE.js +22 -0
  8. package/dist/chunks/{73R33XMD.js → 2GF6TA4C.js} +1 -1
  9. package/dist/chunks/4DDSGFFD.js +95 -0
  10. package/dist/chunks/{7XVI5JLP.js → 5UI3Q5JO.js} +2 -2
  11. package/dist/chunks/{RZ525VLP.js → 6RX5KVMR.js} +2 -2
  12. package/dist/chunks/{6RXVXPHC.js → BKOIWNJP.js} +1 -1
  13. package/dist/chunks/{ZSKMWUIQ.js → CJPHHWRE.js} +2 -2
  14. package/dist/chunks/{NSQAN2ME.js → CNUOWB6T.js} +2 -2
  15. package/dist/chunks/{RYI2OB52.js → I56MGYTD.js} +2 -2
  16. package/dist/chunks/{KJWHR5BP.js → KUFTU2AJ.js} +2 -2
  17. package/dist/chunks/MALOKTVW.js +13 -0
  18. package/dist/chunks/{CA4VJGGG.js → OV2D7HYG.js} +1 -1
  19. package/dist/chunks/PUILCUFX.js +2 -0
  20. package/dist/chunks/{T2Q5CKLL.js → SE3MXMQD.js} +2 -2
  21. package/dist/chunks/{KHHJRNAO.js → WPE6J77U.js} +1 -1
  22. package/dist/chunks/{KYJJJUEU.js → XGWTZGWR.js} +2 -2
  23. package/dist/chunks/{M4XLAPDF.js → XSPSDUZA.js} +2 -2
  24. package/dist/chunks/{MAYLG7WE.js → YSTCOQFT.js} +2 -2
  25. package/dist/chunks/ZHHMA7V4.js +2 -0
  26. package/dist/chunks/{5RTSNQ4X.js → ZRV54HT6.js} +2 -2
  27. package/dist/cli.js +129 -127
  28. package/dist/refuse/ai.js +1 -1
  29. package/dist/refuse/backend.js +1 -1
  30. package/dist/refuse/server.js +1 -1
  31. package/dist/server/index.js +2 -2
  32. package/dist/server/testing.js +2 -2
  33. package/dist/web/index.js +2 -2
  34. package/dist/web/message.js +2 -0
  35. package/dist/web/palbe.js +2 -2
  36. package/dist/web/paywall.js +2 -2
  37. package/dist/web/push-sw.js +2 -0
  38. package/dist/web/ssr.js +2 -2
  39. package/dist/web/vite.js +2 -2
  40. package/package.json +7 -2
  41. package/types/backend/src/services.d.ts +2 -2
  42. package/types/internal/src/modules/ai.d.ts +1 -1
  43. package/types/internal/src/modules/analytics.d.ts +618 -1
  44. package/types/internal/src/modules/auth.d.ts +409 -90
  45. package/types/internal/src/modules/events.d.ts +7 -3
  46. package/types/internal/src/modules/flags.d.ts +380 -14
  47. package/types/internal/src/modules/notify.d.ts +2270 -99
  48. package/types/internal/src/modules/purchases.d.ts +672 -9
  49. package/types/server/src/webhooks.d.ts +1 -1
  50. package/types/web/src/analytics.d.ts +56 -5
  51. package/types/web/src/client.d.ts +26 -4
  52. package/types/web/src/consent.d.ts +218 -0
  53. package/types/web/src/flags.d.ts +75 -0
  54. package/types/web/src/inapp.d.ts +129 -0
  55. package/types/web/src/inbox.d.ts +59 -0
  56. package/types/web/src/index.d.ts +9 -3
  57. package/types/web/src/installation.d.ts +16 -0
  58. package/types/web/src/message/index.d.ts +5 -0
  59. package/types/web/src/message/present.d.ts +20 -0
  60. package/types/web/src/notify.d.ts +67 -0
  61. package/types/web/src/paywall/index.d.ts +4 -4
  62. package/types/web/src/paywall/placement.d.ts +11 -12
  63. package/types/web/src/paywall/prices.d.ts +7 -2
  64. package/types/web/src/purchases.d.ts +32 -0
  65. package/types/web/src/{paywall → screen}/assets.d.ts +6 -6
  66. package/types/web/src/screen/render.d.ts +186 -0
  67. package/types/web/src/{paywall → screen}/resolve.d.ts +56 -8
  68. package/dist/chunks/5M3HV3X4.js +0 -2
  69. package/dist/chunks/Q4XTWEAW.js +0 -92
  70. package/dist/chunks/Y6AQWQBE.js +0 -2
  71. package/types/web/src/paywall/render.d.ts +0 -93
  72. /package/types/web/src/{paywall → screen}/icons.d.ts +0 -0
@@ -1,5 +1,5 @@
1
- /*! palbase 0.8.1 — Palbase SDK License (see LICENSE) */
2
- import{a as ht,c as se,d as Un,e as Ln,f as ge,h as _,i as In}from"./M4XLAPDF.js";import{b as Ze,d as ft,e as jn,f as Mn,g as pt,h as mt,k as Dn,q as Nn}from"./ZSKMWUIQ.js";import{b as pe}from"./KYJJJUEU.js";import"reflect-metadata";var Lt=[{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}],zn="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)",gt=/^\d+$/;function Es(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),i=1;if(a!==-1){let g=s.slice(a+1);if(!gt.test(g)||Number(g)<1||Number(g)>n)return;i=Number(g)}let u=t,p=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),x=o.slice(g+1);if(!gt.test(k)||!gt.test(x)||Number(k)<t||Number(x)>n||Number(k)>Number(x))return;u=Number(k),p=Number(x)}else{if(!gt.test(o)||Number(o)<t||Number(o)>n)return;u=Number(o),p=a===-1?u:n}for(let g=u;g<=p;g+=i)r.add(g)}return r}function Gn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${zn}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let g=Es(t[p],Lt[p].lo,Lt[p].hi);if(!g)return`${zn}; its ${Lt[p].name} "${t[p]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),i=t[4].startsWith("*"),u=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,u.setUTCDate(u.getUTCDate()+1)){if(!s.has(u.getUTCMonth()+1))continue;let g=r.has(u.getUTCDate()),k=a.has(u.getUTCDay());if(o||i?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Pe=Symbol.for("palbase.backend.controller"),Ce=Symbol.for("palbase.backend.routes"),zt=Symbol.for("palbase.backend.params"),Gt=Symbol.for("palbase.backend.injectable"),Ht=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),je=Symbol.for("palbase.backend.webhook"),we=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var It=Symbol.for("palbase.backend.declared");function ce(){let e=globalThis;return e[It]instanceof Set||(e[It]=new Set),e[It]}var Me=new Set(["webhooks","_palbase"]);function ii(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&&Me.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,Pe,()=>({basePath:e,options:t})),ce().add(n)}}function De(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,Ce,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var di=De("GET"),ci=De("POST"),ui=De("PUT"),li=De("PATCH"),fi=De("DELETE"),pi=De("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=de(n.constructor,zt,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function qt(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 mi=e=>ue("body",{schema:qt("Body",e)}),hi=e=>ue("query",{schema:qt("QueryParams",e)}),gi=e=>ue("headers",e===void 0?{}:{schema:qt("Headers",e)}),yi=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},wi=()=>ue("user"),bi=()=>ue("optionalUser"),ki=()=>ue("req"),vi=()=>ue("requestId"),$i=()=>ue("requestId"),Ti=()=>ue("client");function Si(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 Ei(){return e=>{de(e,Gt,()=>!0),ce().add(e)}}function _i(e){return t=>{de(t,Ht,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Fn=/^[a-z]+(\.[a-z_]+)+$/,_s=/^[a-z][a-z0-9-]{1,62}$/,Ft=e=>e.startsWith("file.");function xi(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"||!_s.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(!Ft(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),ce().add(r.constructor)}}var Bt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,xs=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Hn(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(!xs.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 Oi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bt.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=Gn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Hn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Hn(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,we))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,we,{value:s,enumerable:!1}),ce().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Os=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ri(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(!Os.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&&!qn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${qn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Rs(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=U(t,Se)??[];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:i}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,je,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:i})=>({event:o,fn:i}))})),ce().add(t)}}function Rs(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 U(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ai(){return[...ce()].filter(e=>U(e,Pe)!==void 0)}function Pi(e){return(U(e,Ce)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var yt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Ni(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bt.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,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),ce().add(s)}}var Wt;function Kn(e){Wt=e}function Kt(){if(!Wt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Wt}var As=720*3600;function Ps(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>As))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 Cs(e){if(typeof e=="string")return e;let t=e[ye];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Ui=ht("Tasks",{async enqueue(e,t,n={}){return Ps(n),Kt().enqueue(Cs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Kt().cancel(e,t.machine)},async get(e,t={}){return Kt().get(e,t.machine)}}),Jt=(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 Jn(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 ge.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 Jt(a.data,a.status===200)},async cancel(n,r){return Jt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Jt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var js=1e4,Ms=36e5,Bn=24*36e5,wt=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 pe({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 pe({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 pe({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 u of this.tasks.values())if(u.task===t&&u.key===r.key&&(u.finishedAt===void 0||this.now()-u.finishedAt<Bn))return this.view(u,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,i={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(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new pe({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 pe({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(i){a={status:500,message:i.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(js*2**Math.min(t.attempt-1,16),Ms),_.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>=Bn&&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 Vt="/_palbase/storage/upload/authorize",Wn="/_palbase/storage/upload/complete",Zt="/_palbase/realtime/rooms";var Ds=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ne(e){if(!Ds(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 Vn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Zn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function bt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ns=/^[a-z][a-z0-9-]{1,62}$/,Qn=1024,Us=new Set(["userId","uploadId","filename"]);function Hi(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(!Ns.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=Ls(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,i,u)=>{if(typeof i!="string"||u===void 0||typeof u.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(o.constructor,Ce,()=>[]).push({method:"POST",subpath:e,fn:i,options:a,upload:s})}}function qi(){return ue("uploadedObject")}function Ls(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Us.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(!Yn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Yn(e){if(e===""||new TextEncoder().encode(e).byteLength>Qn)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 Is(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>zs(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function zs(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 Xn(e,t){let n=Is(e,t);return Yn(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Qn} bytes)`}}function er(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 Qt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function tr(e,t){if(!Qt(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=Ne(t.user);if(!o)return"user is { id?, session?, role }";let i=Vn(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,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let u=Gs(t.uploadedObject);return u?u.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:"",uploadedObject:u,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Gs(e){if(!Qt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:i,height:u,thumbhash:p,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||u!==void 0&&typeof u!="number"||p!==void 0&&typeof p!="string")&&!(!Qt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...i!==void 0?{width:i}:{},...u!==void 0?{height:u}:{},...p!==void 0?{thumbhash:p}:{},variants:{...g}}}import{markData as Hs}from"palgres";var Ee=Symbol.for("palbase.backend.gateway"),Ie=Symbol.for("palbase.backend.gatewayHooks"),nr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},qs={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(nr),output:()=>structuredClone(nr)}}},cr=Symbol.for("palbase.backend.gatewayRefusal"),rr=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,cr,{value:!0})}},Fs=e=>typeof e=="object"&&e!==null&&e[cr]===!0&&typeof e.reason=="string",Ue=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Bs=6e4,Ks=86400,sr=604800,ar=65536,be=255,Js=["roles:","flags:","messaging:","debug:"],Ws=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(" ")),Le=e=>new TextEncoder().encode(e).byteLength,Yt=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Vs(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(Le(e)>be)return`a channel is ${be} 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=Js.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 ur(e){if(typeof e!="string"||e==="")return"is a name";if(Le(e)>be)return`is ${be} bytes at most`}function Vi(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Vs(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=Zs(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)||Ws.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 i=a.events??{};if(typeof i!="object"||i===null||Array.isArray(i))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(i,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,k]of Object.entries(i)){let x=ur(g);if(x)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${x}`);if(!Yt(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let u=de(a,Ie,nn),p={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...i,chat:qs}:{...i},chat:r.chat===!0,graceMs:r.graceMs??Bs,hooks:{...u.hooks},messages:Object.assign(Object.create(null),u.messages)};if(p.access===void 0&&p.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(p.access!==void 0&&p.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${p.access}' and @Authorize both say who may join \u2014 keep one`);if(p.publish&&Ue(p))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(p.publish&&p.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(p.chat&&!Ue(p))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,Ee,()=>p),ce().add(a)}}function Zs(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ks;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>sr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${sr} (a week)`);return n}var nn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Qs={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function Qe(e){let t=Qs[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Ie,nn),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,ce().add(n.constructor)}}var Zi=Qe("authorize"),Qi=Qe("first"),Yi=Qe("connect"),Xi=Qe("disconnect"),ed=Qe("empty");function td(e,t,n={}){let r=ur(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!Yt(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!Yt(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 i=de(s.constructor,Ie,nn),u=i.messages[e];if(u!==void 0&&u.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${u.fn} and ${a}).`);i.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},ce().add(s.constructor)}}function Ys(e){return U(e,Ee)}function Xs(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 lr(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 Le(r)>be?{problem:`a channel is ${be} bytes at most`}:r}function ea(e,t,n){let r=tn(e).map(i=>i.slice(1,-1));for(let i of Object.keys(t))if(!r.includes(i))return{problem:`{${i}} 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(i=>Object.hasOwn(t,i))?lr(e,t):ta(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(i=>`{${i}}`).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 ta(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 na=1e4,ra=1e3,sa=100,rn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),me=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),or={first:"first",join:"connect",leave:"disconnect",empty:"empty"},ir=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function fr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let w=Ys(b),T=a.get(w.name);if(T!==void 0&&T!==b)throw new TypeError(`@Gateway("${w.pattern}"): two gateways are named ${w.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(w.name,b);let O=s.get(ir(w.pattern));if(O!==void 0)throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: ${n.get(O)?.cls.name}'s "${O}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(ir(w.pattern),w.pattern);for(let[q,J]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([I,j])=>[`message ${I}`,j.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: its ${q} is ${J}, which is no method of it`);let N={cls:b,instance:E,g:w};n.set(w.pattern,N),r.set(b,N)}let o=new Map,i=new Set,u=new Set,p=new en(t.broadcast),g=b=>{let E=o.get(b);return E||(E=new AbortController,o.set(b,E)),E},k=(b,E)=>{E?.abort(),o.get(b)===E&&o.delete(b)},x=(b,E,w,T,O,N)=>{if(!Object.hasOwn(b.g.events,w)){_.warn(`[palbase] ${O}: emit("${w}") is not sent \u2014 ${b.cls.name} declares no event "${w}" (static events)`);return}if(b.g.chat&&w==="chat"){_.warn(`[palbase] ${O}: 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}p.send({topic:E,event:w,payload:T??{},...N!==void 0?{conn_id:N}:{}},O)},W=async(b,E,w)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${w}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(E)};function L(b,E,w,T,O,N,q){let J=T?.signal??AbortSignal.abort(),I=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...w}),signal:J,count:O,user:N,emit:(j,G)=>x(b,E,j,G,I,q),pipe:j=>W(j,E,I),owner:{hold(j){se.exit(async()=>{try{await j(J)}catch(G){J.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(E,T)}}}function z(b){let{room:E,channel:w}=b;if(typeof E!="string"||typeof w!="string")return me(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!Ue(T.g)?me(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:w,params:Xs(E,w)}}let Z=(b,E)=>me(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function Y(b,E){let w=z(b);if("status"in w)return w;let{entry:T,channel:O,params:N}=w,q={status:200,body:{subscribe:!1,publish:!1}};if(!N)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${O}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),q;let J=Ne(b.user),I=J?.id;if(!I)return q;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return N[tn(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:q;let j=T.g.hooks.authorize;if(!j)return q;let G,F;try{G=await t.run(J,`${T.cls.name}.${j}`,E,async()=>T.instance[j]({user:{id:I},params:Object.freeze({...N})})),F=aa(G)}catch(oe){if(t.isOutage(oe)||E?.aborted)throw oe;return _.error(`[palbase] ${T.cls.name}.${j} (@Authorize of ${O}) failed; the join is refused`,{error:oe}),q}return F==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${j} (@Authorize of ${O}) answered ${oa(G)}, which is no grant (true, { read, write } or null); the join is refused`),q):{status:200,body:F}}async function ne(b,E){let w=z(b);if("status"in w)return w;if(!w.params)return Z(w.entry.g.pattern,w.channel);let T=Ne(b.user);if(!T?.id||typeof b.event!="string")return me(400,"bad_request","A message names its member (user) and its event");let O=Object.hasOwn(w.entry.g.messages,b.event)?w.entry.g.messages[b.event]:void 0;if(!O)return{status:200,body:{ok:!1,reason:Xt(`gateway "${w.channel}" takes no message "${b.event}"`,kt)}};let N=await O.schema["~standard"].validate(Hs(b.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:dr(N.issues)}};let q=g(w.channel),J={...L(w.entry,w.channel,w.params,q,0,{id:T.id}),payload:N.value},I=`${w.entry.cls.name}.${O.fn} (@Subscribe "${b.event}" of ${w.channel})`,j;try{j=await t.run(T,`${w.entry.cls.name}.${O.fn}`,E,async()=>w.entry.instance[O.fn](J))}catch(F){if(t.isOutage(F))throw F;return Fs(F)?{status:200,body:{ok:!1,reason:Xt(F.reason,kt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:F}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(j===void 0)return{status:200,body:{ok:!0}};if(O.reply){let F=await O.reply["~standard"].validate(j);if(F.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${dr(F.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};j=F.value}let G;try{G=JSON.stringify(j)}catch(F){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:F}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Le(G)>ar?(_.error(`[palbase] ${I} returned an ack of ${Le(G)} bytes, past ${ar}; 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 v(b,E){let w=z(b);if("status"in w)return w;if(!w.params)return Z(w.entry.g.pattern,w.channel);let T=b.event;if(typeof T!="string"||!Object.hasOwn(or,T))return me(400,"bad_request","A gateway's moment is first, join, leave or empty");let O=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(O===void 0)return me(400,"bad_request","A gateway's moment says its count of members");let N=T==="join"||T==="leave",q=N?Ne(b.user):void 0,J=N?b.connId:void 0;if(N&&(!q?.id||typeof J!="string"||J===""))return me(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${w.channel}\0${typeof J=="string"?J:""}`;if(N&&i.has(I))return{status:204};if(u.has(I))return me(503,"in_progress","This moment of the gateway is being handled",5);u.add(I);try{let j=w.entry.g.hooks[or[T]],G;if(T==="empty"?(G=o.get(w.channel),k(w.channel,G)):G=T==="leave"?o.get(w.channel):g(w.channel),j){let F=L(w.entry,w.channel,w.params,G,O,{id:q?.id??""},T==="join"?J:void 0);try{await t.run(q,`${w.entry.cls.name}.${j}`,E,async()=>w.entry.instance[j](F))}catch(oe){if(t.isOutage(oe))throw oe;return E?.aborted||_.error(`[palbase] ${w.entry.cls.name}.${j} (${T} of ${w.channel}) failed; realtime tells it again`,{error:oe}),me(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return N&&(i.add(I),i.size>na&&i.delete(i.values().next().value)),{status:204}}finally{u.delete(I)}}function X(b,E){let w=r.get(b),T=`Palbase.gateways.to(${b?.name??String(b)})`;if(!w)throw new TypeError(`${T}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let O=lr(w.g.pattern,E??{});if(typeof O!="string")throw new TypeError(`${T}: ${O.problem}`);return{entry:w,channel:O,where:T}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,w){return rn(E)?b==="authorize"?Y(E,w):b==="message"?ne(E,w):b==="lifecycle"?v(E,w):me(404,"not_found",`No gateway call ${JSON.stringify(b)}`):me(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,w,T){let{entry:O,channel:N,where:q}=X(b,E);x(O,N,w,T,q)},async pipe(b,E,w){let{channel:T,where:O}=X(b,E);await W(w,T,O)},async revalidate(b,E,w={}){let T=r.get(b),O=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!T)throw new TypeError(`${O}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=ea(T.g.pattern,E??{},w);if("problem"in N)throw new TypeError(`${O}: ${N.problem}`);await t.revalidate(N)},close(){for(let b of o.values())b.abort();o.clear()}}}function aa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!rn(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 oa(e){return Array.isArray(e)?"an array":rn(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 ia=20,kt=256;function dr(e){let t="";for(let n of e.slice(0,ia)){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)>=kt)break}return Xt(t,kt)}function Xt(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 en=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Le(t.event)>be){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${be} 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>=ra?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),se.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,sa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as sn,createHmac as da,createPublicKey as gr,timingSafeEqual as ca,verify as yr}from"node:crypto";function ad(e){let t=U(e,je);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 wr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let i=U(o,je),u=s.get(i.name);if(u)throw new TypeError(`@Webhook "${i.name}" is declared by ${u.cls.name} and by ${o.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${o.name})`,g=n[i.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=ua(i,g)}catch(L){a.push(`${p}: ${i.secret.env} ${L.message}`)}let x=t(o),W=new Map(i.events.map(({event:L,fn:z})=>[L,{name:`${o.name}.${z}`,call:(Z,Y)=>x[z](Z,Y)}]));s.set(i.name,{name:i.name,cls:o,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:W})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as ht,c as se,d as Un,e as Ln,f as ge,h as _,i as In}from"./XSPSDUZA.js";import{b as Ze,d as ft,e as jn,f as Mn,g as pt,h as mt,k as Dn,q as Nn}from"./CJPHHWRE.js";import{b as pe}from"./XGWTZGWR.js";import"reflect-metadata";var Lt=[{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}],zn="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)",gt=/^\d+$/;function Es(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),i=1;if(a!==-1){let g=s.slice(a+1);if(!gt.test(g)||Number(g)<1||Number(g)>n)return;i=Number(g)}let u=t,p=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),x=o.slice(g+1);if(!gt.test(k)||!gt.test(x)||Number(k)<t||Number(x)>n||Number(k)>Number(x))return;u=Number(k),p=Number(x)}else{if(!gt.test(o)||Number(o)<t||Number(o)>n)return;u=Number(o),p=a===-1?u:n}for(let g=u;g<=p;g+=i)r.add(g)}return r}function Gn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${zn}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let g=Es(t[p],Lt[p].lo,Lt[p].hi);if(!g)return`${zn}; its ${Lt[p].name} "${t[p]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),i=t[4].startsWith("*"),u=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,u.setUTCDate(u.getUTCDate()+1)){if(!s.has(u.getUTCMonth()+1))continue;let g=r.has(u.getUTCDate()),k=a.has(u.getUTCDay());if(o||i?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Pe=Symbol.for("palbase.backend.controller"),Ce=Symbol.for("palbase.backend.routes"),zt=Symbol.for("palbase.backend.params"),Gt=Symbol.for("palbase.backend.injectable"),Ht=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),je=Symbol.for("palbase.backend.webhook"),we=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var It=Symbol.for("palbase.backend.declared");function ce(){let e=globalThis;return e[It]instanceof Set||(e[It]=new Set),e[It]}var Me=new Set(["webhooks","_palbase"]);function ii(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&&Me.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,Pe,()=>({basePath:e,options:t})),ce().add(n)}}function De(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,Ce,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var di=De("GET"),ci=De("POST"),ui=De("PUT"),li=De("PATCH"),fi=De("DELETE"),pi=De("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=de(n.constructor,zt,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function qt(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 mi=e=>ue("body",{schema:qt("Body",e)}),hi=e=>ue("query",{schema:qt("QueryParams",e)}),gi=e=>ue("headers",e===void 0?{}:{schema:qt("Headers",e)}),yi=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},wi=()=>ue("user"),bi=()=>ue("optionalUser"),ki=()=>ue("req"),vi=()=>ue("requestId"),$i=()=>ue("requestId"),Ti=()=>ue("client");function Si(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 Ei(){return e=>{de(e,Gt,()=>!0),ce().add(e)}}function _i(e){return t=>{de(t,Ht,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Fn=/^[a-z]+(\.[a-z_]+)+$/,_s=/^[a-z][a-z0-9-]{1,62}$/,Ft=e=>e.startsWith("file.");function xi(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"||!_s.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(!Ft(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),ce().add(r.constructor)}}var Bt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,xs=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Hn(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(!xs.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 Oi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bt.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=Gn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Hn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Hn(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,we))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,we,{value:s,enumerable:!1}),ce().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Os=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ri(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(!Os.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&&!qn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${qn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Rs(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=U(t,Se)??[];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:i}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,je,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:i})=>({event:o,fn:i}))})),ce().add(t)}}function Rs(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 U(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ai(){return[...ce()].filter(e=>U(e,Pe)!==void 0)}function Pi(e){return(U(e,Ce)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var yt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Ni(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bt.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,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),ce().add(s)}}var Wt;function Kn(e){Wt=e}function Kt(){if(!Wt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Wt}var As=720*3600;function Ps(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>As))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 Cs(e){if(typeof e=="string")return e;let t=e[ye];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Ui=ht("Tasks",{async enqueue(e,t,n={}){return Ps(n),Kt().enqueue(Cs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Kt().cancel(e,t.machine)},async get(e,t={}){return Kt().get(e,t.machine)}}),Jt=(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 Jn(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 ge.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 Jt(a.data,a.status===200)},async cancel(n,r){return Jt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Jt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var js=1e4,Ms=36e5,Bn=24*36e5,wt=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 pe({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 pe({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 pe({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 u of this.tasks.values())if(u.task===t&&u.key===r.key&&(u.finishedAt===void 0||this.now()-u.finishedAt<Bn))return this.view(u,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,i={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(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new pe({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 pe({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(i){a={status:500,message:i.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(js*2**Math.min(t.attempt-1,16),Ms),_.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>=Bn&&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 Vt="/_palbase/storage/upload/authorize",Wn="/_palbase/storage/upload/complete",Zt="/_palbase/realtime/rooms";var Ds=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ne(e){if(!Ds(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 Vn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Zn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function bt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ns=/^[a-z][a-z0-9-]{1,62}$/,Qn=1024,Us=new Set(["userId","uploadId","filename"]);function Hi(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(!Ns.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=Ls(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,i,u)=>{if(typeof i!="string"||u===void 0||typeof u.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(o.constructor,Ce,()=>[]).push({method:"POST",subpath:e,fn:i,options:a,upload:s})}}function qi(){return ue("uploadedObject")}function Ls(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Us.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(!Yn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Yn(e){if(e===""||new TextEncoder().encode(e).byteLength>Qn)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 Is(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>zs(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function zs(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 Xn(e,t){let n=Is(e,t);return Yn(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Qn} bytes)`}}function er(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 Qt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function tr(e,t){if(!Qt(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=Ne(t.user);if(!o)return"user is { id?, session?, role }";let i=Vn(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,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let u=Gs(t.uploadedObject);return u?u.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:"",uploadedObject:u,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Gs(e){if(!Qt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:i,height:u,thumbhash:p,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||u!==void 0&&typeof u!="number"||p!==void 0&&typeof p!="string")&&!(!Qt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...i!==void 0?{width:i}:{},...u!==void 0?{height:u}:{},...p!==void 0?{thumbhash:p}:{},variants:{...g}}}import{markData as Hs}from"palgres";var Ee=Symbol.for("palbase.backend.gateway"),Ie=Symbol.for("palbase.backend.gatewayHooks"),nr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},qs={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(nr),output:()=>structuredClone(nr)}}},cr=Symbol.for("palbase.backend.gatewayRefusal"),rr=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,cr,{value:!0})}},Fs=e=>typeof e=="object"&&e!==null&&e[cr]===!0&&typeof e.reason=="string",Ue=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Bs=6e4,Ks=86400,sr=604800,ar=65536,be=255,Js=["roles:","flags:","messaging:","debug:"],Ws=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(" ")),Le=e=>new TextEncoder().encode(e).byteLength,Yt=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Vs(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(Le(e)>be)return`a channel is ${be} 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=Js.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 ur(e){if(typeof e!="string"||e==="")return"is a name";if(Le(e)>be)return`is ${be} bytes at most`}function Vi(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Vs(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=Zs(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)||Ws.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 i=a.events??{};if(typeof i!="object"||i===null||Array.isArray(i))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(i,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,k]of Object.entries(i)){let x=ur(g);if(x)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${x}`);if(!Yt(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let u=de(a,Ie,nn),p={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...i,chat:qs}:{...i},chat:r.chat===!0,graceMs:r.graceMs??Bs,hooks:{...u.hooks},messages:Object.assign(Object.create(null),u.messages)};if(p.access===void 0&&p.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(p.access!==void 0&&p.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${p.access}' and @Authorize both say who may join \u2014 keep one`);if(p.publish&&Ue(p))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(p.publish&&p.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(p.chat&&!Ue(p))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,Ee,()=>p),ce().add(a)}}function Zs(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ks;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>sr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${sr} (a week)`);return n}var nn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Qs={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function Qe(e){let t=Qs[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Ie,nn),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,ce().add(n.constructor)}}var Zi=Qe("authorize"),Qi=Qe("first"),Yi=Qe("connect"),Xi=Qe("disconnect"),ed=Qe("empty");function td(e,t,n={}){let r=ur(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!Yt(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!Yt(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 i=de(s.constructor,Ie,nn),u=i.messages[e];if(u!==void 0&&u.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${u.fn} and ${a}).`);i.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},ce().add(s.constructor)}}function Ys(e){return U(e,Ee)}function Xs(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 lr(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 Le(r)>be?{problem:`a channel is ${be} bytes at most`}:r}function ea(e,t,n){let r=tn(e).map(i=>i.slice(1,-1));for(let i of Object.keys(t))if(!r.includes(i))return{problem:`{${i}} 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(i=>Object.hasOwn(t,i))?lr(e,t):ta(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(i=>`{${i}}`).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 ta(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 na=1e4,ra=1e3,sa=100,rn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),me=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),or={first:"first",join:"connect",leave:"disconnect",empty:"empty"},ir=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function fr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let w=Ys(b),T=a.get(w.name);if(T!==void 0&&T!==b)throw new TypeError(`@Gateway("${w.pattern}"): two gateways are named ${w.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(w.name,b);let O=s.get(ir(w.pattern));if(O!==void 0)throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: ${n.get(O)?.cls.name}'s "${O}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(ir(w.pattern),w.pattern);for(let[q,J]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([I,j])=>[`message ${I}`,j.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: its ${q} is ${J}, which is no method of it`);let N={cls:b,instance:E,g:w};n.set(w.pattern,N),r.set(b,N)}let o=new Map,i=new Set,u=new Set,p=new en(t.broadcast),g=b=>{let E=o.get(b);return E||(E=new AbortController,o.set(b,E)),E},k=(b,E)=>{E?.abort(),o.get(b)===E&&o.delete(b)},x=(b,E,w,T,O,N)=>{if(!Object.hasOwn(b.g.events,w)){_.warn(`[palbase] ${O}: emit("${w}") is not sent \u2014 ${b.cls.name} declares no event "${w}" (static events)`);return}if(b.g.chat&&w==="chat"){_.warn(`[palbase] ${O}: 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}p.send({topic:E,event:w,payload:T??{},...N!==void 0?{conn_id:N}:{}},O)},W=async(b,E,w)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${w}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(E)};function L(b,E,w,T,O,N,q){let J=T?.signal??AbortSignal.abort(),I=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...w}),signal:J,count:O,user:N,emit:(j,G)=>x(b,E,j,G,I,q),pipe:j=>W(j,E,I),owner:{hold(j){se.exit(async()=>{try{await j(J)}catch(G){J.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(E,T)}}}function z(b){let{room:E,channel:w}=b;if(typeof E!="string"||typeof w!="string")return me(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!Ue(T.g)?me(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:w,params:Xs(E,w)}}let Z=(b,E)=>me(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function Y(b,E){let w=z(b);if("status"in w)return w;let{entry:T,channel:O,params:N}=w,q={status:200,body:{subscribe:!1,publish:!1}};if(!N)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${O}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),q;let J=Ne(b.user),I=J?.id;if(!I)return q;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return N[tn(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:q;let j=T.g.hooks.authorize;if(!j)return q;let G,F;try{G=await t.run(J,`${T.cls.name}.${j}`,E,async()=>T.instance[j]({user:{id:I},params:Object.freeze({...N})})),F=aa(G)}catch(oe){if(t.isOutage(oe)||E?.aborted)throw oe;return _.error(`[palbase] ${T.cls.name}.${j} (@Authorize of ${O}) failed; the join is refused`,{error:oe}),q}return F==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${j} (@Authorize of ${O}) answered ${oa(G)}, which is no grant (true, { read, write } or null); the join is refused`),q):{status:200,body:F}}async function ne(b,E){let w=z(b);if("status"in w)return w;if(!w.params)return Z(w.entry.g.pattern,w.channel);let T=Ne(b.user);if(!T?.id||typeof b.event!="string")return me(400,"bad_request","A message names its member (user) and its event");let O=Object.hasOwn(w.entry.g.messages,b.event)?w.entry.g.messages[b.event]:void 0;if(!O)return{status:200,body:{ok:!1,reason:Xt(`gateway "${w.channel}" takes no message "${b.event}"`,kt)}};let N=await O.schema["~standard"].validate(Hs(b.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:dr(N.issues)}};let q=g(w.channel),J={...L(w.entry,w.channel,w.params,q,0,{id:T.id}),payload:N.value},I=`${w.entry.cls.name}.${O.fn} (@Subscribe "${b.event}" of ${w.channel})`,j;try{j=await t.run(T,`${w.entry.cls.name}.${O.fn}`,E,async()=>w.entry.instance[O.fn](J))}catch(F){if(t.isOutage(F))throw F;return Fs(F)?{status:200,body:{ok:!1,reason:Xt(F.reason,kt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:F}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(j===void 0)return{status:200,body:{ok:!0}};if(O.reply){let F=await O.reply["~standard"].validate(j);if(F.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${dr(F.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};j=F.value}let G;try{G=JSON.stringify(j)}catch(F){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:F}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Le(G)>ar?(_.error(`[palbase] ${I} returned an ack of ${Le(G)} bytes, past ${ar}; 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 v(b,E){let w=z(b);if("status"in w)return w;if(!w.params)return Z(w.entry.g.pattern,w.channel);let T=b.event;if(typeof T!="string"||!Object.hasOwn(or,T))return me(400,"bad_request","A gateway's moment is first, join, leave or empty");let O=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(O===void 0)return me(400,"bad_request","A gateway's moment says its count of members");let N=T==="join"||T==="leave",q=N?Ne(b.user):void 0,J=N?b.connId:void 0;if(N&&(!q?.id||typeof J!="string"||J===""))return me(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${w.channel}\0${typeof J=="string"?J:""}`;if(N&&i.has(I))return{status:204};if(u.has(I))return me(503,"in_progress","This moment of the gateway is being handled",5);u.add(I);try{let j=w.entry.g.hooks[or[T]],G;if(T==="empty"?(G=o.get(w.channel),k(w.channel,G)):G=T==="leave"?o.get(w.channel):g(w.channel),j){let F=L(w.entry,w.channel,w.params,G,O,{id:q?.id??""},T==="join"?J:void 0);try{await t.run(q,`${w.entry.cls.name}.${j}`,E,async()=>w.entry.instance[j](F))}catch(oe){if(t.isOutage(oe))throw oe;return E?.aborted||_.error(`[palbase] ${w.entry.cls.name}.${j} (${T} of ${w.channel}) failed; realtime tells it again`,{error:oe}),me(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return N&&(i.add(I),i.size>na&&i.delete(i.values().next().value)),{status:204}}finally{u.delete(I)}}function X(b,E){let w=r.get(b),T=`Palbase.gateways.to(${b?.name??String(b)})`;if(!w)throw new TypeError(`${T}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let O=lr(w.g.pattern,E??{});if(typeof O!="string")throw new TypeError(`${T}: ${O.problem}`);return{entry:w,channel:O,where:T}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,w){return rn(E)?b==="authorize"?Y(E,w):b==="message"?ne(E,w):b==="lifecycle"?v(E,w):me(404,"not_found",`No gateway call ${JSON.stringify(b)}`):me(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,w,T){let{entry:O,channel:N,where:q}=X(b,E);x(O,N,w,T,q)},async pipe(b,E,w){let{channel:T,where:O}=X(b,E);await W(w,T,O)},async revalidate(b,E,w={}){let T=r.get(b),O=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!T)throw new TypeError(`${O}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=ea(T.g.pattern,E??{},w);if("problem"in N)throw new TypeError(`${O}: ${N.problem}`);await t.revalidate(N)},close(){for(let b of o.values())b.abort();o.clear()}}}function aa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!rn(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 oa(e){return Array.isArray(e)?"an array":rn(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 ia=20,kt=256;function dr(e){let t="";for(let n of e.slice(0,ia)){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)>=kt)break}return Xt(t,kt)}function Xt(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 en=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Le(t.event)>be){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${be} 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>=ra?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),se.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,sa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as sn,createHmac as da,createPublicKey as gr,timingSafeEqual as ca,verify as yr}from"node:crypto";function ad(e){let t=U(e,je);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 wr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let i=U(o,je),u=s.get(i.name);if(u)throw new TypeError(`@Webhook "${i.name}" is declared by ${u.cls.name} and by ${o.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${o.name})`,g=n[i.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=ua(i,g)}catch(L){a.push(`${p}: ${i.secret.env} ${L.message}`)}let x=t(o),W=new Map(i.events.map(({event:L,fn:z})=>[L,{name:`${o.name}.${z}`,call:(Z,Y)=>x[z](Z,Y)}]));s.set(i.name,{name:i.name,cls:o,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:W})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
3
  - ${a.join(`
4
4
  - `)}`);return s}function br(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var ze=1024,pr=1024*ze;function ua(e,t){if(e.signature)return _e(void 0,e.signature.header,1/0,va(e.signature,t));switch(e.provider){case"stripe":return _e("stripe","stripe-signature",512*ze,pa(t));case"github":return _e("github","x-hub-signature-256",25*pr,ma(t));case"slack":return _e("slack","x-slack-signature",64*ze,ha(t));case"discord":return _e("discord","x-signature-ed25519",64*ze,ga(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*ze),check:wa(t)};case"sendgrid":return _e("sendgrid","x-twilio-email-event-webhook-signature",pr,ba(t));case"livekit":return _e("livekit","authorization",512*ze,ka(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function _e(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??kr(e,s)}}function kr(e,t){let n=an(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:vr(e,t.headers,r),event:r,...la(e,t,r)}}function vr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=xe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Sr(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 xe(n,"EventType");case"livekit":return xe(n,"event");default:return xe(n,"type")}}function la(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(xe(n,"id"));case"slack":return r(xe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${$r(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>xe(s,"sg_event_id")||void 0)}:{};default:return{}}}var fa=300;function pa(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let u of r.split(",")){let p=u.indexOf("=");if(p<=0)continue;let g=u.slice(0,p).trim(),k=u.slice(p+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(g==="v1"){let x=le(k,"hex");if(!x)return"malformed_signature";a.push(x)}}let o=Ye(s);if(o===void 0||a.length===0)return"malformed_signature";if(Xe(o,n))return"stale_timestamp";let i=Ge("sha256",e,`${s}.`,t.body);return a.some(u=>ke(u,i))?void 0:"signature_mismatch"}}function ma(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?le(n.slice(7),"hex"):void 0;return r?ke(r,Ge("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function ha(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=Ye(s),o=r.startsWith("v0=")?le(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":Xe(a,n)?"stale_timestamp":ke(o,Ge("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function ga(e){let t=le(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=gr({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,i=Ye(o),u=le(a,"hex");return i===void 0||!u||u.byteLength!==64?"malformed_signature":Xe(i,s)?"stale_timestamp":yr(null,Tr(o,r.body),n,u)?void 0:"signature_mismatch"}}var ya=1e3;function wa(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=le(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="",i;if(a!==null){if(!ke(Buffer.from(a.toLowerCase()),Buffer.from(sn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let W=1;for(let Z of t.body)if(Z===38&&++W>ya)return"malformed_signature";let L=new Map;for(let[Z,Y]of new URLSearchParams(an(t.body))){let ne=L.get(Z);ne||L.set(Z,ne=new Set),ne.add(Y)}let z=[];for(let Z of[...L.keys()].sort()){let Y=[...L.get(Z)].sort();for(let ne of Y)o+=Z+ne;z.push([Z,Y.length===1?Y[0]:Y])}i=Object.fromEntries(z)}let u=s.protocol==="https:"?"443":"80",p=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||u}${s.pathname}${s.search}`;if(![p,g].some(W=>ke(r,Ge("sha1",e,W,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),x=k?{id:`${k}:${$r(`${p}
5
5
  ${o}`)}`}:{};return i?{type:vr("twilio",t.headers,i),event:i,...x}:{...kr("twilio",t),...x}}}function ba(e){let t;try{let n=le(e,"base64");if(!n)throw new Error;t=gr({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=Ye(a),i=le(s.trim(),"base64");return o===void 0||!i?"malformed_signature":Xe(o,r)?"stale_timestamp":yr("sha256",Tr(a,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var mr=60;function ka(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=hr(le(s[0],"base64url")),o=le(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!ke(o,Ge("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=hr(le(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+mr||typeof i.nbf=="number"&&n<i.nbf-mr)return"stale_timestamp";let u=typeof i.sha256=="string"?le(i.sha256,"base64"):void 0;return u&&ke(u,sn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function va(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 i="";if(n.includes("{ts}")){i=s.headers.get(e.timestampHeader)?.trim()??"";let p=Ye(i);if(p===void 0)return"malformed_signature";if(Xe(p,a))return"stale_timestamp"}let u=le(o.trim(),e.encoding);return u?ke(u,Ge(r,t,...n.map(p=>p==="{body}"?s.body:p==="{ts}"?i:p)))?void 0:"signature_mismatch":"malformed_signature"}}var $a=new TextEncoder;function Ge(e,t,...n){let r=da(e,t);for(let s of n)r.update(s);return r.digest()}function $r(e){return sn("sha256").update(e).digest("hex")}function Tr(e,t){return Buffer.concat([$a.encode(e),t])}function ke(e,t){return e.byteLength===t.byteLength&&ca(e,t)}var Ta={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 le(e,t){return Ta[t].test(e)?Buffer.from(e,t):void 0}function Ye(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Xe(e,t){return Math.abs(t-e)>fa}function an(e){return new TextDecoder().decode(e)}function hr(e){if(e)try{return JSON.parse(an(e))}catch{return}}function Sr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xe(e,t){let n=Sr(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var K=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
@@ -0,0 +1,13 @@
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
+ import{p as R,t as k,u as H}from"./4DDSGFFD.js";var N=40,V=`
3
+ :host{display:contents}
4
+ .pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
5
+ .pm-modal::backdrop,.pm-full::backdrop{background:transparent}
6
+ .pm-modal{align-items:center;justify-content:center;box-sizing:border-box;padding:max(16px,env(safe-area-inset-top,0px)) max(16px,env(safe-area-inset-right,0px)) max(16px,env(safe-area-inset-bottom,0px)) max(16px,env(safe-area-inset-left,0px))}
7
+ .pm-full{padding:0}
8
+ .pm-panel{display:flex;flex-direction:column;min-height:0;width:100%;max-height:100%;outline:none}
9
+ .pm-full>.pm-panel{flex:1 1 auto;height:100%}
10
+ .pm-banner{position:fixed;z-index:2147483000;left:50%;transform:translateX(-50%);width:min(640px,calc(100% - 16px - env(safe-area-inset-left,0px) - env(safe-area-inset-right,0px)));display:flex;flex-direction:column;touch-action:none;outline:none}
11
+ .pm-banner.top{top:calc(8px + env(safe-area-inset-top,0px))}
12
+ .pm-banner.bottom{bottom:calc(8px + env(safe-area-inset-bottom,0px))}
13
+ `;function I(r,y={},Y={}){let g=Y.root??globalThis.document?.body;if(!g)throw new Error("presentMessage needs a page");let l=g.ownerDocument,A=l.defaultView,t=R(r.definition,{locale:r.locale,appearance:r.appearance,platform:r.platform??"web",variables:r.variables??{}}).presentation;if(t.type==="card")throw new Error("a card is drawn in its inbox (renderMessage), not shown over the page");let m=l.createElement("div");m.setAttribute("data-palbase-message-layer","");let b=m.attachShadow({mode:"open"});H(l,b,V);let d=t.type==="banner",e=l.createElement(d?"div":"dialog"),f=d?e:l.createElement("div");d?(e.className=`pm-banner ${t.position}`,e.setAttribute("role","dialog"),e.setAttribute("aria-modal","false")):(e.className=t.type==="modal"?"pm-modal":"pm-full",t.type==="modal"&&(e.style.background=t.backdrop),f.className="pm-panel",e.append(f));let u=l.createElement("div");u.style.cssText="display:flex;flex-direction:column;min-height:0;flex:1 1 auto",f.append(u),b.append(e),g.append(m);let x=t.type!=="fullscreen"&&t.dismissible,h=()=>r.reduceMotion??A?.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1,v=!1,w="button",M,D=new Promise(n=>M=n),E=[],L=k(u,r,{...y,onAction(n){w=n.type==="close"?"button":"action",y.onAction?.(n)},onClose:()=>p(w)}),T=u.querySelector("[data-palbase-message]")?.shadowRoot?.querySelector("h1,h2,h3,.pw-text")?.textContent?.trim();if(T&&e.setAttribute("aria-label",T),d){let n=t.auto_dismiss_seconds;if(n!==void 0){let o=n*1e3,a=Date.now(),c,s=0,i=()=>{a=Date.now(),c=setTimeout(()=>p("timeout"),o)},C=()=>{s++===0&&(clearTimeout(c),o-=Date.now()-a)},P=()=>{--s===0&&i()};e.addEventListener("pointerenter",C),e.addEventListener("pointerleave",P),e.addEventListener("focusin",C),e.addEventListener("focusout",P),i(),E.push(()=>clearTimeout(c))}if(x){let o=t.position==="top",a=null;e.addEventListener("pointerdown",s=>{a=s.clientY}),e.addEventListener("pointermove",s=>{if(a===null)return;let i=Math.max(0,o?a-s.clientY:s.clientY-a);e.style.transform=`translateX(-50%) translateY(${o?-i:i}px)`,e.style.opacity=String(Math.max(.3,1-i/120))});let c=s=>{if(a===null)return;let i=o?a-s.clientY:s.clientY-a;a=null,i>N?p("swipe"):(e.style.transform="",e.style.opacity="")};e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}}else{let n=e;n.addEventListener("cancel",o=>{o.preventDefault(),x&&p("escape")}),t.type==="modal"&&n.addEventListener("click",o=>{o.target===n&&x&&p("outside")}),n.showModal()}S();function S(){if(h()||typeof e.animate!="function")return;let n=t.type==="banner"?t.position==="top"?-24:24:0,o=t.type==="modal"?[{opacity:0,transform:"scale(0.96)"},{opacity:1,transform:"none"}]:t.type==="banner"?[{opacity:0,transform:`translateX(-50%) translateY(${n}px)`},{opacity:1,transform:"translateX(-50%)"}]:[{opacity:0,transform:"translateY(24px)"},{opacity:1,transform:"none"}];(t.type==="banner"?e:f).animate(o,{duration:220,easing:"cubic-bezier(0.16, 1, 0.3, 1)"}),t.type==="modal"&&e.animate([{opacity:0},{opacity:1}],{duration:180,easing:"ease-out"})}function p(n){if(v)return;v=!0,E.forEach(a=>a());let o=()=>{d||e.close(),L.destroy(),m.remove()};h()||typeof e.animate!="function"?o():e.animate([{opacity:Number(e.style.opacity||1)},{opacity:0}],{duration:160,easing:"ease-in",fill:"forwards"}).finished.then(o,o),M(n),y.onClose?.(n)}return{view:L,closed:D,close:()=>p("app")}}export{I as a};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.8.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
2
  function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
+ import{c as D,g as b,l as O,m as _,s as F}from"./4DDSGFFD.js";import{b as w}from"./XGWTZGWR.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.9.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,5 +1,5 @@
1
- /*! palbase 0.8.1 — Palbase SDK License (see LICENSE) */
2
- import{a as L,c as me,d as he,e as ye}from"./RZ525VLP.js";import{a as we}from"./CA4VJGGG.js";import{a as ue}from"./Y6AQWQBE.js";import{a as pe,b as ge,c as fe}from"./RYI2OB52.js";import{b as I,d as le}from"./KYJJJUEU.js";async function*be(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",u="",l=[],m,s=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:r}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(r,{stream:!0});for(let d=i.indexOf(`
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as L,c as me,d as he,e as ye}from"./6RX5KVMR.js";import{a as we}from"./OV2D7HYG.js";import{a as ue}from"./ZHHMA7V4.js";import{a as pe,b as ge,c as fe}from"./I56MGYTD.js";import{b as I,d as le}from"./XGWTZGWR.js";async function*be(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",u="",l=[],m,s=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:r}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(r,{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===""?(u!==""&&(yield m===void 0?{event:u,data:l.join(`
5
5
  `)}:{event:u,data:l.join(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.8.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
2
  var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.8.1 — Palbase SDK License (see LICENSE) */
2
- import{a as g,b}from"./KHHJRNAO.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await U(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status];if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await P(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function U(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:$(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function $(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+O(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!e.secretKey;case"userJWT":return!!a;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function O(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function P(t,e){let n=await _(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=B(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function _(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function B(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as g,b}from"./WPE6J77U.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await U(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status];if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await P(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function U(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:$(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function $(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+O(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!e.secretKey;case"userJWT":return!!a;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function O(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function P(t,e){let n=await _(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=B(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function _(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function B(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
@@ -1,4 +1,4 @@
1
- /*! palbase 0.8.1 — Palbase SDK License (see LICENSE) */
2
- import{f as m}from"./T2Q5CKLL.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
+ import{f as m}from"./SE3MXMQD.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
3
3
  `):process.stdout.write(`${o}
4
4
  `)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.8.1 — Palbase SDK License (see LICENSE) */
2
- import{a as k,b as S}from"./KHHJRNAO.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};
1
+ /*! palbase 0.9.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as k,b as S}from"./WPE6J77U.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};