palbase 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +2 -2
  3. package/dist/ai/index.js +17 -0
  4. package/dist/backend/engine.js +2 -0
  5. package/dist/backend/env.js +1 -0
  6. package/dist/backend/index.js +12 -0
  7. package/dist/backend/stack.js +1 -0
  8. package/dist/backend/test.js +2 -0
  9. package/dist/chunks/3OGEBGYZ.js +20 -0
  10. package/dist/chunks/3VASGTIN.js +2 -0
  11. package/dist/chunks/3XT4L2XV.js +2 -0
  12. package/dist/chunks/45J7YXRB.js +2 -0
  13. package/dist/chunks/6FWCNTAM.js +2 -0
  14. package/dist/chunks/DAOLIUNZ.js +2 -0
  15. package/dist/chunks/E5Q4VTW4.js +2 -0
  16. package/dist/chunks/HKJU2FKE.js +2 -0
  17. package/dist/chunks/IKVOXHEE.js +2 -0
  18. package/dist/chunks/JAWWIVZH.js +2 -0
  19. package/dist/chunks/LYEFPLJZ.js +4 -0
  20. package/dist/chunks/QXUMLO7O.js +13 -0
  21. package/dist/chunks/UAY56IQR.js +6 -0
  22. package/dist/cli.js +815 -0
  23. package/dist/refuse/ai.js +2 -0
  24. package/dist/refuse/backend.js +2 -0
  25. package/dist/refuse/server.js +2 -0
  26. package/dist/server/index.js +2 -0
  27. package/dist/server/testing.js +2 -0
  28. package/dist/web/index.js +2 -0
  29. package/dist/web/palbe.js +2 -0
  30. package/dist/web/vite.js +3 -0
  31. package/package.json +107 -4
  32. package/types/ai/src/ai.d.ts +178 -0
  33. package/types/ai/src/index.d.ts +5 -0
  34. package/types/ai/src/partial.d.ts +1 -0
  35. package/types/ai/src/schema.d.ts +47 -0
  36. package/types/backend/src/bootstrap.d.ts +72 -0
  37. package/types/backend/src/cache.d.ts +32 -0
  38. package/types/backend/src/container.d.ts +49 -0
  39. package/types/backend/src/database.d.ts +148 -0
  40. package/types/backend/src/db-env.d.ts +4 -0
  41. package/types/backend/src/decorators.d.ts +293 -0
  42. package/types/backend/src/engine-db.d.ts +24 -0
  43. package/types/backend/src/engine-exports.d.ts +3 -0
  44. package/types/backend/src/engine.d.ts +124 -0
  45. package/types/backend/src/env.d.ts +27 -0
  46. package/types/backend/src/errors.d.ts +70 -0
  47. package/types/backend/src/i18n.d.ts +21 -0
  48. package/types/backend/src/index.d.ts +23 -0
  49. package/types/backend/src/openapi.d.ts +73 -0
  50. package/types/backend/src/platform-calls.d.ts +41 -0
  51. package/types/backend/src/requests.d.ts +81 -0
  52. package/types/backend/src/rooms.d.ts +168 -0
  53. package/types/backend/src/router.d.ts +22 -0
  54. package/types/backend/src/runtime.d.ts +56 -0
  55. package/types/backend/src/services.d.ts +262 -0
  56. package/types/backend/src/stack.d.ts +20 -0
  57. package/types/backend/src/strings-files.d.ts +3 -0
  58. package/types/backend/src/testing/index.d.ts +3 -0
  59. package/types/backend/src/testing/unit.d.ts +66 -0
  60. package/types/backend/src/upload.d.ts +125 -0
  61. package/types/backend/src/webhooks.d.ts +113 -0
  62. package/types/internal/src/event.d.ts +9 -0
  63. package/types/internal/src/modules/ai.d.ts +678 -0
  64. package/types/internal/src/modules/analytics.d.ts +1414 -0
  65. package/types/internal/src/modules/auth.d.ts +5660 -0
  66. package/types/internal/src/modules/cache.d.ts +158 -0
  67. package/types/internal/src/modules/events.d.ts +19 -0
  68. package/types/internal/src/modules/flags.d.ts +957 -0
  69. package/types/internal/src/modules/index.d.ts +13 -0
  70. package/types/internal/src/modules/machines.d.ts +1584 -0
  71. package/types/internal/src/modules/notify.d.ts +1450 -0
  72. package/types/internal/src/modules/purchases.d.ts +2944 -0
  73. package/types/internal/src/modules/realtime.d.ts +326 -0
  74. package/types/internal/src/modules/secrets.d.ts +275 -0
  75. package/types/internal/src/modules/storage.d.ts +691 -0
  76. package/types/internal/src/modules/stores.d.ts +1516 -0
  77. package/types/internal/src/retry.d.ts +14 -0
  78. package/types/internal/src/transport.d.ts +106 -0
  79. package/types/server/src/auth/dpop.d.ts +47 -0
  80. package/types/server/src/auth/jwt.d.ts +115 -0
  81. package/types/server/src/index.d.ts +9 -0
  82. package/types/server/src/pages.d.ts +4 -0
  83. package/types/server/src/purchases.d.ts +51 -0
  84. package/types/server/src/secrets-env.d.ts +22 -0
  85. package/types/server/src/server.d.ts +40 -0
  86. package/types/server/src/testing.d.ts +91 -0
  87. package/types/server/src/webhooks.d.ts +72 -0
  88. package/types/web/src/analytics.d.ts +87 -0
  89. package/types/web/src/auth.d.ts +155 -0
  90. package/types/web/src/backend-error.d.ts +38 -0
  91. package/types/web/src/backend-names.d.ts +25 -0
  92. package/types/web/src/backends.d.ts +84 -0
  93. package/types/web/src/client.d.ts +51 -0
  94. package/types/web/src/index.d.ts +11 -0
  95. package/types/web/src/palbe.d.ts +2 -0
  96. package/types/web/src/purchases.d.ts +73 -0
  97. package/types/web/src/rooms.d.ts +61 -0
  98. package/types/web/src/session.d.ts +91 -0
  99. package/types/web/src/socket.d.ts +87 -0
  100. package/types/web/src/vite.d.ts +49 -0
