palbase 0.4.0 → 0.5.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 (61) hide show
  1. package/dist/ai/index.js +10 -10
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +8 -8
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{TRHIZOIS.js → 32RCJNOH.js} +3 -3
  8. package/dist/chunks/{BJL2FT5W.js → 3AUBDHV2.js} +1 -1
  9. package/dist/chunks/{IVDNNHII.js → 7BA7LGEM.js} +2 -2
  10. package/dist/chunks/A7EL6JKQ.js +20 -0
  11. package/dist/chunks/AWHTWL65.js +2 -0
  12. package/dist/chunks/{2AT72FFB.js → B45UFKBR.js} +2 -2
  13. package/dist/chunks/{ST2NZ4TZ.js → DNHDO6AJ.js} +1 -1
  14. package/dist/chunks/{BHT2IHBE.js → EHJKMDP3.js} +2 -2
  15. package/dist/chunks/{3OIKIBMG.js → FSXD7MN3.js} +2 -2
  16. package/dist/chunks/{SUNHFMDO.js → KSJ6AMCG.js} +2 -2
  17. package/dist/chunks/PALOWH6U.js +6 -0
  18. package/dist/chunks/{RKNVSAGY.js → PFSUOVTB.js} +1 -1
  19. package/dist/chunks/{6JO3UVPT.js → QIN2NQPN.js} +2 -2
  20. package/dist/chunks/{FS222NNP.js → R43DXJZE.js} +2 -2
  21. package/dist/chunks/{ODFLUINN.js → TTZRGQWF.js} +1 -1
  22. package/dist/chunks/{UNTTPATW.js → ZXYDN6NA.js} +1 -1
  23. package/dist/cli.js +133 -129
  24. package/dist/refuse/ai.js +1 -1
  25. package/dist/refuse/backend.js +1 -1
  26. package/dist/refuse/server.js +1 -1
  27. package/dist/server/index.js +2 -2
  28. package/dist/server/testing.js +2 -2
  29. package/dist/web/index.js +2 -2
  30. package/dist/web/palbe.js +2 -2
  31. package/dist/web/paywall.js +2 -2
  32. package/dist/web/vite.js +2 -2
  33. package/package.json +2 -2
  34. package/types/ai/src/ai.d.ts +20 -2
  35. package/types/ai/src/chats.d.ts +75 -1
  36. package/types/ai/src/index.d.ts +2 -2
  37. package/types/ai/src/tools.d.ts +35 -0
  38. package/types/backend/src/channels.d.ts +81 -0
  39. package/types/backend/src/container.d.ts +4 -2
  40. package/types/backend/src/decorators.d.ts +32 -17
  41. package/types/backend/src/engine.d.ts +12 -4
  42. package/types/backend/src/env.d.ts +1 -1
  43. package/types/backend/src/index.d.ts +4 -2
  44. package/types/backend/src/openapi.d.ts +3 -0
  45. package/types/backend/src/rooms.d.ts +10 -0
  46. package/types/backend/src/tasks.d.ts +168 -0
  47. package/types/internal/src/chat.d.ts +17 -1
  48. package/types/internal/src/modules/ai.d.ts +314 -0
  49. package/types/internal/src/modules/auth.d.ts +64 -47
  50. package/types/internal/src/modules/machines.d.ts +320 -79
  51. package/types/internal/src/modules/notify.d.ts +3 -3
  52. package/types/internal/src/modules/purchases.d.ts +562 -3
  53. package/types/internal/src/modules/storage.d.ts +32 -3
  54. package/types/web/src/ai.d.ts +25 -2
  55. package/types/web/src/client.d.ts +7 -0
  56. package/types/web/src/index.d.ts +1 -1
  57. package/types/web/src/paywall/placement.d.ts +2 -0
  58. package/types/web/src/purchases.d.ts +3 -1
  59. package/dist/chunks/CY6B75KF.js +0 -6
  60. package/dist/chunks/EGRDFD5C.js +0 -20
  61. package/dist/chunks/ZFX4BFQR.js +0 -2
@@ -37,7 +37,7 @@ export type BucketList = {
37
37
  };
38
38
  export type BucketVariant = {
39
39
  /**
40
- * cover fills the box and crops; contain and inside keep the whole picture inside it (inside never enlarges). Absent: contain.
40
+ * cover fills the box and crops; contain and inside keep the whole picture inside it (inside never enlarges). Absent: inside — at most the box, a smaller source kept at its own size.
41
41
  */
42
42
  fit: "cover" | "contain" | "inside";
43
43
  /**
@@ -61,6 +61,35 @@ export type BucketVariant = {
61
61
  */
62
62
  width: number;
63
63
  };
64
+ /**
65
+ * A rendition as a bucket is written with it: its name, and its width, its height or both; what is left out takes its default.
66
+ */
67
+ export type BucketVariantWrite = {
68
+ /**
69
+ * cover fills the box and crops; contain and inside keep the whole picture inside it (inside never enlarges). Absent: inside — at most the box, a smaller source kept at its own size.
70
+ */
71
+ fit?: "cover" | "contain" | "inside";
72
+ /**
73
+ * The rendition's format. Absent: jpeg.
74
+ */
75
+ format?: "jpeg" | "png" | "webp";
76
+ /**
77
+ * Pixels; 0 or absent derives it from the width and the picture's aspect.
78
+ */
79
+ height?: number;
80
+ /**
81
+ * The rendition's name: a lowercase letter, then lowercase letters, digits and _ (32 at most).
82
+ */
83
+ name: string;
84
+ /**
85
+ * 1 to 100 for jpeg and webp; 0 or absent: the format's default.
86
+ */
87
+ quality?: number;
88
+ /**
89
+ * Pixels; 0 or absent derives it from the height and the picture's aspect.
90
+ */
91
+ width?: number;
92
+ };
64
93
  export type BucketWrite = {
65
94
  /**
66
95
  * The content types it takes; empty or absent: any. image/* names a family. 64 at most.
@@ -77,7 +106,7 @@ export type BucketWrite = {
77
106
  /**
78
107
  * The renditions made of every picture put in it; 16 at most.
79
108
  */
80
- variants?: BucketVariant[];
109
+ variants?: BucketVariantWrite[];
81
110
  };
82
111
  export type ErrorResponse = {
83
112
  /**
@@ -262,7 +291,7 @@ export type StorageObject = {
262
291
  */
263
292
  export type StorageStats = {
264
293
  /**
265
- * Every bucket of the project, by name; an empty one with zeros. A platform module's own bucket is listed with its share too, though the project does not reach it otherwise: _ai holds the pictures its agents' tools returned, deleted with their chat (or once a one-shot answer is answered) — counted in the project's storage as its other files are.
294
+ * Every bucket of the project, by name; an empty one with zeros. A platform module's own bucket is listed with its share too, though the project does not reach it otherwise: _ai holds the pictures its agents' tools returned and, under palai/, its chats' workspaces — their files, their runs' checkpoints and the artifacts their agents published — each deleted with its chat (or once a one-shot answer is answered); counted in the project's storage as its other files are.
266
295
  */
267
296
  buckets: StorageStatsBucket[];
268
297
  /**
@@ -1,10 +1,10 @@
1
- import { type AgentEvent, type ToolEvent, type TurnEvent } from '../../internal/src/chat.js';
1
+ import { type AgentEvent, type ToolEvent, type TurnEvent, type VoiceEvent } from '../../internal/src/chat.js';
2
2
  import { ai as aiModule } from '../../internal/src/modules/index.js';
3
3
  import { type ToolResult } from '../../internal/src/tool-output.js';
4
4
  import { type Transport } from '../../internal/src/transport.js';
5
5
  import type { SessionManager } from './session.js';
6
6
  export type Chat = aiModule.Chat;
7
- export type { AgentEvent, ChatEvent, ToolEvent, TurnEvent } from '../../internal/src/chat.js';
7
+ export type { AgentEvent, ChatEvent, ToolEvent, TurnEvent, VoiceEvent } from '../../internal/src/chat.js';
8
8
  export type { ToolResult } from '../../internal/src/tool-output.js';
9
9
  /** A member's message as this client holds it: one it sent is here at once, pending until the agent has it. */
10
10
  export interface ChatMessageView {
@@ -86,6 +86,18 @@ export interface ChatState {
86
86
  approvals: ToolEvent[];
87
87
  outputs: ToolEvent[];
88
88
  };
89
+ /** The chat's live voice as it went: what was said either way, in order, and when it began, ended or handed a task over. */
90
+ voice: VoiceEvent[];
91
+ }
92
+ /**
93
+ * A chat's live voice this app started (startVoice): its id, its peer connection, and stop. What the voice is
94
+ * told besides what it hears is the app's server's to say (the server SDK), never a member's.
95
+ */
96
+ export interface ChatVoice {
97
+ readonly id: string;
98
+ readonly peer: RTCPeerConnection;
99
+ /** Ends the voice; how long it lasted, in seconds. */
100
+ stop(): Promise<number>;
89
101
  }
90
102
  export interface ChatOptions {
91
103
  /** The journal id to follow from (default 0: the chat from its start). */
@@ -108,6 +120,7 @@ export declare class ChatSession implements AsyncIterable<ChatState> {
108
120
  private readonly order;
109
121
  private turn;
110
122
  private readonly calls;
123
+ private readonly voiceParts;
111
124
  private readonly handlers;
112
125
  private readonly answering;
113
126
  private readonly listeners;
@@ -163,6 +176,16 @@ export declare class ChatSession implements AsyncIterable<ChatState> {
163
176
  deny(approvalId: string, reason?: string): Promise<void>;
164
177
  /** Stops the turn the agent is working on: what it wrote stays. Its response's id, or null when none ran. */
165
178
  stop(): Promise<string | null>;
179
+ /**
180
+ * Starts the chat's live voice from the microphone's stream: the voice's
181
+ * audio plays in audio (a new element unless given), and what is said
182
+ * either way comes into the state's voice parts. One voice a chat at a time.
183
+ */
184
+ startVoice(options: {
185
+ stream: MediaStream;
186
+ voice?: string;
187
+ audio?: HTMLAudioElement;
188
+ }): Promise<ChatVoice>;
166
189
  /** A message for one of the agent's subagents at work (an agent part's run_id), at its next step. */
167
190
  sendToSubagent(runId: string, text: string): Promise<void>;
168
191
  /** Stops following the chat. */
@@ -37,6 +37,13 @@ export interface ClientOptions {
37
37
  * without one.
38
38
  */
39
39
  appVersion?: string;
40
+ /**
41
+ * The registered app's id, as palbase apps:sync writes it into the app's
42
+ * settings: said with a paywall's request, for a placement's rules that
43
+ * name an app. Like the publishable key it ships in the app — it says
44
+ * which app asks, it does not prove it. Its id, not its slug: a UUID.
45
+ */
46
+ appId?: string;
40
47
  }
41
48
  /**
42
49
  * The app's client. A backend's generated Palbe module (palbase apps:sync)
@@ -3,7 +3,7 @@ export type { Auth, CredentialsLike, SignInResult, User } from './auth.js';
3
3
  export { localStore, memoryStore, SessionChangedError, type AuthEvent, type Session, type SessionStore } from './session.js';
4
4
  export { Channel, RealtimeSocket, type PushReply } from './socket.js';
5
5
  export { Analytics, type AnalyticsOptions } from './analytics.js';
6
- export { AI, ChatSession, type AgentEvent, type Chat, type ChatEvent, type ChatItem, type ChatMessageView, type ChatOptions, type ChatPart, type ChatResponse, type ChatState, type ClientToolHandlers, type ToolEvent, type ToolResult, type TurnEvent, } from './ai.js';
6
+ export { AI, ChatSession, type AgentEvent, type Chat, type ChatEvent, type ChatItem, type ChatMessageView, type ChatOptions, type ChatPart, type ChatResponse, type ChatState, type ChatVoice, type ClientToolHandlers, type ToolEvent, type ToolResult, type TurnEvent, type VoiceEvent, } from './ai.js';
7
7
  export { Purchases, type CustomerInfo, type CustomerInfoListener, type MergeGrant, type Offerings } from './purchases.js';
8
8
  export type { Paywall, PaywallRenderOptions } from './paywall/placement.js';
9
9
  export type { PaywallAttribute } from './paywall/attributes.js';
@@ -95,5 +95,7 @@ export declare function loadPaywall(api: Api, ref: string, placement: string, ch
95
95
  locale?: string;
96
96
  /** The app's version, when the client was given one. */
97
97
  appVersion?: string;
98
+ /** The registered app's id, when the client was given one. */
99
+ app?: string;
98
100
  }): Promise<Paywall | null>;
99
101
  export {};
@@ -20,12 +20,14 @@ export declare class Purchases {
20
20
  private fetch;
21
21
  /** The app's version, when it gave one: a paywall's request says it. */
22
22
  private appVersion;
23
+ /** The registered app's id, when the client was given one: a paywall's request says it. */
24
+ private app;
23
25
  private listeners;
24
26
  private watch;
25
27
  private following;
26
28
  /** What listeners were last told: undefined until the first read (or sign-out) is known. */
27
29
  private last;
28
- constructor(transport: Transport, session: SessionManager, socket: RealtimeSocket, ref: string, fetch?: Fetch, appVersion?: string);
30
+ constructor(transport: Transport, session: SessionManager, socket: RealtimeSocket, ref: string, fetch?: Fetch, appVersion?: string, app?: string);
29
31
  /** Everything the signed-in customer has, read now (the first read makes the user a customer). */
30
32
  me(): Promise<CustomerInfo>;
31
33
  /** The paywall's catalog: each product's text and price on a channel — the web's unless another is named. */
@@ -1,6 +0,0 @@
1
- /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
- import{a as k,b as E}from"./2AT72FFB.js";async function*S(e,t={}){let n=e.getReader(),o=new TextDecoder,r="",i="",a=[],g,w=()=>{n.cancel().catch(()=>{})};t.signal?.addEventListener("abort",w,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:T,value:A}=await n.read();if(T||t.signal?.aborted)return;t.onBytes?.(),r+=o.decode(A,{stream:!0});for(let y=r.indexOf(`
3
- `);y>=0;y=r.indexOf(`
4
- `)){let s=r.slice(0,r[y-1]==="\r"?y-1:y);r=r.slice(y+1),s===""?(i!==""&&(yield g===void 0?{event:i,data:a.join(`
5
- `)}:{event:i,data:a.join(`
6
- `),id:g}),i="",a=[],g=void 0):s.startsWith("event:")?i=C(s,6):s.startsWith("data:")?a.push(C(s,5)):s.startsWith("id:")&&(g=C(s,3))}}}finally{t.signal?.removeEventListener("abort",w);try{await n.cancel()}catch{}}}function C(e,t){let n=e.slice(t);return n.startsWith(" ")?n.slice(1):n}function P(e){let t=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o<128?t+=1:o<2048?t+=2:o>=55296&&o<=56319&&n+1<e.length&&(e.charCodeAt(n+1)&64512)===56320?(t+=4,n++):t+=3}return t}function q(e,t){if(t<=0)return 0;let n=0;for(let o=0;o<e.length;o++){let r=e.charCodeAt(o),i=3,a=1;if(r<128?i=1:r<2048?i=2:r>=55296&&r<=56319&&o+1<e.length&&(e.charCodeAt(o+1)&64512)===56320&&(i=4,a=2),n+=i,n>=t)return o+a;o+=a-1}return e.length}function j(e,t){return e.slice(q(e,t))}var M={too_many_streams:()=>"too many chat streams are open at once (4 a user, 32 a project): close one \u2014 chat.close(), or leave a stream's loop \u2014 then follow again",too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:e=>`this user has sent as many messages this minute as the project allows${e.retryAfter!==void 0?`: write again in ${e.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:e=>`the project's storage did not answer when the model was to read a picture${e.retryAfter!==void 0?`: try again in ${e.retryAfter} s`:"; try again shortly"}`},O=new WeakSet;function R(e){if(!(e instanceof E)||O.has(e))return e;let t=M[e.code];if(!t)return e;let n=new E({op:e.op,status:e.status,code:e.code,message:`${t(e)} (${e.op}: ${e.status} ${e.code})`,requestId:e.requestId,retryAfter:e.retryAfter,body:e.body,cause:e});return O.add(n),n}function Y(e){return e.catch(t=>{throw R(t)})}var m=class extends Error{constructor(t){super(t),this.name="StreamCut"}};function z(e,t={}){let n=t.resumeFor??12e4,o=t.idleFor??45e3,r=t.signal,i=t.after,a=t.response,g=new Map;a!==void 0&&g.set(a,t.offset??0);let w=!1,T=()=>{let s={};return i!==void 0&&(s.after=i),a!==void 0&&(s.response=a,s.offset=g.get(a)??0),s};function A(s,_,h){let f=h!==void 0&&/^\d+$/.test(h)?Number(h):void 0;if(f!==void 0&&i!==void 0&&f<=i)return;let c;try{c=k(JSON.parse(_))}catch{throw new m(`a ${s} frame is not JSON`)}if(typeof c!="object"||c===null)throw new m(`a ${s} frame is not an object`);let p;switch(s){case"message":p={type:"message",seq:f??0,message:c};break;case"turn":{let d={...c,type:"turn",seq:f??0};d.waiting??=null,d.error??=null,(d.status==="running"||d.status==="waiting")&&(a=d.response_id),p=d;break}case"text":{let d=String(c.response_id),l=Number(c.offset),u=String(c.text??"");if(!Number.isInteger(l)||l<0)throw new m("a text frame names no offset");a=d;let b=g.get(d)??0,x=l+P(u);if(x<=b)return;let v=l>=b?u:j(u,b-l);g.set(d,x),p={type:"text",response_id:d,offset:Math.max(l,b),text:v};break}case"reset":{let d=String(c.response_id),l=Number(c.offset),u=g.get(d)??0;if(!Number.isInteger(l)||l<0||l>=u)return;g.set(d,l),p={type:"reset",response_id:d,offset:l};break}case"tool":case"agent":p={...c,type:s,seq:f??0};break;default:break}return f!==void 0&&(i=f),p}async function*y(){let s=Date.now()+n,_;for(let h=0;;h++){if(r?.aborted)throw r.reason;let f=new AbortController,c=()=>f.abort(r?.reason);r?.addEventListener("abort",c,{once:!0});let p,d=()=>{clearTimeout(p),p=setTimeout(()=>f.abort(new m(`no byte for ${o} ms`)),o)},l;try{let u=await e(T(),f.signal);if(!u.body)throw new m("the stream has no body");d();let b=S(u.body,{signal:f.signal,onBytes:()=>{d(),s=Date.now()+n,h=0}});for await(let x of b){let v=A(x.event,x.data,x.id);v&&(yield v)}_=new m("the stream ended")}catch(u){if(r?.aborted)throw r.reason;if(u instanceof E){if(u.status>0&&u.status<500&&u.status!==429||u.code==="too_many_streams")throw R(u);u.retryAfter!==void 0&&(l=u.retryAfter*1e3)}_=f.signal.aborted&&f.signal.reason instanceof m?f.signal.reason:u}finally{clearTimeout(p),r?.removeEventListener("abort",c),f.abort()}if(Date.now()+(l??0)>s)throw _;await L(l??Math.min(250*2**Math.min(h,4),4e3),r)}}return{get position(){return T()},[Symbol.asyncIterator](){if(w)throw new TypeError("a chat stream is read once: follow the chat again from its position for another reader");return w=!0,y()}}}function L(e,t){return new Promise((n,o)=>{if(t?.aborted)return o(t.reason);let i=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(i),o(t?.reason)};t?.addEventListener("abort",a,{once:!0})})}var N=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function K(e){return Array.isArray(e)&&e.length>0&&e.every(F)?e.map($):F(e)?[$(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function F(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.type==="text"?typeof t.text=="string":t.type==="image"?(typeof t.mediaType=="string"||typeof t.media_type=="string")&&(typeof t.data=="string"||t.data instanceof Uint8Array):t.type===void 0&&typeof t.mediaType=="string"&&t.bytes instanceof Uint8Array}function $(e){if("type"in e&&e.type==="text")return{type:"text",text:e.text};let t="bytes"in e||"mediaType"in e?e.mediaType:e.media_type;if(!N.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let n="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof n=="string"?n:B(n)}}function B(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}export{S as a,P as b,q as c,j as d,R as e,Y as f,z as g,K as h};
@@ -1,20 +0,0 @@
1
- /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
- import{a as wn,c as Q,d as bn,e as $e,g as _,h as vn}from"./ST2NZ4TZ.js";import{b as Ze,d as bt,e as mn,f as hn,g as Xe,h as Qe,k as gn,q as yn}from"./SUNHFMDO.js";import{b as ke}from"./2AT72FFB.js";import"reflect-metadata";var vt=[{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}],kn="a schedule is five fields \u2014 minute hour day-of-month month day-of-week, in UTC \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",et=/^\d+$/;function qr(e,t,r){let n=new Set;for(let o of e.split(",")){let s=o.indexOf("/"),a=s===-1?o:o.slice(0,s),i=1;if(s!==-1){let h=o.slice(s+1);if(!et.test(h)||Number(h)<1||Number(h)>r)return;i=Number(h)}let c=t,l=r;if(a!=="*")if(a.includes("-")){let h=a.indexOf("-"),b=a.slice(0,h),S=a.slice(h+1);if(!et.test(b)||!et.test(S)||Number(b)<t||Number(S)>r||Number(b)>Number(S))return;c=Number(b),l=Number(S)}else{if(!et.test(a)||Number(a)<t||Number(a)>r)return;c=Number(a),l=s===-1?c:r}for(let h=c;h<=l;h+=i)n.add(h)}return n}function $n(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${kn}; "${e}" is not`;let r=[];for(let l=0;l<5;l++){let h=qr(t[l],vt[l].lo,vt[l].hi);if(!h)return`${kn}; its ${vt[l].name} "${t[l]}" is not one`;r.push(h)}let[,,n,o,s]=r;s.has(7)&&s.add(0);let a=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let l=0;l<366*8+2;l++,c.setUTCDate(c.getUTCDate()+1)){if(!o.has(c.getUTCMonth()+1))continue;let h=n.has(c.getUTCDate()),b=s.has(c.getUTCDay());if(a||i?h&&b:h||b)return}return`"${e}" is never due: no date has that day in that month`}var Re=Symbol.for("palbase.backend.controller"),Ee=Symbol.for("palbase.backend.routes"),$t=Symbol.for("palbase.backend.params"),Rt=Symbol.for("palbase.backend.injectable"),Et=Symbol.for("palbase.backend.module"),me=Symbol.for("palbase.backend.events"),_e=Symbol.for("palbase.backend.webhook"),ue=Symbol.for("palbase.backend.jobs");function ne(e,t,r){let n=e;return Object.prototype.hasOwnProperty.call(n,t)||Object.defineProperty(n,t,{value:r(),enumerable:!1}),n[t]}var kt=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[kt]instanceof Set||(e[kt]=new Set),e[kt]}var Se=new Set(["webhooks","_palbase"]);function da(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return r=>{let n=e.split("/").filter(Boolean)[0];if(n!==void 0&&Se.has(n))throw new TypeError(`@Controller("${e}") on ${r.name}: /${n} is the platform's; a controller is served elsewhere`);ne(r,Re,()=>({basePath:e,options:t})),se().add(r)}}function xe(e){return(t,r={})=>{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(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ne(n.constructor,Ee,()=>[]).push({method:e,subpath:t,fn:o,options:r})}}}var ca=xe("GET"),ua=xe("POST"),la=xe("PUT"),fa=xe("PATCH"),pa=xe("DELETE"),ma=xe("QUERY");function re(e,t={}){return(r,n,o)=>{if(typeof n!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let s=ne(r.constructor,$t,()=>new Map);s.has(n)||s.set(n,[]),s.get(n).push({index:o,kind:e,...t})}}function _t(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 ha=e=>re("body",{schema:_t("Body",e)}),ga=e=>re("query",{schema:_t("QueryParams",e)}),ya=e=>re("headers",e===void 0?{}:{schema:_t("Headers",e)}),wa=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return re("param",{name:e})},ba=()=>re("user"),va=()=>re("optionalUser"),ka=()=>re("req"),$a=()=>re("requestId"),Ra=()=>re("requestId"),Ea=()=>re("client");function _a(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 re("resolve",{resolver:e,options:t[0]})}function Sa(){return e=>{ne(e,Rt,()=>!0),se().add(e)}}function xa(e){return t=>{ne(t,Et,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var En=/^[a-z]+(\.[a-z_]+)+$/,Br=/^[a-z][a-z0-9-]{1,62}$/,St=e=>e.startsWith("file.");function Oa(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let r=t?.bucket;if(r!==void 0){if(typeof r!="string"||!Br.test(r))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(r)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!St(e))throw new TypeError(`@On("${e}", { bucket: "${r}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ne(n.constructor,me,()=>[]).push(r===void 0?{event:e,fn:o}:{event:e,fn:o,bucket:r}),se().add(n.constructor)}}var zr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function Ta(e){let t=e??{},r=`@Job(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!zr.test(t.name))throw new TypeError(`${r}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${r}: schedule is five fields of cron's, like "0 3 * * *"`);let n=$n(t.schedule);if(n)throw new TypeError(`${r}: ${n}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>300))throw new TypeError(`${r}: timeout is whole seconds, 1 to 300 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${r}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let o={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeout:t.timeout??30,retries:t.retry??5};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${r} on ${s.name}: a job is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(s,ue))throw new TypeError(`${r} on ${s.name}: a class is one job`);Object.defineProperty(s,ue,{value:o,enumerable:!1}),se().add(s)}}var Rn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Fr=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Aa(e){return t=>{let r=`@Webhook on ${t.name}`,n=e??{};if(typeof n.name!="string"||n.name==="")throw new TypeError(`${r}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!Fr.test(n.name))throw new TypeError(`${r}: name "${n.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(n.name==="palbase")throw new TypeError(`${r}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(n.provider===void 0&&n.signature===void 0)throw new TypeError(`${r}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(n.provider!==void 0&&n.signature!==void 0)throw new TypeError(`${r}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(n.provider!==void 0&&!Rn.includes(n.provider))throw new TypeError(`${r}: provider "${String(n.provider)}" is not one of ${Rn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(n.signature!==void 0&&Wr(n.signature,r),typeof n.secret?.env!="string"||n.secret.env==="")throw new TypeError(`${r}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let o=j(t,me)??[];if(o.length===0)throw new TypeError(`${r}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let s=new Set;for(let{event:a,bucket:i}of o){if(s.has(a))throw new TypeError(`${r}: @On("${a}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${r}: @On("${a}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${n.name}'s are a third party's`);s.add(a)}ne(t,_e,()=>({name:n.name,provider:n.provider,signature:n.signature&&{...n.signature},secret:{env:n.secret.env},events:o.map(({event:a,fn:i})=>({event:a,fn:i}))})),se().add(t)}}function Wr(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 j(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Pa(){return[...se()].filter(e=>j(e,Re)!==void 0)}function ja(e){return(j(e,Ee)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var xt="/_palbase/storage/upload/authorize",_n="/_palbase/storage/upload/complete",Ot="/_palbase/realtime/rooms";var Kr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Oe(e){if(!Kr(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 Sn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function xn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function tt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Vr=/^[a-z][a-z0-9-]{1,62}$/,On=1024,Yr=new Set(["userId","uploadId","filename"]);function Na(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let r=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 r.bucket!="string"||r.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Vr.test(r.bucket))throw new TypeError(`@Upload("${e}"): bucket "${r.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof r.pathTemplate!="string"||r.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let n=Gr(r.pathTemplate);if(n)throw new TypeError(`@Upload("${e}"): pathTemplate "${r.pathTemplate}" ${n}`);let o={bucket:r.bucket,pathTemplate:r.pathTemplate},s={...r.auth!==void 0?{auth:r.auth}:{},...r.rateLimit!==void 0?{rateLimit:r.rateLimit}:{}};return(a,i,c)=>{if(typeof i!="string"||c===void 0||typeof c.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ne(a.constructor,Ee,()=>[]).push({method:"POST",subpath:e,fn:i,options:s,upload:o})}}function Ia(){return re("uploadedObject")}function Gr(e){for(let r of e.matchAll(/\{([^{}]*)\}/g))if(!Yr.has(r[1]))return`names {${r[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(!Tn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Tn(e){if(e===""||new TextEncoder().encode(e).byteLength>On)return!1;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32||r===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Zr(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(r,n)=>Xr(n==="userId"?t.userId??"anonymous":n==="uploadId"?t.uploadId:t.filename??"file"))}function Xr(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 An(e,t){let r=Zr(e,t);return Tn(r)?{path:r}:{problem:`the file's name makes its path longer than storage keeps (${On} bytes)`}}function Pn(e){let t=new Map;for(let r of e)r.meta.upload&&t.set(r.controller,(t.get(r.controller)??new Set).add(r.fn));for(let r of e){let n=`${r.controller.name}.${r.fn}`;if(!r.meta.upload){if(t.get(r.controller)?.has(r.fn))throw new TypeError(`${n}: @Upload and @${r.method[0]}${r.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(r.params.some(s=>s.kind==="uploadedObject"))throw new TypeError(`${n}: @UploadedObject() on ${r.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let o=r.params.find(s=>s.kind==="headers"||s.kind==="req"||s.kind==="client");if(o){let s=o.kind==="headers"?"Headers":o.kind==="req"?"Req":"Client";throw new TypeError(`${n}: @${s}() 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 Tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function jn(e,t){if(!Tt(t))return"a call is a JSON object";let{route:r,method:n,query:o,uploadId:s}=t;if(typeof r!="string"||!r.startsWith("/"))return"route is the upload route's path";if(typeof n!="string"||n==="")return"method is the route's";if(typeof o!="string")return'query is the query string, "" for none';if(typeof s!="string"||s==="")return"uploadId is the upload's id";let a=Oe(t.user);if(!a)return"user is { id?, session?, role }";let i=Sn(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:r,method:n,query:o,uploadId:s,user:a,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Qr(t.uploadedObject);return c?c.uploadId!==s?"uploadedObject is another upload's":{route:r,method:n,query:o,uploadId:s,user:a,...i?{client:i}:{},filename:"",uploadedObject:c,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Qr(e){if(!Tt(e))return;let{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,width:i,height:c,thumbhash:l,variants:h}=e;if(!(typeof t!="string"||typeof r!="string"||typeof n!="string"||typeof s!="string"||typeof a!="string")&&!(typeof o!="number"||!Number.isInteger(o)||o<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||l!==void 0&&typeof l!="string")&&!(!Tt(h)||!Object.values(h).every(b=>typeof b=="string")))return{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...l!==void 0?{thumbhash:l}:{},variants:{...h}}}import{markData as eo}from"palgres";var he=Symbol.for("palbase.backend.room"),Ae=Symbol.for("palbase.backend.roomHooks"),to=6e4,Te=255,no=["roles:","flags:","messaging:","debug:"],jt=e=>new TextEncoder().encode(e).byteLength,Cn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function ro(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(jt(e)>Te)return`a channel is ${Te} 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=no.find(n=>e.startsWith(n));if(t)return`${t} channels are the platform's`;let r=new Set;for(let n of e.split(":")){if(n==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(n)){if(n==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(n))return`"${n}" \u2014 a parameter is a whole segment, {name}`;if(r.has(n))return`parameter "${n}" appears twice.`;r.add(n)}}}function Mn(e){if(typeof e!="string"||e==="")return"is a name";if(jt(e)>Te)return`is ${Te} bytes at most`}function za(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let r=ro(e);if(r)throw new TypeError(`@Room("${e}"): ${r}`);let n=t??{};if(typeof n.events!="object"||n.events===null||Array.isArray(n.events))throw new TypeError(`@Room("${e}"): events is required \u2014 what the room sends, by name, each its payload's schema ({} for none)`);for(let[a,i]of Object.entries(n.events)){let c=Mn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!Cn(i))throw new TypeError(`@Room("${e}"): event "${a}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}if(n.graceMs!==void 0&&(!Number.isSafeInteger(n.graceMs)||n.graceMs<=0))throw new TypeError(`@Room("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(n.graceMs)})`);let o={...n.events},s=n.graceMs??to;return a=>{let i=ne(a,Ae,Ct);ne(a,he,()=>({pattern:e,events:o,graceMs:s,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),se().add(a)}}var Ct=()=>({hooks:Object.create(null),messages:Object.create(null)});function Ie(e){let t=`On${e[0].toUpperCase()}${e.slice(1)}`;return()=>(r,n,o)=>{if(typeof n!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof r=="function")throw new TypeError(`@${t}() on static ${r.name}.${n}: a room's methods are its instance's`);let s=ne(r.constructor,Ae,Ct),a=s.hooks[e];if(a!==void 0&&a!==n)throw new TypeError(`@${t}() is declared twice in one room (${a} and ${n}). A room has one of each hook.`);s.hooks[e]=n,se().add(r.constructor)}}var Fa=Ie("authorize"),Wa=Ie("first"),Ka=Ie("join"),Va=Ie("leave"),Ya=Ie("empty");function Ga(e,t){let r=Mn(e);if(r)throw new TypeError(`@OnMessage(name, schema): name ${r}`);if(!Cn(t))throw new TypeError(`@OnMessage("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@OnMessage("${e}") goes on a method`);if(typeof n=="function")throw new TypeError(`@OnMessage("${e}") on static ${n.name}.${o}: a room's methods are its instance's`);let a=ne(n.constructor,Ae,Ct),i=a.messages[e];if(i!==void 0&&i.fn!==o)throw new TypeError(`@OnMessage("${e}") is declared twice in one room (${i.fn} and ${o}).`);a.messages[e]={fn:o,schema:t},se().add(n.constructor)}}function oo(e){return j(e,he)}function so(e,t){let r=e.split(":"),n=t.split(":");if(r.length!==n.length)return;let o=[];for(let s=0;s<r.length;s++){let a=r[s];if(a.length>=2&&a.startsWith("{")&&a.endsWith("}")){if(n[s]==="")return;o.push([a.slice(1,-1),n[s]])}else if(a!==n[s])return}return Object.fromEntries(o)}var ao=1e4,io=1e3,co=100,Mt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ie=(e,t,r,n)=>({status:e,code:t,message:r,...n!==void 0?{retryAfter:n}:{}}),uo=new Set(["first","join","leave","empty"]);function Dn(e,t){let r=new Map,n=new Map;for(let{cls:k,instance:$}of e){let v=oo(k),O=v.pattern.split(":").map(A=>A.startsWith("{")?"{}":A).join(":"),M=n.get(O);if(M!==void 0)throw new TypeError(`@Room("${v.pattern}") on ${k.name}: ${r.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one room is told of them; keep one`);n.set(O,v.pattern);for(let[A,J]of[...Object.entries(v.hooks),...Object.entries(v.messages).map(([B,U])=>[`message ${B}`,U.fn])])if(typeof $[J]!="function")throw new TypeError(`@Room("${v.pattern}") on ${k.name}: its ${A} is ${J}, which is no method of it`);r.set(v.pattern,{cls:k,instance:$,room:v})}let o=new Map,s=new Set,a=new Set,i=new Pt(t.broadcast),c=k=>{let $=o.get(k);return $||($=new AbortController,o.set(k,$)),$},l=(k,$)=>{$?.abort(),o.get(k)===$&&o.delete(k)};function h(k,$,v,O,M,A,J){let B=O?.signal??AbortSignal.abort(),U=`${k.cls.name} (${$})`;return{room:$,params:Object.freeze({...v}),signal:B,count:M,user:A,emit:(F,V)=>i.send({topic:$,event:F,payload:V??{},...J!==void 0?{conn_id:J}:{}},U),owner:{hold(F){Q.exit(async()=>{try{await F(B)}catch(V){B.aborted||_.error(`[palbase] ${U}: a task owner.hold ran failed`,{error:V})}}).catch(()=>{})},release:()=>l($,O)}}}function b(k){let{room:$,channel:v}=k;if(typeof $!="string"||typeof v!="string")return ie(400,"bad_request","A room's call names its room (the pattern) and its channel");let O=r.get($);return O?{entry:O,channel:v,params:so($,v)}:ie(404,"not_found",`This app declares no room "${$}"`)}let S=(k,$)=>ie(400,"bad_request",`"${$}" is not a channel of the room "${k}"`);async function I(k,$){let v=b(k);if("status"in v)return v;let{entry:O,channel:M,params:A}=v,J={status:200,body:{subscribe:!1,publish:!1}};if(!A)return _.warn(`[palbase] ${O.cls.name}: realtime asked about "${M}", which is not a channel of the room "${O.room.pattern}"; the join is refused`),J;let B=Oe(k.user),U=B?.id;if(!U)return J;let F=O.room.hooks.authorize;if(!F)return J;let V,Y;try{V=await t.run(B,`${O.cls.name}.${F}`,$,async()=>O.instance[F]({user:{id:U},params:Object.freeze({...A})})),Y=lo(V)}catch(G){if(t.isOutage(G)||$?.aborted)throw G;return _.error(`[palbase] ${O.cls.name}.${F} (@OnAuthorize of ${M}) failed; the join is refused`,{error:G}),J}return Y==="malformed"?(_.warn(`[palbase] ${O.cls.name}.${F} (@OnAuthorize of ${M}) answered ${fo(V)}, which is no grant (true, { read, write } or null); the join is refused`),J):{status:200,body:Y}}async function y(k,$){let v=b(k);if("status"in v)return v;if(!v.params)return S(v.entry.room.pattern,v.channel);let O=Oe(k.user);if(!O?.id||typeof k.event!="string")return ie(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(v.entry.room.messages,k.event)?v.entry.room.messages[k.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:Un(`room "${v.channel}" declares no message "${k.event}"`,At)}};let A=await M.schema["~standard"].validate(eo(k.payload??{}));if(A.issues)return{status:200,body:{ok:!1,reason:mo(A.issues)}};let J=c(v.channel),B={...h(v.entry,v.channel,v.params,J,0,{id:O.id}),payload:A.value};try{await t.run(O,`${v.entry.cls.name}.${M.fn}`,$,async()=>v.entry.instance[M.fn](B))}catch(U){if(t.isOutage(U))throw U;return $?.aborted||_.error(`[palbase] ${v.entry.cls.name}.${M.fn} (@OnMessage "${k.event}" of ${v.channel}) failed`,{error:U}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function C(k,$){let v=b(k);if("status"in v)return v;if(!v.params)return S(v.entry.room.pattern,v.channel);let O=k.event;if(typeof O!="string"||!uo.has(O))return ie(400,"bad_request","A room's moment is first, join, leave or empty");let M=typeof k.count=="number"&&Number.isInteger(k.count)&&k.count>=0?k.count:void 0;if(M===void 0)return ie(400,"bad_request","A room's moment says its count of members");let A=O==="join"||O==="leave",J=A?Oe(k.user):void 0,B=A?k.connId:void 0;if(A&&(!J?.id||typeof B!="string"||B===""))return ie(400,"bad_request",`A ${O} names its member: user and connId`);let U=`${O}\0${v.channel}\0${typeof B=="string"?B:""}`;if(A&&s.has(U))return{status:204};if(a.has(U))return ie(503,"in_progress","This moment of the room is being handled",5);a.add(U);try{let F=v.entry.room.hooks[O],V;if(O==="empty"?(V=o.get(v.channel),l(v.channel,V)):V=O==="leave"?o.get(v.channel):c(v.channel),F){let Y=h(v.entry,v.channel,v.params,V,M,{id:J?.id??""},O==="join"?B:void 0);try{await t.run(J,`${v.entry.cls.name}.${F}`,$,async()=>v.entry.instance[F](Y))}catch(G){if(t.isOutage(G))throw G;return $?.aborted||_.error(`[palbase] ${v.entry.cls.name}.${F} (${O} of ${v.channel}) failed; realtime tells it again`,{error:G}),ie(500,"handler_failed",`The room's ${O} could not be handled`)}}return A&&(s.add(U),s.size>ao&&s.delete(s.values().next().value)),{status:204}}finally{a.delete(U)}}return{declarations:[...r.values()].map(k=>k.room),async serve(k,$,v){return Mt($)?k==="authorize"?I($,v):k==="message"?y($,v):k==="lifecycle"?C($,v):ie(404,"not_found",`No room call ${JSON.stringify(k)}`):ie(400,"bad_request","A room's call is a JSON object")},close(){for(let k of o.values())k.abort();o.clear()}}}function lo(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!Mt(e))return"malformed";let r=Object.hasOwn(e,"read"),n=Object.hasOwn(e,"write");if(r&&typeof e.read!="boolean"||n&&typeof e.write!="boolean"||!r&&!n)return"malformed";let o=r?e.read:void 0,s=n?e.write:void 0;return o===!1?t:{subscribe:!0,publish:s!==!1}}function fo(e){return Array.isArray(e)?"an array":Mt(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 po=20,At=256;function mo(e){let t="";for(let r of e.slice(0,po)){let n=(r.path??[]).slice(0,8).map(s=>String(typeof s=="object"&&s!==null&&"key"in s?s.key:s).slice(0,64)).join("."),o=n===""?r.message:`${n}: ${r.message}`;if(t=t===""?o:`${t}; ${o}`,Buffer.byteLength(t)>=At)break}return Un(t,At)}function Un(e,t){if(Buffer.byteLength(e)<=t)return e;let r="";for(let n of e){if(Buffer.byteLength(r+n)>t-3)break;r+=n}return`${r}\u2026`}var Pt=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,r){if(typeof t.event!="string"||t.event===""||jt(t.event)>Te){_.warn(`[palbase] ${r}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Te} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${r}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let n=this.queues.get(t.topic);if(n){n.length>=io?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):n.push(t);return}let o=[t];this.queues.set(t.topic,o),Q.exit(()=>this.drain(t.topic,o,r))}async drain(t,r,n){for(;;){if(r.length===0){this.queues.delete(t);return}let o=r.splice(0,co);try{await this.broadcast(o)}catch(a){_.warn(`[palbase] ${n}: ${o.length} event(s) to ${t} were not sent`,{error:a})}let s=this.dropped.get(t);s&&(this.dropped.delete(t),_.warn(`[palbase] ${n}: ${s} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Dt,createHmac as ho,createPublicKey as Jn,timingSafeEqual as go,verify as Hn}from"node:crypto";function ei(e){let t=j(e,_e);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(r=>r.event)}}function qn(e,t,r,n={}){let o=new Map,s=[];for(let a of e){let i=j(a,_e),c=o.get(i.name);if(c)throw new TypeError(`@Webhook "${i.name}" is declared by ${c.cls.name} and by ${a.name}: /webhooks/${i.name} is one endpoint`);let l=`@Webhook "${i.name}" (${a.name})`,h=r[i.secret.env],b;if(n.secrets!==!1)if(h===void 0||h==="")s.push(`${l} reads its signing secret from ${i.secret.env}, which is not set`);else try{b=yo(i,h)}catch(y){s.push(`${l}: ${i.secret.env} ${y.message}`)}let S=t(a),I=new Map(i.events.map(({event:y,fn:C})=>[y,{name:`${a.name}.${C}`,call:(k,$)=>S[C](k,$)}]));o.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:b,events:I})}if(s.length>0)throw new Error(`[palbase] the app cannot start:
3
- - ${s.join(`
4
- - `)}`);return o}function Bn(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Pe=1024,Nn=1024*Pe;function yo(e,t){if(e.signature)return ge(void 0,e.signature.header,1/0,Oo(e.signature,t));switch(e.provider){case"stripe":return ge("stripe","stripe-signature",512*Pe,vo(t));case"github":return ge("github","x-hub-signature-256",25*Nn,ko(t));case"slack":return ge("slack","x-slack-signature",64*Pe,$o(t));case"discord":return ge("discord","x-signature-ed25519",64*Pe,Ro(t));case"twilio":return{header:"x-twilio-signature",maxBytes:r=>Math.min(r,64*Pe),check:_o(t)};case"sendgrid":return ge("sendgrid","x-twilio-email-event-webhook-signature",Nn,So(t));case"livekit":return ge("livekit","authorization",512*Pe,xo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function ge(e,t,r,n){return{header:t,maxBytes:o=>Math.min(o,r),check:(o,s)=>n(o,s)??zn(e,o)}}function zn(e,t){let r=Ut(t.body),n;try{n=JSON.parse(r)}catch{if(n=r,e==="slack"){let o=new URLSearchParams(r).get("payload");if(o!==null)try{n=JSON.parse(o)}catch{}}}return{type:Fn(e,t.headers,n),event:n,...wo(e,t,n)}}function Fn(e,t,r){switch(e){case"github":{let n=t.get("x-github-event")??"",o=ye(r,"action");return n!==""&&o!==""?`${n}.${o}`:n}case"discord":{let n=Vn(r)?r.type:void 0;return n===1?"PING":n===2?"INTERACTION_CREATE":Number.isInteger(n)?`type_${String(n)}`:""}case"sendgrid":return"event_batch";case"twilio":return ye(r,"EventType");case"livekit":return ye(r,"event");default:return ye(r,"type")}}function wo(e,t,r){let n=o=>o?{id:o}:{};switch(e){case"stripe":case"discord":case"livekit":return n(ye(r,"id"));case"slack":return n(ye(r,"event_id"));case"github":{let o=t.headers.get("x-github-delivery");return o?{id:`${o}:${Wn(t.body)}`}:{}}case"sendgrid":return Array.isArray(r)?{ids:r.map(o=>ye(o,"sg_event_id")||void 0)}:{};default:return{}}}var bo=300;function vo(e){return(t,r)=>{let n=t.headers.get("stripe-signature");if(!n)return"missing_signature";let o,s=[];for(let c of n.split(",")){let l=c.indexOf("=");if(l<=0)continue;let h=c.slice(0,l).trim(),b=c.slice(l+1).trim();if(h==="t"){if(o!==void 0)return"malformed_signature";o=b}else if(h==="v1"){let S=oe(b,"hex");if(!S)return"malformed_signature";s.push(S)}}let a=Le(o);if(a===void 0||s.length===0)return"malformed_signature";if(Je(a,r))return"stale_timestamp";let i=je("sha256",e,`${o}.`,t.body);return s.some(c=>le(c,i))?void 0:"signature_mismatch"}}function ko(e){return t=>{let r=t.headers.get("x-hub-signature-256");if(!r)return"missing_signature";let n=r.startsWith("sha256=")?oe(r.slice(7),"hex"):void 0;return n?le(n,je("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function $o(e){return(t,r)=>{let n=t.headers.get("x-slack-signature");if(!n)return"missing_signature";let o=t.headers.get("x-slack-request-timestamp")?.trim(),s=Le(o),a=n.startsWith("v0=")?oe(n.slice(3),"hex"):void 0;return s===void 0||!a?"malformed_signature":Je(s,r)?"stale_timestamp":le(a,je("sha256",e,`v0:${o}:`,t.body))?void 0:"signature_mismatch"}}function Ro(e){let t=oe(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 r=Jn({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(n,o)=>{let s=n.headers.get("x-signature-ed25519");if(!s)return"missing_signature";let a=n.headers.get("x-signature-timestamp")??void 0,i=Le(a),c=oe(s,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Je(i,o)?"stale_timestamp":Hn(null,Kn(a,n.body),r,c)?void 0:"signature_mismatch"}}var Eo=1e3;function _o(e){return t=>{let r=t.headers.get("x-twilio-signature");if(!r)return"missing_signature";let n=oe(r.trim(),"base64");if(!n||n.byteLength!==20)return"malformed_signature";let o;try{o=new URL(t.url)}catch{return"signature_mismatch"}let s=o.searchParams.get("bodySHA256"),a="",i;if(s!==null){if(!le(Buffer.from(s.toLowerCase()),Buffer.from(Dt("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let I=1;for(let k of t.body)if(k===38&&++I>Eo)return"malformed_signature";let y=new Map;for(let[k,$]of new URLSearchParams(Ut(t.body))){let v=y.get(k);v||y.set(k,v=new Set),v.add($)}let C=[];for(let k of[...y.keys()].sort()){let $=[...y.get(k)].sort();for(let v of $)a+=k+v;C.push([k,$.length===1?$[0]:$])}i=Object.fromEntries(C)}let c=o.protocol==="https:"?"443":"80",l=`${o.protocol}//${o.hostname}${o.pathname}${o.search}`,h=`${o.protocol}//${o.hostname}:${o.port||c}${o.pathname}${o.search}`;if(![l,h].some(I=>le(n,je("sha1",e,I,a))))return"signature_mismatch";let b=t.headers.get("i-twilio-idempotency-token"),S=b?{id:`${b}:${Wn(`${l}
5
- ${a}`)}`}:{};return i?{type:Fn("twilio",t.headers,i),event:i,...S}:{...zn("twilio",t),...S}}}function So(e){let t;try{let r=oe(e,"base64");if(!r)throw new Error;t=Jn({key:Buffer.from(r),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(r,n)=>{let o=r.headers.get("x-twilio-email-event-webhook-signature");if(!o)return"missing_signature";let s=r.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),a=Le(s),i=oe(o.trim(),"base64");return a===void 0||!i?"malformed_signature":Je(a,n)?"stale_timestamp":Hn("sha256",Kn(s,r.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var In=60;function xo(e){return(t,r)=>{let n=t.headers.get("authorization");if(!n)return"missing_signature";let o=n.split(".");if(o.length!==3)return"malformed_signature";let s=Ln(oe(o[0],"base64url")),a=oe(o[2],"base64url");if(s?.alg!=="HS256"||!a)return"malformed_signature";if(!le(a,je("sha256",e,`${o[0]}.${o[1]}`)))return"signature_mismatch";let i=Ln(oe(o[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(r>i.exp+In||typeof i.nbf=="number"&&r<i.nbf-In)return"stale_timestamp";let c=typeof i.sha256=="string"?oe(i.sha256,"base64"):void 0;return c&&le(c,Dt("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function Oo(e,t){let r=e.signs.split(/(\{body\}|\{ts\})/),n=e.algo==="hmac-sha1"?"sha1":"sha256";return(o,s)=>{let a=o.headers.get(e.header);if(!a)return"missing_signature";if(e.prefix){if(!a.startsWith(e.prefix))return"malformed_signature";a=a.slice(e.prefix.length)}let i="";if(r.includes("{ts}")){i=o.headers.get(e.timestampHeader)?.trim()??"";let l=Le(i);if(l===void 0)return"malformed_signature";if(Je(l,s))return"stale_timestamp"}let c=oe(a.trim(),e.encoding);return c?le(c,je(n,t,...r.map(l=>l==="{body}"?o.body:l==="{ts}"?i:l)))?void 0:"signature_mismatch":"malformed_signature"}}var To=new TextEncoder;function je(e,t,...r){let n=ho(e,t);for(let o of r)n.update(o);return n.digest()}function Wn(e){return Dt("sha256").update(e).digest("hex")}function Kn(e,t){return Buffer.concat([To.encode(e),t])}function le(e,t){return e.byteLength===t.byteLength&&go(e,t)}var Ao={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 oe(e,t){return Ao[t].test(e)?Buffer.from(e,t):void 0}function Le(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Je(e,t){return Math.abs(t-e)>bo}function Ut(e){return new TextDecoder().decode(e)}function Ln(e){if(e)try{return JSON.parse(Ut(e))}catch{return}}function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ye(e,t){let r=Vn(e)?e[t]:void 0;return typeof r=="string"?r:""}import"reflect-metadata";var z=class extends Error{kind;path;constructor(t,r,n,o,s){super(`
6
- Kind: ${t}
7
- Path: ${r.join(" -> ")}
8
- At: ${n}
9
- ${o}
10
-
11
- Potential solutions:
12
- ${s.map(a=>` - ${a}`).join(`
13
- `)}`),this.name="DiError",this.kind=t,this.path=r}},Po=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],jo=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),nt=class{owner=new Map;defs=new Map;instances=new Map;order=[];controllers=[];eventProviders=[];webhooks=[];jobProviders=[];rooms=[];constructor(t){this.collect(t),this.validate()}collect(t){let r=(n,o)=>{if(this.defs.has(n))return;let s=j(n,Et);if(!s)throw new z("unknown import",[...o,n.name],n.name,`${n.name} is not a @Module`,["decorate it with @Module({ \u2026 })","or list the module itself, not one of its classes"]);this.defs.set(n,s);for(let a of s.imports){if(a===n)throw new z("unknown import",[n.name],n.name,`${n.name} imports itself`,["remove it from its own imports"]);r(a,[...o,n.name])}};for(let n of t)r(n,[]);for(let[n,o]of this.defs){for(let s of[...o.controllers,...o.providers]){let a=this.owner.get(s);if(a&&a!==n)throw new z("duplicate ownership",[a.name,s.name,n.name],s.name,`${s.name} is listed by ${a.name} and by ${n.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(s,n)}for(let s of o.controllers){if(!j(s,Re))throw new z("undeclared provider",[n.name,s.name],s.name,`${s.name} is in ${n.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(j(s,ue))throw new z("undeclared provider",[n.name,s.name],s.name,`${s.name} is a controller and a @Job: a job is a provider's`,["give the job a class of its own \u2014 @Injectable() @Job({ name, schedule }) with run(meta) \u2014 listed in the module's providers"]);if(j(s,he)||j(s,Ae))throw new z("undeclared provider",[n.name,s.name],s.name,`${s.name} is a controller and a @Room: a room is a provider's`,["give the room a class of its own, listed in the module's providers"]);this.controllers.push({cls:s,module:n})}}}validate(){for(let t of se())if(!this.owner.has(t))throw new z("unowned class",[t.name],t.name,`${t.name} is declared but no module lists it: it would never be built`,["list it in a module's controllers or providers","or delete it"]);for(let[t,r]of this.defs){for(let n of r.exports)if(this.owner.get(n)!==t)throw new z("unknown export",[t.name,n.name],t.name,`${t.name} exports ${n.name}, which it does not own`,[`list ${n.name} in ${t.name}'s providers`,"or export it from the module that owns it"]);for(let n of r.providers){if(j(n,Ae)&&!j(n,he))throw new z("undeclared provider",[t.name,n.name],n.name,`${n.name} has a room's methods (@OnAuthorize, @OnFirst, @OnMessage\u2026) but is no @Room`,["decorate it with @Room(pattern, { events })"]);if(!j(n,Rt)&&!j(n,me)&&!j(n,he)&&!j(n,ue)){let o=Reflect.getMetadata("design:paramtypes",n);throw n.length>0&&!o?new z("metadata missing",[t.name,n.name],n.name,`${n.name} has constructor parameters but no emitted types`,["decorate it with @Injectable()","enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json"]):new z("undeclared provider",[t.name,n.name],n.name,`${n.name} is in ${t.name}'s providers but is not @Injectable() (nor an @On handler, a @Room or a @Job)`,["decorate it with @Injectable()"])}j(n,he)&&this.rooms.push(n),j(n,_e)?this.webhooks.push(n):j(n,me)&&this.eventProviders.push(n),j(n,ue)&&this.jobProviders.push(n)}}for(let t of this.owner.keys())for(let r of Po)if(typeof t.prototype[r]=="function")throw new z("nest lifecycle name",[t.name],`${t.name}.${r}`,`${r} is NestJS's; it is never called here`,["use onStart() and onShutdown()"]);for(let t of this.owner.keys())this.resolve(t,[])}get(t){let r=this.instances.get(t);if(!r)throw new Error(`${t.name} is not built by this app`);return r}resolve(t,r){let n=this.instances.get(t);if(n)return n;if(r.includes(t.name))throw new z("dependency cycle",[...r,t.name],t.name,`${[...r,t.name].join(" -> ")} goes round`,["move the shared part into a third class both depend on"]);let o=[...r,t.name],s=t.length,a=Reflect.getMetadata("design:paramtypes",t)??[];if(s>0&&a.length===0)throw new z("metadata missing",o,t.name,`${t.name} takes ${s} constructor parameter(s) but no types were emitted`,["enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json","build with tsc, Bun or SWC (esbuild does not emit them)"]);let i=[];a.slice(0,s).forEach((l,h)=>{if(jo.has(l)||typeof l!="function")throw new z("unresolvable dependency",o,`${t.name} constructor parameter ${h}`,`parameter ${h} of ${t.name} is typed as ${l===void 0?"something with no runtime class":l.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);i.push(this.resolve(this.reachable(t,l,o),o))});let c=new t(...i);return this.instances.set(t,c),this.order.push(c),c}dependencyOf(t,r,n){let o=t;return this.resolve(this.reachable(o,r,[o.name,n]),[o.name,n])}reachable(t,r,n){let o=this.owner.get(t),s=this.target(r,n),a=this.owner.get(s);if(a!==o){if(!this.defs.get(o).imports.includes(a))throw new z("missing import",[...n,s.name],`${o.name}`,`${t.name} (in ${o.name}) needs ${s.name}, owned by ${a.name}, which ${o.name} does not import`,[`add ${a.name} to ${o.name}'s imports (imports are not transitive)`]);if(!this.defs.get(a).exports.includes(s))throw new z("private dependency",[...n,s.name],`${a.name}`,`${s.name} is ${a.name}'s own: it is not in its exports`,[`add ${s.name} to ${a.name}'s exports`])}return s}target(t,r){if(this.owner.has(t))return t;let n=[...this.owner.keys()].filter(o=>o.prototype instanceof t);if(n.length===1)return n[0];throw n.length>1?new z("duplicate ownership",[...r,t.name],t.name,`${t.name} has ${n.length} owned subclasses (${n.map(o=>o.name).join(", ")}): which one is meant cannot be told`,["ask for the subclass itself"]):new z("unowned class",[...r,t.name],t.name,`${t.name} is needed but no module lists it`,[`list ${t.name} in a module's providers (and export it if another module needs it)`])}async start(){let t=[];for(let r of this.order){let n=r.onStart;if(typeof n=="function")try{await n.call(r)}catch(o){throw await this.shutdown(t),new Error(`[palbase] ${r.constructor.name}.onStart() failed: ${o instanceof Error?o.message:String(o)}`,{cause:o})}t.push(r)}}async shutdown(t=this.order){for(let r of[...t].reverse()){let n=r.onShutdown;if(typeof n=="function")try{await n.call(r)}catch(o){console.error(`[palbase] ${r.constructor.name}.onShutdown() failed`,o)}}}};import{HTTP_ERROR_BRAND as Co,HttpError as He}from"palgres";import{z as fe}from"zod";import{BadRequest as li,Conflict as fi,DeadlockDetected as pi,HttpError as mi,NotFound as hi,SerializationFailure as gi,TooManyRequests as yi,UniqueViolation as wi}from"palgres";function qe(e){if(typeof e!="object"||e===null||e[Co]!==!0)return!1;let t=e;return Number.isInteger(t.status)&&t.status>=400&&t.status<=599&&typeof t.error=="string"&&typeof t.errorDescription=="string"}var Yn=class extends He{constructor(t,r,n,o){super(t,r,n,o),this.name=new.target.name}},Gn=class extends He{constructor(t="Unauthorized",r="unauthorized",n){super(401,r,t,n),this.name="Unauthorized"}},Zn=class extends He{constructor(t="Forbidden",r="forbidden",n){super(403,r,t,n),this.name="Forbidden"}};function Qn(e,t){let r={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(r.data=e.data),r}var Mo=Symbol.for("palbase.backend.errorRegistry"),Do={bad_request:fe.object({fields:fe.array(fe.object({field:fe.string(),message:fe.string()})),more:fe.number().int().optional()}),too_many_requests:fe.object({retryAfter:fe.number().int()})},Uo=new Set(["auth_unavailable","check_failed","client_closed_request","database_unavailable","duplicate_upload","email_not_verified","handler_failed","idempotency_key_in_use","idempotency_key_reused","in_progress","internal_error","invalid_idempotency_key","invalid_signature","invalid_token","job_failed","job_not_found","method_not_allowed","missing_signature","payload_too_large","service_unavailable","signature_mismatch","temporarily_unavailable","unknown_token","upload_required","webhook_secret_missing"]);function No(){let e=new Map;for(let[t,r,n]of[["bad_request",400,"BadRequest"],["unauthorized",401,"Unauthorized"],["forbidden",403,"Forbidden"],["not_found",404,"NotFound"],["conflict",409,"Conflict"],["unique_violation",409,"UniqueViolation"],["too_many_requests",429,"TooManyRequests"]]){let o=Do[t];e.set(t,{code:t,status:r,className:n,builtin:!0,...o?{data:o}:{}})}return e}function Io(){let e=globalThis;return e[Mo]??=No()}function di(e,t,r){if(typeof e!="string"||!/^[a-z][a-z0-9_]*$/.test(e))throw new TypeError(`defineError(code, status): code is a lowercase wire code like room_locked, not ${JSON.stringify(e)}`);if(!Number.isInteger(t)||t<400||t>599)throw new TypeError(`defineError("${e}", status): status is a 4xx or 5xx integer, not ${String(t)} \u2014 an error is never a success`);if(r!==void 0&&typeof r?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if(Uo.has(e))throw new TypeError(`defineError("${e}", ${t}): "${e}" is the framework's own answer \u2014 a client would read the framework's refusal as the project's error; give the project's its own code`);let n=Io(),o=n.get(e);if(o&&(o.builtin||o.status!==t||o.data===void 0!=(r===void 0)||r!==void 0&&o.data!==r&&Xn(o.data)!==Xn(r)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${o.builtin?`the built-in ${o.className}`:`defined with status ${o.status}${o.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let s=e.split("_").map(b=>b.charAt(0).toUpperCase()+b.slice(1)).join(""),a=e.replace(/_/g," "),i=a.charAt(0).toUpperCase()+a.slice(1),h=r?(b=>class extends He{static code=e;static status=t;constructor(S,I){let y=Lo(e,b,S);super(t,e,I??(typeof y=="string"?y:i),y),this.name=s}})(r):class extends He{static code=e;static status=t;constructor(b){super(t,e,b??i),this.name=s}};return Object.defineProperty(h,"name",{value:s}),n.set(e,{code:e,status:t,className:s,builtin:!1,...r?{data:r}:{}}),h}function Lo(e,t,r){let n=t["~standard"].validate(r);if(n instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(n.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${n.issues.map(o=>o.message).join("; ")}`);return n.value}function Xn(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}var er="/_palbase/ai/tools",tr="/_palbase/ai/agents";var Jo=Symbol.for("palbase.ai.tool_error");function nr(e){return e instanceof Error&&e[Jo]===!0}var Ho=Symbol.for("palbase.ai.declared");function rr(){let e=globalThis[Ho];if(!e)return{tools:new Map,agents:new Map};if(e.twice.size>0){let t=[...e.twice].map(r=>r.replace(":"," "));throw new TypeError(`[palbase] ${t.join(", ")}: declared twice with different values \u2014 an ai.tool's and an ai.agent's name is its own; make each once, at a module's top level`)}return{tools:new Map(e.tools),agents:new Map(e.agents)}}var Nt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function It(e){if(!Nt(e))return"context is {chat_id, agent, user, metadata}";if(typeof e.chat_id!="string")return"context.chat_id is the chat (empty for a one-shot answer's call)";if(typeof e.agent!="string")return"context.agent is the agent's name";let t=null;if(e.user!==null&&e.user!==void 0){if(!Nt(e.user)||typeof e.user.id!="string"||e.user.id===""||e.user.name!==void 0&&typeof e.user.name!="string")return"context.user is {id, name}, or null";t={id:e.user.id,name:typeof e.user.name=="string"?e.user.name:""}}let r={};if(e.metadata!==void 0&&e.metadata!==null){if(!Nt(e.metadata))return"context.metadata is an object of strings";for(let[n,o]of Object.entries(e.metadata)){if(typeof o!="string")return"context.metadata is an object of strings";Object.defineProperty(r,n,{value:o,enumerable:!0,writable:!0,configurable:!0})}}return{chatId:e.chat_id,agent:e.agent,user:t,metadata:r}}var qo=1e3,Bo=256*1024,rt=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,r){this.running.delete(t),!(r===void 0||r.answer.length>Bo)&&(this.answers.set(t,r),this.answers.size>qo&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as Tr,isEngineRaised as en,markData as ae}from"palgres";import{createHash as Ar}from"node:crypto";import{createHash as zo,randomInt as Fo}from"node:crypto";import{ago as Lt,isRetryable as Wo,now as or}from"palgres";import{defineSchema as Ko,defineTable as Vo,index as Yo,integer as Go,jsonb as Zo,raw as Xo,text as Jt,timestamp as sr}from"palgres/dsl";var lr=new Set(["POST","PUT","PATCH","DELETE"]),ar=255,ir=35,dr=24,Qo=65536,cr=1e3,es=64,qt={description:"Makes the write safe to send again (at most 255 characters). A retry with the same key and the same request gets the first answer back, marked `Idempotent-Replayed: true`, and changes nothing; the same key with a different request is refused with 422, and while the first request still runs a retry gets 409 with Retry-After. Answers are kept for 24 hours.",in:"header",name:"Idempotency-Key",required:!1,schema:{maxLength:255,type:"string"}},ts=Vo("idempotency_keys",{columns:{key:Jt().primaryKey(),fingerprint:Jt(),started_at:sr().defaultNow(),completed_at:sr().nullable(),status_code:Go().nullable(),response_headers:Zo().nullable(),response_body:Jt().nullable()},indexes:e=>[Yo("idempotency_keys_started").on(e.col("started_at"))]}),Si=Ko("palbase",{tables:[ts],raw:[Xo("idempotency_answer",`CREATE OR REPLACE FUNCTION palbase.idempotency_answer(record_key text, claimed_at timestamptz, answer_status integer, answer_headers jsonb, answer_body text) RETURNS boolean
14
- LANGUAGE sql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp
15
- AS $answer$
16
- UPDATE palbase.idempotency_keys
17
- SET completed_at = now(), status_code = answer_status, response_headers = answer_headers, response_body = answer_body
18
- WHERE key = record_key AND started_at = claimed_at AND completed_at IS NULL
19
- RETURNING true
20
- $answer$`,{drop:"DROP FUNCTION IF EXISTS palbase.idempotency_answer(text, timestamptz, integer, jsonb, text)"})]}),ns={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},rs={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},os={status:409,code:"idempotency_key_in_use",message:"This request's Idempotency-Key was taken over by a retry; what it did is not kept",retryAfter:1},ss={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},st=class extends Error{};function Be(e){return lr.has(e.method)&&e.meta.upload===void 0}function fr(e,t){if(!lr.has(e))return;let r=t.get("idempotency-key");return r===null||r===""?void 0:r}function as(e,t){return pr([e.role,e.uid,t]).digest("hex")}function is(e){return pr([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function pr(e){let t=zo("sha256");for(let r of e)t.update(r).update("\0");return t}function ds(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function Ht(e){return e<500&&e!==429&&e!==499}function cs(e,t){return t&&Ht(e)}function mr(e){let t=e["~standard"].jsonSchema?.input,r;try{r=t?.({target:"draft-2020-12"})}catch{return!1}let n=r?.properties;return typeof n=="object"&&n!==null&&Object.keys(n).some(o=>o.toLowerCase()==="idempotency-key")}var us={role:"service",claims:{}},at=class{constructor(t){this.db=t}db;async serve(t,r,n){if(t.key.length>ar)return n.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${ar} characters`});let o;try{o=await this.begin(as(t.caller,t.key),is(t))}catch(i){return _.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),n.refusal(ss)}if("kept"in o)return ls(o.kept,n.requestId);if("refused"in o)return n.refusal(o.refused==="reused"?ns:rs);let s=o.claim,a;try{a=await r(i=>this.record(s,i))}catch(i){if(i instanceof st)return n.refusal(os);let c=n.failure(i);return cs(c.status,n.ran())&&!Wo(i)?this.keep(s,c):(await this.release(s),c)}return Ht(a.status)||await this.release(s),a}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:Lt({hours:dr})}}}))}async begin(t,r){return Fo(es)===0&&await this.sweep().catch(n=>_.warn("[palbase] the expired Idempotency-Keys could not be taken away; the next sweep tries again",{error:n})),this.asService(async n=>{for(let o=0;o<3;o++){let[s]=await n.insertMany([{key:t,fingerprint:r}],{onConflict:["key"],action:"ignore"});if(s)return{claim:{key:t,started:s.started_at}};if(await n.deleteMany({where:{key:t,started_at:{lt:Lt({hours:dr})}}})>0)continue;let a=await n.findUnique({where:{key:t}});if(a===null)continue;let i=ds(a,r);if(i==="reused")return{refused:"reused"};if(i==="replay")return{kept:{status:a.status_code,headers:a.response_headers??[],body:a.response_body}};let[c]=await n.updateMany({where:{key:t,completed_at:null,started_at:{lt:Lt({seconds:ir})}},set:{started_at:or()}});return c?{claim:{key:t,started:c.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,r){if(!Ht(r.status))return r;let{response:n,kept:o}=await ur(r),s=Q.getStore()?.database;if(!s)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let[a]=await s.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,o.status,JSON.stringify(o.headers),o.body]);if(a?.answered!==!0)throw new st;return n}async keep(t,r){let{response:n,kept:o}=await ur(r);try{await this.asService(s=>s.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:or(),status_code:o.status,response_headers:o.headers,response_body:o.body}}))}catch(s){_.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:s})}return n}async release(t){if(await this.releaseOnce(t))return;let r=Date.now()+ir*1e3,n=()=>{Date.now()+cr>=r||setTimeout(()=>{this.releaseOnce(t).then(o=>o||n())},cr).unref()};n()}async releaseOnce(t){try{return await this.asService(r=>r.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let r=this.db.request(us),n;try{n=await t(r.database.palbase.idempotency_keys)}catch(o){throw await r.rollback(o).catch(()=>{}),o}try{await r.commit()}catch(o){throw await r.rollback(o).catch(()=>{}),o}return n}};function ls(e,t){let r=new Headers(e.headers);return r.set("x-request-id",t),r.set("idempotent-replayed","true"),new Response(e.body===null?null:Buffer.from(e.body,"base64"),{status:e.status,headers:r})}var ot=Symbol("waits");function fs(e){return new Promise((t,r)=>{let n=setImmediate(()=>t(ot));e.then(o=>{clearImmediate(n),t(o)},o=>{clearImmediate(n),r(o)})})}async function ur(e){let t=[];e.headers.forEach((i,c)=>{c!=="x-request-id"&&t.push([c,i])});let r=i=>new Response(i,{status:e.status,statusText:e.statusText,headers:e.headers});if(e.body===null)return{response:r(null),kept:{status:e.status,headers:t,body:null}};let n=e.body.getReader(),o=[],s=0;for(;;){let i=n.read(),c=await fs(i);if(c!==ot&&c.done)break;if(c!==ot&&(o.push(c.value),s+=c.value.byteLength,s<=Qo))continue;let l=c===ot?i:void 0,h=new ReadableStream({start(b){for(let S of o)b.enqueue(S)},async pull(b){let S=await(l??n.read());l=void 0,S.done?b.close():b.enqueue(S.value)},cancel:b=>n.cancel(b)});return{response:r(h),kept:{status:e.status,headers:t.filter(([b])=>b!=="content-length"&&b!=="content-encoding"),body:null}}}let a=Buffer.concat(o);return{response:r(a),kept:{status:e.status,headers:t,body:a.byteLength===0?null:a.toString("base64")}}}import{createHash as ps}from"node:crypto";var Bt="/webhooks/palbase",vr="PalbaseErrorEnvelope",hr="PalbaseBearer",ms={$ref:`#/components/schemas/${vr}`},hs={type:"object",description:"Every refusal: the framework's, a handler's HttpError, the database's.",properties:{error:{type:"string",description:"A stable code, like bad_request"},error_description:{type:"string",description:"What went wrong, for a person"},status:{type:"integer",description:"The HTTP status"},request_id:{type:"string",description:"The request's id, as the app's log has it"},data:{description:"Details, when the refusal has them: a validation's fields, a token's reason, a limit's retryAfter"}},required:["error","error_description","status","request_id"]},gr={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Ce={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function kr(e,t,r){let n={[vr]:hs},o={},s=[],a=[],i=new Set,c=new Map;for(let y of e){let C=a.find(H=>ws(H,y));if(C){s.push({route:y.id,handler:yr(y),answeredBy:C.id});continue}a.push(y);let k=y.segments.map(H=>typeof H=="string"?H:"{}").join("/");c.has(k)||c.set(k,vs(y.segments.flatMap(H=>typeof H=="string"?[]:[H.param])));let $=c.get(k),v=0,O=`/${y.segments.map(H=>typeof H=="string"?H:`{${$[v++]}}`).join("/")}`,M=t(y),A=it(bs(y),i),J=y.method!=="GET"&&y.method!=="HEAD",B=H=>{let pe=y.params.filter(we=>we.kind===H&&we.schema).map((we,Ye)=>ut(we.schema,`${A}.${H}${Ye===0?"":`.${Ye+1}`}`,n));return pe.length===0?void 0:pe.length===1?pe[0]:{allOf:pe}},U=$.map(H=>({name:H,in:"path",required:!0,schema:{type:"string"}})),F=B("query");F&&U.push(...br(F,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:F}]);let V=B("headers");V&&U.push(...br(V,"header")??[]);let Y=r.idempotency===!0&&Be(y);Y&&U.push({...qt,schema:{...qt.schema}});let G=J?B("body"):void 0,Z={operationId:A};y.controller.name!==""&&(Z.tags=[y.controller.name]),U.length>0&&(Z.parameters=U),G&&(Z.requestBody={required:!_s(G),content:{"application/json":{schema:G}}});let gt=y.params.some(H=>H.schema!==void 0),Ve=r.routes?.(y),Ue=xs(A,Ve?.throws??[],r.errors);Z.responses={...Ss(Ve,A,n),...As(M,{validates:gt,hasPathParams:$.length>0,readsBody:J,keyed:Y}),...Ts(Ue,A,n)},Ue.length>0&&(Z["x-palbase-errors"]=Os(A,Ue)),M.auth.required&&(Z.security=[{[hr]:[]}]),Z["x-palbase-handler"]=yr(y);let yt=y.params.some(H=>H.kind==="optionalUser")||r.databaseSeesCaller;Z["x-palbase-auth"]=M.auth.required?"required":yt?"optional":"public",Z["x-palbase-verified-email"]=M.auth.verifiedEmail,Z["x-palbase-rate-limit"]=M.limit===!1?!1:{max:M.limit.max,window:M.limit.window},y.meta.upload&&(Z["x-palbase-upload"]={bucket:y.meta.upload.bucket,pathTemplate:y.meta.upload.pathTemplate}),(o[O]??={})[y.method.toLowerCase()]=Z}for(let y of r.webhooks??[]){let C={operationId:it(`webhooks.${y.name}`,i)};y.cls!==""&&(C.tags=[y.cls]),C.description=y.provider?`${gr[y.provider]??y.provider}'s deliveries: verified with ${gr[y.provider]??y.provider}'s signature scheme under the secret in ${y.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${y.signatureHeader} header: verified under the secret in ${y.secretEnv}, then handed to the @On of their event type.`,C.responses={200:{description:"Taken: { ok: true, handled } \u2014 handled is false when no @On takes the event's type, and duplicate is true for a delivery already run; or the handler's answer: a Response as it is, text as text, anything else as JSON",content:{"application/json":{},[y.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:K("invalid_signature: the delivery is not signed with the secret \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:K("in_progress: the same delivery is being handled; the sender delivers it again",Ce),413:K("payload_too_large: the body is over what this sender sends"),500:K("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:K("service_unavailable, auth_unavailable or database_unavailable: what the handler needs of the platform did not answer \u2014 the sender delivers it again after Retry-After",Ce)},C["x-palbase-webhook"]=y.provider?{provider:y.provider,secretEnv:y.secretEnv,events:y.events}:{signatureHeader:y.signatureHeader,secretEnv:y.secretEnv,events:y.events},o[`/webhooks/${y.name}`]={post:C}}let l=[...new Set(r.platformEvents??[])].sort();if(l.length>0){let y={operationId:it("webhooks.palbase",i)};y.description="The project's events, delivered by the platform to the app's machine: verified under the secret in PALBASE_WEBHOOK_SECRET, then handed to the @On of their type \u2014 user.deleted first to forgetting the rows the app keeps of that user.",y.responses={204:{description:"Taken: handled, or a delivery already run"},401:K("invalid_signature: the delivery is not the platform's \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:K("in_progress: the same event is being handled; the platform delivers it again",Ce),500:K("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:K("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let C=[...new Set(r.platformEventBuckets??[])].sort();y["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:l,...C.length>0?{buckets:C}:{}},o[Bt]={post:y}}let h=gs(r.rooms??[],n),b=Object.keys(h).length>0,S={schemas:n,securitySchemes:{[hr]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},I={openapi:"3.2.0",info:{title:"Palbase backend",version:ps("sha256").update(JSON.stringify({paths:o,components:S,unreachable:s,...b?{rooms:h}:{}})).digest("hex").slice(0,12),description:"The routes this app serves, as its decorators declare them, and \u2014 when its source was read as the contract was written \u2014 what each answers and the errors it throws (x-palbase-errors). Every refusal is the PalbaseErrorEnvelope; a declared error's carries its code and its data."},paths:o,components:S};return s.length>0&&(I["x-palbase-unreachable"]=s),b&&(I["x-palbase-room"]=h),I}function gs(e,t){let r=[];for(let n of e){let o=n.pattern.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_|_$/g,""),s=(c,l,h,b)=>{let S=ct(`Room_${o}_${l}`),I={},y=ut(h,S,I,b);y.$ref===void 0&&(I[S]=y),ys(n.pattern,c,l,I[S]);for(let[C,k]of Object.entries(I)){if(Object.hasOwn(t,C)&&JSON.stringify(t[C])!==JSON.stringify(k))throw new Error(`@Room("${n.pattern}") ${c} "${l}": its schema is the component ${C}, which another room's event or message names with another schema \u2014 rename one of them`);t[C]=k}return{$ref:`#/components/schemas/${S}`}},a=Object.fromEntries(Object.entries(n.events).map(([c,l])=>[c,s("event",c,l,"answered")])),i=Object.fromEntries(Object.entries(n.messages).map(([c,l])=>[c,s("message",c,l.schema,"sent")]));r.push([n.pattern,{events:a,messages:i,graceMs:n.graceMs}])}return Object.fromEntries(r)}function ys(e,t,r,n){if(!(!ee(n)||!ee(n.properties))){for(let[o,s]of Object.entries(n.properties))if(s===!0||ee(s)&&Object.keys(s).length===0)throw new Error(t==="event"?`@Room("${e}") event "${r}" has an untyped field "${o}". An untyped payload makes every generated client opaque \u2014 declare its shape.`:`@Room("${e}") message "${r}" has an untyped field "${o}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`)}}function ws(e,t){return e.method===t.method&&e.segments.length===t.segments.length&&e.segments.every((r,n)=>typeof r!="string"||r===t.segments[n])}function yr(e){return`${e.controller.name}.${e.fn}`}function bs(e){let t=e.controller.name;if(t.endsWith("Controller")&&(t=t.slice(0,-10)),t!=="")return`${t[0].toLowerCase()}${t.slice(1)}.${e.fn}`;let r=n=>n.charAt(0).toUpperCase()+n.slice(1);return e.method.toLowerCase()+e.segments.map(n=>typeof n=="string"?r(n):`By${r(n.param)}`).join("")}function it(e,t){let r=e;for(let n=2;t.has(r);n++)r=`${e}_${n}`;return t.add(r),r}function vs(e){let t=new Set;return e.map(r=>it(r,t))}function ut(e,t,r,n="sent"){let o=e["~standard"],s=o.jsonSchema?.input;if(typeof s!="function")return{};let a;try{a=s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...o.vendor==="zod"?{override:ks}:{}}})}catch{return{}}let i=ct(t);for(;Object.keys(r).some(c=>c===i||c.startsWith(`${i}.`));)i=`${i}_`;return $s(a,i,r,n)}function ks(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function $s(e,t,r,n){let o=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},s=!1,a=l=>l==="#"?(s=!0,`#/components/schemas/${t}`):l.startsWith("#/$defs/")?`#/components/schemas/${t}.${ct(Es(l.slice(8)))}`:l,i="all";if(n==="sent"){let l=new Set;for(let h of[e,...Object.values(o)])dt(h,l);i=l}for(let[l,h]of Object.entries(o))r[`${t}.${ct(l)}`]=Fe(ze(h,a,i));let c=Fe(ze(e,a,i));return s?(r[t]=c,{$ref:`#/components/schemas/${t}`}):c}var Rs=new Set(["type","enum","required","dependentRequired","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","contentEncoding","contentMediaType","minItems","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties","readOnly","writeOnly","deprecated"]),zt=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),Ft=new Set(["anyOf","oneOf","allOf","prefixItems"]),Wt=new Set(["properties","patternProperties","dependentSchemas"]),ee=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ze(e,t,r){if(!ee(e))return typeof e=="boolean"?e:{};let n={};for(let[o,s]of Object.entries(e))o==="$ref"&&typeof s=="string"?n.$ref=t(s):o==="const"?(r==="all"||r.has(e))&&(n.const=s):Rs.has(o)?n[o]=s:zt.has(o)?n[o]=ze(s,t,r):Ft.has(o)&&Array.isArray(s)?n[o]=s.map(a=>ze(a,t,r)):Wt.has(o)&&ee(s)&&(n[o]=Object.fromEntries(Object.entries(s).map(([a,i])=>[a,ze(i,t,r)])));return n}var wr=Number.MAX_SAFE_INTEGER;function Fe(e){if(!ee(e))return e;let t={};for(let[n,o]of Object.entries(e))zt.has(n)?t[n]=Fe(o):Ft.has(n)&&Array.isArray(o)?t[n]=o.map(Fe):Wt.has(n)&&ee(o)?t[n]=Object.fromEntries(Object.entries(o).map(([s,a])=>[s,Fe(a)])):t[n]=o;if("const"in t){let{const:n,...o}=t;t={...o,enum:[n]}}if(t.type==="integer"&&(t.minimum===-wr&&delete t.minimum,t.maximum===wr&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,ee(t.propertyNames)&&Object.keys(t.propertyNames).length===1&&t.propertyNames.type==="string"&&delete t.propertyNames,Array.isArray(t.type)&&t.type.filter(n=>n!=="null").length>1&&Object.keys(t).length===1)return{anyOf:t.type.map(n=>({type:n}))};let r=t.anyOf;if(Array.isArray(r)&&r.length===2&&Object.keys(t).length===1){let n=r.findIndex(s=>ee(s)&&Object.keys(s).length===1&&s.type==="null"),o=r[1-n];if(n!==-1&&ee(o)&&typeof o.type=="string")return{...o,type:[o.type,"null"]}}return t}function dt(e,t){if(ee(e)){for(let r of["anyOf","oneOf"]){let n=e[r];if(!Array.isArray(n)||n.length<2||!n.every(ee))continue;if(n.every(s=>"const"in s||Array.isArray(s.enum)))for(let s of n)t.add(s);let o=n.map(s=>ee(s.properties)?s.properties:{});for(let s of Object.keys(o[0]))if(o.every(a=>ee(a[s])&&"const"in a[s]))for(let a of o)t.add(a[s])}for(let[r,n]of Object.entries(e))if(zt.has(r))dt(n,t);else if(Ft.has(r)&&Array.isArray(n))for(let o of n)dt(o,t);else if(Wt.has(r)&&ee(n))for(let o of Object.values(n))dt(o,t)}}function Es(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function ct(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function br(e,t){if(e.type!=="object"||typeof e.properties!="object"||e.properties===null)return;let r=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([n,o])=>({name:n,in:t,required:r.has(n),schema:o}))}function _s(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function K(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:ms}}}}function Ss(e,t,r){if(!e)return{200:{description:"The handler's answer, as JSON",content:{"application/json":{}}},204:{description:"The handler answered nothing (undefined or null)"}};if(e.returns.kind==="void")return{204:{description:"No Content"}};if(e.returns.kind==="raw")return{default:{description:"The handler's own Response, as it built it"}};let n=ut(e.returns.schema,`${t}.response`,r,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:n}:n}}}}}function xs(e,t,r){let n=new Set,o=[];for(let s of t){if(n.has(s.code))continue;n.add(s.code);let a=r?.get(s.code);if(a&&s.status!==a.status)throw new Error(`${e} throws "${s.code}" with status ${s.status}, but the code is defined with status ${a.status} \u2014 a client matches an error by its code, so one code carries one status`);o.push({...s,...a?.data?{data:a.data}:{}})}return o}function Os(e,t){let r=Object.create(null);for(let n of t){let o=n.name.charAt(0).toLowerCase()+n.name.slice(1),s=Object.hasOwn(r,o)?r[o]:void 0;if(s)throw new Error(`${e} throws "${s.code}" and "${n.code}" under one name, "${n.name}" \u2014 every client names an error case after it; give one of them its own defineError`);r[o]={status:n.status,code:n.code,hasData:n.data!==void 0,description:""}}return r}function Ts(e,t,r){let n=new Map;for(let s of e)n.set(s.status,[...n.get(s.status)??[],s]);let o={};for(let s of[...n.keys()].sort((a,i)=>a-i)){let a=n.get(s),i=a.map(c=>{let l={error:{type:"string",const:c.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},h=["error","error_description","status","request_id"];return c.data&&(l.data=ut(c.data,`${t}.${c.code}.data`,r,"answered"),h.push("data")),{type:"object",properties:l,required:h}});o[String(s)]={description:a.map(c=>c.code).join(" | "),content:{"application/json":{schema:i.length===1?i[0]:{oneOf:i}}}}}return o}function As(e,t){let r={},n=[t.validates&&"a parameter failed its schema (data.fields names each field, data.more how many more)",t.hasPathParams&&"the path is not valid percent-encoding"].filter(Boolean),o=[n.length>0&&`bad_request: ${n.join("; or ")}`,t.keyed&&"invalid_idempotency_key: the Idempotency-Key is over 255 characters"].filter(Boolean);return o.length>0&&(r[400]=K(o.join("; "))),e.auth.required&&(r[401]=K("unauthorized: no access token was sent; invalid_token: the token is not valid (data.reason says why), or the Authorization header is not a Bearer token")),e.auth.verifiedEmail&&(r[403]=K("email_not_verified: the user's email address is not verified")),t.keyed&&(r[409]=K("idempotency_key_in_use: a request with this Idempotency-Key is still running",Ce)),t.readsBody&&(r[413]=K("payload_too_large: the body is over the app's body limit")),t.keyed&&(r[422]=K("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(r[429]=K("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Ce)),r[500]=K("internal_error: the handler failed; the app's log has it under the request id"),r[503]=K(`${e.auth.required?"auth_unavailable: sign-ins cannot be checked right now; ":""}service_unavailable: a platform service the request needs did not answer${t.keyed?"; temporarily_unavailable: the Idempotency-Key could not be recorded":""}`,Ce),r}var lt=class{windows=new Map;now;maxKeys;constructor(t=Date.now,r=1e5){this.now=t,this.maxKeys=r}take(t,r){let n=this.now(),o=this.windows.get(t);if((!o||n>=o.resetAt)&&(o={count:0,resetAt:n+r.window*1e3}),this.windows.delete(t),this.windows.set(t,o),this.windows.size>this.maxKeys&&this.windows.delete(this.windows.keys().next().value),o.count++,o.count>r.max)return Math.max(1,Math.ceil((o.resetAt-n)/1e3))}reserve(t,r){let n=this.take(t,r);return n!==void 0?{wait:n}:{window:this.windows.get(t).resetAt}}give(t,r){let n=this.windows.get(t);n&&n.resetAt===r&&n.count>0&&n.count--}};function ft(e,t){let n=e.get("x-forwarded-for")?.split(",").map(o=>o.trim()).filter(Boolean).at(-1);return Ps(n??t??"unknown")}function Ps(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let r=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(r)return r[1];let[n,o=""]=t.split("::"),s=n?n.split(":"):[],a=o?o.split(":"):[],i=t.includes("::")?[...s,...Array(8-s.length-a.length).fill("0"),...a]:s;return i.length!==8||i.some(c=>!/^[0-9a-f]{1,4}$/i.test(c))?t:`${i.slice(0,4).map(c=>parseInt(c,16).toString(16)).join(":")}::/64`}function $r(e){let t=[];for(let r of e){let n=j(r,Re),o=j(r,Ee)??[];if(o.length===0)throw new TypeError(`@Controller ${r.name} has no routes: a controller with nothing to serve is a mistake`);let s=j(r,$t)??new Map;for(let a of o){let i=`${n.basePath}${a.subpath}`||"/",c=i.split("/").filter(Boolean).map(h=>{let b=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(h)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(h);return b?{param:b[1]}:h});if(typeof c[0]=="string"&&Se.has(c[0]))throw new TypeError(`${r.name}.${a.fn}: ${a.method} ${i} \u2014 /${c[0]} is the platform's; a route is served elsewhere`);let l=[...s.get(a.fn)??[]].sort((h,b)=>h.index-b.index);for(let h of l)if(h.kind==="param"&&!c.some(b=>typeof b!="string"&&b.param===h.name))throw new TypeError(`${r.name}.${a.fn}: @Param("${h.name}") names no {${h.name}} in ${a.method} ${i}`);t.push({id:`${a.method} ${i}`,method:a.method,segments:c,controller:r,fn:a.fn,params:l,meta:a,controllerAuth:n.options.auth})}}return Pn(t),t}function Kt(e,t,r){let n=r.split("/").filter(Boolean);for(let o of e){if(o.method!==t||o.segments.length!==n.length)continue;let s={},a=!0;for(let i=0;i<n.length&&a;i++){let c=o.segments[i];if(typeof c=="string")a=c===n[i];else try{s[c.param]=decodeURIComponent(n[i])}catch{return{malformed:!0}}}if(a)return{route:o,params:s}}return null}function Yt(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Me(e,t,r,n,o){return Gt(e,e?Yt(e.requests,t):void 0,r,n,o)}var Rr={role:"service",claims:{}};async function Gt(e,t,r,n,o){if(!e||!t)return o();let s=l=>_.warn(`[palbase] ${n}: a transaction of the request could not be given back \u2014 it wrote, locked, is an $atomic or an $attempt, ran SQL of its own, or the database keeps one snapshot for it \u2014 and sat ${l} ms with no statement running: the handler waited on something else, and a database connection waited with it. Make the outside call before the first write, or outside $atomic.`,{waitedMs:l}),a=e.app.request(t,{signal:r,heldIdle:s}),i=Q.getStore();i&&(i.database=a.database);let c;try{c=await o()}catch(l){throw await a.rollback(l).catch(h=>_.error("[palbase] the request's transaction could not be rolled back",{error:h})),l}try{await a.commit()}catch(l){throw await a.rollback(l).catch(h=>_.error("[palbase] the request's transaction could not be rolled back",{error:h})),l}return c}var Cs=1024*1024,Ms=20,Ds={max:300,window:60},De="/_palbase/jobs",Er=50,Us=4096,Ns=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,pt=1e4,Is=6e4;function Ls(e,t){let r=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof r=="boolean")return{required:r,verifiedEmail:!1};if((r.role??"").trim()!==""||(r.permission??"").trim()!=="")throw new TypeError(`${e.id}: auth { role, permission } were checked against v2's database; v3 has none yet \u2014 check the role in the service`);return{required:r.required!==!1,verifiedEmail:r.verifiedEmail===!0}}var X=class extends Error{constructor(r,n,o,s,a,i){super(o);this.status=r;this.code=n;this.data=s;this.retryAfter=a;this.challenge=i}status;code;data;retryAfter;challenge};function Js(e){if(e==="proof")return'DPoP error="invalid_dpop_proof", algs="ES256"';if(e==="bound"||e==="not_bound")return'DPoP error="invalid_token", algs="ES256"'}var Hs=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function qs(e,t){let r=new Headers(e.headers);for(let n of Hs)r.delete(n);return e.url!==""&&(r.delete("content-encoding"),r.delete("content-length")),r.set("x-request-id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}function _r(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),ht(e.headers,"Accept-Language")),e}function ht(e,t){let r=(e.get("vary")??"").split(",").map(n=>n.trim()).filter(Boolean);r.includes("*")||r.some(n=>n.toLowerCase()===t.toLowerCase())||e.set("vary",[...r,t].join(", "))}function de(e,t,r,n={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":r,...n}})}function E(e,t){let r={error:e.code,error_description:e.message,status:e.status,request_id:t};e.data!==void 0&&(r.data=e.data);let n={};return e.retryAfter!==void 0&&(n["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(n["www-authenticate"]=e.challenge),de(e.status,r,t,n)}var Pr=new Set([0,429,502,503,504]);function Sr(e,t,r,n){if(n?.aborted)return _.info(`[palbase] ${r}: the client left before its answer`),E({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof X)return E({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(qe(e)){let s=e;return s.status>=500&&_.error(`[palbase] ${r} answered ${s.status} ${s.error}`,{error:e}),de(s.status,Qn(s,t),t,s.retryAfter!==void 0?{"retry-after":String(s.retryAfter)}:{})}let o=Zt(e,r);return o?E(o,t):(e instanceof ke?_.error(`[palbase] ${r}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):_.error(`[palbase] unhandled error in ${r}`,{error:e}),E({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Zt(e,t){if(e instanceof Qe)return _.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ke&&Pr.has(e.status))return _.warn(`[palbase] ${t}: a platform service did not answer (${e.op}: ${e.status} ${e.code})`,{error:e}),{status:503,code:"service_unavailable",message:"A service this request needs did not answer; try again shortly",retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))};let r=Tr(e);if(r!==void 0)return _.warn(`[palbase] ${t}: the database connection ${r==="lost"?"was lost":"could not be opened"}`,{error:e}),{status:503,code:"database_unavailable",message:"The database is temporarily unavailable",data:{retrySafe:r==="never"},retryAfter:1}}function Bs(e){let t=r=>(r.length>1e3?`${r.slice(0,1e3)}\u2026`:r)||"The tool failed";return nr(e)?t(e.message):qe(e)&&!en(e)&&!Xt(e)?t(e.errorDescription):Xt(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function Xt(e){return e instanceof Qe||e instanceof ke&&Pr.has(e.status)||Tr(e)!==void 0||qe(e)&&e.status===503&&en(e)}async function Vt(e,t,r){let n=await e["~standard"].validate(t);if(n.issues){let o=n.issues.slice(0,Ms).map(a=>({field:(a.path??[]).map(i=>String(typeof i=="object"&&i!==null&&"key"in i?i.key:i)).join("."),message:a.message})),s=n.issues.length-o.length;throw new X(400,"bad_request",`${r} failed validation`,s>0?{fields:o,more:s}:{fields:o})}return n.value}async function mt(e,t){let r=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>t)throw new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let n=e.body.getReader(),o=[],s=0;for(;;){let{done:c,value:l}=await n.read();if(c)break;if(s+=l.byteLength,s>t)throw await n.cancel().catch(()=>{}),new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);o.push(l)}let a=new Uint8Array(s),i=0;for(let c of o)a.set(c,i),i+=c.byteLength;return a}function zs(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ae(t)}function Fs(e){let t=e.claims.custom_claims;return{id:e.id,email:e.email,role:e.role,emailVerified:e.emailVerified,metadata:typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},sessionId:e.sessionId,test:e.claims.test===!0}}function Ws(e){return e.id?{id:e.id,email:e.email??null,role:e.role,emailVerified:e.emailVerified??!1,metadata:{},sessionId:e.session??null,test:!1}:null}var Ks=/^[A-Za-z0-9._:-]{8,128}$/,Vs=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ys={max:20,window:60},Gs=10*6e4,Zs=1e4,Ke=class extends Error{constructor(r){super("too many unknown tokens from this address");this.wait=r}wait},Qt=class{constructor(t,r){this.limiter=t;this.now=r}limiter;now;known=new Map;async ask(t,r,n){let o=Ar("sha256").update(t).digest("hex"),s=(this.known.get(o)??0)>this.now(),a=`token-misses\0a:${r}`,i;if(!s){let l=this.limiter.reserve(a,Ys);if("wait"in l)throw new Ke(l.wait);i=l}let c=await n();if(!c)throw this.known.delete(o),new Xe("unknown_token","The token is not one of the app's");return i&&this.limiter.give(a,i.window),this.known.delete(o),this.known.set(o,this.now()+Gs),this.known.size>Zs&&this.known.delete(this.known.keys().next().value),c}};function Qi(e){let t=new nt(e.modules),r=$r(t.controllers.map(d=>d.cls)),n=new Map(r.map(d=>[d,Ls(d,e.auth)]));for(let[d,u]of n){if(!u.required&&d.params.some(f=>f.kind==="user"))throw new TypeError(`${d.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(d.meta.upload&&u.verifiedEmail)throw new TypeError(`${d.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`)}let o=new Map;for(let d of r)for(let u of d.params)u.kind==="resolve"&&o.set(u,t.dependencyOf(d.controller,u.resolver,`${d.id} @Resolve(${u.resolver?.name})`));let s=new Map;for(let d of t.jobProviders){let u=t.get(d),f=j(d,ue),p=s.get(f.name);if(p)throw new TypeError(`@Job "${f.name}" is ${p.owner} and ${d.name}: a job's name is its own \u2014 name one of them`);s.set(f.name,{declaration:f,owner:d.name,run:g=>u.run(g)})}let a=new Set,i=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(s.size>Er)throw new TypeError(`${s.size} @Job classes: a machine runs ${Er} jobs at most`);s.size>0&&!e.platform&&_.info(`[palbase] ${s.size} @Job(s): the platform runs them on a machine; nothing calls them here`);let c=Dn(t.rooms.map(d=>({cls:d,instance:t.get(d)})),{run:(d,u,f,p)=>Q.run({requestId:Q.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>Gt(e.database,e.database?d?.id?Yt(e.database.requests,tt(d)):Rr:void 0,f,u,async()=>{let g=await p();if(f?.aborted)throw new Error(`realtime gave up on ${u} before it ended`);return g})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),isOutage:Xt});c.declarations.length>0&&!e.platform&&_.info(`[palbase] ${c.declarations.length} @Room(s): realtime tells a machine of them; nothing does here`);let l=rr();(l.tools.size>0||l.agents.size>0)&&!e.platform&&_.info(`[palbase] ${l.tools.size} ai.tool(s) and ${l.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let h=new rt,b=new Set,S=e.database!==void 0||e.contractOnly?.database===!0;if(S){for(let d of r)if(Be(d)&&d.params.some(u=>u.kind==="headers"&&u.schema!==void 0&&mr(u.schema)))throw new TypeError(`${d.id}: its @Headers schema declares Idempotency-Key \u2014 the framework takes that header on every write of an app with a database and answers a retry from it; a handler reads it with @Headers() (no schema)`)}let I=e.database?new at(e.database.app):void 0,y=oa(e.cors),C=e.now??Date.now,k=new lt(e.now),$=new Qt(k,e.now??Date.now),v=e.maxBodyBytes??Cs,O=d=>{let u=d.meta.options.rateLimit??e.rateLimit??Ds;return u!==!1&&u.max>0&&u.window>0?u:!1},M=e.env??process.env,A=qn(t.webhooks,d=>t.get(d),M,{secrets:e.contractOnly===void 0}),J=A.size===0&&s.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(M).filter(d=>typeof d[1]=="string"&&!yn(d[0])))),B=new Map([...A.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),U=new Map([...A.keys()].map(d=>[d,{counts:new Map,at:void 0}])),F,V=()=>F??=kr(r,d=>({auth:n.get(d),limit:O(d)}),{databaseSeesCaller:S,idempotency:S,webhooks:[...A.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...Y.keys()],rooms:c.declarations,platformEventBuckets:Qs(Y),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),Y=new Map;for(let[d,u]of Object.entries(e.events??{}))Y.set(d,u.map(f=>({name:`palbase(${d})`,call:p=>f(p)})));for(let d of t.eventProviders){let u=t.get(d);for(let{event:f,fn:p,bucket:g}of j(d,me)??[]){if(!En.test(f))throw new TypeError(`@On("${f}") on ${d.name}.${p}: a platform event's type is dotted lowercase words, like user.deleted \u2014 a third party's event is taken by an @On in its @Webhook class`);Y.has(f)||Y.set(f,[]),Y.get(f).push({name:`${d.name}.${p}`,bucket:g,call:async(m,w)=>u[p](m,w)})}}let G=new Set,Z=new Set;bn(e.server);async function gt(d,u){let f;try{f=await hn(d,e.webhookSecret,{now:e.now})}catch(p){if(p instanceof Ze)return E({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${p.code}`},u);throw p}if(ae(f.data),G.has(f.id))return new Response(null,{status:204,headers:{"x-request-id":u}});if(Z.has(f.id))return E({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},u);Z.add(f.id);try{let p;try{await Me(e.database,null,void 0,`event ${f.type}`,async()=>{for(let g of Y.get(f.type)??[])if(!(g.bucket!==void 0&&Xs(f)!==g.bucket))try{await g.call(f,{requestId:u})}catch(m){throw p=g.name,m}})}catch(g){return _.error(`[palbase] ${p??"the delivery"} failed on ${f.type} ${f.id}; the platform delivers it again`,{error:g}),E({status:500,code:"handler_failed",message:"The event could not be handled"},u)}return G.add(f.id),G.size>pt&&G.delete(G.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}finally{Z.delete(f.id)}}async function Ve(d,u={}){let f=d.headers.get("origin");if(y&&f!==null){let p=y.allows(f);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return p?new Response(null,{status:204,headers:y.preflight(f,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let g=await dn(d,u);if(p)for(let[m,w]of Object.entries(y.headers(f)))m==="vary"?ht(g.headers,w):g.headers.set(m,w);else ht(g.headers,"Origin");return g}return dn(d,u)}async function Ue(d,u,f,p){if(!d.headers.get(f.scheme.header))return H(f,"missing_signature",p);let g={headers:d.headers,body:await mt(d,f.scheme.maxBytes(v)),url:Bn(d,u)},m;try{m=f.scheme.check(g,C()/1e3)}catch{return H(f,"signature_mismatch",p,"check_failed")}if(typeof m=="string")return H(f,m,p);let w=f.events.get(m.type);if(!w)return _.info(`[palbase] webhook ${f.name}: no @On takes "${m.type}"; acknowledged`),de(200,{ok:!0,handled:!1},p);let R=B.get(f.name),T=m.event,D=[];if(m.id!==void 0){if(R.seen.has(m.id))return de(200,{ok:!0,handled:!1,duplicate:!0},p);D=[m.id]}else if(m.ids&&Array.isArray(T)){let x=m.ids,P=T.map((L,ce)=>[L,x[ce]]).filter(([,L])=>L===void 0||!R.seen.has(L));if(P.length===0)return de(200,{ok:!0,handled:!1,duplicate:!0},p);T=P.map(([L])=>L),D=P.flatMap(([,L])=>L===void 0?[]:[L])}if(D.some(x=>R.inflight.has(x)))return E({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},p);ae(T);for(let x of D)R.inflight.add(x);let q;try{q=await Me(e.database,null,void 0,`webhook ${f.name}`,()=>w.call(T,{env:J,requestId:p,environmentId:e.projectId??""}))}catch(x){let P=Zt(x,`webhook ${f.name}`)??ea(x,f.name);return P?E(P,p):(_.error(`[palbase] ${w.name} failed on ${f.name} "${m.type}"; the sender delivers it again`,{error:x}),E({status:500,code:"handler_failed",message:"The event could not be handled"},p))}finally{for(let x of D)R.inflight.delete(x)}for(let x of D)R.seen.add(x),R.seen.size>pt&&R.seen.delete(R.seen.values().next().value);return yt(q,f,p)}function yt(d,u,f){if(d instanceof Response)return d;if(typeof d=="string"){let p=u.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(d,{status:200,headers:{"content-type":p,"x-request-id":f}})}return de(200,d??{ok:!0,handled:!0},f)}function H(d,u,f,p=u){let g=U.get(d.name);g.counts.set(p,(g.counts.get(p)??0)+1);let m=C();return(g.at===void 0||m-g.at>=Is)&&(pe(d.name),g.at=m),E({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${u}`},f)}function pe(d){let u=U.get(d).counts;if(u.size===0)return;let f=[...u.values()].reduce((p,g)=>p+g,0);_.warn(`[palbase] webhook ${d}: ${f} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(u)}),u.clear()}function we(d){let u=d.split("/").filter(Boolean);return u.length===2&&u[0]==="webhooks"?A.get(u[1]):void 0}async function Ye(d,u,f,p){let g=u.pathname===De;if(d.method!==(g?"GET":"POST"))return E({status:405,code:"method_not_allowed",message:g?"The jobs are listed with GET":"A job is run with POST"},p);let m=g?new Uint8Array(0):await mt(d,Us);try{await bt({secret:f,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(te){if(te instanceof Ze)return E({status:401,code:"invalid_signature",message:`The jobs are the platform's to call: ${te.code}`},p);throw te}if(g){let te=[...s.values()].map(({declaration:W})=>({name:W.name,schedule:W.schedule,timeout:W.timeout,retry:W.retries}));return de(200,{jobs:te},p,{"cache-control":"no-store"})}let w=u.pathname.slice(De.length+1),R=s.get(w);if(!R)return E({status:404,code:"job_not_found",message:`This version has no job ${JSON.stringify(w)}`},p);let T;try{T=JSON.parse(new TextDecoder().decode(m))}catch{return E({status:400,code:"bad_request",message:"A run is the JSON {job, run_id, scheduled_at, attempt}"},p)}let{job:D,run_id:q,scheduled_at:x,attempt:P}=T??{};if(D!==w||typeof q!="string"||q===""||typeof x!="string"||!Ns.test(x)||Number.isNaN(Date.parse(x))||!Number.isInteger(P)||P<1)return E({status:400,code:"bad_request",message:`A run of ${w} is the JSON {job: "${w}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},p);let L=`${q}#${String(P)}`;if(a.has(L))return new Response(null,{status:204,headers:{"x-request-id":p}});if(i.has(L))return E({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},p);i.add(L);let ce={env:J,environmentId:e.projectId??"",job:w,runId:q,scheduledAt:new Date(x),attempt:P};try{await Gt(e.database,e.database?Rr:void 0,d.signal,`job ${w}`,async()=>{if(await R.run(ce),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${w} before it ended`)})}catch(te){return d.signal.aborted||_.error(`[palbase] job ${w} failed (run ${q}, attempt ${String(P)})`,{error:te}),E({status:500,code:"job_failed",message:`The job ${w} failed; the platform tries it again`},p)}finally{i.delete(L)}return a.add(L),a.size>pt&&a.delete(a.values().next().value),new Response(null,{status:204,headers:{"x-request-id":p}})}async function Ge(d,u,f,p){if(d.method!=="POST")return E({status:405,code:"method_not_allowed",message:`${p} is POSTed`},f);let g;try{mn({signature:d.headers.get("palbase-signature"),now:e.now}),g=await mt(d,1048576),await bt({secret:u,signature:d.headers.get("palbase-signature"),body:g,now:e.now})}catch(w){if(w instanceof Ze)return E({status:401,code:"invalid_signature",message:`${p} is the platform's to call: ${w.code}`},f);throw w}let m;try{m=JSON.parse(new TextDecoder().decode(g))}catch{return E({status:400,code:"bad_request",message:`${p} is JSON`},f)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(d.url).pathname?E({status:401,code:"invalid_signature",message:`${p} is the platform's to call: signed_for_another_call`},f):{body:m}}async function Mr(d,u,f,p,g){let m=await Ge(u,f,p,`An upload's ${d}`);if(m instanceof Response)return m;let w=jn(d,m.body);if(typeof w=="string")return E({status:400,code:"bad_request",message:`An upload's ${d}: ${w}`},p);if(d==="complete"){if(b.has(w.uploadId))return E({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},p);b.add(w.uploadId),b.size>pt&&b.delete(b.values().next().value)}let R=Kt(r,w.method,w.route);if(!R||"malformed"in R||!R.route.meta.upload)return E({status:404,code:"not_found",message:`No upload route for ${w.method} ${w.route}`},p);let{route:T,params:D}=R,q=R.route.meta.upload,x=Ws(w.user);if(x&&cn(g,x.id),n.get(T).required&&!x)throw new X(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let ce=O(T);if(ce!==!1){let W=k.take(`${T.id}\0${xn(w.user,w.client)}`,ce);if(W!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:W},W)}let te=An(q.pathTemplate,{userId:x?.id??null,uploadId:w.uploadId,filename:w.filename});if("problem"in te)throw new X(400,"bad_request",te.problem);return await Me(e.database,tt(w.user),u.signal,T.id,async()=>{let W={request:u,query:new URLSearchParams(w.query),params:D,user:x,body:w.body===void 0||w.body===null?{}:ae(w.body),requestId:p};await an(T,W);for(let be of T.params)(be.kind==="query"||be.kind==="body"&&w.body!==void 0)&&await Or(be,W)}),de(200,{bucket:q.bucket,path:te.path},p)}g.endpoint=T.id.slice(T.id.indexOf(" ")+1);let P=new URLSearchParams(w.query),L=w.body===null||w.body===void 0?{}:ae(w.body);return wt(T,{request:u,query:P,params:D,user:x,body:L,requestId:p,uploadedObject:ae(w.uploadedObject)},tt(w.user))}function on(d,u,f,p){let g=d?{sub:d.id,role:"authenticated"}:null;return Q.run({requestId:Q.getStore()?.requestId??"",...d?{userId:d.id}:{}},()=>Me(e.database,g,f,u,async()=>{let m=await p();if(f.aborted)throw new Error(`the platform gave up on ${u} before it ended`);return m}))}let sn=(d,u)=>new Response(d,{status:200,headers:{"content-type":"application/json","x-request-id":u}});async function Dr(d,u,f){let p=await Ge(d,u,f,"A tool call");if(p instanceof Response)return p;let g=p.body,m=g.tool;if(typeof m!="string"||m==="")return E({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},f);let w=l.tools.get(m);if(!w)return E({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},f);let R=g.call_id,T=It(g.context);if(typeof R!="string"||R===""||R.length>256||typeof T=="string")return E({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof T=="string"?`: ${T}`:""}`},f);let D=Ar("sha256").update(JSON.stringify(g)).digest("hex"),q=h.answered(R);if(q!==void 0)return q.digest!==D?E({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},f):sn(q.answer,f);if(h.isRunning(R))return E({status:409,code:"in_progress",message:"This call is running",retryAfter:2},f);h.start(R);let x;try{let P=await on(T.user,`ai.tool ${m}`,d.signal,()=>w.call(ae(g.input??{}),{...T,callId:R,signal:d.signal}));x=JSON.stringify({output:P.output,is_error:P.is_error});let L=new TextEncoder().encode(x).byteLength;L>4194304&&(_.error(`[palbase] ai.tool ${m} answered ${L} bytes (call ${R}): a machine's answer is ${4194304} at most; the agent is told it failed`),x=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${4194304/(1<<20)} MiB it may be`}],is_error:!0}))}catch(P){if(d.signal.aborted)return h.end(R,void 0),E({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);_.error(`[palbase] ai.tool ${m} failed (call ${R}, chat ${T.chatId}); the agent is told`,{error:P}),x=JSON.stringify({output:[{type:"text",text:Bs(P)}],is_error:!0})}return h.end(R,{digest:D,answer:x}),sn(x,f)}async function Ur(d,u,f){let p=await Ge(d,u,f,"An agent's turn");if(p instanceof Response)return p;let g=It(p.body);if(typeof g=="string"||g.agent==="")return E({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata}${typeof g=="string"?`: ${g}`:": agent names it"}`},f);let m=g.agent,w=l.agents.get(m);if(!w)return E({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},f);let R;try{R=await on(g.user,`ai.agent ${m}`,d.signal,()=>w.resolve({...g,signal:d.signal}))}catch(q){if(d.signal.aborted)return E({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let x=Zt(q,`ai.agent ${m}`);return x?E(x,f):(_.error(`[palbase] ai.agent ${m} failed for chat ${g.chatId}; the turn is not started`,{error:q}),E({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f))}let T=R.tools.find(q=>l.tools.get(q.name)!==q);if(T)return _.error(`[palbase] ai.agent ${m} handed out ai.tool ${JSON.stringify(T.name)}, which this app did not declare when it was made \u2014 make each ai.tool once, at a module's top level, and hand that one out`),E({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f);let D=JSON.stringify(R.definition);return new TextEncoder().encode(D).byteLength>4194304?(_.error(`[palbase] ai.agent ${m}'s definition is larger than the ${4194304} bytes a machine's answer may be`),E({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f)):new Response(D,{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function Nr(d,u,f,p){let g=await Ge(u,f,p,`A room's ${d}`);if(g instanceof Response)return g;let m=await c.serve(d,g.body,u.signal);return"code"in m?E({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},p):"body"in m?de(200,m.body,p):new Response(null,{status:204,headers:{"x-request-id":p}})}async function an(d,u){let f=[],p={params:Object.freeze({...u.params}),user:ae(u.user),headers:d.meta.upload?new Headers:u.request.headers,requestId:u.requestId};for(let g of d.params)g.kind==="resolve"&&(f[g.index]=await o.get(g).resolve(p,g.options));return f}async function wt(d,u,f,p){let g=t.get(d.controller),m=await Me(e.database,f,u.request.signal,d.id,async()=>{let w=await an(d,u);for(let T of d.params)T.kind!=="resolve"&&(w[T.index]=await Or(T,u));p?.ran();let R=await g[d.fn](...w);if(u.uploadedObject&&u.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return p?p.record(_r(xr(R,u.requestId),Q.getStore()?.usedLocales)):R});return p?m:_r(xr(m,u.requestId),Q.getStore()?.usedLocales)}async function dn(d,u){let f=d.headers.get("x-request-id")??"",p=Ks.test(f)?f:`req_${crypto.randomUUID()}`,g=performance.now(),m=new URL(d.url).pathname,w={endpoint:m},R=await Ir(d,u,p,w);return e.telemetry?.record({requestId:p,method:d.method,endpoint:w.endpoint,path:m,status:R.status,durationMs:performance.now()-g,userId:w.userId}),R}function cn(d,u){d.userId=u;let f=Q.getStore();f&&(f.userId=u)}async function Ir(d,u,f,p){let g=e.strings,m=g?{requestId:f,strings:g,locales:vn(d.headers.get("accept-language"),g.source),usedLocales:[]}:{requestId:f},w=await Lr(m,d,u,f,p);return g&&ht(w.headers,"Accept-Language"),w}async function Lr(d,u,f,p,g){return Q.run(d,async()=>{let m=new URL(u.url),w=`${u.method} ${m.pathname}`;try{if(m.pathname===Bt&&Y.size>0)return u.method!=="POST"?E({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},p):e.webhookSecret?await gt(u,p):E({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},p);let R=we(m.pathname);if(R)return w=`webhook ${R.name}`,u.method!=="POST"?E({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},p):await Ue(u,m,R,p);if(e.platform&&(m.pathname===De||m.pathname.startsWith(`${De}/`)))return w=m.pathname===De?"jobs":`job ${m.pathname.slice(De.length+1)}`,await Ye(u,m,e.platform.secret,p);if(e.platform&&(m.pathname===xt||m.pathname===_n)){let N=m.pathname===xt?"authorize":"complete";return w=`upload ${N}`,await Mr(N,u,e.platform.secret,p,g)}if(e.platform&&m.pathname.startsWith(`${Ot}/`)){let N=m.pathname.slice(Ot.length+1);return w=`room ${N}`,await Nr(N,u,e.platform.secret,p)}if(e.platform&&m.pathname===er)return w="ai tool call",await Dr(u,e.platform.secret,p);if(e.platform&&m.pathname===tr)return w="ai agent's turn",await Ur(u,e.platform.secret,p);if(ta(m.pathname))return E({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},p);let T=Kt(r,u.method,m.pathname);if(T&&"malformed"in T)return E({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},p);if(!T)return E({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},p);let{route:D,params:q}=T;if(w=D.id,g.endpoint=D.id.slice(D.id.indexOf(" ")+1),D.meta.upload)throw new X(400,"upload_required",`${D.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let x=n.get(D),P=null,L=null,ce=u.headers.get("authorization")??"",te=/^(bearer|dpop)\s+(\S+)$/i.exec(ce),W=te?.[2],be=te?.[1].toLowerCase()==="dpop";if(W)try{let N=!be&&e.tokens&&!Vs.test(W)&&e.tokens.accepts(W)?e.tokens:void 0,ve=N?await $.ask(W,ft(u.headers,f.remoteAddress),()=>Me(e.database,null,u.signal,"token",()=>N.resolve(W))):await e.verifier.verify(W,be?{proof:u.headers.get("dpop"),method:u.method,url:gn(u.headers,m)}:void 0);P=Fs(ve),L=ve.claims}catch(N){if(!x.required&&(N instanceof Xe||N instanceof Qe||N instanceof Ke))P=null;else throw N instanceof Ke?new X(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:N.wait},N.wait):N instanceof Xe?new X(401,"invalid_token","The access token is not valid",{reason:N.reason},void 0,Js(N.reason)):N}else if(ce!==""&&x.required)throw new X(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(P&&cn(g,P.id),x.required&&!P)throw new X(401,"unauthorized","This route needs a signed-in user");if(x.verifiedEmail&&!P?.emailVerified)throw new X(403,"email_not_verified","This route needs a verified email address");let un=O(D);if(un!==!1){let N=P?`u:${P.id}`:`a:${ft(u.headers,f.remoteAddress)}`,ve=k.take(`${D.id}\0${N}`,un);if(ve!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:ve},ve)}let Ne=u.method==="GET"||u.method==="HEAD"?void 0:await mt(u,v),Jr=Ne===void 0?void 0:zs(Ne),ln={request:u,query:m.searchParams,params:q,user:P,body:Jr,raw:Ne,requestId:p},fn=I&&Ne!==void 0&&Be(D)?fr(u.method,u.headers):void 0;if(!I||fn===void 0)return await wt(D,ln,L);let Hr={role:Yt(e.database.requests,L).role,uid:P?.id??`a:${ft(u.headers,f.remoteAddress)}`},pn=!1;return await I.serve({key:fn,caller:Hr,method:u.method,uri:`${m.pathname}${m.search}`,body:Ne},N=>wt(D,ln,L,{record:N,ran:()=>{pn=!0}}),{requestId:p,refusal:N=>E(N,p),failure:N=>Sr(N,p,w,u.signal),ran:()=>pn})}catch(R){return Sr(R,p,w,u.signal)}})}return{handle:Ve,routes:r.map(d=>d.id),contract:V,start:()=>t.start(),stop:async()=>{c.close();for(let d of U.keys())pe(d);await t.shutdown(),await e.telemetry?.flush()}}}function Xs(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Qs(e){let t=new Set;for(let[r,n]of e)if(St(r))for(let o of n){if(o.bucket===void 0)return;t.add(o.bucket)}return t.size===0?void 0:[...t].sort()}function xr(e,t){return e instanceof Response?qs(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):de(200,e,t)}function ea(e,t){if(!(!qe(e)||e.status!==503||!en(e)))return _.warn(`[palbase] webhook ${t}: the database did not answer (${e.error})`,{error:e}),{status:503,code:e.error,message:e.errorDescription,data:e.data,retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))}}function ta(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return Se.has(decodeURIComponent(t))}catch{return Se.has(t)}}var na="GET, POST, PUT, PATCH, DELETE, QUERY",ra=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function oa(e){if(!e)return;if(e.origins!=="*"){for(let n of e.origins)if(!ra.test(n)||n.startsWith("http://")&&!/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(n))throw new TypeError(`cors origin ${JSON.stringify(n)} is https://host[:port] (http only for localhost), with no path`)}let t=e.origins==="*"?null:new Set(e.origins),r=String(e.maxAge??600);return{allows:n=>t===null||t.has(n),headers:n=>({"access-control-allow-origin":t===null?"*":n,"access-control-expose-headers":"idempotent-replayed, retry-after, x-request-id",vary:"Origin"}),preflight:(n,o)=>({"access-control-allow-origin":t===null?"*":n,"access-control-allow-methods":na,"access-control-allow-headers":o&&/^[A-Za-z0-9-]+(\s*,\s*[A-Za-z0-9-]+)*$/.test(o)?o:"authorization, content-type","access-control-max-age":r,vary:"Origin"})}}async function Or(e,t){switch(e.kind){case"body":return Vt(e.schema,t.body??{},"Request body");case"query":return Vt(e.schema,ae(Object.fromEntries(t.query)),"Query parameters");case"headers":{let r={};return t.request.headers.forEach((n,o)=>r[o.toLowerCase()]=n),ae(r),e.schema?Vt(e.schema,r,"Request headers"):r}case"param":return t.params[e.name];case"user":case"optionalUser":return ae(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"client":{let r=t.request.headers;return ae({sdkVersion:r.get("x-palbase-sdk-version"),appVersion:r.get("x-palbase-client-version"),platform:r.get("x-platform"),osVersion:r.get("x-os-version")})}}}var nn=720*3600;function tn(e){return e instanceof ke&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function jr(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),nn)}function Cr(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var rn=class{filling=new Map;async get(t){try{let r=await $e.cache.getCacheEntry({query:{key:t}});return r.data.found?r.data.value??null:null}catch(r){if(!tn(r))throw r;return _.warn("cache: a read could not reach the cache; it is a miss",{key:t,status:r.status}),null}}async set(t,r,n){try{await $e.cache.putCacheEntry({query:{key:t},body:{value:Cr(r),ttl:jr(n)}})}catch(o){if(!tn(o))throw o;_.warn("cache: a write could not reach the cache; it is let go",{key:t,status:o.status})}}async del(t){await $e.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await $e.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,r,n){let o=this.filling.get(t);if(o)return o;let s=(async()=>{try{let a;try{a=(await $e.cache.getCacheEntry({query:{key:t}})).data}catch(c){if(!tn(c))throw c;_.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:c.status})}if(a?.found)return a.value??null;let i=await n();return await this.set(t,i,r),i}finally{this.filling.delete(t)}})();return this.filling.set(t,s),s}},rd=wn("Cache",new rn);function od(e={}){let t=e.maxEntries??5e4,r=e.now??(()=>Date.now()),n=new Map,o=new Map,s=l=>{let h=n.get(l);if(h&&h.expiresAt<=r()){n.delete(l);return}return h},a=()=>{let l=r();for(let[b,S]of n)S.expiresAt<=l&&n.delete(b);if(n.size<t)return;let h=[...n.entries()].sort((b,S)=>b[1].expiresAt-S[1].expiresAt);for(let[b]of h.slice(0,Math.ceil(h.length/4)))n.delete(b)},i=async(l,h,b)=>{n.size>=t&&!n.has(l)&&a(),n.set(l,{value:Cr(h),expiresAt:r()+(jr(b)??nn)*1e3})};return{get:async l=>{let h=s(l);return h?structuredClone(h.value):null},set:i,async del(l){n.delete(l)},async incr(l){let h=s(l),b=(typeof h?.value=="number"&&Number.isInteger(h.value)?h.value:0)+1;return n.set(l,{value:b,expiresAt:h?.expiresAt??r()+nn*1e3}),b},getOrSet(l,h,b){let S=s(l);if(S)return Promise.resolve(structuredClone(S.value));let I=o.get(l);if(I)return I;let y=(async()=>{try{let C=await b();return await i(l,C,h),C}finally{o.delete(l)}})();return o.set(l,y),y}}}export{Et as a,me as b,_e as c,da as d,ca as e,ua as f,la as g,fa as h,pa as i,ma as j,ha as k,ga as l,ya as m,wa as n,ba as o,va as p,ka as q,$a as r,Ra as s,Ea as t,_a as u,Sa as v,xa as w,Oa as x,Ta as y,Aa as z,j as A,Pa as B,ja as C,Na as D,Ia as E,za as F,Fa as G,Wa as H,Ka as I,Va as J,Ya as K,Ga as L,ei as M,z as N,Yn as O,Gn as P,Zn as Q,Io as R,di as S,li as T,fi as U,pi as V,mi as W,hi as X,gi as Y,yi as Z,wi as _,Si as $,Cs as aa,Qi as ba,nn as ca,rd as da,od as ea};