package/LICENSE ADDED
@@ -0,0 +1,27 @@
1
+ Palbase SDK License
2
+
3
+ Copyright (c) 2024-present Palbase. All rights reserved.
4
+
5
+ The Palbase SDK — the compiled libraries, their interface files and the documentation distributed with them
6
+ ("the SDK") — is licensed, not sold. Its source code is not part of this distribution.
7
+
8
+ 1. Use. You may use the SDK, free of charge, to develop, test and distribute applications that use Palbase
9
+ services, and you may redistribute the SDK only as an unmodified, embedded part of such an application.
10
+
11
+ 2. Restrictions. You may not:
12
+ a. distribute the SDK on its own, or as part of a library, framework or SDK of your own;
13
+ b. modify, decompile, disassemble or otherwise reverse engineer the SDK, or attempt to derive its source
14
+ code, except to the extent applicable law expressly permits it notwithstanding this restriction;
15
+ c. remove or alter any notice in the SDK.
16
+
17
+ 3. Ownership. Palbase keeps all rights in the SDK that this license does not expressly grant.
18
+
19
+ 4. No warranty. The SDK is provided "as is", without warranty of any kind, express or implied, including the
20
+ warranties of merchantability, fitness for a particular purpose and non-infringement.
21
+
22
+ 5. Limitation of liability. In no event shall Palbase be liable for any claim, damages or other liability,
23
+ whether in an action of contract, tort or otherwise, arising from, out of or in connection with the SDK or
24
+ its use.
25
+
26
+ 6. Termination. This license ends automatically if you break its terms; you must then stop using and
27
+ distributing the SDK.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # palbase
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Part of [Palbase](https://palbase.studio). Distributed compiled; licensed under the Palbase SDK License (`LICENSE`).
@@ -0,0 +1,17 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as V}from"../chunks/6FWCNTAM.js";import{a as W}from"../chunks/IKVOXHEE.js";import{b as U,d as z,f as q,g as Y}from"../chunks/HKJU2FKE.js";import"../chunks/DAOLIUNZ.js";import"../chunks/45J7YXRB.js";async function*Z(e){let t=e.getReader(),a=new TextDecoder,r="",o="",l="";try{for(;;){let{done:d,value:g}=await t.read();if(d)return;r+=a.decode(g,{stream:!0}).replace(/\r\n/g,`
3
+ `);for(let b=r.indexOf(`
4
+ `);b>=0;b=r.indexOf(`
5
+ `)){let v=r.slice(0,b);r=r.slice(b+1),v===""?(o!==""&&(yield{event:o,data:l}),o="",l=""):v.startsWith("event: ")?o=v.slice(7):v.startsWith("data: ")&&(l=v.slice(6))}}}finally{try{await t.cancel()}catch{}}}var se=/\s/;function M(e,t){for(;t<e.length&&se.test(e[t]);)t++;return t}function H(e,t){let a="";for(let r=t+1;r<e.length;r++){let o=e[r];if(o==='"')return{value:a,complete:!0,empty:!1,at:r+1};if(o!=="\\"){a+=o;continue}let l=e[r+1];if(l===void 0)break;if(l==="u"){let d=e.slice(r+2,r+6);if(d.length<4)break;a+=String.fromCharCode(Number.parseInt(d,16)),r+=5;continue}a+={n:`
6
+ `,t:" ",r:"\r",b:"\b",f:"\f"}[l]??l,r++}return{value:a,complete:!1,empty:!1,at:e.length}}function J(e,t){t=M(e,t);let a=e[t];if(a===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(a==='"')return H(e,t);if(a==="{")return oe(e,t);if(a==="[")return ie(e,t);let r=t;for(;r<e.length&&/[-+0-9.A-Za-z]/.test(e[r]);)r++;if(r===e.length)return{value:void 0,complete:!1,empty:!0,at:r};try{return{value:JSON.parse(e.slice(t,r)),complete:!0,empty:!1,at:r}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function oe(e,t){let a={},r=t+1;for(;;){if(r=M(e,r),e[r]==="}")return{value:a,complete:!0,empty:!1,at:r+1};if(e[r]===","){r++;continue}if(e[r]!=='"')return{value:a,complete:!1,empty:!1,at:e.length};let o=H(e,r);if(!o.complete)return{value:a,complete:!1,empty:!1,at:e.length};if(r=M(e,o.at),e[r]!==":")return{value:a,complete:!1,empty:!1,at:e.length};let l=J(e,r+1);if(l.empty||Object.defineProperty(a,o.value,{value:l.value,enumerable:!0,writable:!0,configurable:!0}),!l.complete)return{value:a,complete:!1,empty:!1,at:e.length};r=l.at}}function ie(e,t){let a=[],r=t+1;for(;;){if(r=M(e,r),e[r]==="]")return{value:a,complete:!0,empty:!1,at:r+1};if(e[r]===","){r++;continue}if(r>=e.length)return{value:a,complete:!1,empty:!1,at:r};let o=J(e,r);if(o.empty||a.push(o.value),!o.complete)return{value:a,complete:!1,empty:!1,at:e.length};r=o.at}}function B(e){let t=J(e,0);return t.empty?void 0:t.value}var m=class extends Error{path;constructor(t,a){super(`${t}: ${a}`),this.name="AISchemaError",this.path=t}},de=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),ce=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),le=new Set(["object","array","string","integer","number","boolean"]),X=12,Q=512,ue=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function D(e,t="answer"){if(!ue.test(t))throw new m(t||"(name)","a schema name starts with a letter and holds letters, digits, _ and -, 64 at most");let a=e?.["~standard"];if(!a||a.version!==1||typeof a.validate!="function")throw new m(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!a.jsonSchema||typeof a.jsonSchema.output!="function")throw new m(t,`${a.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let r;try{r=a.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(d){throw new m(t,`the schema has a part JSON Schema cannot say (${d.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(r.type!=="object")throw new m(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let l=K(r,t,0,{properties:0});return{name:t,json:l,async check(d){let g=await a.validate(d);if(g.issues){let b=g.issues[0],v=(b?.path??[]).map(n=>String(typeof n=="object"?n.key:n)).join(".");throw new m(v?`${t}.${v}`:t,`the model's answer does not match the schema: ${b?.message??"invalid"}`)}return g.value}}}function K(e,t,a,r){if(a>X)throw new m(t,`nests deeper than ${X} levels, the most the provider takes`);for(let d of["anyOf","oneOf","allOf"])if(d in e)throw new m(t,me(e[d])??"is a union of several shapes: the provider holds a model to one shape per field \u2014 use an enum, or one object with every field");for(let d of["$ref","$defs","definitions","$dynamicRef"])if(d in e)throw new m(t,"refers to another schema (a recursive or shared type): the provider takes no references \u2014 write the shape out, a bounded number of levels deep");if(e.type==="object"&&("propertyNames"in e||"patternProperties"in e||e.additionalProperties!==void 0&&e.additionalProperties!==!1))throw new m(t,"accepts fields it does not name (a record, passthrough or catchall): the provider holds a model only to the fields named \u2014 name them");for(let d of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(d in e)throw new m(t,`uses ${d}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new m(t,`may be ${e.type.join(" or ")}: one type per field \u2014 a nullable field is not expressible; give it a value that means "none" (an empty string, an enum member)`);let o=e.type;if(typeof o!="string"&&!("enum"in e))throw new m(t,"has no type: the provider holds a model only to a typed value");if(typeof o=="string"&&!le.has(o))throw new m(t,`is of type ${o}, which the provider does not take`);let l={};for(let[d,g]of Object.entries(e))if(!(d==="$schema"||d==="id"||d==="$id")&&!ce.has(d)){if(!de.has(d))throw new m(t,`uses ${d}, which the provider cannot hold a model to`);l[d]=g}if("enum"in e&&typeof o!="string"){let d=e.enum,g=new Set(d.map(b=>b===null?"null":typeof b));if(g.size!==1||g.has("null"))throw new m(t,"an enum of values of several types (or with null): one type per field");l.type=g.has("string")?"string":g.has("boolean")?"boolean":"number"}if(o==="object"){let d=e.properties??{},g=Object.keys(d);if(g.length===0)throw new m(t,"is an object with no fields (a record, or any object): the provider holds a model only to named fields \u2014 name them");if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new m(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(r.properties+=g.length,r.properties>Q)throw new m(t,`the schema has more than ${Q} fields in all, the most the provider takes`);let b=new Set(e.required??[]),v={};for(let n of g){if(!b.has(n))throw new m(`${t}.${n}`,'is optional: the provider makes the model write every field \u2014 make it required (give it a value that means "none"), or leave it out of the schema');v[n]=K(d[n],`${t}.${n}`,a+1,r)}l.properties=v,l.required=g,l.additionalProperties=!1}if(o==="array"){let d=e.items;if(!d||typeof d!="object"||Array.isArray(d))throw new m(t,"is a list with no one shape for its items: the provider takes a list of one shape");l.items=K(d,`${t}[]`,a+1,r)}return l}function me(e){if(Array.isArray(e)&&e.length===2&&e.some(t=>t?.type==="null"))return'is nullable: the provider makes the model write a value of one type \u2014 drop .nullable() and give it a value that means "none"'}var pe=/^pb_[a-z0-9]+_s/;function ee(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function F(){return"ai_"+crypto.randomUUID()}function L(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:D(t,"answer")}}function N(e,t={}){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let a={...t};return e.prompt!==void 0&&(a.input=e.prompt),e.messages!==void 0&&(a.messages=e.messages),e.instructions!==void 0&&(a.instructions=e.instructions),e.model!==void 0&&(a.model=e.model),e.metadata!==void 0&&(a.metadata=e.metadata),a}var x=class extends Error{code;response;constructor(t){super(t.error?.message??`the response ended ${t.status}`),this.name="AIResponseError",this.code=t.error?.code??t.status,this.response=t}};function fe(e){let t=Uint8Array.from(atob(e),o=>o.charCodeAt(0)),a=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new Array(t.byteLength/4);for(let o=0;o<r.length;o++)r[o]=a.getFloat32(o*4,!0);return r}async function te(e){let t,a;e instanceof Uint8Array?(t=e,a=ne(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),a=e.type||ne(t)):(t=e.bytes,a=e.mediaType);let r="";for(let o=0;o<t.length;o+=32768)r+=String.fromCharCode(...t.subarray(o,o+32768));return{media_type:a,data:btoa(r)}}function ne(e){return e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"application/octet-stream"}function he(e){let t=e.url??ee("PALBASE_URL"),a=e.secretKey??ee("PALBASE_SECRET_KEY");if(typeof t!="string"||t==="")throw new TypeError("url is the project address (https://<ref>.<domain>) \u2014 or set PALBASE_URL");if(typeof a!="string"||!pe.test(a))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026) \u2014 or set PALBASE_SECRET_KEY; a model call is billed to the project, so it is never made with a publishable key");let r=Y(z({baseUrl:t,credentials:{secretKey:a},fetch:e.fetch}),e.retry??q);return W.client(r)}function ge(e){return new Proxy({},{get:(t,a)=>e.ai[a]})}function ye(e={}){if(V())throw new TypeError("palbase/ai runs on a server: it speaks with the project secret key, which never goes into a browser or a mobile app \u2014 call your backend, and let it ask the model");let t=e.server?ge(e.server):he(e),a=e.resumeFor??12e4;async function r(n,s,c=F()){return t.createResponse({headers:{"Idempotency-Key":c},body:n,signal:s})}async function o(n,s={}){return(await t.getResponse({path:{response_id:n},signal:s.signal})).data}async function l(n,s,c,u,p){let h=0,w=n,k=F(),O=()=>Date.now()+a,j=O();for(let I=0;;I++)try{if(w||(s===null?w=(await r({...p,stream:!0},u,k)).data:w=(await t.followResponse({path:{response_id:s},query:{offset:h},signal:u})).data),!w.body)throw new Error("the stream has no body");for await(let f of Z(w.body)){let S=JSON.parse(f.data);switch(f.event){case"response":s===null&&(s=S.id,c.admitted(S));break;case"delta":if(S.offset+S.text.length>h){let T=S.text.slice(Math.max(0,h-S.offset));c.delta(h,T),h+=T.length}j=O();break;case"reset":S.offset<h&&(h=S.offset,c.reset(h));break;case"terminal":return S}}throw new Error("the stream ended before its answer did")}catch(f){if(w=null,u?.aborted||f instanceof U&&f.status>0&&f.status<500&&f.status!==429||s===null&&!(f instanceof U)||Date.now()>j)throw f;await new Promise(S=>setTimeout(S,Math.min(250*2**Math.min(I,4),4e3)))}}function d(n){if(n.status!=="completed")throw new x(n);return n.text??""}function g(n,s){let c=N(n,s?{schema:s.prepared.json,schema_name:s.name}:{}),u=[],p=!1,h,w=null,k=()=>{let i=w;w=null,i?.()},O,j,I=new Promise((i,y)=>{O=i,j=y});I.catch(()=>{});let f="",S=l(null,null,{admitted:i=>O(i.id),delta:(i,y)=>{f+=y,u.push(y),k()},reset:i=>{f=f.slice(0,i),u.push("\0reset:"+i),k()}},n.signal,c).then(i=>{let y=i.status==="completed"?i.text??"":"";return y.length>f.length&&y.startsWith(f)&&(u.push(y.slice(f.length)),f=y),p=!0,k(),i},i=>{throw p=!0,h=i,j(i),k(),i});S.catch(()=>{});async function*T(){for(let i=0;;i++){for(;i>=u.length;){if(p){if(h)throw h;return}await new Promise(y=>w=y)}yield u[i]}}async function*re(){for await(let i of T())i.startsWith("\0reset:")||(yield i)}async function*ae(){let i="",y="";for await(let _ of T()){_.startsWith("\0reset:")?i=i.slice(0,Number(_.slice(7))):i+=_;let A=B(i);if(A===void 0)continue;let P=JSON.stringify(A);P!==y&&(y=P,yield A)}}let E=S.then(i=>{if(i.status!=="completed")throw new x(i);return i});E.catch(()=>{});let C=s?E.then(i=>s.prepared.check(i.output)):Promise.reject(new TypeError("object is a schema stream's"));C.catch(()=>{});let G=E.then(i=>i.text??f);return G.catch(()=>{}),{id:I,response:E,text:G,get textStream(){return re()},get partialObjectStream(){return ae()},object:C,toResponse(i={}){let y=new TextEncoder,_=new ReadableStream({async start(P){try{for await(let $ of T())$.startsWith("\0reset:")?P.enqueue(y.encode(`event: reset
7
+ data: ${JSON.stringify({offset:Number($.slice(7))})}
8
+
9
+ `)):P.enqueue(y.encode(`data: ${JSON.stringify({text:$})}
10
+
11
+ `));let R=await E;P.enqueue(y.encode(`event: done
12
+ data: ${JSON.stringify({id:R.id,text:R.text,output:R.output,usage:R.usage})}
13
+
14
+ `))}catch(R){let $=R instanceof x||R instanceof U?R.code:"stream_failed";P.enqueue(y.encode(`event: error
15
+ data: ${JSON.stringify({code:$})}
16
+
17
+ `))}finally{P.close()}}}),A=new Headers(i.headers);return A.set("content-type","text/event-stream"),A.set("cache-control","no-store"),A.set("x-accel-buffering","no"),new globalThis.Response(_,{...i,headers:A})}}}async function b(n,s){return l(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},n.signal,N(n,s))}return{module:t,async ask(n,s={}){let c=typeof n=="string"?{...s,prompt:n}:n;return d(await b(c,{}))},async generate(n){let s=L(n.schema),c={schema:s.prepared.json,schema_name:s.name};if(n.background){let h=(await r(N(n,{...c,background:!0}),n.signal)).data;return{id:h.id,status:h.status}}let u=await b(n,c);if(u.status!=="completed")throw new x(u);return s.prepared.check(u.output)},stream(n){return g(n,n.schema?L(n.schema):void 0)},async start(n){let s=(await r(N(n,{background:!0}),n.signal)).data;return{id:s.id,status:s.status}},schema(n,s){return{name:n,schema:s,prepared:D(s,n)}},response:o,async result(n,s){let c=L(s),u=await o(n);if(u.status!=="completed")throw new x(u);return c.prepared.check(u.output)},async cancel(n){return(await t.cancelResponse({path:{response_id:n}})).data},async embed(n,s={}){let c=Array.isArray(n)?n:[n],u=[];for(let p=0;p<c.length;p+=1024){let h=await t.createEmbeddings({body:{input:c.slice(p,p+1024),model:s.model,dimensions:s.dimensions},signal:s.signal});for(let w of h.data.vectors)u.push(fe(w))}return Array.isArray(n)?u:u[0]},async image(n){let s={prompt:n.prompt};for(let p of["model","size","quality","background","format","count"])n[p]!==void 0&&(s[p]=n[p]);n.references?.length&&(s.references=await Promise.all(n.references.map(te))),n.mask&&(s.mask=await te(n.mask));let c=(await t.createImage({headers:{"Idempotency-Key":F()},body:s,signal:n.signal})).data;for(let p=0;c.status==="running";p++){if(await new Promise(h=>setTimeout(h,Math.min(500+p*250,3e3))),n.signal?.aborted)throw n.signal.reason;c=(await t.getImage({path:{image_id:c.id},signal:n.signal})).data}if(c.status!=="completed")throw new Error(`the image failed: ${c.error?.code??"image_failed"}: ${c.error?.message??""}`);let u=await Promise.all(c.files.map(async p=>{let w=(await t.getImageFile({path:{image_id:c.id,position:p.position},signal:n.signal})).data;return{mediaType:p.media_type,bytes:new Uint8Array(await w.arrayBuffer())}}));return{id:c.id,model:c.model,pictures:u,costNanoUSD:c.usage?.cost_nano_usd??0,save(p,h,w=0){let k=u[w];if(!k)throw new RangeError(`the job made ${u.length} picture(s)`);return p.upload(h,k.bytes,{contentType:k.mediaType})}}},async models(){return(await t.listModels({})).data},async usage(n={}){let s=(await t.listUsage({query:{kind:n.kind,limit:n.limit,cursor:n.cursor}})).data;return{usage:s.usage,nextCursor:s.next_cursor}},async connectProvider(n,s){return(await t.connectProvider({path:{provider:n},body:{key:s}})).data},async disconnectProvider(n){await t.disconnectProvider({path:{provider:n}})}}}export{x as AIResponseError,m as AISchemaError,ye as createAI,B as partial,D as prepare};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ import{ba as h,ea as d}from"../chunks/3OGEBGYZ.js";import"../chunks/LYEFPLJZ.js";import"../chunks/3XT4L2XV.js";import"../chunks/6FWCNTAM.js";import"../chunks/IKVOXHEE.js";import"../chunks/HKJU2FKE.js";import"../chunks/DAOLIUNZ.js";import"../chunks/45J7YXRB.js";import{binding as R,createDatabase as v}from"palgres";var b=new WeakMap;function q(l,e,n){if(!n?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=n.schemas,s=b.get(l);s||b.set(l,s=new Map);let r=s.get(u);r||s.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",f=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},g=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(g);i||(i=v({sql:l,schemas:u,binding:R(0,!0),roles:f}),r.set(g,i));let w=JSON.parse(e.claimsJson),m=i.then(a=>a.request({role:o,claims:w},{diagnostics:n.diagnostics,signal:n.signal})),y=a=>new Proxy(()=>{},{apply:async(t,D,c)=>{let p=(await m).client;return a(p).apply(p,c)}});return{client:new Proxy({},{get(a,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:y(p=>p.asService()[c])}):y(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async a=>(await m).rollback(a)}}export{h as createApp,q as createRequestDatabase,d as makeMemoryCache};
@@ -0,0 +1 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
@@ -0,0 +1,12 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as Et}from"../chunks/JAWWIVZH.js";import{$ as C,A as T,B as Qe,C as Xe,D as Ze,E as et,F as rt,G as st,H as nt,I as at,J as ot,K as it,L as lt,M as ct,N as dt,O as ut,P as pt,Q as ht,R as Y,S as bt,T as mt,U as gt,V as ft,W as yt,X as wt,Y as Pt,Z as St,_ as vt,a as K,aa as kt,b as z,ba as B,c as G,ca as At,d as _e,da as Rt,e as Oe,f as Te,g as Ce,h as Be,i as Fe,j as Me,k as Ie,l as Le,m as $e,n as Ue,o as De,p as je,q as Ne,r as qe,s as Ve,t as We,u as Ke,v as ze,w as Ge,x as He,y as Je,z as Ye}from"../chunks/3OGEBGYZ.js";import{a as E,b as H,c as J,e as h,f as tt,g as d}from"../chunks/LYEFPLJZ.js";import{a as j,g as Ee,h as xe,i as q,j as O,q as V,r as W}from"../chunks/3XT4L2XV.js";import"../chunks/6FWCNTAM.js";import{m as Re}from"../chunks/IKVOXHEE.js";import{b as _}from"../chunks/HKJU2FKE.js";import"../chunks/DAOLIUNZ.js";import"../chunks/45J7YXRB.js";import"reflect-metadata";import{existsSync as er,writeFileSync as tr,writeSync as he}from"node:fs";import{createServer as rr}from"node:http";import{dirname as N,join as sr,resolve as nr}from"node:path";import{Readable as ar}from"node:stream";var xt=2e3,_t=1e4,Ot=/^[A-Za-z0-9_-]{1,64}$/,Tt=512,F=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??_t,this.shutdownMs=r.shutdownMs??xt,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Ot.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Tt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let l=a.status,o=l??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Ct}from"node:crypto";import{bind as Bt,bunDriver as Ft,createDatabase as Mt,createSearchWorker as It,cutOff as Lt,forgetUser as $t,MigrationOpen as Ut,MigrationRefused as Dt,Migrator as ee,renewingBunPool as Q,VersionNotMigrated as jt}from"palgres";import{toModel as te}from"palgres/dsl";var Nt=["start","complete","rollback","plan","status"],qt=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function re(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!Nt.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan or status, not ${e}`);return e}}function se(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===C.name)throw new Error(`[palbase] db.schemas: the ${C.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,C]}function L(t){return te(se(t))}function Vt(t){return t.tables.some(e=>e.search!==void 0)}function $(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function ne(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function Wt(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var X=5;function ae(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=Q(()=>new r.SQL({url:n,prepare:!1,max:s})),l=Q(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:Ft(a,l),poolSize:s,close:async()=>{await a.close({timeout:X}),await l.close({timeout:X})}}}}function oe(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),M(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function ie(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!qt.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=ae(t,ne(e)),l=a(s),o,c=i=>d.error(`[palbase] migrate ${r}: ${i}`);try{let i=L(t),u=new ee(l.pool,{log:p=>{/ is held by others | held by writers/.test(p)&&(o=p.trim()),d.info(p)},shadow:p=>{let g=new URL(s);g.pathname=`/${p}`;let P=a(g.toString());return{reserve:()=>P.pool.reserve(),end:()=>P.close()}},openedBy:n});if(r==="plan"){let p=await u.plan(i);return M(r,p),p.refusals.length>0?1:0}if(r==="status")return M(r,await u.status()),0;let m=r==="start"?await Kt(u,i,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:m}),M(r,m),0}catch(i){return i instanceof Dt?(d.error(`[palbase] migrate ${r}: refused`,{refusals:i.refusals}),c(`refused \u2014 ${i.refusals.join("; ")}`),1):Lt(i)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:i}),c(`cut off \u2014 ${o??Z(i)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:i}),c(`failed \u2014 ${Z(i)}`),1)}finally{await l.close().catch(()=>{})}}async function Kt(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof Ut)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}function M(t,e){process.stdout.write(`${JSON.stringify({palbase_migrate:t,result:e})}
3
+ `)}function Z(t){return(t instanceof Error?t.message:String(t)).split(`
4
+ `)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function zt(t,e){try{return await new ee(t).plan(e)}catch{return}}var I=class extends Error{digest;plan;constructor(e,r){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...r?Gt(r):[" palbase db:plan says what it would change"]].join(`
5
+ `)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function Gt(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let r of t.changes)e.push(` + ${r}`);for(let r of t.refusals)e.push(` \u2717 ${r}`);return e}async function le(t,e,r,s){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=se(t),l=te(a),o=ae(t,ne(e))(n);try{let c=await Bt(o.engine,l,{waitMs:s.onPlatform?6e4:0}).catch(async g=>{throw s.onPlatform||!(g instanceof jt)?g:new I(g.digest,await zt(o.pool,l))}),i=Ct("sha256",r).update("palgres page cursor").digest("hex"),u=t.embed??s.embed,m=await Mt({sql:o.engine,schemas:a,binding:c,cursorSecret:i,admission:Wt(o.poolSize),embed:u,log:g=>d.warn(`[palbase] ${g}`)}),p=Vt(l)?It({sql:o.engine,embed:u,log:g=>d.info(`[palbase] ${g}`)}):void 0;return{model:l,binding:c,app:m,requests:t.requests??"caller",forget:g=>$t(o.engine,c,l,g),...p?{search:p}:{},close:()=>o.close()}}catch(c){throw await o.close(),c}}function Ht(t){let e=Buffer.from(t,"base64"),r=new Array(e.byteLength/4);for(let s=0;s<r.length;s++)r[s]=e.readFloatLE(s*4);return r}function ce(t){return async({texts:e,model:r,dimensions:s})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:r,dimensions:s}});return{model:n.model,vectors:n.vectors.map(Ht)}}}var Jt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function de(t,e,r){let s=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&s.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&s.push("palbase.url / PALBASE_URL is the project origin alone")}catch{s.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let l=t.projectId??e.PALBASE_PROJECT_ID??"";Jt.test(l)||s.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&s.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let i=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(c!==void 0||i!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(i??"")&&s.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),s.length>0)throw new Error(`[palbase] the app cannot start:
6
+ - ${s.join(`
7
+ - `)}`);return{url:a,projectId:l,secretKey:o,webhookSecret:r.needsWebhookSecret?i:void 0,platformSecret:c}}import{createHash as Yt}from"node:crypto";import{gzipSync as Qt}from"node:zlib";var Xt="palbase-contract-v1 begin",Zt="palbase-contract-v1 end",ue=76;function pe(t){let e=Buffer.from(t,"utf8"),r=Qt(e).toString("base64"),s=[`${Xt} ${Yt("sha256").update(e).digest("hex")} ${e.length}`];for(let n=0;n<r.length;n+=ue)s.push(r.slice(n,n+ue));return s.push(Zt),`
8
+ ${s.join(`
9
+ `)}
10
+ `}var be=2e4,me=5e3,or=15e3,ir="/_palbase/health";function lr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=T(s,K);return n?n.providers.some(a=>T(a,z)!==void 0&&T(a,G)===void 0)||n.imports.some(r):!1};return t.some(r)}var cr={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=re(s);if(n!==void 0){let y=e.db?await ie(e.db,s,n):oe(n);throw process.exit(y),new U(y)}let a=s.PALBASE_CONTRACT_OUT;if(a){let y;try{y=await dr(r,e,s)}catch(S){throw he(2,`[palbase] the contract: ${S instanceof Error?S.message:String(S)}
11
+ `),process.exit(1),new x}throw a==="/dev/stdout"?he(1,pe(y)):tr(a,`${y}
12
+ `),process.exit(0),new x}let l=e.db?L(e.db):void 0,o=await W({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&d.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(y=>JSON.stringify(y)).join(", ")}`);let c=lr(r)||l!==void 0&&$(l),i=de(e.palbase??{},s,{needsWebhookSecret:c});c&&i.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let u=j({url:i.url,secretKey:i.secretKey}),m=e.port??Number(s.PORT??"8080");if(!Number.isInteger(m)||m<0||m>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let p=e.db?await le(e.db,s,i.secretKey,{onPlatform:i.platformSecret!==void 0,embed:ce(u)}):void 0;p&&d.info(`[palbase] database: version ${p.binding.version}`);let g=p&&$(p.model)?{"user.deleted":[y=>ur(p,y)]}:void 0,P=i.platformSecret===void 0?void 0:{secret:i.platformSecret},v=e.requestTelemetry===!1?void 0:new F(u.analytics),b=()=>B({modules:r,verifier:new O({issuer:i.url,projectId:i.projectId,standing:q({url:i.url,secretKey:i.secretKey})}),server:u,webhookSecret:i.webhookSecret,env:s,projectId:i.projectId,telemetry:v,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,platform:P,events:g,database:p&&{app:p.app,requests:p.requests}}),f=b(),A=e.boot?.attempts??5,R=e.boot?.backoffMs??1e3;for(let y=1;;y++)try{await f.start();break}catch(S){if(y>=A)throw d.error(`[palbase] the app did not start after ${A} attempts`,{error:S}),S;d.warn(`[palbase] the app did not start (attempt ${y} of ${A}); trying again in ${R} ms`,{error:S}),await new Promise(Ae=>setTimeout(Ae,R)),R*=2,f=b()}return pr(f,u,m,e.host??"0.0.0.0",e.exitOnFatal??!0,p)}};async function dr(t,e,r){let s=nr(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=N(s);for(;!er(sr(n,"package.json"))&&N(n)!==n;)n=N(n);let{analyzeProject:a}=await import("../chunks/UAY56IQR.js"),{routeContracts:l}=await import("../chunks/3VASGTIN.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",i=B({modules:t,verifier:new O({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:j({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await l(o.routes),errors:Y()},events:e.db&&$(L(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(i.contract(),null,2)}var x=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},U=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function ur(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r);d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function pr(t,e,r,s,n,a){let l,o={on:!1},c=(b,f)=>new URL(b.url).pathname===ir&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,f),i=rr((b,f)=>{hr(c,b,f,o).finally(()=>{o.on&&i.closeIdleConnections()})});i.keepAliveTimeout=29e4,i.headersTimeout=3e5;try{await new Promise((b,f)=>{i.once("error",f),i.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=i.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let m=b=>l??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let f=new Promise(R=>i.close(()=>R()));i.closeIdleConnections();let A=setTimeout(()=>i.closeAllConnections(),b);await f,clearTimeout(A),process.off("SIGINT",P),process.off("uncaughtException",v),process.off("unhandledRejection",v);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",P)}})(),p=()=>m(be),g=!1,P=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},be+or);b.unref(),p().then(()=>{clearTimeout(b),process.exit(0)},f=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:f}),process.exit(1)})},v=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let f=setTimeout(()=>process.exit(1),me+1e3);m(me).finally(()=>{clearTimeout(f),process.exit(1)})};return process.on("SIGTERM",P),process.once("SIGINT",P),n&&(process.on("uncaughtException",v),process.on("unhandledRejection",v)),{routes:t.routes,palbase:e,port:u,handle:c,close:p}}async function hr(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let l=new Headers;for(let[m,p]of Object.entries(e.headers))if(p!==void 0)if(Array.isArray(p))for(let g of p)l.append(m,g);else l.set(m,p);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let i=new Request(a,{method:e.method,headers:l,body:o?ar.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(i,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((m,p)=>r.setHeader(p,m)),s.on&&r.setHeader("connection","close"),u.body)for await(let m of u.body)r.write(m);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}import{bigint as gs,boolean as fs,check as ys,date as ws,defineSchema as Ps,defineTable as Ss,enumType as vs,foreignKey as ks,index as As,integer as Rs,jsonb as Es,numeric as xs,ownedByUser as _s,policy as Os,raw as Ts,sqlType as Cs,text as Bs,timestamp as Fs,userRef as Ms,uuid as Is}from"palgres/dsl";import{increment as $s,now as Us}from"palgres";function k(t){if(t instanceof _)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function w(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return k(r)}}var br=E("Secrets",{async get(t){if(V(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),mr=100,gr=1e3,fr=168*3600,yr={s:1,m:60,h:3600,d:86400};function wr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*yr[n]*1e3);return Math.ceil(r/1e3)}function ve(t,e,r){let s=`${h.url}/storage/public/${encodeURIComponent(t)}/${encodeURIComponent(e)}`;return r?`${s}?variant=${encodeURIComponent(r)}`:s}function ge(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,ve(t.bucket,t.path,e)]))}}function Pr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await h.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:ge(a.data),error:null,status:a.status}}catch(a){return a instanceof _&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:k(a)}},async download(e){try{let r=await h.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return k(r)}},getPublicUrl(e,r){return ve(t,e,r?.variant)},async createSignedUrl(e,r){let s=wr(r?.expiresIn);return s===void 0||s<1||s>fr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:w(()=>h.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??mr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(gr,n+s-a.length)),i=await h.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...l?{cursor:l}:{}}});o=i.status;for(let u of i.data.objects)n>0?n--:a.length<s&&a.push(ge(u));if(l=i.data.next_cursor,!l)break}}catch(c){return k(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await h.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return k(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return w(()=>h.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return w(()=>h.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Sr={bucket:Pr},fe=t=>H("Storage",t,Sr),vr={bucket:t=>fe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?fe("buckets").bucket(e):void 0})},kr=E("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return w(()=>h.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return w(()=>h.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let o of e)try{let c=await h.notify.sendEmail({body:{...n,to:o}});l=c.status,a.push(c.data.message_id??null)}catch(c){return k(c)}return{data:{message_ids:a},error:null,status:l}}}}),ye=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",we=t=>typeof t=="string"?{name:t}:null,Pe=t=>t==="override"?"user":"system",Ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&("userId"in t||"properties"in t);function ke(){return J.getStore()?.userId}function D(t){let e=t&&"userId"in t?t.userId??void 0:ke();return w(()=>e?h.flags.getUserValues({path:{user_id:e}}):h.flags.getValues(),r=>r.values??{})}var Se={setOverrideForUser:(t,e,r)=>w(()=>h.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Pe(s.source)})),setOverridesForUser:(t,e)=>w(()=>h.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>w(()=>h.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Pe(r.source)})),clearAllOverridesForUser:t=>w(()=>h.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>w(()=>h.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Rr=E("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await D(e);return s.error?r(`${s.error.code}: ${s.error.message}`):ye(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await D(e);return r.error?{data:null,error:r.error,status:r.status}:{data:we(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await D(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=we(s);return{name:r,enabled:ye(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Ar(e)?a=e:e!==void 0&&(s=e,n=!0);let l=await D(a);if(l.error)return n?{data:s??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let o=l.data[t];return{data:o===void 0?s??null:o,error:null,status:l.status}},async setOverride(t,e){let r=ke();return r?Se.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Se}}),Er=E("Realtime",{broadcast(t,e,r){return w(()=>h.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return w(()=>h.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return w(()=>h.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as zs}from"zod";export{xe as AuthUnavailable,mt as BadRequest,Ie as Body,At as CACHE_MAX_TTL,Rt as Cache,We as Client,gt as Conflict,x as ContractRunEnded,_e as Controller,tt as Database,ft as DeadlockDetected,Fe as Delete,dt as DiError,Re as EVENT_TYPES,Rr as Flags,ht as Forbidden,Oe as Get,$e as Headers,yt as HttpError,ze as Injectable,Je as Job,d as Log,kt as MAX_BODY_BYTES,U as MigrationRunEnded,Ge as Module,wt as NotFound,kr as Notifications,He as On,st as OnAuthorize,it as OnEmpty,nt as OnFirst,at as OnJoin,ot as OnLeave,lt as OnMessage,je as OptionalUser,ut as PalError,h as Palbase,_ as PalbaseError,cr as PalbaseFactory,Ue as Param,Be as Patch,Te as Post,Ce as Put,Me as Query,Le as QueryParams,Er as Realtime,Ne as Req,qe as RequestId,Ke as Resolve,rt as Room,I as SchemaNotPushed,br as Secrets,Pt as SerializationFailure,vr as Storage,Ee as TokenError,O as TokenVerifier,St as TooManyRequests,Ve as TraceId,pt as Unauthorized,vt as UniqueViolation,Ze as Upload,et as UploadedObject,De as User,Ye as Webhook,gs as bigint,fs as boolean,ys as check,B as createApp,ws as date,bt as defineError,Ps as defineSchema,Ss as defineTable,vs as enumType,ks as foreignKey,Qe as getRegisteredControllers,Xe as getRoutes,ct as getWebhookManifest,$s as increment,As as index,Rs as integer,Es as jsonb,Us as now,xs as numeric,_s as ownedByUser,Os as policy,Ts as raw,Cs as sqlType,Et as t,Bs as text,Fs as timestamp,Ms as userRef,Is as uuid,zs as z};
@@ -0,0 +1 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as k,b as $,c as R,d as E}from"../chunks/E5Q4VTW4.js";import{a as h}from"../chunks/JAWWIVZH.js";import{c as m}from"../chunks/LYEFPLJZ.js";import"../chunks/DAOLIUNZ.js";import"../chunks/45J7YXRB.js";import"reflect-metadata";import{randomUUID as C}from"node:crypto";import{createFakeClient as O,typedDatabase as b}from"palgres/testing";function x(t,r,n){if(n?.acceptLanguage!==void 0&&n.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:o,...i}=t,e=n?.strings;return m.run({requestId:`test_${C()}`,database:o===void 0?void 0:b(o),services:i,...e!==void 0?{strings:e,locales:h(n?.acceptLanguage??null,e.source),usedLocales:[]}:{}},r)}function D(){let t=new Map,r=new Map,n=[],o=e=>{if(t.has(e))return t.get(e);if(r.has(e))return r.get(e);if(n.includes(e)){let a=[...n.slice(n.indexOf(e)),e].map(c=>c.name??String(c));throw new TypeError(`isolated(): ${a.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}n.push(e);try{let a=Reflect.getMetadata("design:paramtypes",e)??[],c=new e(...a.map(o));return r.set(e,c),c}finally{n.pop()}},i={with(e,a){return t.set(e,a),i},get:e=>o(e)};return i}function F(){let t=O();return{db:b(t),raw:t,queries:t.queries,seed:(r,n)=>t.seed(r,n),inserted:r=>t.inserted(r),updated:r=>t.updated(r),deleted:r=>t.deleted(r)}}import{lstat as N,readdir as j,readFile as L}from"node:fs/promises";import{join as T}from"node:path";var l="palbase/strings",u="_meta.json",f=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function S(t){try{return Intl.getCanonicalLocales(t),!0}catch{return!1}}function v(t,r){try{return JSON.parse(t)}catch(n){throw new Error(`${r} is not JSON: ${n.message}`)}}async function I(t){let r=T(t,l);try{if(!(await N(r)).isDirectory())throw new Error(`${l} is not a directory: the strings live in a directory of their own`)}catch(s){if(s.code==="ENOENT")return;throw s}let n=new Map;for(let s of await j(r,{withFileTypes:!0}))if(!(s.name.startsWith(".")||!s.name.endsWith(".json"))){if(!s.isFile())throw new Error(`${l}/${s.name} is not a regular file`);n.set(s.name,await L(T(r,s.name),"utf8"))}if(n.size===0)return;let o=n.get(u);if(o===void 0)throw new Error(`${l}/${u} is missing: it names the source language, and without it the language files are not a table`);let i=v(o,`${l}/${u}`);if(!f(i)||i.version!==2)throw new Error(`${l}/${u}: version ${JSON.stringify(f(i)?i.version:i)} is not one this reads (2)`);let e=i.source;if(typeof e!="string"||e===""||!S(e))throw new Error(`${l}/${u}: source ${JSON.stringify(e)} is not a language tag`);let a={},c=[];Object.setPrototypeOf(a,null);for(let s of[...n.keys()].sort()){if(s===u)continue;let g=s.slice(0,-5),d=`${l}/${s}`;if(g===""||!S(g))throw new Error(`${d}: ${JSON.stringify(g)} is not a language tag`);if(g===e)throw new Error(`${d}: ${g} is the source language \u2014 its text is the key itself, and it has no file`);let w=v(n.get(s),d);if(!f(w))throw new Error(`${d}: not a JSON object`);for(let[y,p]of Object.entries(w)){if(!f(p)||typeof p.value!="string"||typeof p.state!="string")throw new Error(`${d}: key ${JSON.stringify(y)} is not {"value": string, "state": string}`);(a[y]??={})[g]={value:p.value,state:p.state}}c.push(g)}return{version:1,source:e,locales:[e,...c],strings:a}}export{k as TestApiError,E as api,$ as createTestApi,F as fakeDatabase,D as isolated,I as loadStringsTable,R as testRun,x as withServices};
@@ -0,0 +1,20 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as sn,c as se,d as an,e as Ee,g as S}from"./LYEFPLJZ.js";import{b as Ye,d as ht,e as tn,f as nn,g as Ge,h as Ze,k as rn,q as on}from"./3XT4L2XV.js";import{b as $e}from"./HKJU2FKE.js";import"reflect-metadata";var gt=[{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}],dn="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)",Xe=/^\d+$/;function $r(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 f=o.slice(s+1);if(!Xe.test(f)||Number(f)<1||Number(f)>r)return;i=Number(f)}let c=t,u=r;if(a!=="*")if(a.includes("-")){let f=a.indexOf("-"),y=a.slice(0,f),E=a.slice(f+1);if(!Xe.test(y)||!Xe.test(E)||Number(y)<t||Number(E)>r||Number(y)>Number(E))return;c=Number(y),u=Number(E)}else{if(!Xe.test(a)||Number(a)<t||Number(a)>r)return;c=Number(a),u=s===-1?c:r}for(let f=c;f<=u;f+=i)n.add(f)}return n}function cn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${dn}; "${e}" is not`;let r=[];for(let u=0;u<5;u++){let f=$r(t[u],gt[u].lo,gt[u].hi);if(!f)return`${dn}; its ${gt[u].name} "${t[u]}" is not one`;r.push(f)}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 u=0;u<366*8+2;u++,c.setUTCDate(c.getUTCDate()+1)){if(!o.has(c.getUTCMonth()+1))continue;let f=n.has(c.getUTCDate()),y=s.has(c.getUTCDay());if(a||i?f&&y:f||y)return}return`"${e}" is never due: no date has that day in that month`}var Re=Symbol.for("palbase.backend.controller"),Se=Symbol.for("palbase.backend.routes"),wt=Symbol.for("palbase.backend.params"),bt=Symbol.for("palbase.backend.injectable"),vt=Symbol.for("palbase.backend.module"),he=Symbol.for("palbase.backend.events"),Oe=Symbol.for("palbase.backend.webhook"),ue=Symbol.for("palbase.backend.jobs");function X(e,t,r){let n=e;return Object.prototype.hasOwnProperty.call(n,t)||Object.defineProperty(n,t,{value:r(),enumerable:!1}),n[t]}var yt=Symbol.for("palbase.backend.declared");function oe(){let e=globalThis;return e[yt]instanceof Set||(e[yt]=new Set),e[yt]}var _e=new Set(["webhooks","_palbase"]);function Ls(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&&_e.has(n))throw new TypeError(`@Controller("${e}") on ${r.name}: /${n} is the platform's; a controller is served elsewhere`);X(r,Re,()=>({basePath:e,options:t})),oe().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`);X(n.constructor,Se,()=>[]).push({method:e,subpath:t,fn:o,options:r})}}}var qs=xe("GET"),Hs=xe("POST"),Js=xe("PUT"),Bs=xe("PATCH"),zs=xe("DELETE"),Fs=xe("QUERY");function te(e,t={}){return(r,n,o)=>{if(typeof n!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let s=X(r.constructor,wt,()=>new Map);s.has(n)||s.set(n,[]),s.get(n).push({index:o,kind:e,...t})}}function kt(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 Ks=e=>te("body",{schema:kt("Body",e)}),Ws=e=>te("query",{schema:kt("QueryParams",e)}),Vs=e=>te("headers",e===void 0?{}:{schema:kt("Headers",e)}),Ys=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return te("param",{name:e})},Gs=()=>te("user"),Zs=()=>te("optionalUser"),Xs=()=>te("req"),Qs=()=>te("requestId"),ea=()=>te("requestId"),ta=()=>te("client");function na(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 te("resolve",{resolver:e,options:t[0]})}function ra(){return e=>{X(e,bt,()=>!0),oe().add(e)}}function oa(e){return t=>{X(t,vt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var ln=/^[a-z]+(\.[a-z_]+)+$/,Er=/^[a-z][a-z0-9-]{1,62}$/,$t=e=>e.startsWith("file.");function sa(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"||!Er.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(!$t(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`);X(n.constructor,he,()=>[]).push(r===void 0?{event:e,fn:o}:{event:e,fn:o,bucket:r}),oe().add(n.constructor)}}var Rr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function aa(e){let t=e??{},r=`@Job(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Rr.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=cn(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}),oe().add(s)}}var un=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Sr=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function ia(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(!Sr.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&&!un.includes(n.provider))throw new TypeError(`${r}: provider "${String(n.provider)}" is not one of ${un.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(n.signature!==void 0&&Or(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=T(t,he)??[];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)}X(t,Oe,()=>({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}))})),oe().add(t)}}function Or(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 T(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function da(){return[...oe()].filter(e=>T(e,Re)!==void 0)}function ca(e){return(T(e,Se)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Et="/_palbase/storage/upload/authorize",fn="/_palbase/storage/upload/complete",Rt="/_palbase/realtime/rooms";var _r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Te(e){if(!_r(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 mn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function pn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Qe(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var xr=/^[a-z][a-z0-9-]{1,62}$/,hn=1024,Tr=new Set(["userId","uploadId","filename"]);function pa(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(!xr.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=Ar(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`);X(a.constructor,Se,()=>[]).push({method:"POST",subpath:e,fn:i,options:s,upload:o})}}function ha(){return te("uploadedObject")}function Ar(e){for(let r of e.matchAll(/\{([^{}]*)\}/g))if(!Tr.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(!gn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function gn(e){if(e===""||new TextEncoder().encode(e).byteLength>hn)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 Pr(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(r,n)=>jr(n==="userId"?t.userId??"anonymous":n==="uploadId"?t.uploadId:t.filename??"file"))}function jr(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 yn(e,t){let r=Pr(e,t);return gn(r)?{path:r}:{problem:`the file's name makes its path longer than storage keeps (${hn} bytes)`}}function wn(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 St=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bn(e,t){if(!St(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=Te(t.user);if(!a)return"user is { id?, session?, role }";let i=mn(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=Cr(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 Cr(e){if(!St(e))return;let{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,width:i,height:c,thumbhash:u,variants:f}=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"||u!==void 0&&typeof u!="string")&&!(!St(f)||!Object.values(f).every(y=>typeof y=="string")))return{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...u!==void 0?{thumbhash:u}:{},variants:{...f}}}import{markData as Mr}from"palgres";var ge=Symbol.for("palbase.backend.room"),Pe=Symbol.for("palbase.backend.roomHooks"),Dr=6e4,Ae=255,Ur=["roles:","flags:","messaging:","debug:"],xt=e=>new TextEncoder().encode(e).byteLength,vn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function Nr(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(xt(e)>Ae)return`a channel is ${Ae} 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=Ur.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 kn(e){if(typeof e!="string"||e==="")return"is a name";if(xt(e)>Ae)return`is ${Ae} bytes at most`}function ka(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let r=Nr(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=kn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!vn(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??Dr;return a=>{let i=X(a,Pe,Tt);X(a,ge,()=>({pattern:e,events:o,graceMs:s,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),oe().add(a)}}var Tt=()=>({hooks:Object.create(null),messages:Object.create(null)});function Ue(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=X(r.constructor,Pe,Tt),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,oe().add(r.constructor)}}var $a=Ue("authorize"),Ea=Ue("first"),Ra=Ue("join"),Sa=Ue("leave"),Oa=Ue("empty");function _a(e,t){let r=kn(e);if(r)throw new TypeError(`@OnMessage(name, schema): name ${r}`);if(!vn(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=X(n.constructor,Pe,Tt),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},oe().add(n.constructor)}}function Ir(e){return T(e,ge)}function Lr(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 qr=1e4,Hr=1e3,Jr=100,At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ae=(e,t,r,n)=>({status:e,code:t,message:r,...n!==void 0?{retryAfter:n}:{}}),Br=new Set(["first","join","leave","empty"]);function $n(e,t){let r=new Map,n=new Map;for(let{cls:b,instance:$}of e){let w=Ir(b),R=w.pattern.split(":").map(C=>C.startsWith("{")?"{}":C).join(":"),P=n.get(R);if(P!==void 0)throw new TypeError(`@Room("${w.pattern}") on ${b.name}: ${r.get(P)?.cls.name}'s "${P}" is the same channels \u2014 one room is told of them; keep one`);n.set(R,w.pattern);for(let[C,I]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([L,U])=>[`message ${L}`,U.fn])])if(typeof $[I]!="function")throw new TypeError(`@Room("${w.pattern}") on ${b.name}: its ${C} is ${I}, which is no method of it`);r.set(w.pattern,{cls:b,instance:$,room:w})}let o=new Map,s=new Set,a=new Set,i=new _t(t.broadcast),c=b=>{let $=o.get(b);return $||($=new AbortController,o.set(b,$)),$},u=(b,$)=>{$?.abort(),o.get(b)===$&&o.delete(b)};function f(b,$,w,R,P,C,I){let L=R?.signal??AbortSignal.abort(),U=`${b.cls.name} (${$})`;return{room:$,params:Object.freeze({...w}),signal:L,count:P,user:C,emit:(M,q)=>i.send({topic:$,event:M,payload:q??{},...I!==void 0?{conn_id:I}:{}},U),owner:{hold(M){se.exit(async()=>{try{await M(L)}catch(q){L.aborted||S.error(`[palbase] ${U}: a task owner.hold ran failed`,{error:q})}}).catch(()=>{})},release:()=>u($,R)}}}function y(b){let{room:$,channel:w}=b;if(typeof $!="string"||typeof w!="string")return ae(400,"bad_request","A room's call names its room (the pattern) and its channel");let R=r.get($);return R?{entry:R,channel:w,params:Lr($,w)}:ae(404,"not_found",`This app declares no room "${$}"`)}let E=(b,$)=>ae(400,"bad_request",`"${$}" is not a channel of the room "${b}"`);async function N(b,$){let w=y(b);if("status"in w)return w;let{entry:R,channel:P,params:C}=w,I={status:200,body:{subscribe:!1,publish:!1}};if(!C)return S.warn(`[palbase] ${R.cls.name}: realtime asked about "${P}", which is not a channel of the room "${R.room.pattern}"; the join is refused`),I;let L=Te(b.user),U=L?.id;if(!U)return I;let M=R.room.hooks.authorize;if(!M)return I;let q,re;try{q=await t.run(L,`${R.cls.name}.${M}`,$,async()=>R.instance[M]({user:{id:U},params:Object.freeze({...C})})),re=zr(q)}catch(Q){if(t.isOutage(Q)||$?.aborted)throw Q;return S.error(`[palbase] ${R.cls.name}.${M} (@OnAuthorize of ${P}) failed; the join is refused`,{error:Q}),I}return re==="malformed"?(S.warn(`[palbase] ${R.cls.name}.${M} (@OnAuthorize of ${P}) answered ${Fr(q)}, which is no grant (true, { read, write } or null); the join is refused`),I):{status:200,body:re}}async function g(b,$){let w=y(b);if("status"in w)return w;if(!w.params)return E(w.entry.room.pattern,w.channel);let R=Te(b.user);if(!R?.id||typeof b.event!="string")return ae(400,"bad_request","A message names its member (user) and its event");let P=Object.hasOwn(w.entry.room.messages,b.event)?w.entry.room.messages[b.event]:void 0;if(!P)return{status:200,body:{ok:!1,reason:En(`room "${w.channel}" declares no message "${b.event}"`,Ot)}};let C=await P.schema["~standard"].validate(Mr(b.payload??{}));if(C.issues)return{status:200,body:{ok:!1,reason:Wr(C.issues)}};let I=c(w.channel),L={...f(w.entry,w.channel,w.params,I,0,{id:R.id}),payload:C.value};try{await t.run(R,`${w.entry.cls.name}.${P.fn}`,$,async()=>w.entry.instance[P.fn](L))}catch(U){if(t.isOutage(U))throw U;return $?.aborted||S.error(`[palbase] ${w.entry.cls.name}.${P.fn} (@OnMessage "${b.event}" of ${w.channel}) failed`,{error:U}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function A(b,$){let w=y(b);if("status"in w)return w;if(!w.params)return E(w.entry.room.pattern,w.channel);let R=b.event;if(typeof R!="string"||!Br.has(R))return ae(400,"bad_request","A room's moment is first, join, leave or empty");let P=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(P===void 0)return ae(400,"bad_request","A room's moment says its count of members");let C=R==="join"||R==="leave",I=C?Te(b.user):void 0,L=C?b.connId:void 0;if(C&&(!I?.id||typeof L!="string"||L===""))return ae(400,"bad_request",`A ${R} names its member: user and connId`);let U=`${R}\0${w.channel}\0${typeof L=="string"?L:""}`;if(C&&s.has(U))return{status:204};if(a.has(U))return ae(503,"in_progress","This moment of the room is being handled",5);a.add(U);try{let M=w.entry.room.hooks[R],q;if(R==="empty"?(q=o.get(w.channel),u(w.channel,q)):q=R==="leave"?o.get(w.channel):c(w.channel),M){let re=f(w.entry,w.channel,w.params,q,P,{id:I?.id??""},R==="join"?L:void 0);try{await t.run(I,`${w.entry.cls.name}.${M}`,$,async()=>w.entry.instance[M](re))}catch(Q){if(t.isOutage(Q))throw Q;return $?.aborted||S.error(`[palbase] ${w.entry.cls.name}.${M} (${R} of ${w.channel}) failed; realtime tells it again`,{error:Q}),ae(500,"handler_failed",`The room's ${R} could not be handled`)}}return C&&(s.add(U),s.size>qr&&s.delete(s.values().next().value)),{status:204}}finally{a.delete(U)}}return{declarations:[...r.values()].map(b=>b.room),async serve(b,$,w){return At($)?b==="authorize"?N($,w):b==="message"?g($,w):b==="lifecycle"?A($,w):ae(404,"not_found",`No room call ${JSON.stringify(b)}`):ae(400,"bad_request","A room's call is a JSON object")},close(){for(let b of o.values())b.abort();o.clear()}}}function zr(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!At(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 Fr(e){return Array.isArray(e)?"an array":At(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 Kr=20,Ot=256;function Wr(e){let t="";for(let r of e.slice(0,Kr)){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)>=Ot)break}return En(t,Ot)}function En(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 _t=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,r){if(typeof t.event!="string"||t.event===""||xt(t.event)>Ae){S.warn(`[palbase] ${r}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Ae} bytes`);return}try{JSON.stringify(t.payload)}catch(s){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>=Hr?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),se.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,Jr);try{await this.broadcast(o)}catch(a){S.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),S.warn(`[palbase] ${n}: ${s} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Pt,createHmac as Vr,createPublicKey as _n,timingSafeEqual as Yr,verify as xn}from"node:crypto";function Pa(e){let t=T(e,Oe);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 Tn(e,t,r,n={}){let o=new Map,s=[];for(let a of e){let i=T(a,Oe),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 u=`@Webhook "${i.name}" (${a.name})`,f=r[i.secret.env],y;if(n.secrets!==!1)if(f===void 0||f==="")s.push(`${u} reads its signing secret from ${i.secret.env}, which is not set`);else try{y=Gr(i,f)}catch(g){s.push(`${u}: ${i.secret.env} ${g.message}`)}let E=t(a),N=new Map(i.events.map(({event:g,fn:A})=>[g,{name:`${a.name}.${A}`,call:(b,$)=>E[A](b,$)}]));o.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:y,events:N})}if(s.length>0)throw new Error(`[palbase] the app cannot start:
3
+ - ${s.join(`
4
+ - `)}`);return o}function An(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var je=1024,Rn=1024*je;function Gr(e,t){if(e.signature)return ye(void 0,e.signature.header,1/0,io(e.signature,t));switch(e.provider){case"stripe":return ye("stripe","stripe-signature",512*je,Qr(t));case"github":return ye("github","x-hub-signature-256",25*Rn,eo(t));case"slack":return ye("slack","x-slack-signature",64*je,to(t));case"discord":return ye("discord","x-signature-ed25519",64*je,no(t));case"twilio":return{header:"x-twilio-signature",maxBytes:r=>Math.min(r,64*je),check:oo(t)};case"sendgrid":return ye("sendgrid","x-twilio-email-event-webhook-signature",Rn,so(t));case"livekit":return ye("livekit","authorization",512*je,ao(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function ye(e,t,r,n){return{header:t,maxBytes:o=>Math.min(o,r),check:(o,s)=>n(o,s)??Pn(e,o)}}function Pn(e,t){let r=jt(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:jn(e,t.headers,n),event:n,...Zr(e,t,n)}}function jn(e,t,r){switch(e){case"github":{let n=t.get("x-github-event")??"",o=we(r,"action");return n!==""&&o!==""?`${n}.${o}`:n}case"discord":{let n=Dn(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 we(r,"EventType");case"livekit":return we(r,"event");default:return we(r,"type")}}function Zr(e,t,r){let n=o=>o?{id:o}:{};switch(e){case"stripe":case"discord":case"livekit":return n(we(r,"id"));case"slack":return n(we(r,"event_id"));case"github":{let o=t.headers.get("x-github-delivery");return o?{id:`${o}:${Cn(t.body)}`}:{}}case"sendgrid":return Array.isArray(r)?{ids:r.map(o=>we(o,"sg_event_id")||void 0)}:{};default:return{}}}var Xr=300;function Qr(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 u=c.indexOf("=");if(u<=0)continue;let f=c.slice(0,u).trim(),y=c.slice(u+1).trim();if(f==="t"){if(o!==void 0)return"malformed_signature";o=y}else if(f==="v1"){let E=ne(y,"hex");if(!E)return"malformed_signature";s.push(E)}}let a=Ne(o);if(a===void 0||s.length===0)return"malformed_signature";if(Ie(a,r))return"stale_timestamp";let i=Ce("sha256",e,`${o}.`,t.body);return s.some(c=>le(c,i))?void 0:"signature_mismatch"}}function eo(e){return t=>{let r=t.headers.get("x-hub-signature-256");if(!r)return"missing_signature";let n=r.startsWith("sha256=")?ne(r.slice(7),"hex"):void 0;return n?le(n,Ce("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function to(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=Ne(o),a=n.startsWith("v0=")?ne(n.slice(3),"hex"):void 0;return s===void 0||!a?"malformed_signature":Ie(s,r)?"stale_timestamp":le(a,Ce("sha256",e,`v0:${o}:`,t.body))?void 0:"signature_mismatch"}}function no(e){let t=ne(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=_n({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=Ne(a),c=ne(s,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Ie(i,o)?"stale_timestamp":xn(null,Mn(a,n.body),r,c)?void 0:"signature_mismatch"}}var ro=1e3;function oo(e){return t=>{let r=t.headers.get("x-twilio-signature");if(!r)return"missing_signature";let n=ne(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(Pt("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let N=1;for(let b of t.body)if(b===38&&++N>ro)return"malformed_signature";let g=new Map;for(let[b,$]of new URLSearchParams(jt(t.body))){let w=g.get(b);w||g.set(b,w=new Set),w.add($)}let A=[];for(let b of[...g.keys()].sort()){let $=[...g.get(b)].sort();for(let w of $)a+=b+w;A.push([b,$.length===1?$[0]:$])}i=Object.fromEntries(A)}let c=o.protocol==="https:"?"443":"80",u=`${o.protocol}//${o.hostname}${o.pathname}${o.search}`,f=`${o.protocol}//${o.hostname}:${o.port||c}${o.pathname}${o.search}`;if(![u,f].some(N=>le(n,Ce("sha1",e,N,a))))return"signature_mismatch";let y=t.headers.get("i-twilio-idempotency-token"),E=y?{id:`${y}:${Cn(`${u}
5
+ ${a}`)}`}:{};return i?{type:jn("twilio",t.headers,i),event:i,...E}:{...Pn("twilio",t),...E}}}function so(e){let t;try{let r=ne(e,"base64");if(!r)throw new Error;t=_n({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=Ne(s),i=ne(o.trim(),"base64");return a===void 0||!i?"malformed_signature":Ie(a,n)?"stale_timestamp":xn("sha256",Mn(s,r.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var Sn=60;function ao(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=On(ne(o[0],"base64url")),a=ne(o[2],"base64url");if(s?.alg!=="HS256"||!a)return"malformed_signature";if(!le(a,Ce("sha256",e,`${o[0]}.${o[1]}`)))return"signature_mismatch";let i=On(ne(o[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(r>i.exp+Sn||typeof i.nbf=="number"&&r<i.nbf-Sn)return"stale_timestamp";let c=typeof i.sha256=="string"?ne(i.sha256,"base64"):void 0;return c&&le(c,Pt("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function io(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 u=Ne(i);if(u===void 0)return"malformed_signature";if(Ie(u,s))return"stale_timestamp"}let c=ne(a.trim(),e.encoding);return c?le(c,Ce(n,t,...r.map(u=>u==="{body}"?o.body:u==="{ts}"?i:u)))?void 0:"signature_mismatch":"malformed_signature"}}var co=new TextEncoder;function Ce(e,t,...r){let n=Vr(e,t);for(let o of r)n.update(o);return n.digest()}function Cn(e){return Pt("sha256").update(e).digest("hex")}function Mn(e,t){return Buffer.concat([co.encode(e),t])}function le(e,t){return e.byteLength===t.byteLength&&Yr(e,t)}var uo={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 ne(e,t){return uo[t].test(e)?Buffer.from(e,t):void 0}function Ne(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Ie(e,t){return Math.abs(t-e)>Xr}function jt(e){return new TextDecoder().decode(e)}function On(e){if(e)try{return JSON.parse(jt(e))}catch{return}}function Dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function we(e,t){let r=Dn(e)?e[t]:void 0;return typeof r=="string"?r:""}import"reflect-metadata";var J=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}},lo=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],fo=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),et=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=T(n,vt);if(!s)throw new J("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 J("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 J("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(!T(s,Re))throw new J("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(T(s,ue))throw new J("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(T(s,ge)||T(s,Pe))throw new J("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 oe())if(!this.owner.has(t))throw new J("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 J("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(T(n,Pe)&&!T(n,ge))throw new J("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(!T(n,bt)&&!T(n,he)&&!T(n,ge)&&!T(n,ue)){let o=Reflect.getMetadata("design:paramtypes",n);throw n.length>0&&!o?new J("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 J("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()"])}T(n,ge)&&this.rooms.push(n),T(n,Oe)?this.webhooks.push(n):T(n,he)&&this.eventProviders.push(n),T(n,ue)&&this.jobProviders.push(n)}}for(let t of this.owner.keys())for(let r of lo)if(typeof t.prototype[r]=="function")throw new J("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 J("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 J("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((u,f)=>{if(fo.has(u)||typeof u!="function")throw new J("unresolvable dependency",o,`${t.name} constructor parameter ${f}`,`parameter ${f} of ${t.name} is typed as ${u===void 0?"something with no runtime class":u.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,u,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 J("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 J("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 J("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 J("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 mo,HttpError as Le}from"palgres";import{z as fe}from"zod";import{BadRequest as Ja,Conflict as Ba,DeadlockDetected as za,HttpError as Fa,NotFound as Ka,SerializationFailure as Wa,TooManyRequests as Va,UniqueViolation as Ya}from"palgres";function tt(e){if(typeof e!="object"||e===null||e[mo]!==!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 Un=class extends Le{constructor(t,r,n,o){super(t,r,n,o),this.name=new.target.name}},Nn=class extends Le{constructor(t="Unauthorized",r="unauthorized",n){super(401,r,t,n),this.name="Unauthorized"}},In=class extends Le{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 po=Symbol.for("palbase.backend.errorRegistry"),ho={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()})},go=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 yo(){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=ho[t];e.set(t,{code:t,status:r,className:n,builtin:!0,...o?{data:o}:{}})}return e}function wo(){let e=globalThis;return e[po]??=yo()}function La(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(go.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=wo(),o=n.get(e);if(o&&(o.builtin||o.status!==t||o.data===void 0!=(r===void 0)||r!==void 0&&o.data!==r&&Ln(o.data)!==Ln(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(y=>y.charAt(0).toUpperCase()+y.slice(1)).join(""),a=e.replace(/_/g," "),i=a.charAt(0).toUpperCase()+a.slice(1),f=r?(y=>class extends Le{static code=e;static status=t;constructor(E,N){let g=bo(e,y,E);super(t,e,N??(typeof g=="string"?g:i),g),this.name=s}})(r):class extends Le{static code=e;static status=t;constructor(y){super(t,e,y??i),this.name=s}};return Object.defineProperty(f,"name",{value:s}),n.set(e,{code:e,status:t,className:s,builtin:!1,...r?{data:r}:{}}),f}function bo(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 Ln(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{connectionFailure as fr,isEngineRaised as mr,markData as ie}from"palgres";import{createHash as cs}from"node:crypto";import{createHash as vo,randomInt as ko}from"node:crypto";import{ago as Ct,isRetryable as $o,now as Hn}from"palgres";import{defineSchema as Eo,defineTable as Ro,index as So,integer as Oo,jsonb as _o,raw as xo,text as Mt,timestamp as Jn}from"palgres/dsl";var Vn=new Set(["POST","PUT","PATCH","DELETE"]),Bn=255,zn=35,Fn=24,To=65536,Kn=1e3,Ao=64,Ut={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"}},Po=Ro("idempotency_keys",{columns:{key:Mt().primaryKey(),fingerprint:Mt(),started_at:Jn().defaultNow(),completed_at:Jn().nullable(),status_code:Oo().nullable(),response_headers:_o().nullable(),response_body:Mt().nullable()},indexes:e=>[So("idempotency_keys_started").on(e.col("started_at"))]}),ni=Eo("palbase",{tables:[Po],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)"})]}),jo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Co={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},Mo={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},Do={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},rt=class extends Error{};function qe(e){return Vn.has(e.method)&&e.meta.upload===void 0}function Yn(e,t){if(!Vn.has(e))return;let r=t.get("idempotency-key");return r===null||r===""?void 0:r}function Uo(e,t){return Gn([e.role,e.uid,t]).digest("hex")}function No(e){return Gn([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Gn(e){let t=vo("sha256");for(let r of e)t.update(r).update("\0");return t}function Io(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function Dt(e){return e<500&&e!==429&&e!==499}function Lo(e,t){return t&&Dt(e)}function Zn(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 qo={role:"service",claims:{}},ot=class{constructor(t){this.db=t}db;async serve(t,r,n){if(t.key.length>Bn)return n.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Bn} characters`});let o;try{o=await this.begin(Uo(t.caller,t.key),No(t))}catch(i){return S.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),n.refusal(Do)}if("kept"in o)return Ho(o.kept,n.requestId);if("refused"in o)return n.refusal(o.refused==="reused"?jo:Co);let s=o.claim,a;try{a=await r(i=>this.record(s,i))}catch(i){if(i instanceof rt)return n.refusal(Mo);let c=n.failure(i);return Lo(c.status,n.ran())&&!$o(i)?this.keep(s,c):(await this.release(s),c)}return Dt(a.status)||await this.release(s),a}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:Ct({hours:Fn})}}}))}async begin(t,r){return ko(Ao)===0&&await this.sweep().catch(n=>S.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:Ct({hours:Fn})}}})>0)continue;let a=await n.findUnique({where:{key:t}});if(a===null)continue;let i=Io(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:Ct({seconds:zn})}},set:{started_at:Hn()}});return c?{claim:{key:t,started:c.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,r){if(!Dt(r.status))return r;let{response:n,kept:o}=await Wn(r),s=se.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 rt;return n}async keep(t,r){let{response:n,kept:o}=await Wn(r);try{await this.asService(s=>s.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Hn(),status_code:o.status,response_headers:o.headers,response_body:o.body}}))}catch(s){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()+zn*1e3,n=()=>{Date.now()+Kn>=r||setTimeout(()=>{this.releaseOnce(t).then(o=>o||n())},Kn).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(qo),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 Ho(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 nt=Symbol("waits");function Jo(e){return new Promise((t,r)=>{let n=setImmediate(()=>t(nt));e.then(o=>{clearImmediate(n),t(o)},o=>{clearImmediate(n),r(o)})})}async function Wn(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 Jo(i);if(c!==nt&&c.done)break;if(c!==nt&&(o.push(c.value),s+=c.value.byteLength,s<=To))continue;let u=c===nt?i:void 0,f=new ReadableStream({start(y){for(let E of o)y.enqueue(E)},async pull(y){let E=await(u??n.read());u=void 0,E.done?y.close():y.enqueue(E.value)},cancel:y=>n.cancel(y)});return{response:r(f),kept:{status:e.status,headers:t.filter(([y])=>y!=="content-length"&&y!=="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 Bo}from"node:crypto";var Nt="/webhooks/palbase",rr="PalbaseErrorEnvelope",Xn="PalbaseBearer",zo={$ref:`#/components/schemas/${rr}`},Fo={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"]},Qn={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Me={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function or(e,t,r){let n={[rr]:Fo},o={},s=[],a=[],i=new Set,c=new Map;for(let g of e){let A=a.find(H=>Vo(H,g));if(A){s.push({route:g.id,handler:er(g),answeredBy:A.id});continue}a.push(g);let b=g.segments.map(H=>typeof H=="string"?H:"{}").join("/");c.has(b)||c.set(b,Go(g.segments.flatMap(H=>typeof H=="string"?[]:[H.param])));let $=c.get(b),w=0,R=`/${g.segments.map(H=>typeof H=="string"?H:`{${$[w++]}}`).join("/")}`,P=t(g),C=st(Yo(g),i),I=g.method!=="GET"&&g.method!=="HEAD",L=H=>{let be=g.params.filter(pe=>pe.kind===H&&pe.schema).map((pe,We)=>dt(pe.schema,`${C}.${H}${We===0?"":`.${We+1}`}`,n));return be.length===0?void 0:be.length===1?be[0]:{allOf:be}},U=$.map(H=>({name:H,in:"path",required:!0,schema:{type:"string"}})),M=L("query");M&&U.push(...nr(M,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:M}]);let q=L("headers");q&&U.push(...nr(q,"header")??[]);let re=r.idempotency===!0&&qe(g);re&&U.push({...Ut,schema:{...Ut.schema}});let Q=I?L("body"):void 0,G={operationId:C};g.controller.name!==""&&(G.tags=[g.controller.name]),U.length>0&&(G.parameters=U),Q&&(G.requestBody={required:!ts(Q),content:{"application/json":{schema:Q}}});let mt=g.params.some(H=>H.schema!==void 0),Fe=r.routes?.(g),me=rs(C,Fe?.throws??[],r.errors);G.responses={...ns(Fe,C,n),...as(P,{validates:mt,hasPathParams:$.length>0,readsBody:I,keyed:re}),...ss(me,C,n)},me.length>0&&(G["x-palbase-errors"]=os(C,me)),P.auth.required&&(G.security=[{[Xn]:[]}]),G["x-palbase-handler"]=er(g);let Ke=g.params.some(H=>H.kind==="optionalUser")||r.databaseSeesCaller;G["x-palbase-auth"]=P.auth.required?"required":Ke?"optional":"public",G["x-palbase-verified-email"]=P.auth.verifiedEmail,G["x-palbase-rate-limit"]=P.limit===!1?!1:{max:P.limit.max,window:P.limit.window},g.meta.upload&&(G["x-palbase-upload"]={bucket:g.meta.upload.bucket,pathTemplate:g.meta.upload.pathTemplate}),(o[R]??={})[g.method.toLowerCase()]=G}for(let g of r.webhooks??[]){let A={operationId:st(`webhooks.${g.name}`,i)};g.cls!==""&&(A.tags=[g.cls]),A.description=g.provider?`${Qn[g.provider]??g.provider}'s deliveries: verified with ${Qn[g.provider]??g.provider}'s signature scheme under the secret in ${g.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${g.signatureHeader} header: verified under the secret in ${g.secretEnv}, then handed to the @On of their event type.`,A.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":{},[g.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",Me),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",Me)},A["x-palbase-webhook"]=g.provider?{provider:g.provider,secretEnv:g.secretEnv,events:g.events}:{signatureHeader:g.signatureHeader,secretEnv:g.secretEnv,events:g.events},o[`/webhooks/${g.name}`]={post:A}}let u=[...new Set(r.platformEvents??[])].sort();if(u.length>0){let g={operationId:st("webhooks.palbase",i)};g.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.",g.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",Me),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 A=[...new Set(r.platformEventBuckets??[])].sort();g["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:u,...A.length>0?{buckets:A}:{}},o[Nt]={post:g}}let f=Ko(r.rooms??[],n),y=Object.keys(f).length>0,E={schemas:n,securitySchemes:{[Xn]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},N={openapi:"3.2.0",info:{title:"Palbase backend",version:Bo("sha256").update(JSON.stringify({paths:o,components:E,unreachable:s,...y?{rooms:f}:{}})).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:E};return s.length>0&&(N["x-palbase-unreachable"]=s),y&&(N["x-palbase-room"]=f),N}function Ko(e,t){let r=[];for(let n of e){let o=n.pattern.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_|_$/g,""),s=(c,u,f,y)=>{let E=it(`Room_${o}_${u}`),N={},g=dt(f,E,N,y);g.$ref===void 0&&(N[E]=g),Wo(n.pattern,c,u,N[E]);for(let[A,b]of Object.entries(N)){if(Object.hasOwn(t,A)&&JSON.stringify(t[A])!==JSON.stringify(b))throw new Error(`@Room("${n.pattern}") ${c} "${u}": its schema is the component ${A}, which another room's event or message names with another schema \u2014 rename one of them`);t[A]=b}return{$ref:`#/components/schemas/${E}`}},a=Object.fromEntries(Object.entries(n.events).map(([c,u])=>[c,s("event",c,u,"answered")])),i=Object.fromEntries(Object.entries(n.messages).map(([c,u])=>[c,s("message",c,u.schema,"sent")]));r.push([n.pattern,{events:a,messages:i,graceMs:n.graceMs}])}return Object.fromEntries(r)}function Wo(e,t,r,n){if(!(!Y(n)||!Y(n.properties))){for(let[o,s]of Object.entries(n.properties))if(s===!0||Y(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 Vo(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 er(e){return`${e.controller.name}.${e.fn}`}function Yo(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 st(e,t){let r=e;for(let n=2;t.has(r);n++)r=`${e}_${n}`;return t.add(r),r}function Go(e){let t=new Set;return e.map(r=>st(r,t))}function dt(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:Zo}:{}}})}catch{return{}}let i=it(t);for(;Object.keys(r).some(c=>c===i||c.startsWith(`${i}.`));)i=`${i}_`;return Xo(a,i,r,n)}function Zo(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function Xo(e,t,r,n){let o=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},s=!1,a=u=>u==="#"?(s=!0,`#/components/schemas/${t}`):u.startsWith("#/$defs/")?`#/components/schemas/${t}.${it(es(u.slice(8)))}`:u,i="all";if(n==="sent"){let u=new Set;for(let f of[e,...Object.values(o)])at(f,u);i=u}for(let[u,f]of Object.entries(o))r[`${t}.${it(u)}`]=Je(He(f,a,i));let c=Je(He(e,a,i));return s?(r[t]=c,{$ref:`#/components/schemas/${t}`}):c}var Qo=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"]),It=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),Lt=new Set(["anyOf","oneOf","allOf","prefixItems"]),qt=new Set(["properties","patternProperties","dependentSchemas"]),Y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function He(e,t,r){if(!Y(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):Qo.has(o)?n[o]=s:It.has(o)?n[o]=He(s,t,r):Lt.has(o)&&Array.isArray(s)?n[o]=s.map(a=>He(a,t,r)):qt.has(o)&&Y(s)&&(n[o]=Object.fromEntries(Object.entries(s).map(([a,i])=>[a,He(i,t,r)])));return n}var tr=Number.MAX_SAFE_INTEGER;function Je(e){if(!Y(e))return e;let t={};for(let[n,o]of Object.entries(e))It.has(n)?t[n]=Je(o):Lt.has(n)&&Array.isArray(o)?t[n]=o.map(Je):qt.has(n)&&Y(o)?t[n]=Object.fromEntries(Object.entries(o).map(([s,a])=>[s,Je(a)])):t[n]=o;if("const"in t){let{const:n,...o}=t;t={...o,enum:[n]}}if(t.type==="integer"&&(t.minimum===-tr&&delete t.minimum,t.maximum===tr&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,Y(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=>Y(s)&&Object.keys(s).length===1&&s.type==="null"),o=r[1-n];if(n!==-1&&Y(o)&&typeof o.type=="string")return{...o,type:[o.type,"null"]}}return t}function at(e,t){if(Y(e)){for(let r of["anyOf","oneOf"]){let n=e[r];if(!Array.isArray(n)||n.length<2||!n.every(Y))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=>Y(s.properties)?s.properties:{});for(let s of Object.keys(o[0]))if(o.every(a=>Y(a[s])&&"const"in a[s]))for(let a of o)t.add(a[s])}for(let[r,n]of Object.entries(e))if(It.has(r))at(n,t);else if(Lt.has(r)&&Array.isArray(n))for(let o of n)at(o,t);else if(qt.has(r)&&Y(n))for(let o of Object.values(n))at(o,t)}}function es(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function it(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function nr(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 ts(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:zo}}}}function ns(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=dt(e.returns.schema,`${t}.response`,r,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:n}:n}}}}}function rs(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 ss(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 u={error:{type:"string",const:c.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},f=["error","error_description","status","request_id"];return c.data&&(u.data=dt(c.data,`${t}.${c.code}.data`,r,"answered"),f.push("data")),{type:"object",properties:u,required:f}});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",Me)),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)",Me)),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":""}`,Me),r}var ct=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 ut(e,t){let n=e.get("x-forwarded-for")?.split(",").map(o=>o.trim()).filter(Boolean).at(-1);return is(n??t??"unknown")}function is(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 sr(e){let t=[];for(let r of e){let n=T(r,Re),o=T(r,Se)??[];if(o.length===0)throw new TypeError(`@Controller ${r.name} has no routes: a controller with nothing to serve is a mistake`);let s=T(r,wt)??new Map;for(let a of o){let i=`${n.basePath}${a.subpath}`||"/",c=i.split("/").filter(Boolean).map(f=>{let y=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(f)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(f);return y?{param:y[1]}:f});if(typeof c[0]=="string"&&_e.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 u=[...s.get(a.fn)??[]].sort((f,y)=>f.index-y.index);for(let f of u)if(f.kind==="param"&&!c.some(y=>typeof y!="string"&&y.param===f.name))throw new TypeError(`${r.name}.${a.fn}: @Param("${f.name}") names no {${f.name}} in ${a.method} ${i}`);t.push({id:`${a.method} ${i}`,method:a.method,segments:c,controller:r,fn:a.fn,params:u,meta:a,controllerAuth:n.options.auth})}}return wn(t),t}function Ht(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 Bt(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Be(e,t,r,n,o){return zt(e,e?Bt(e.requests,t):void 0,r,n,o)}var ar={role:"service",claims:{}};async function zt(e,t,r,n,o){if(!e||!t)return o();let s=u=>S.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 ${u} 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:u}),a=e.app.request(t,{signal:r,heldIdle:s}),i=se.getStore();i&&(i.database=a.database);let c;try{c=await o()}catch(u){throw await a.rollback(u).catch(f=>S.error("[palbase] the request's transaction could not be rolled back",{error:f})),u}try{await a.commit()}catch(u){throw await a.rollback(u).catch(f=>S.error("[palbase] the request's transaction could not be rolled back",{error:f})),u}return c}var us=1024*1024,ls=20,fs={max:300,window:60},De="/_palbase/jobs",ir=50,ms=4096,ps=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,lt=1e4,hs=6e4;function gs(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 V=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 ys(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 ws=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function bs(e,t){let r=new Headers(e.headers);for(let n of ws)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 dr(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 x(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 cr(e,t,r,n){if(n?.aborted)return S.info(`[palbase] ${r}: the client left before its answer`),x({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof V)return x({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(tt(e)){let s=e;return s.status>=500&&S.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=hr(e,r);return o?x(o,t):(e instanceof $e?S.error(`[palbase] ${r}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):S.error(`[palbase] unhandled error in ${r}`,{error:e}),x({status:500,code:"internal_error",message:"The request could not be completed"},t))}function hr(e,t){if(e instanceof Ze)return S.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 $e&&pr.has(e.status))return S.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=fr(e);if(r!==void 0)return S.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 vs(e){return e instanceof Ze||e instanceof $e&&pr.has(e.status)||fr(e)!==void 0||tt(e)&&e.status===503&&mr(e)}async function Jt(e,t,r){let n=await e["~standard"].validate(t);if(n.issues){let o=n.issues.slice(0,ls).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 V(400,"bad_request",`${r} failed validation`,s>0?{fields:o,more:s}:{fields:o})}return n.value}async function ft(e,t){let r=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>t)throw new V(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:u}=await n.read();if(c)break;if(s+=u.byteLength,s>t)throw await n.cancel().catch(()=>{}),new V(413,"payload_too_large",`Request body exceeds ${t} bytes`);o.push(u)}let a=new Uint8Array(s),i=0;for(let c of o)a.set(c,i),i+=c.byteLength;return a}function ks(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ie(t)}function $s(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 Es(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 Rs=/^[A-Za-z0-9._:-]{8,128}$/,Ss=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Os={max:20,window:60},_s=10*6e4,xs=1e4,ze=class extends Error{constructor(r){super("too many unknown tokens from this address");this.wait=r}wait},Ft=class{constructor(t,r){this.limiter=t;this.now=r}limiter;now;known=new Map;async ask(t,r,n){let o=cs("sha256").update(t).digest("hex"),s=(this.known.get(o)??0)>this.now(),a=`token-misses\0a:${r}`,i;if(!s){let u=this.limiter.reserve(a,Os);if("wait"in u)throw new ze(u.wait);i=u}let c=await n();if(!c)throw this.known.delete(o),new Ge("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()+_s),this.known.size>xs&&this.known.delete(this.known.keys().next().value),c}};function _i(e){let t=new et(e.modules),r=sr(t.controllers.map(d=>d.cls)),n=new Map(r.map(d=>[d,gs(d,e.auth)]));for(let[d,m]of n){if(!m.required&&d.params.some(l=>l.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&&m.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 m of d.params)m.kind==="resolve"&&o.set(m,t.dependencyOf(d.controller,m.resolver,`${d.id} @Resolve(${m.resolver?.name})`));let s=new Map;for(let d of t.jobProviders){let m=t.get(d),l=T(d,ue),p=s.get(l.name);if(p)throw new TypeError(`@Job "${l.name}" is ${p.owner} and ${d.name}: a job's name is its own \u2014 name one of them`);s.set(l.name,{declaration:l,owner:d.name,run:h=>m.run(h)})}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>ir)throw new TypeError(`${s.size} @Job classes: a machine runs ${ir} jobs at most`);s.size>0&&!e.platform&&S.info(`[palbase] ${s.size} @Job(s): the platform runs them on a machine; nothing calls them here`);let c=$n(t.rooms.map(d=>({cls:d,instance:t.get(d)})),{run:(d,m,l,p)=>se.run({requestId:se.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>zt(e.database,e.database?d?.id?Bt(e.database.requests,Qe(d)):ar:void 0,l,m,async()=>{let h=await p();if(l?.aborted)throw new Error(`realtime gave up on ${m} before it ended`);return h})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),isOutage:vs});c.declarations.length>0&&!e.platform&&S.info(`[palbase] ${c.declarations.length} @Room(s): realtime tells a machine of them; nothing does here`);let u=new Set,f=e.database!==void 0||e.contractOnly?.database===!0;if(f){for(let d of r)if(qe(d)&&d.params.some(m=>m.kind==="headers"&&m.schema!==void 0&&Zn(m.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 y=e.database?new ot(e.database.app):void 0,E=Ds(e.cors),N=e.now??Date.now,g=new ct(e.now),A=new Ft(g,e.now??Date.now),b=e.maxBodyBytes??us,$=d=>{let m=d.meta.options.rateLimit??e.rateLimit??fs;return m!==!1&&m.max>0&&m.window>0?m:!1},w=e.env??process.env,R=Tn(t.webhooks,d=>t.get(d),w,{secrets:e.contractOnly===void 0}),P=R.size===0&&s.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(w).filter(d=>typeof d[1]=="string"&&!on(d[0])))),C=new Map([...R.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),I=new Map([...R.keys()].map(d=>[d,{counts:new Map,at:void 0}])),L,U=()=>L??=or(r,d=>({auth:n.get(d),limit:$(d)}),{databaseSeesCaller:f,idempotency:f,webhooks:[...R.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...M.keys()],rooms:c.declarations,platformEventBuckets:As(M),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),M=new Map;for(let[d,m]of Object.entries(e.events??{}))M.set(d,m.map(l=>({name:`palbase(${d})`,call:p=>l(p)})));for(let d of t.eventProviders){let m=t.get(d);for(let{event:l,fn:p,bucket:h}of T(d,he)??[]){if(!ln.test(l))throw new TypeError(`@On("${l}") 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`);M.has(l)||M.set(l,[]),M.get(l).push({name:`${d.name}.${p}`,bucket:h,call:async(k,v)=>m[p](k,v)})}}let q=new Set,re=new Set;an(e.server);async function Q(d,m){let l;try{l=await nn(d,e.webhookSecret,{now:e.now})}catch(p){if(p instanceof Ye)return x({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${p.code}`},m);throw p}if(ie(l.data),q.has(l.id))return new Response(null,{status:204,headers:{"x-request-id":m}});if(re.has(l.id))return x({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},m);re.add(l.id);try{let p;try{await Be(e.database,null,void 0,`event ${l.type}`,async()=>{for(let h of M.get(l.type)??[])if(!(h.bucket!==void 0&&Ts(l)!==h.bucket))try{await h.call(l,{requestId:m})}catch(k){throw p=h.name,k}})}catch(h){return S.error(`[palbase] ${p??"the delivery"} failed on ${l.type} ${l.id}; the platform delivers it again`,{error:h}),x({status:500,code:"handler_failed",message:"The event could not be handled"},m)}return q.add(l.id),q.size>lt&&q.delete(q.values().next().value),new Response(null,{status:204,headers:{"x-request-id":m}})}finally{re.delete(l.id)}}async function G(d,m={}){let l=d.headers.get("origin");if(E&&l!==null){let p=E.allows(l);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return p?new Response(null,{status:204,headers:E.preflight(l,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let h=await Gt(d,m);if(p)for(let[k,v]of Object.entries(E.headers(l)))k==="vary"?dr(h.headers,v):h.headers.set(k,v);else dr(h.headers,"Origin");return h}return Gt(d,m)}async function mt(d,m,l,p){if(!d.headers.get(l.scheme.header))return me(l,"missing_signature",p);let h={headers:d.headers,body:await ft(d,l.scheme.maxBytes(b)),url:An(d,m)},k;try{k=l.scheme.check(h,N()/1e3)}catch{return me(l,"signature_mismatch",p,"check_failed")}if(typeof k=="string")return me(l,k,p);let v=l.events.get(k.type);if(!v)return S.info(`[palbase] webhook ${l.name}: no @On takes "${k.type}"; acknowledged`),de(200,{ok:!0,handled:!1},p);let j=C.get(l.name),_=k.event,ee=[];if(k.id!==void 0){if(j.seen.has(k.id))return de(200,{ok:!0,handled:!1,duplicate:!0},p);ee=[k.id]}else if(k.ids&&Array.isArray(_)){let O=k.ids,z=_.map((B,ce)=>[B,O[ce]]).filter(([,B])=>B===void 0||!j.seen.has(B));if(z.length===0)return de(200,{ok:!0,handled:!1,duplicate:!0},p);_=z.map(([B])=>B),ee=z.flatMap(([,B])=>B===void 0?[]:[B])}if(ee.some(O=>j.inflight.has(O)))return x({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},p);ie(_);for(let O of ee)j.inflight.add(O);let W;try{W=await Be(e.database,null,void 0,`webhook ${l.name}`,()=>v.call(_,{env:P,requestId:p,environmentId:e.projectId??""}))}catch(O){let z=hr(O,`webhook ${l.name}`)??Ps(O,l.name);return z?x(z,p):(S.error(`[palbase] ${v.name} failed on ${l.name} "${k.type}"; the sender delivers it again`,{error:O}),x({status:500,code:"handler_failed",message:"The event could not be handled"},p))}finally{for(let O of ee)j.inflight.delete(O)}for(let O of ee)j.seen.add(O),j.seen.size>lt&&j.seen.delete(j.seen.values().next().value);return Fe(W,l,p)}function Fe(d,m,l){if(d instanceof Response)return d;if(typeof d=="string"){let p=m.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":l}})}return de(200,d??{ok:!0,handled:!0},l)}function me(d,m,l,p=m){let h=I.get(d.name);h.counts.set(p,(h.counts.get(p)??0)+1);let k=N();return(h.at===void 0||k-h.at>=hs)&&(Ke(d.name),h.at=k),x({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${m}`},l)}function Ke(d){let m=I.get(d).counts;if(m.size===0)return;let l=[...m.values()].reduce((p,h)=>p+h,0);S.warn(`[palbase] webhook ${d}: ${l} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(m)}),m.clear()}function H(d){let m=d.split("/").filter(Boolean);return m.length===2&&m[0]==="webhooks"?R.get(m[1]):void 0}async function be(d,m,l,p){let h=m.pathname===De;if(d.method!==(h?"GET":"POST"))return x({status:405,code:"method_not_allowed",message:h?"The jobs are listed with GET":"A job is run with POST"},p);let k=h?new Uint8Array(0):await ft(d,ms);try{await ht({secret:l,signature:d.headers.get("palbase-signature"),body:k,now:e.now})}catch(F){if(F instanceof Ye)return x({status:401,code:"invalid_signature",message:`The jobs are the platform's to call: ${F.code}`},p);throw F}if(h){let F=[...s.values()].map(({declaration:Z})=>({name:Z.name,schedule:Z.schedule,timeout:Z.timeout,retry:Z.retries}));return de(200,{jobs:F},p,{"cache-control":"no-store"})}let v=m.pathname.slice(De.length+1),j=s.get(v);if(!j)return x({status:404,code:"job_not_found",message:`This version has no job ${JSON.stringify(v)}`},p);let _;try{_=JSON.parse(new TextDecoder().decode(k))}catch{return x({status:400,code:"bad_request",message:"A run is the JSON {job, run_id, scheduled_at, attempt}"},p)}let{job:ee,run_id:W,scheduled_at:O,attempt:z}=_??{};if(ee!==v||typeof W!="string"||W===""||typeof O!="string"||!ps.test(O)||Number.isNaN(Date.parse(O))||!Number.isInteger(z)||z<1)return x({status:400,code:"bad_request",message:`A run of ${v} is the JSON {job: "${v}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},p);let B=`${W}#${String(z)}`;if(a.has(B))return new Response(null,{status:204,headers:{"x-request-id":p}});if(i.has(B))return x({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},p);i.add(B);let ce={env:P,environmentId:e.projectId??"",job:v,runId:W,scheduledAt:new Date(O),attempt:z};try{await zt(e.database,e.database?ar:void 0,d.signal,`job ${v}`,async()=>{if(await j.run(ce),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${v} before it ended`)})}catch(F){return d.signal.aborted||S.error(`[palbase] job ${v} failed (run ${W}, attempt ${String(z)})`,{error:F}),x({status:500,code:"job_failed",message:`The job ${v} failed; the platform tries it again`},p)}finally{i.delete(B)}return a.add(B),a.size>lt&&a.delete(a.values().next().value),new Response(null,{status:204,headers:{"x-request-id":p}})}async function pe(d,m,l,p){if(d.method!=="POST")return x({status:405,code:"method_not_allowed",message:`${p} is POSTed`},l);let h;try{tn({signature:d.headers.get("palbase-signature"),now:e.now}),h=await ft(d,1048576),await ht({secret:m,signature:d.headers.get("palbase-signature"),body:h,now:e.now})}catch(v){if(v instanceof Ye)return x({status:401,code:"invalid_signature",message:`${p} is the platform's to call: ${v.code}`},l);throw v}let k;try{k=JSON.parse(new TextDecoder().decode(h))}catch{return x({status:400,code:"bad_request",message:`${p} is JSON`},l)}return typeof k!="object"||k===null||!Object.hasOwn(k,"call")||k.call!==new URL(d.url).pathname?x({status:401,code:"invalid_signature",message:`${p} is the platform's to call: signed_for_another_call`},l):{body:k}}async function We(d,m,l,p,h){let k=await pe(m,l,p,`An upload's ${d}`);if(k instanceof Response)return k;let v=bn(d,k.body);if(typeof v=="string")return x({status:400,code:"bad_request",message:`An upload's ${d}: ${v}`},p);if(d==="complete"){if(u.has(v.uploadId))return x({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},p);u.add(v.uploadId),u.size>lt&&u.delete(u.values().next().value)}let j=Ht(r,v.method,v.route);if(!j||"malformed"in j||!j.route.meta.upload)return x({status:404,code:"not_found",message:`No upload route for ${v.method} ${v.route}`},p);let{route:_,params:ee}=j,W=j.route.meta.upload,O=Es(v.user);if(O&&Zt(h,O.id),n.get(_).required&&!O)throw new V(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let ce=$(_);if(ce!==!1){let Z=g.take(`${_.id}\0${pn(v.user,v.client)}`,ce);if(Z!==void 0)throw new V(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Z},Z)}let F=yn(W.pathTemplate,{userId:O?.id??null,uploadId:v.uploadId,filename:v.filename});if("problem"in F)throw new V(400,"bad_request",F.problem);return await Be(e.database,Qe(v.user),m.signal,_.id,async()=>{let Z={request:m,query:new URLSearchParams(v.query),params:ee,user:O,body:v.body===void 0||v.body===null?{}:ie(v.body),requestId:p};await Yt(_,Z);for(let ve of _.params)(ve.kind==="query"||ve.kind==="body"&&v.body!==void 0)&&await lr(ve,Z)}),de(200,{bucket:W.bucket,path:F.path},p)}h.endpoint=_.id.slice(_.id.indexOf(" ")+1);let z=new URLSearchParams(v.query),B=v.body===null||v.body===void 0?{}:ie(v.body);return pt(_,{request:m,query:z,params:ee,user:O,body:B,requestId:p,uploadedObject:ie(v.uploadedObject)},Qe(v.user))}async function wr(d,m,l,p){let h=await pe(m,l,p,`A room's ${d}`);if(h instanceof Response)return h;let k=await c.serve(d,h.body,m.signal);return"code"in k?x({status:k.status,code:k.code,message:k.message,retryAfter:k.retryAfter},p):"body"in k?de(200,k.body,p):new Response(null,{status:204,headers:{"x-request-id":p}})}async function Yt(d,m){let l=[],p={params:Object.freeze({...m.params}),user:ie(m.user),headers:d.meta.upload?new Headers:m.request.headers,requestId:m.requestId};for(let h of d.params)h.kind==="resolve"&&(l[h.index]=await o.get(h).resolve(p,h.options));return l}async function pt(d,m,l,p){let h=t.get(d.controller),k=await Be(e.database,l,m.request.signal,d.id,async()=>{let v=await Yt(d,m);for(let _ of d.params)_.kind!=="resolve"&&(v[_.index]=await lr(_,m));p?.ran();let j=await h[d.fn](...v);if(m.uploadedObject&&m.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return p?p.record(ur(j,m.requestId)):j});return p?k:ur(k,m.requestId)}async function Gt(d,m){let l=d.headers.get("x-request-id")??"",p=Rs.test(l)?l:`req_${crypto.randomUUID()}`,h=performance.now(),k=new URL(d.url).pathname,v={endpoint:k},j=await br(d,m,p,v);return e.telemetry?.record({requestId:p,method:d.method,endpoint:v.endpoint,path:k,status:j.status,durationMs:performance.now()-h,userId:v.userId}),j}function Zt(d,m){d.userId=m;let l=se.getStore();l&&(l.userId=m)}async function br(d,m,l,p){return se.run({requestId:l},async()=>{let h=new URL(d.url),k=`${d.method} ${h.pathname}`;try{if(h.pathname===Nt&&M.size>0)return d.method!=="POST"?x({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):e.webhookSecret?await Q(d,l):x({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},l);let v=H(h.pathname);if(v)return k=`webhook ${v.name}`,d.method!=="POST"?x({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):await mt(d,h,v,l);if(e.platform&&(h.pathname===De||h.pathname.startsWith(`${De}/`)))return k=h.pathname===De?"jobs":`job ${h.pathname.slice(De.length+1)}`,await be(d,h,e.platform.secret,l);if(e.platform&&(h.pathname===Et||h.pathname===fn)){let D=h.pathname===Et?"authorize":"complete";return k=`upload ${D}`,await We(D,d,e.platform.secret,l,p)}if(e.platform&&h.pathname.startsWith(`${Rt}/`)){let D=h.pathname.slice(Rt.length+1);return k=`room ${D}`,await wr(D,d,e.platform.secret,l)}if(js(h.pathname))return x({status:404,code:"not_found",message:`No route for ${d.method} ${h.pathname}`},l);let j=Ht(r,d.method,h.pathname);if(j&&"malformed"in j)return x({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},l);if(!j)return x({status:404,code:"not_found",message:`No route for ${d.method} ${h.pathname}`},l);let{route:_,params:ee}=j;if(k=_.id,p.endpoint=_.id.slice(_.id.indexOf(" ")+1),_.meta.upload)throw new V(400,"upload_required",`${_.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let W=n.get(_),O=null,z=null,B=d.headers.get("authorization")??"",ce=/^(bearer|dpop)\s+(\S+)$/i.exec(B),F=ce?.[2],Z=ce?.[1].toLowerCase()==="dpop";if(F)try{let D=!Z&&e.tokens&&!Ss.test(F)&&e.tokens.accepts(F)?e.tokens:void 0,ke=D?await A.ask(F,ut(d.headers,m.remoteAddress),()=>Be(e.database,null,d.signal,"token",()=>D.resolve(F))):await e.verifier.verify(F,Z?{proof:d.headers.get("dpop"),method:d.method,url:rn(d.headers,h)}:void 0);O=$s(ke),z=ke.claims}catch(D){if(!W.required&&(D instanceof Ge||D instanceof Ze||D instanceof ze))O=null;else throw D instanceof ze?new V(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:D.wait},D.wait):D instanceof Ge?new V(401,"invalid_token","The access token is not valid",{reason:D.reason},void 0,ys(D.reason)):D}else if(B!==""&&W.required)throw new V(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(O&&Zt(p,O.id),W.required&&!O)throw new V(401,"unauthorized","This route needs a signed-in user");if(W.verifiedEmail&&!O?.emailVerified)throw new V(403,"email_not_verified","This route needs a verified email address");let ve=$(_);if(ve!==!1){let D=O?`u:${O.id}`:`a:${ut(d.headers,m.remoteAddress)}`,ke=g.take(`${_.id}\0${D}`,ve);if(ke!==void 0)throw new V(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:ke},ke)}let Ve=d.method==="GET"||d.method==="HEAD"?void 0:await ft(d,b),vr=Ve===void 0?void 0:ks(Ve),Xt={request:d,query:h.searchParams,params:ee,user:O,body:vr,requestId:l},Qt=y&&Ve!==void 0&&qe(_)?Yn(d.method,d.headers):void 0;if(!y||Qt===void 0)return await pt(_,Xt,z);let kr={role:Bt(e.database.requests,z).role,uid:O?.id??`a:${ut(d.headers,m.remoteAddress)}`},en=!1;return await y.serve({key:Qt,caller:kr,method:d.method,uri:`${h.pathname}${h.search}`,body:Ve},D=>pt(_,Xt,z,{record:D,ran:()=>{en=!0}}),{requestId:l,refusal:D=>x(D,l),failure:D=>cr(D,l,k,d.signal),ran:()=>en})}catch(v){return cr(v,l,k,d.signal)}})}return{handle:G,routes:r.map(d=>d.id),contract:U,start:()=>t.start(),stop:async()=>{c.close();for(let d of I.keys())Ke(d);await t.shutdown(),await e.telemetry?.flush()}}}function Ts(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function As(e){let t=new Set;for(let[r,n]of e)if($t(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 ur(e,t){return e instanceof Response?bs(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):de(200,e,t)}function Ps(e,t){if(!(!tt(e)||e.status!==503||!mr(e)))return S.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 js(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return _e.has(decodeURIComponent(t))}catch{return _e.has(t)}}var Cs="GET, POST, PUT, PATCH, DELETE, QUERY",Ms=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function Ds(e){if(!e)return;if(e.origins!=="*"){for(let n of e.origins)if(!Ms.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":Cs,"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 lr(e,t){switch(e.kind){case"body":return Jt(e.schema,t.body??{},"Request body");case"query":return Jt(e.schema,ie(Object.fromEntries(t.query)),"Query parameters");case"headers":{let r={};return t.request.headers.forEach((n,o)=>r[o.toLowerCase()]=n),ie(r),e.schema?Jt(e.schema,r,"Request headers"):r}case"param":return t.params[e.name];case"user":case"optionalUser":return ie(t.user);case"req":return t.request;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 ie({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 Wt=720*3600;function Kt(e){return e instanceof $e&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function gr(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),Wt)}function yr(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Vt=class{filling=new Map;async get(t){try{let r=await Ee.cache.getCacheEntry({query:{key:t}});return r.data.found?r.data.value??null:null}catch(r){if(!Kt(r))throw r;return S.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 Ee.cache.putCacheEntry({query:{key:t},body:{value:yr(r),ttl:gr(n)}})}catch(o){if(!Kt(o))throw o;S.warn("cache: a write could not reach the cache; it is let go",{key:t,status:o.status})}}async del(t){await Ee.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await Ee.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 Ee.cache.getCacheEntry({query:{key:t}})).data}catch(c){if(!Kt(c))throw c;S.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}},Pi=sn("Cache",new Vt);function ji(e={}){let t=e.maxEntries??5e4,r=e.now??(()=>Date.now()),n=new Map,o=new Map,s=u=>{let f=n.get(u);if(f&&f.expiresAt<=r()){n.delete(u);return}return f},a=()=>{let u=r();for(let[y,E]of n)E.expiresAt<=u&&n.delete(y);if(n.size<t)return;let f=[...n.entries()].sort((y,E)=>y[1].expiresAt-E[1].expiresAt);for(let[y]of f.slice(0,Math.ceil(f.length/4)))n.delete(y)},i=async(u,f,y)=>{n.size>=t&&!n.has(u)&&a(),n.set(u,{value:yr(f),expiresAt:r()+(gr(y)??Wt)*1e3})};return{get:async u=>{let f=s(u);return f?structuredClone(f.value):null},set:i,async del(u){n.delete(u)},async incr(u){let f=s(u),y=(typeof f?.value=="number"&&Number.isInteger(f.value)?f.value:0)+1;return n.set(u,{value:y,expiresAt:f?.expiresAt??r()+Wt*1e3}),y},getOrSet(u,f,y){let E=s(u);if(E)return Promise.resolve(structuredClone(E.value));let N=o.get(u);if(N)return N;let g=(async()=>{try{let A=await y();return await i(u,A,f),A}finally{o.delete(u)}})();return o.set(u,g),g}}}export{vt as a,he as b,Oe as c,Ls as d,qs as e,Hs as f,Js as g,Bs as h,zs as i,Fs as j,Ks as k,Ws as l,Vs as m,Ys as n,Gs as o,Zs as p,Xs as q,Qs as r,ea as s,ta as t,na as u,ra as v,oa as w,sa as x,aa as y,ia as z,T as A,da as B,ca as C,pa as D,ha as E,ka as F,$a as G,Ea as H,Ra as I,Sa as J,Oa as K,_a as L,Pa as M,J as N,Un as O,Nn as P,In as Q,wo as R,La as S,Ja as T,Ba as U,za as V,Fa as W,Ka as X,Wa as Y,Va as Z,Ya as _,ni as $,us as aa,_i as ba,Wt as ca,Pi as da,ji as ea};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ import"./45J7YXRB.js";import{pathToFileURL as i}from"node:url";import{z as c}from"zod";async function f(e){let n=new Map,t=new Map;for(let r of e){let a=`${r.className}.${r.method}`,o=t.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(r.className,r.file),n.set(a,{returns:await u(r),throws:r.throws})}return r=>n.get(`${r.controller.name}.${r.fn}`)}async function u(e){let n=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(i(e.returns.file).href))[e.returns.exportName];if(!s(r))throw new Error(`${n}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let t=new Function("z",`return (${e.returns.expression});`)(c);if(!s(t))throw new Error(`${n}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function s(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{f as routeContracts};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as D}from"./6FWCNTAM.js";import{a as A,b as R,c as b,d as x,e as O,f as j,g as U,h as C,i as L,j as M,k as K,l as $}from"./IKVOXHEE.js";import{b as v,d as w,f as N,g as I}from"./HKJU2FKE.js";var ae=/^pb_[a-z0-9]+_s/;function E(n){if(D())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ae.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=I(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??N);return{ai:A.client(e),analytics:R.client(e),auth:b.client(e),cache:x.client(e),flags:O.client(e),machines:j.client(e),notify:U.client(e),purchases:C.client(e),realtime:L.client(e),secrets:M.client(e),storage:K.client(e),stores:$.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,de=/^[0-9]{1,12}$/,le=/^[0-9a-f]{64}$/,W=8,fe=/^whsec_[0-9A-Za-z]{32,}$/,he=1024*1024;async function B(n){if(typeof n.secret!="string"||!fe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await F(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(z(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!be(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function F(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=z(n.body),{t,v1:r}=H(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,we(new TextEncoder().encode(`${t}.`),e))),i=!1;for(let u of r)me(o,ge(u))&&(i=!0);if(!i)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function H(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let i of r.split(",")){let u=i.indexOf("=");if(u<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=i.slice(0,u).trim(),a=i.slice(u+1).trim();if(c==="t"){if(s!==void 0||!de.test(a))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!le.test(a))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(a)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function pe(n,e,t={}){let r=await ye(n,t.maxBytes??he);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ye(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],i=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(i+=l.byteLength,i>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let u=new Uint8Array(i),c=0;for(let a of o)u.set(a,c),c+=a.byteLength;return u}function z(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function ge(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function me(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function we(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function be(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var V=60,ke=60,Se=8*1024,ve=1e5;function _(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function J(n){let e=Y(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var k=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ve){this.max=e}spend(e,t){if(t>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new d("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,i]of s)i>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Ee(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return _(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function q(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function G(n,e,t,r){let s=ie=>{throw new d("proof",`the DPoP proof is not taken: ${ie}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>Se)return s("it is too long");let i=o.split(".");if(i.length!==3)return s("it is not a JWS of three parts");let u=J(i[0]),c=J(i[1]);if(!u||!c)return s("its header or claims are not base64url JSON");if(u.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(u.alg!=="ES256")return s(`it is signed with ${String(u.alg)}; only ES256 is taken`);let a=u.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Ee(a.x,a.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=Y(i[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${i[0]}.${i[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?q(c.htu):void 0,y=q(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let re=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-re)>V)return s("it was not made within a minute of now");let se=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:oe,until:(c.iat+V+ke)*1e3+1}}var d=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}};function _e(n){return async e=>{let t=b.client(w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch}));try{return await t.verifyTokenUser(),!0}catch(r){if(r instanceof v&&r.status===401)return!1;throw r}}}var T={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},X=60,Te=16*1024,Pe=10*6e4,Ae=5e4,Z=n=>typeof n=="string"&&Object.hasOwn(T,n),P=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new k;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Te)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let s=Q(r[0]),o=Q(r[1]);if(!s||!o)throw new d("malformed","the token header or claims are not base64url JSON");let i=s.alg;if(!Z(i))throw new d("algorithm",`the token is signed with ${String(i)}; only ES256 and PS256 are taken`);let u=s.kid;if(typeof u!="string"||u==="")throw new d("malformed","the token header names no kid");let c=await this.key(u);if(!c)throw new d("unknown_key",`no key ${u} in the project's key set`);if(c.alg!==i)throw new d("algorithm",`key ${u} is ${c.alg}, the token says ${i}`);let a=te(r[2]);if(!a)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(T[c.alg].verify,c.key,a,l).catch(()=>!1))throw new d("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");y=await G(e,h.jkt,t,this.now())}else if(t)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:xe(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",i=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:ee(t,i)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let i;try{i=await o}catch(u){throw new g("a session's standing cannot be read now",{cause:u})}return this.standings.delete(t),this.standings.set(t,{live:i,until:this.now()+this.standingTtlMs}),this.standings.size>Ae&&this.standings.delete(this.standings.keys().next().value),i}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+X<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-X>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Pe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let i=o.alg;if(typeof o.kid!="string"||!Z(i))continue;let u=T[i];if(o.kty!==u.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...a}=o;try{r.set(o.kid,{alg:i,key:await crypto.subtle.importKey("jwk",a,u.import,!1,["verify"])})}catch{}}this.keys=r;let s=Oe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Re.test(s)?`${r}://${s}${e.pathname}`:""}var Re=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function xe(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Oe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function te(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Q(n){let e=te(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function je(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var S=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Ue(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:i,metadata:u}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...i!==void 0?{ttl_seconds:i}:{},...u!==void 0?{metadata:u}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new S(a);let l={customer_id:a.customer,spend_id:a.id},p;try{p=await r(a)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Ce(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Le=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Me=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ne(n){return!Le.test(n)||Me.test(n)||/_PROXY$/i.test(n)}var Ke=/^(PORT|PALBASE_(URL|PROJECT_ID|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function $e(n){return Ke.test(n)}async function Ne(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=E({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:i}=await o.secrets.getEnvironmentValues({path:{environment:t}}),u=[],c=[],a=[];for(let[l,p]of Object.entries(i.values)){if(ne(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,u.push(l)}return{set:t,loaded:u.sort(),kept:c.sort(),refused:a.sort()}}export{E as a,f as b,B as c,F as d,H as e,pe as f,d as g,g as h,_e as i,P as j,ee as k,je as l,S as m,Ue as n,Ce as o,ne as p,$e as q,Ne as r};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.1.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as k,b as S}from"./DAOLIUNZ.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};