palbase 0.3.3 → 0.4.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 (48) hide show
  1. package/dist/ai/index.js +10 -13
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +9 -9
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{UXRIXHHY.js → 2AT72FFB.js} +2 -2
  8. package/dist/chunks/{IXHR57QC.js → 3OIKIBMG.js} +2 -2
  9. package/dist/chunks/{YWOS5WH2.js → 6JO3UVPT.js} +2 -2
  10. package/dist/chunks/{P5JIZEPB.js → BHT2IHBE.js} +2 -2
  11. package/dist/chunks/BJL2FT5W.js +2 -0
  12. package/dist/chunks/CY6B75KF.js +6 -0
  13. package/dist/chunks/EGRDFD5C.js +20 -0
  14. package/dist/chunks/{47V66C2X.js → FS222NNP.js} +2 -2
  15. package/dist/chunks/{4AQYBTIN.js → IVDNNHII.js} +2 -2
  16. package/dist/chunks/{PRM2UXWG.js → ODFLUINN.js} +1 -1
  17. package/dist/chunks/{OKZJIY6F.js → RKNVSAGY.js} +1 -1
  18. package/dist/chunks/ST2NZ4TZ.js +4 -0
  19. package/dist/chunks/{PB7UKHCY.js → SUNHFMDO.js} +2 -2
  20. package/dist/chunks/{TJ5SQTW5.js → TRHIZOIS.js} +3 -3
  21. package/dist/chunks/{4YD2XCGF.js → UNTTPATW.js} +1 -1
  22. package/dist/chunks/{NK54UVDI.js → ZFX4BFQR.js} +2 -2
  23. package/dist/cli.js +131 -128
  24. package/dist/refuse/ai.js +1 -1
  25. package/dist/refuse/backend.js +1 -1
  26. package/dist/refuse/server.js +1 -1
  27. package/dist/server/index.js +2 -2
  28. package/dist/server/testing.js +2 -2
  29. package/dist/web/index.js +2 -2
  30. package/dist/web/palbe.js +2 -2
  31. package/dist/web/paywall.js +2 -2
  32. package/dist/web/vite.js +2 -2
  33. package/package.json +2 -2
  34. package/types/ai/src/ai.d.ts +63 -2
  35. package/types/ai/src/chats.d.ts +147 -0
  36. package/types/ai/src/index.d.ts +6 -1
  37. package/types/ai/src/tools.d.ts +167 -0
  38. package/types/backend/src/engine.d.ts +12 -1
  39. package/types/backend/src/i18n.d.ts +8 -7
  40. package/types/backend/src/strings-files.d.ts +28 -1
  41. package/types/internal/src/chat.d.ts +117 -0
  42. package/types/internal/src/tool-output.d.ts +20 -0
  43. package/types/web/src/ai.d.ts +201 -0
  44. package/types/web/src/client.d.ts +3 -0
  45. package/types/web/src/index.d.ts +1 -0
  46. package/dist/chunks/CJCMQ73A.js +0 -20
  47. package/dist/chunks/CZQ7KIRM.js +0 -2
  48. package/dist/chunks/M5B52IE6.js +0 -4
package/dist/ai/index.js CHANGED
@@ -1,17 +1,14 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
2
- import{a as V}from"../chunks/4YD2XCGF.js";import{a as W}from"../chunks/NK54UVDI.js";import{a as q,b as Y}from"../chunks/IXHR57QC.js";import{b as U,d as z}from"../chunks/UXRIXHHY.js";import"../chunks/OKZJIY6F.js";import"../chunks/PRM2UXWG.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))})}
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as ie,b as de,c as le,d as ce,f as N,g as ue,h as U}from"../chunks/CY6B75KF.js";import{a as pe}from"../chunks/UNTTPATW.js";import{a as re}from"../chunks/ZFX4BFQR.js";import{a as ae,b as oe,c as se}from"../chunks/3OIKIBMG.js";import{b as I,d as ne}from"../chunks/2AT72FFB.js";import"../chunks/RKNVSAGY.js";import"../chunks/ODFLUINN.js";var _e=/\s/;function J(e,t){for(;t<e.length&&_e.test(e[t]);)t++;return t}function me(e,t){let a="";for(let n=t+1;n<e.length;n++){let s=e[n];if(s==='"')return{value:a,complete:!0,empty:!1,at:n+1};if(s!=="\\"){a+=s;continue}let u=e[n+1];if(u===void 0)break;if(u==="u"){let r=e.slice(n+2,n+6);if(r.length<4)break;a+=String.fromCharCode(Number.parseInt(r,16)),n+=5;continue}a+={n:`
3
+ `,t:" ",r:"\r",b:"\b",f:"\f"}[u]??u,n++}return{value:a,complete:!1,empty:!1,at:e.length}}function F(e,t){t=J(e,t);let a=e[t];if(a===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(a==='"')return me(e,t);if(a==="{")return Oe(e,t);if(a==="[")return $e(e,t);let n=t;for(;n<e.length&&/[-+0-9.A-Za-z]/.test(e[n]);)n++;if(n===e.length)return{value:void 0,complete:!1,empty:!0,at:n};try{return{value:JSON.parse(e.slice(t,n)),complete:!0,empty:!1,at:n}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function Oe(e,t){let a={},n=t+1;for(;;){if(n=J(e,n),e[n]==="}")return{value:a,complete:!0,empty:!1,at:n+1};if(e[n]===","){n++;continue}if(e[n]!=='"')return{value:a,complete:!1,empty:!1,at:e.length};let s=me(e,n);if(!s.complete)return{value:a,complete:!1,empty:!1,at:e.length};if(n=J(e,s.at),e[n]!==":")return{value:a,complete:!1,empty:!1,at:e.length};let u=F(e,n+1);if(u.empty||Object.defineProperty(a,s.value,{value:u.value,enumerable:!0,writable:!0,configurable:!0}),!u.complete)return{value:a,complete:!1,empty:!1,at:e.length};n=u.at}}function $e(e,t){let a=[],n=t+1;for(;;){if(n=J(e,n),e[n]==="]")return{value:a,complete:!0,empty:!1,at:n+1};if(e[n]===","){n++;continue}if(n>=e.length)return{value:a,complete:!1,empty:!1,at:n};let s=F(e,n);if(s.empty||a.push(s.value),!s.complete)return{value:a,complete:!1,empty:!1,at:e.length};n=s.at}}function H(e){let t=F(e,0);return t.empty?void 0:t.value}var h=class extends Error{path;constructor(t,a){super(`${t}: ${a}`),this.name="AISchemaError",this.path=t}},Me=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),je=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),Be=new Set(["object","array","string","integer","number","boolean"]),fe=12,ge=512,De=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function L(e,t="answer"){if(!De.test(t))throw new h(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 h(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!a.jsonSchema||typeof a.jsonSchema.output!="function")throw new h(t,`${a.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let n;try{n=a.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(r){throw new h(t,`the schema has a part JSON Schema cannot say (${r.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(n.type!=="object")throw new h(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let u=W(n,t,0,{properties:0});return{name:t,json:u,async check(r){let o=await a.validate(r);if(o.issues){let d=o.issues[0],p=(d?.path??[]).map(y=>String(typeof y=="object"?y.key:y)).join(".");throw new h(p?`${t}.${p}`:t,`the model's answer does not match the schema: ${d?.message??"invalid"}`)}return o.value}}}function W(e,t,a,n){if(a>fe)throw new h(t,`nests deeper than ${fe} levels, the most the provider takes`);for(let r of["anyOf","oneOf","allOf"])if(r in e)throw new h(t,Ne(e[r])??"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 r of["$ref","$defs","definitions","$dynamicRef"])if(r in e)throw new h(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 h(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 r of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(r in e)throw new h(t,`uses ${r}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new h(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 s=e.type;if(typeof s!="string"&&!("enum"in e))throw new h(t,"has no type: the provider holds a model only to a typed value");if(typeof s=="string"&&!Be.has(s))throw new h(t,`is of type ${s}, which the provider does not take`);let u={};for(let[r,o]of Object.entries(e))if(!(r==="$schema"||r==="id"||r==="$id")&&!je.has(r)){if(!Me.has(r))throw new h(t,`uses ${r}, which the provider cannot hold a model to`);u[r]=o}if("enum"in e&&typeof s!="string"){let r=e.enum,o=new Set(r.map(d=>d===null?"null":typeof d));if(o.size!==1||o.has("null"))throw new h(t,"an enum of values of several types (or with null): one type per field");u.type=o.has("string")?"string":o.has("boolean")?"boolean":"number"}if(s==="object"){let r=e.properties??{},o=Object.keys(r);if(o.length===0)throw new h(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 h(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(n.properties+=o.length,n.properties>ge)throw new h(t,`the schema has more than ${ge} fields in all, the most the provider takes`);let d=new Set(e.required??[]),p={};for(let y of o){if(!d.has(y))throw new h(`${t}.${y}`,'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');p[y]=W(r[y],`${t}.${y}`,a+1,n)}u.properties=p,u.required=o,u.additionalProperties=!1}if(s==="array"){let r=e.items;if(!r||typeof r!="object"||Array.isArray(r))throw new h(t,"is a list with no one shape for its items: the provider takes a list of one shape");u.items=W(r,`${t}[]`,a+1,n)}return u}function Ne(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 Ue=Symbol.for("palbase.ai.declared"),Je=Symbol.for("palbase.ai.tool_error"),Z=class extends Error{constructor(t){super(t),this.name="ToolError",Object.defineProperty(this,Je,{value:!0})}};function Y(){let e=globalThis;return e[Ue]??={tools:new Map,agents:new Map,twice:new Set}}function he(e,t,a,n){let s=e.get(a);s===void 0?e.set(a,n):s!==n&&Y().twice.add(`${t}:${a}`)}var ye=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,R=/^[a-z][a-z0-9_-]{0,63}$/;function we(e,t){if(e===void 0)return{type:"object",properties:{}};let a=e?.["~standard"];if(!a||a.version!==1||typeof a.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!a.jsonSchema||typeof a.jsonSchema.output!="function")throw new TypeError(`${t}: ${a.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let n;try{n=a.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(o){throw new TypeError(`${t}: the input has a part JSON Schema cannot say (${o.message}) \u2014 a function, a transform, a date: take a string and convert it in run`)}if(n.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let s=JSON.stringify(n);if(/"\$(ref|defs|dynamicRef)"/.test(s))throw new TypeError(`${t}: the input refers to another schema (a recursive or shared type) \u2014 write the shape out`);let{$schema:u,...r}=n;return r}function be(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!ye.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);if(typeof e.run!="function")throw new TypeError(`${t}: run(input, ctx) is what a call does`);if(e.machine!==void 0&&!R.test(e.machine))throw new TypeError(`${t}: machine is the name of one of the project's machines`);if(e.input===void 0)throw new TypeError(`${t}: input is what it takes \u2014 z.object({}) for nothing`);let a=we(e.input,t),n=e.input["~standard"],s=e.run,u={source:"backend",name:e.name,description:e.description,input:e.input,parameters:a,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(r,o){let d=await n.validate(r);if(d.issues){let p=d.issues[0],y=(p?.path??[]).map(k=>String(typeof k=="object"?k.key:k)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${y?` at ${y}`:""}: ${p?.message??"invalid"}`}],is_error:!0}}return{output:U(await s(d.value,o)),is_error:!1}}};return Object.freeze(u),he(Y().tools,"tool",u.name,u),u}function Se(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!ye.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);return Object.freeze({source:"client",name:e.name,description:e.description,parameters:we(e.input,t),approval:e.approval===!0})}function ke(e,t,a={}){let n=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!R.test(e))throw new TypeError(`${n}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${n}: the agent is a function of the turn's context that returns its definition`);if(a.machine!==void 0&&!R.test(a.machine))throw new TypeError(`${n}: machine is the name of one of the project's machines`);let s={kind:"agent",name:e,...a.machine!==void 0?{machine:a.machine}:{},clients:a.clients===!0,async resolve(u){let r=await t(u),o=q(r,`${n} for chat ${u.chatId}`);if(o.backend!==void 0)throw new TypeError(`${n}: a backend's agent is its definition \u2014 it names no other backend`);return delete o.clients,{definition:o,tools:Le(r)}}};return Object.freeze(s),he(Y().agents,"agent",e,s),s}function Le(e){return[...e.tools??[],...(e.subagents??[]).flatMap(a=>a.tools??[])].filter(a=>a.source==="backend")}function z(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a tool is ai.tool(\u2026), ai.clientTool(\u2026), { source: 'https', name } or { source: 'mcp', name }`);let a=e.approval===!0?{approval:!0}:{};switch(e.source){case"backend":if(typeof e.call!="function")throw new TypeError(`${t}: a backend tool is made with ai.tool({ name, description, input, run })`);return{source:"backend",name:e.name,description:e.description,parameters:e.parameters,...a,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...a};case"https":if(typeof e.name!="string"||!R.test(e.name))throw new TypeError(`${t}: { source: 'https', name } names an endpoint the project put`);return{source:"https",name:e.name,...a};case"mcp":if(typeof e.name!="string"||!R.test(e.name))throw new TypeError(`${t}: { source: 'mcp', name } names an MCP server the project put`);return{source:"mcp",name:e.name,...a,...e.only!==void 0?{only:[...e.only]}:{}};default:throw new TypeError(`${t}: a tool's source is backend, client, https or mcp (got ${JSON.stringify(e.source)})`)}}function q(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { instructions, model, tools, subagents, maxToolCalls }`);let a={};return e.instructions!==void 0&&(a.instructions=e.instructions),e.model!==void 0&&(a.model=e.model),e.maxToolCalls!==void 0&&(a.max_tool_calls=e.maxToolCalls),e.clients!==void 0&&(a.clients=e.clients),e.tools!==void 0&&(a.tools=e.tools.map(n=>z(n,t))),e.subagents!==void 0&&(a.subagents=e.subagents.map(n=>({name:n.name,description:n.description,...n.instructions!==void 0?{instructions:n.instructions}:{},...n.model!==void 0?{model:n.model}:{},...n.required!==void 0?{required:n.required}:{},...n.tools!==void 0?{tools:n.tools.map(s=>z(s,`${t} subagent ${n.name}`))}:{}}))),a}function Te(){return"cm_"+crypto.randomUUID()}async function V(e,t,a=4){for(let n=1;;n++)try{return await e()}catch(s){if(n>=a||!(s instanceof I)||s.status===429||t?.aborted)throw s;let u=se(s,n,30);if(u===void 0)throw s;await new Promise((r,o)=>{let d=setTimeout(r,u*1e3);t?.addEventListener("abort",()=>(clearTimeout(d),o(t.reason)),{once:!0})})}}function ve(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes}}function ze(e){return new Proxy(e,{get(t,a){let n=t[a];return typeof n=="function"?(...s)=>N(n.apply(t,s)):n}})}function xe(e){let t=ze(e);return{chats:{async create(r){let o=typeof r.agent=="object"&&r.agent!==null?r.agent.name:r.agent;if(o===void 0&&r.definition===void 0)throw new TypeError("chats.create: an agent (a named agent of the project) or a definition of the chat's own");let d={agent:o??"assistant"};return r.definition!==void 0&&(d.definition=q(r.definition,"chats.create")),r.title!==void 0&&(d.title=r.title),r.metadata!==void 0&&(d.metadata=r.metadata),r.members!==void 0&&(d.members=r.members.map(p=>({user_id:p.userId,...p.name!==void 0?{name:p.name}:{},...p.owner!==void 0?{owner:p.owner}:{}}))),(await t.createChat({body:d,signal:r.signal})).data},async get(r,o={}){return(await t.getChat({path:{chat_id:r},signal:o.signal})).data},async list(r={}){return(await t.listChats({query:{member:r.member},signal:r.signal})).data.chats},async delete(r){await t.deleteChat({path:{chat_id:r}})},members:{async put(r,o,d){let p={};return d.name!==void 0&&(p.name=d.name),d.owner!==void 0&&(p.owner=d.owner),(await t.putChatMember({path:{chat_id:r,user_id:o},body:p})).data},async delete(r,o){await t.deleteChatMember({path:{chat_id:r,user_id:o}})}},async send(r,o){let d={client_id:o.clientId??Te(),text:o.text};return o.delivery!==void 0&&(d.delivery=o.delivery),o.as!==void 0&&(d.as=o.as),V(async()=>(await t.sendChatMessage({path:{chat_id:r},body:d,signal:o.signal})).data,o.signal)},async messages(r,o={}){let d=(await t.listChatMessages({path:{chat_id:r},query:{limit:o.limit,cursor:o.cursor},signal:o.signal})).data;return d.next_cursor===void 0?{messages:d.messages}:{messages:d.messages,nextCursor:d.next_cursor}},stream(r,o={}){return ue(async(d,p)=>(await t.followChat({path:{chat_id:r},query:d,signal:p})).data,o)},async stop(r){return(await t.stopChat({path:{chat_id:r}})).data.stopped},async approve(r,o,d){return(await t.decideChatApproval({path:{chat_id:r,approval_id:o},body:d===void 0?{approve:!0}:{approve:!0,reason:d}})).data},async deny(r,o,d){return(await t.decideChatApproval({path:{chat_id:r,approval_id:o},body:d===void 0?{approve:!1}:{approve:!1,reason:d}})).data},async answer(r,o,d,p={}){let y={output:U(d)};p.isError&&(y.is_error=!0);try{return await V(()=>t.answerChatToolCall({path:{chat_id:r,call_id:o},body:y})),!0}catch(k){if(k instanceof I&&k.status===409)return!1;throw k}},async sendToSubagent(r,o,d,p={}){let y={client_id:p.clientId??Te(),text:d},k=await V(async()=>(await t.sendSubagentMessage({path:{chat_id:r,run_id:o},body:y})).data);return{runId:k.run_id,clientId:k.client_id}}},agents:{async put(r,o){let d=typeof r=="string"?r:r.name,p=typeof r=="string"?o:r;if(typeof d!="string"||!R.test(d))throw new TypeError("agents.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");if(p===void 0)throw new TypeError(`agents.put(${JSON.stringify(d)}): its definition, or a backend's ai.agent`);let y;if(p.kind==="agent"){let k=p;if(k.name!==d)throw new TypeError(`agents.put(${JSON.stringify(d)}): the backend's agent is named ${JSON.stringify(k.name)} \u2014 its machine is asked for it by that name`);y=k.clients?{backend:k.machine??"backend",clients:!0}:{backend:k.machine??"backend"}}else y=q(p,`agents.put(${JSON.stringify(d)})`);return(await t.putAgent({path:{name:d},body:y})).data},async list(){return(await t.listAgents({})).data.agents},async delete(r){await t.deleteAgent({path:{name:r}})}},endpoints:{async put(r,o){let d={kind:o.kind,url:o.url};return o.description!==void 0&&(d.description=o.description),o.parameters!==void 0&&(d.parameters=o.parameters),o.approval!==void 0&&(d.approval=o.approval),(await t.putEndpoint({path:{name:r},body:d})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(r){await t.deleteEndpoint({path:{name:r}})}},settings:{async get(){return ve((await t.getSettings({})).data)},async put(r){let o={};return r.clients!==void 0&&(o.clients=r.clients),r.userMessagesPerMinute!==void 0&&(o.user_messages_per_minute=r.userMessagesPerMinute),r.historyLimitBytes!==void 0&&(o.history_limit_bytes=r.historyLimitBytes),ve((await t.putSettings({body:o})).data)}}}}var qe=/^pb_[a-z0-9]+_s/;function Ae(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function X(){return"ai_"+crypto.randomUUID()}function Q(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:L(t,"answer")}}var Re=4,Ke=/^[a-z][a-z0-9-]{1,62}$/;function Ge(e){if(!Array.isArray(e))throw new TypeError("images is a list of { bucket, path } (a file of the project's storage) or { url } (an https address)");if(e.length>Re)throw new TypeError(`a question takes ${Re} pictures at most (got ${e.length})`);return e.map((t,a)=>{let n=t??{};if("data"in n||"bytes"in n||t instanceof Uint8Array)throw new TypeError(`images[${a}]: a picture is given where it is, not as its bytes \u2014 upload it to the project's storage (storage.from(bucket).upload(path, file)) and give { bucket, path }, or give { url }`);if(typeof n.url=="string"){if(n.bucket!==void 0||n.path!==void 0)throw new TypeError(`images[${a}] is { bucket, path } or { url }, not both`);let s;try{s=new URL(n.url)}catch{throw new TypeError(`images[${a}].url is not an address: ${JSON.stringify(n.url.slice(0,80))}`)}if(s.protocol!=="https:"||n.url.length>2048)throw new TypeError(`images[${a}].url is an https address of 2048 characters at most`);return{url:n.url}}if(typeof n.bucket!="string"||!Ke.test(n.bucket)||typeof n.path!="string"||n.path==="")throw new TypeError(`images[${a}] is { bucket, path } \u2014 a file of the project's storage \u2014 or { url }`);return{bucket:n.bucket,path:n.path}})}function K(e,t={},a){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let n={...t};if(e.prompt!==void 0&&(n.input=e.prompt),e.messages!==void 0&&(n.messages=e.messages),e.instructions!==void 0&&(n.instructions=e.instructions),e.model!==void 0&&(n.model=e.model),e.metadata!==void 0&&(n.metadata=e.metadata),e.images!==void 0&&(n.images=Ge(e.images)),e.tools!==void 0&&(n.tools=e.tools.map((s,u)=>{if(s?.source==="client")throw new TypeError(`tools[${u}]: ${s.name} is a client tool \u2014 an app answers it, in a chat; a one-shot answer has no app to wait for`);let r=z(s,`tools[${u}]`);return r.source==="backend"&&r.machine===void 0&&a!==void 0&&(r.machine=a),r})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");if(!Number.isInteger(e.maxToolCalls)||e.maxToolCalls<1||e.maxToolCalls>200)throw new TypeError(`maxToolCalls is a whole number, 1 to 200 (got ${String(e.maxToolCalls)})`);n.max_tool_calls=e.maxToolCalls}return n}var C=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),s=>s.charCodeAt(0)),a=new DataView(t.buffer,t.byteOffset,t.byteLength),n=new Array(t.byteLength/4);for(let s=0;s<n.length;s++)n[s]=a.getFloat32(s*4,!0);return n}async function Pe(e){let t,a;e instanceof Uint8Array?(t=e,a=Ee(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),a=e.type||Ee(t)):(t=e.bytes,a=e.mediaType);let n="";for(let s=0;s<t.length;s+=32768)n+=String.fromCharCode(...t.subarray(s,s+32768));return{media_type:a,data:btoa(n)}}function Ee(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??Ae("PALBASE_URL"),a=e.secretKey??Ae("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"||!qe.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 n=oe(ne({baseUrl:t,credentials:{secretKey:a},fetch:e.fetch}),e.retry??ae);return re.client(n)}function We(e){return new Proxy({},{get:(t,a)=>e.ai[a]})}function Ze(e={}){if(pe())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");if(e.machine!==void 0&&!R.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?We(e.server):He(e),a=e.resumeFor??12e4;async function n(i,l,m=X()){return N(t.createResponse({headers:{"Idempotency-Key":m},body:i,signal:l}))}async function s(i,l={}){return(await t.getResponse({path:{response_id:i},signal:l.signal})).data}async function u(i,l,m,f,w){let b=0,T=i,x=X(),O=()=>Date.now()+a,$=O();for(let M=0;;M++)try{if(T||(l===null?T=(await n({...w,stream:!0},f,x)).data:T=(await t.followResponse({path:{response_id:l},query:{offset:b},signal:f})).data),!T.body)throw new Error("the stream has no body");for await(let g of ie(T.body)){let v=JSON.parse(g.data);switch(g.event){case"response":l===null&&(l=v.id,m.admitted(v));break;case"delta":{let _=v.offset+de(v.text);if(_>b){let G=v.offset>=b?v.text:ce(v.text,b-v.offset);m.delta(b,G),b=_}$=O();break}case"reset":v.offset<b&&(b=v.offset,m.reset(b));break;case"terminal":return v}}throw new Error("the stream ended before its answer did")}catch(g){if(T=null,f?.aborted||g instanceof I&&g.status>0&&g.status<500&&g.status!==429||l===null&&!(g instanceof I)||Date.now()>$)throw g;await new Promise(v=>setTimeout(v,Math.min(250*2**Math.min(M,4),4e3)))}}function r(i){if(i.status!=="completed")throw new C(i);return i.text??""}function o(i,l){let m=K(i,l?{schema:l.prepared.json,schema_name:l.name}:{},e.machine),f=[],w=!1,b,T=null,x=()=>{let c=T;T=null,c?.()},O,$,M=new Promise((c,S)=>{O=c,$=S});M.catch(()=>{});let g="",v=u(null,null,{admitted:c=>O(c.id),delta:(c,S)=>{g+=S,f.push(S),x()},reset:c=>{let S=le(g,c);g=g.slice(0,S),f.push("\0reset:"+S),x()}},i.signal,m).then(c=>{let S=c.status==="completed"?c.text??"":"";return S.length>g.length&&S.startsWith(g)&&(f.push(S.slice(g.length)),g=S),w=!0,x(),c},c=>{throw w=!0,b=c,$(c),x(),c});v.catch(()=>{});async function*_(){for(let c=0;;c++){for(;c>=f.length;){if(w){if(b)throw b;return}await new Promise(S=>T=S)}yield f[c]}}async function*G(){for await(let c of _())c.startsWith("\0reset:")||(yield c)}async function*Ie(){let c="",S="";for await(let B of _()){B.startsWith("\0reset:")?c=c.slice(0,Number(B.slice(7))):c+=B;let P=H(c);if(P===void 0)continue;let E=JSON.stringify(P);E!==S&&(S=E,yield P)}}let j=v.then(c=>{if(c.status!=="completed")throw new C(c);return c});j.catch(()=>{});let ee=l?j.then(c=>l.prepared.check(c.output)):Promise.reject(new TypeError("object is a schema stream's"));ee.catch(()=>{});let te=j.then(c=>c.text??g);return te.catch(()=>{}),{id:M,response:j,text:te,get textStream(){return G()},get partialObjectStream(){return Ie()},object:ee,toResponse(c={}){let S=new TextEncoder,B=new ReadableStream({async start(E){try{for await(let D of _())D.startsWith("\0reset:")?E.enqueue(S.encode(`event: reset
4
+ data: ${JSON.stringify({offset:Number(D.slice(7))})}
8
5
 
9
- `)):P.enqueue(y.encode(`data: ${JSON.stringify({text:$})}
6
+ `)):E.enqueue(S.encode(`data: ${JSON.stringify({text:D})}
10
7
 
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})}
8
+ `));let A=await j;E.enqueue(S.encode(`event: done
9
+ data: ${JSON.stringify({id:A.id,text:A.text,output:A.output,usage:A.usage})}
13
10
 
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:$})}
11
+ `))}catch(A){let D=A instanceof C||A instanceof I?A.code:"stream_failed";E.enqueue(S.encode(`event: error
12
+ data: ${JSON.stringify({code:D})}
16
13
 
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};
14
+ `))}finally{E.close()}}}),P=new Headers(c.headers);return P.set("content-type","text/event-stream"),P.set("cache-control","no-store"),P.set("x-accel-buffering","no"),new globalThis.Response(B,{...c,headers:P})}}}async function d(i,l){return u(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},i.signal,K(i,l,e.machine))}let{chats:p,agents:y,endpoints:k,settings:Ce}=xe(t);return{module:t,chats:p,agents:y,endpoints:k,settings:Ce,tool:be,clientTool:Se,agent:ke,async ask(i,l={}){let m=typeof i=="string"?{...l,prompt:i}:i;return r(await d(m,{}))},async generate(i){let l=Q(i.schema),m={schema:l.prepared.json,schema_name:l.name};if(i.background){let b=(await n(K(i,{...m,background:!0},e.machine),i.signal)).data;return{id:b.id,status:b.status}}let f=await d(i,m);if(f.status!=="completed")throw new C(f);return l.prepared.check(f.output)},stream(i){return o(i,i.schema?Q(i.schema):void 0)},async start(i){let l=(await n(K(i,{background:!0},e.machine),i.signal)).data;return{id:l.id,status:l.status}},schema(i,l){return{name:i,schema:l,prepared:L(l,i)}},response:s,async result(i,l){let m=Q(l),f=await s(i);if(f.status!=="completed")throw new C(f);return m.prepared.check(f.output)},async cancel(i){return(await t.cancelResponse({path:{response_id:i}})).data},async embed(i,l={}){let m=Array.isArray(i)?i:[i],f=[];for(let w=0;w<m.length;w+=1024){let b=await t.createEmbeddings({body:{input:m.slice(w,w+1024),model:l.model,dimensions:l.dimensions},signal:l.signal});for(let T of b.data.vectors)f.push(Fe(T))}return Array.isArray(i)?f:f[0]},async image(i){let l={prompt:i.prompt};for(let w of["model","size","quality","background","format","count"])i[w]!==void 0&&(l[w]=i[w]);i.references?.length&&(l.references=await Promise.all(i.references.map(Pe))),i.mask&&(l.mask=await Pe(i.mask));let m=(await t.createImage({headers:{"Idempotency-Key":X()},body:l,signal:i.signal})).data;for(let w=0;m.status==="running";w++){if(await new Promise(b=>setTimeout(b,Math.min(500+w*250,3e3))),i.signal?.aborted)throw i.signal.reason;m=(await t.getImage({path:{image_id:m.id},signal:i.signal})).data}if(m.status!=="completed")throw new Error(`the image failed: ${m.error?.code??"image_failed"}: ${m.error?.message??""}`);let f=await Promise.all(m.files.map(async w=>{let T=(await t.getImageFile({path:{image_id:m.id,position:w.position},signal:i.signal})).data;return{mediaType:w.media_type,bytes:new Uint8Array(await T.arrayBuffer())}}));return{id:m.id,model:m.model,pictures:f,costNanoUSD:m.usage?.cost_nano_usd??0,save(w,b,T=0){let x=f[T];if(!x)throw new RangeError(`the job made ${f.length} picture(s)`);return w.upload(b,x.bytes,{contentType:x.mediaType})}}},async models(){return(await t.listModels({})).data},async usage(i={}){let l=(await t.listUsage({query:{kind:i.kind,limit:i.limit,cursor:i.cursor}})).data;return{usage:l.usage,nextCursor:l.next_cursor}},async connectProvider(i,l){return(await t.connectProvider({path:{provider:i},body:{key:l}})).data},async disconnectProvider(i){await t.disconnectProvider({path:{provider:i}})}}}export{C as AIResponseError,h as AISchemaError,Z as ToolError,Ze as createAI,H as partial,L as prepare};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
2
- import{ba as h,ea as d}from"../chunks/CJCMQ73A.js";import"../chunks/M5B52IE6.js";import"../chunks/PB7UKHCY.js";import"../chunks/4YD2XCGF.js";import"../chunks/NK54UVDI.js";import"../chunks/IXHR57QC.js";import"../chunks/UXRIXHHY.js";import"../chunks/OKZJIY6F.js";import"../chunks/PRM2UXWG.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};
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{ba as h,ea as d}from"../chunks/EGRDFD5C.js";import"../chunks/ST2NZ4TZ.js";import"../chunks/SUNHFMDO.js";import"../chunks/UNTTPATW.js";import"../chunks/ZFX4BFQR.js";import"../chunks/3OIKIBMG.js";import"../chunks/2AT72FFB.js";import"../chunks/RKNVSAGY.js";import"../chunks/ODFLUINN.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};
@@ -1 +1 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
@@ -1,12 +1,12 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
2
- 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/CJCMQ73A.js";import{b as Et}from"../chunks/CZQ7KIRM.js";import{a as E,b as H,c as J,e as h,f as tt,g as d}from"../chunks/M5B52IE6.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/PB7UKHCY.js";import"../chunks/4YD2XCGF.js";import{m as Re}from"../chunks/NK54UVDI.js";import"../chunks/IXHR57QC.js";import{b as _}from"../chunks/UXRIXHHY.js";import"../chunks/OKZJIY6F.js";import"../chunks/PRM2UXWG.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:
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{$ as B,A as C,B as ot,C as it,D as lt,E as ct,F as ut,G as pt,H as ht,I as gt,J as bt,K as mt,L as ft,M as yt,N as wt,O as Pt,P as St,Q as vt,R as ee,S as At,T as kt,U as Rt,V as Et,W as xt,X as _t,Y as Ot,Z as Tt,_ as Ct,a as J,aa as Ft,b as Y,ba as F,c as Q,ca as Mt,d as Le,da as It,e as De,f as Ue,g as je,h as Ne,i as qe,j as Ve,k as We,l as Ke,m as ze,n as Ge,o as He,p as Je,q as Ye,r as Qe,s as Xe,t as Ze,u as et,v as tt,w as rt,x as st,y as nt,z as at}from"../chunks/EGRDFD5C.js";import{a as re}from"../chunks/BJL2FT5W.js";import{a as E,b as X,c as Z,e as g,f as dt,g as d,i as te,j as Bt}from"../chunks/ST2NZ4TZ.js";import{a as V,g as Ie,h as $e,i as z,j as T,q as G,r as H}from"../chunks/SUNHFMDO.js";import"../chunks/UNTTPATW.js";import{m as Me}from"../chunks/ZFX4BFQR.js";import"../chunks/3OIKIBMG.js";import{b as O}from"../chunks/2AT72FFB.js";import"../chunks/RKNVSAGY.js";import"../chunks/ODFLUINN.js";import"reflect-metadata";import{existsSync as W,writeFileSync as cr,writeSync as we}from"node:fs";import{createServer as dr}from"node:http";import{dirname as A,join as K,resolve as ke}from"node:path";import{Readable as ur}from"node:stream";var $t=2e3,Lt=1e4,Dt=/^[A-Za-z0-9_-]{1,64}$/,Ut=512,M=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??Lt,this.shutdownMs=r.shutdownMs??$t,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:Dt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Ut),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 jt}from"node:crypto";import{bind as Nt,bunDriver as qt,createDatabase as Vt,createSearchWorker as Wt,cutOff as Kt,forgetUser as zt,MigrationOpen as Gt,MigrationRefused as Ht,Migrator as oe,renewingBunPool as se,VersionNotMigrated as Jt}from"palgres";import{toModel as ie}from"palgres/dsl";var Yt=["start","complete","rollback","plan","status"],Qt=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function le(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!Yt.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan or status, not ${e}`);return e}}function ce(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===B.name)throw new Error(`[palbase] db.schemas: the ${B.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,B]}function L(t){return ie(ce(t))}function Xt(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function de(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 Zt(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 ne=5;function ue(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=se(()=>new r.SQL({url:n,prepare:!1,max:s})),l=se(()=>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:qt(a,l),poolSize:s,close:async()=>{await a.close({timeout:ne}),await l.close({timeout:ne})}}}}function pe(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),I(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function he(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=ue(t,de(e)),l=a(s),o,c=i=>d.error(`[palbase] migrate ${r}: ${i}`);try{let i=L(t),u=new oe(l.pool,{log:h=>{/ is held by others | held by writers/.test(h)&&(o=h.trim()),d.info(h)},shadow:h=>{let b=new URL(s);b.pathname=`/${h}`;let f=a(b.toString());return{reserve:()=>f.pool.reserve(),end:()=>f.close()}},openedBy:n});if(r==="plan"){let h=await u.plan(i);return I(r,h),h.refusals.length>0?1:0}if(r==="status")return I(r,await u.status()),0;let p=r==="start"?await er(u,i,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:p}),I(r,p),0}catch(i){return i instanceof Ht?(d.error(`[palbase] migrate ${r}: refused`,{refusals:i.refusals}),c(`refused \u2014 ${i.refusals.join("; ")}`),1):Kt(i)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:i}),c(`cut off \u2014 ${o??ae(i)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:i}),c(`failed \u2014 ${ae(i)}`),1)}finally{await l.close().catch(()=>{})}}async function er(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof Gt)||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 I(t,e){process.stdout.write(`${JSON.stringify({palbase_migrate:t,result:e})}
3
+ `)}function ae(t){return(t instanceof Error?t.message:String(t)).split(`
4
+ `)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function tr(t,e){try{return await new oe(t).plan(e)}catch{return}}var $=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?rr(r):[" palbase db:plan says what it would change"]].join(`
5
+ `)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function rr(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 ge(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=ce(t),l=ie(a),o=ue(t,de(e))(n);try{let c=await Nt(o.engine,l,{waitMs:s.onPlatform?6e4:0}).catch(async b=>{throw s.onPlatform||!(b instanceof Jt)?b:new $(b.digest,await tr(o.pool,l))}),i=jt("sha256",r).update("palgres page cursor").digest("hex"),u=t.embed??s.embed,p=await Vt({sql:o.engine,schemas:a,binding:c,cursorSecret:i,admission:Zt(o.poolSize),embed:u,log:b=>d.warn(`[palbase] ${b}`)}),h=Xt(l)?Wt({sql:o.engine,embed:u,log:b=>d.info(`[palbase] ${b}`)}):void 0;return{model:l,binding:c,app:p,requests:t.requests??"caller",forget:b=>zt(o.engine,c,l,b),...h?{search:h}:{},close:()=>o.close()}}catch(c){throw await o.close(),c}}function sr(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 be(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(sr)}}}var nr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function me(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??"";nr.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
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),`
7
+ - `)}`);return{url:a,projectId:l,secretKey:o,webhookSecret:r.needsWebhookSecret?i:void 0,platformSecret:c}}import{createHash as ar}from"node:crypto";import{gzipSync as or}from"node:zlib";var ir="palbase-contract-v1 begin",lr="palbase-contract-v1 end",fe=76;function ye(t){let e=Buffer.from(t,"utf8"),r=or(e).toString("base64"),s=[`${ir} ${ar("sha256").update(e).digest("hex")} ${e.length}`];for(let n=0;n<r.length;n+=fe)s.push(r.slice(n,n+fe));return s.push(lr),`
8
8
  ${s.join(`
9
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/P5JIZEPB.js"),{routeContracts:l}=await import("../chunks/47V66C2X.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};
10
+ `}var Pe=2e4,Se=5e3,pr=15e3,hr="/_palbase/health";function gr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=C(s,J);return n?n.providers.some(a=>C(a,Y)!==void 0&&C(a,Q)===void 0)||n.imports.some(r):!1};return t.some(r)}var br={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=le(s);if(n!==void 0){let y=e.db?await he(e.db,s,n):pe(n);throw process.exit(y),new U(y)}let a=s.PALBASE_CONTRACT_OUT;if(a){let y;try{await Ae(ve(s)),y=await mr(r,e,s)}catch(S){throw we(2,`[palbase] the contract: ${S instanceof Error?S.message:String(S)}
11
+ `),process.exit(1),new x}throw a==="/dev/stdout"?we(1,ye(y)):cr(a,`${y}
12
+ `),process.exit(0),new x}let l=ve(s),o=await Ae(l);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${l}/palbase/strings`),te(o?void 0:l);let c=e.db?L(e.db):void 0,i=await H({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});i&&d.info(`[palbase] secrets: ${i.loaded.length} from the project's ${i.set} set${i.kept.length>0?`; ${i.kept.join(", ")} kept as the environment gives them`:""}`),i&&i.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${i.refused.map(y=>JSON.stringify(y)).join(", ")}`);let u=gr(r)||c!==void 0&&D(c),p=me(e.palbase??{},s,{needsWebhookSecret:u});u&&p.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 h=V({url:p.url,secretKey:p.secretKey}),b=e.port??Number(s.PORT??"8080");if(!Number.isInteger(b)||b<0||b>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let f=e.db?await ge(e.db,s,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:be(h)}):void 0;f&&d.info(`[palbase] database: version ${f.binding.version}`);let v=f&&D(f.model)?{"user.deleted":[y=>fr(f,y)]}:void 0,m=p.platformSecret===void 0?void 0:{secret:p.platformSecret},P=e.requestTelemetry===!1?void 0:new M(h.analytics),_=()=>F({modules:r,verifier:new T({issuer:p.url,projectId:p.projectId,standing:z({url:p.url,secretKey:p.secretKey})}),server:h,webhookSecret:p.webhookSecret,env:s,projectId:p.projectId,telemetry:P,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,platform:m,events:v,database:f&&{app:f.app,requests:f.requests},strings:o}),R=_(),N=e.boot?.attempts??5,q=e.boot?.backoffMs??1e3;for(let y=1;;y++)try{await R.start();break}catch(S){if(y>=N)throw d.error(`[palbase] the app did not start after ${N} attempts`,{error:S}),S;d.warn(`[palbase] the app did not start (attempt ${y} of ${N}); trying again in ${q} ms`,{error:S}),await new Promise(Fe=>setTimeout(Fe,q)),q*=2,R=_()}return yr(R,h,b,e.host??"0.0.0.0",e.exitOnFatal??!0,f)}};function ve(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=A(ke(e));for(;!W(K(r,"package.json"))&&A(r)!==r;)r=A(r);return W(K(r,"package.json"))?r:process.cwd()}async function Ae(t){try{return await re(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function mr(t,e,r){let s=ke(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=A(s);for(;!W(K(n,"package.json"))&&A(n)!==n;)n=A(n);let{analyzeProject:a}=await import("../chunks/BHT2IHBE.js"),{routeContracts:l}=await import("../chunks/FS222NNP.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",i=F({modules:t,verifier:new T({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:V({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:ee()},events:e.db&&D(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 fr(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 yr(t,e,r,s,n,a){let l,o={on:!1},c=(m,P)=>new URL(m.url).pathname===hr&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,P),i=dr((m,P)=>{wr(c,m,P,o).finally(()=>{o.on&&i.closeIdleConnections()})});i.keepAliveTimeout=29e4,i.headersTimeout=3e5;try{await new Promise((m,P)=>{i.once("error",P),i.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=i.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=m=>l??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let P=new Promise(R=>i.close(()=>R()));i.closeIdleConnections();let _=setTimeout(()=>i.closeAllConnections(),m);await P,clearTimeout(_),process.off("SIGINT",f),process.off("uncaughtException",v),process.off("unhandledRejection",v);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",f)}})(),h=()=>p(Pe),b=!1,f=()=>{if(b){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}b=!0;let m=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Pe+pr);m.unref(),h().then(()=>{clearTimeout(m),process.exit(0)},P=>{clearTimeout(m),d.error("[palbase] stopping failed; the process ends",{error:P}),process.exit(1)})},v=m=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let P=setTimeout(()=>process.exit(1),Se+1e3);p(Se).finally(()=>{clearTimeout(P),process.exit(1)})};return process.on("SIGTERM",f),process.once("SIGINT",f),n&&(process.on("uncaughtException",v),process.on("unhandledRejection",v)),{routes:t.routes,palbase:e,port:u,handle:c,close:h}}async function wr(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[p,h]of Object.entries(e.headers))if(h!==void 0)if(Array.isArray(h))for(let b of h)l.append(p,b);else l.set(p,h);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?ur.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((p,h)=>r.setHeader(h,p)),s.on&&r.setHeader("connection","close"),u.body)for await(let p of u.body)r.write(p);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 ks,boolean as Rs,check as Es,date as xs,defineSchema as _s,defineTable as Os,enumType as Ts,foreignKey as Cs,index as Bs,integer as Fs,jsonb as Ms,numeric as Is,ownedByUser as $s,policy as Ls,raw as Ds,sqlType as Us,text as js,timestamp as Ns,userRef as qs,uuid as Vs}from"palgres/dsl";import{increment as Ks,now as zs}from"palgres";function k(t){if(t instanceof O)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 Pr=E("Secrets",{async get(t){if(G(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Sr=100,vr=1e3,Ar=168*3600,kr={s:1,m:60,h:3600,d:86400};function Rr(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)*kr[n]*1e3);return Math.ceil(r/1e3)}function Ce(t,e,r){let s=`${g.url}/storage/public/${encodeURIComponent(t)}/${encodeURIComponent(e)}`;return r?`${s}?variant=${encodeURIComponent(r)}`:s}function Re(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,Ce(t.bucket,t.path,e)]))}}function Er(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof O&&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 g.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 Ce(t,e,r?.variant)},async createSignedUrl(e,r){let s=Rr(r?.expiresIn);return s===void 0||s<1||s>Ar?{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(()=>g.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??Sr,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(vr,n+s-a.length)),i=await g.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(Re(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 g.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(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return w(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var xr={bucket:Er},Ee=t=>X("Storage",t,xr),_r={bucket:t=>Ee("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ee("buckets").bucket(e):void 0})},Or=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(()=>g.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(()=>g.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 g.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}}}}),xe=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",_e=t=>typeof t=="string"?{name:t}:null,Oe=t=>t==="override"?"user":"system",Tr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&("userId"in t||"properties"in t);function Be(){return Z.getStore()?.userId}function j(t){let e=t&&"userId"in t?t.userId??void 0:Be();return w(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Te={setOverrideForUser:(t,e,r)=>w(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Oe(s.source)})),setOverridesForUser:(t,e)=>w(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>w(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Oe(r.source)})),clearAllOverridesForUser:t=>w(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>w(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Cr=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 j(e);return s.error?r(`${s.error.code}: ${s.error.message}`):xe(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await j(e);return r.error?{data:null,error:r.error,status:r.status}:{data:_e(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await j(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=_e(s);return{name:r,enabled:xe(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):Tr(e)?a=e:e!==void 0&&(s=e,n=!0);let l=await j(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=Be();return r?Te.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 Te}}),Br=E("Realtime",{broadcast(t,e,r){return w(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return w(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return w(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as en}from"zod";export{$e as AuthUnavailable,kt as BadRequest,We as Body,Mt as CACHE_MAX_TTL,It as Cache,Ze as Client,Rt as Conflict,x as ContractRunEnded,Le as Controller,dt as Database,Et as DeadlockDetected,qe as Delete,wt as DiError,Me as EVENT_TYPES,Cr as Flags,vt as Forbidden,De as Get,ze as Headers,xt as HttpError,tt as Injectable,nt as Job,d as Log,Ft as MAX_BODY_BYTES,U as MigrationRunEnded,rt as Module,_t as NotFound,Or as Notifications,st as On,pt as OnAuthorize,mt as OnEmpty,ht as OnFirst,gt as OnJoin,bt as OnLeave,ft as OnMessage,Je as OptionalUser,Pt as PalError,g as Palbase,O as PalbaseError,br as PalbaseFactory,Ge as Param,Ne as Patch,Ue as Post,je as Put,Ve as Query,Ke as QueryParams,Br as Realtime,Ye as Req,Qe as RequestId,et as Resolve,ut as Room,$ as SchemaNotPushed,Pr as Secrets,Ot as SerializationFailure,_r as Storage,Ie as TokenError,T as TokenVerifier,Tt as TooManyRequests,Xe as TraceId,St as Unauthorized,Ct as UniqueViolation,lt as Upload,ct as UploadedObject,He as User,at as Webhook,ks as bigint,Rs as boolean,Es as check,F as createApp,xs as date,At as defineError,_s as defineSchema,Os as defineTable,Ts as enumType,Cs as foreignKey,ot as getRegisteredControllers,it as getRoutes,yt as getWebhookManifest,Ks as increment,Bs as index,Fs as integer,Ms as jsonb,zs as now,Is as numeric,$s as ownedByUser,Ls as policy,Ds as raw,Us as sqlType,Bt as t,js as text,Ns as timestamp,qs as userRef,Vs as uuid,en as z};
@@ -1 +1 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
@@ -1,2 +1,2 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
2
- import{a as k,b as $,c as R,d as E}from"../chunks/YWOS5WH2.js";import{a as h}from"../chunks/CZQ7KIRM.js";import{c as m}from"../chunks/M5B52IE6.js";import"../chunks/OKZJIY6F.js";import"../chunks/PRM2UXWG.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};
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as l,b as g,c as f,d as m}from"../chunks/6JO3UVPT.js";import{a as u}from"../chunks/BJL2FT5W.js";import{c as p,h as c}from"../chunks/ST2NZ4TZ.js";import"../chunks/RKNVSAGY.js";import"../chunks/ODFLUINN.js";import"reflect-metadata";import{randomUUID as y}from"node:crypto";import{createFakeClient as T,typedDatabase as d}from"palgres/testing";function w(t,n,a){if(a?.acceptLanguage!==void 0&&a.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:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${y()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=T();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,m as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,w as withServices};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
2
- import{a as g,b}from"./OKZJIY6F.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=v(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=E(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await U(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status];if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await P(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function U(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:$(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function $(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function v(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function E(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+O(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!e.secretKey;case"userJWT":return!!a;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function O(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function P(t,e){let n=await _(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=B(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function _(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function B(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,v as e,R as f};
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as g,b}from"./RKNVSAGY.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=v(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=E(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await U(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status];if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await P(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function U(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:$(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function $(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function v(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function E(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+O(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!e.secretKey;case"userJWT":return!!a;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function O(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function P(t,e){let n=await _(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=B(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function _(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function B(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,v as e,R as f};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./UXRIXHHY.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,w as c};
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./2AT72FFB.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
2
- import{a as k,b as S}from"./OKZJIY6F.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as k,b as S}from"./RKNVSAGY.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.3.3 — Palbase SDK License (see LICENSE) */
2
- import"./PRM2UXWG.js";import{realpathSync as Ve}from"node:fs";import{resolve as ue}from"node:path";import wt from"typescript";import{existsSync as Se,readFileSync as Ue}from"node:fs";import{dirname as de,join as pe,relative as qe,resolve as ye,sep as ee}from"node:path";var h=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},W=new Set(["palbase/backend","@palbase/backend","palgres"]),Je=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function Te(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new h(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}function he(e,t){Te(e);let n=pe(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(Se(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new h(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import"./ODFLUINN.js";import{realpathSync as Ve}from"node:fs";import{resolve as ue}from"node:path";import wt from"typescript";import{existsSync as Se,readFileSync as Ue}from"node:fs";import{dirname as de,join as pe,relative as qe,resolve as ye,sep as ee}from"node:path";var h=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},W=new Set(["palbase/backend","@palbase/backend","palgres"]),Je=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function Te(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new h(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}function he(e,t){Te(e);let n=pe(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(Se(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new h(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
3
3
  `)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(a=>/\.d\.[cm]?ts$/.test(a))}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function be(e,t,n,r,s){Te(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=ye(t);return!n.includes(`${ee}node_modules${ee}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+ee))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function xe(e,t){let n=[],r=de(ye(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=pe(r,"package.json");if(Se(o)){try{let c=JSON.parse(Ue(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=de(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function te(e,t){if($(e,t))return!1;let n=xe(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):W.has(n)}function we(e,t){if($(e,t))return!1;let n=xe(e,t)??"";return W.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${qe(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function G(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function D(e,t){let n=G(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function me(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&W.has(me(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&W.has(me(n,i)??""))return(i.propertyName||i.name).text;if(te(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function ge(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function Z(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>ge(e,o)==="Controller"))continue;if(!s.name)throw new h(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Je.has(ge(e,a)??""))){if(P(n,o.name)===null)throw new h(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var Qe=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function We(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function ke(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=f=>{throw new h(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${f}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let f=[];for(let S of n.getSourceFiles()){if(f.length>=5)break;S.isDeclarationFile||n.isSourceFileFromExternalLibrary(S)||/[\\/]node_modules[\\/]/.test(S.fileName)||we(e,S.fileName)||f.push(...n.getSemanticDiagnostics(S).filter(x=>x.category===t.DiagnosticCategory.Error&&!Qe.has(x.code)))}f.length&&u(t.formatDiagnostics(f.slice(0,5),{getCanonicalFileName:S=>S,getCurrentDirectory:()=>e.root,getNewLine:()=>`
4
4
  `})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(We(g))return{kind:"raw"};let p=new Set,d=0;function C(f,S){if(++d>2e3||p.size>24)return u(`${S}: contract is too large; name its schema`);let x=f.flags,y=t.TypeFlags;if(x&(y.Any|y.Unknown|y.Never|y.TypeParameter))return u(`${S}: ${r.typeToString(f)}`);let fe=b=>{let w=r.getPropertiesOfType(b);if(!(b.flags&y.Object)||w.length!==1||w[0].name!=="__pg"||!(w[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(b).length)return!1;let N=r.getTypeOfSymbolAtLocation(w[0],o);return(N.isUnion()?N.types:[N]).every(k=>k.flags&(y.StringLiteral|y.Undefined))};if(f.isIntersection()){let b=f.types.filter(w=>!fe(w));if(b.length===1&&b.length<f.types.length)return C(b[0],S)}if(fe(f))return u(`${S}: unknown PostgreSQL payload; name its response schema`);if(x&y.StringLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.NumberLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.BooleanLiteral)return`z.literal(${r.typeToString(f)==="true"})`;if(x&y.String)return"z.string()";if(x&y.TemplateLiteral){let b=f;if(b.types.length>8||!b.types.every(k=>k.flags&y.String))return u(`${S}: template literal requires an explicit schema`);let w=k=>k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+w(b.texts[0]);for(let k of b.texts.slice(1,-1))if(k){let Y=w(k);N+=`(?:(?!${Y})[\\s\\S])*${Y}`}return N+="[\\s\\S]*"+w(b.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${S}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&y.Number)return"z.number().finite()";if(x&y.Boolean)return"z.boolean()";if(x&y.Null)return"z.null()";if(x&y.Undefined)return"z.undefined()";if(p.has(f))return u(`${S}: recursive response`);p.add(f);try{if(f.isUnion()){if(f.types.length>32)return u(`${S}: union has more than 32 alternatives`);let A=f.types.some(M=>M.flags&y.Null),Q=f.types.some(M=>M.flags&y.Undefined),j=f.types.filter(M=>!(M.flags&(y.Null|y.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?C(j[0],S):`z.union([${j.map(M=>C(M,S)).join(",")}])`)+(A&&j.length?".nullable()":"")+(Q?".optional()":"")}if(r.isTupleType(f))return u(`${S}: tuple requires an explicit schema`);if(r.isArrayType(f)){let A=r.getTypeArguments(f)[0];return A.flags&y.Never?"z.array(z.string()).length(0)":`z.array(${C(A,`${S}[]`)})`}let b=f.isIntersection()&&f.types.every(A=>A.flags&y.Object);if(!(x&y.Object)&&!b||f.getCallSignatures().length||f.getConstructSignatures().length)return u(`${S}: non-JSON type ${r.typeToString(f)}`);let w=f.symbol?.declarations?.[0];if(w&&(t.isClassDeclaration(w)||t.isClassExpression(w)))return u(`${S}: class instance ${r.typeToString(f)}`);let N=r.getPropertiesOfType(f),k=r.getIndexInfosOfType(f);return k.length?k.length!==1||!(k[0].keyType.flags&y.String)||N.length?u(`${S}: mixed or non-string index signature`):`z.record(z.string(), ${C(k[0].type,`${S}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${S}: symbol property`);let Q=A.getName(),j=C(r.getTypeOfSymbolAtLocation(A,o),`${S}.${Q}`);return`${JSON.stringify(Q)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${S}: empty structural type`)}finally{p.delete(f)}}return{kind:"expression",expression:C(g,"return")}}}import{resolve as Ge}from"node:path";var ne=Symbol("not a named schema");function Ee(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=d=>new h(`${i.fileName} \u2014 ${n}.${o}: ${d}`);function c(d){if(s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Promise"&&d.typeArguments&&d.typeArguments.length===1)return c(d.typeArguments[0]);if(d.kind===s.SyntaxKind.VoidKeyword||d.kind===s.SyntaxKind.UndefinedKeyword)return null;let C=s.isArrayTypeNode(d)?d.elementType:s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Array"&&d.typeArguments&&d.typeArguments.length===1?d.typeArguments[0]:void 0,f=l(C??d);return f===ne?f:{...f,isArray:C!==void 0}}function l(d){if(s.isTypeReferenceNode(d)&&!d.typeArguments)return{typeName:d.typeName.getText(i),node:d.typeName};if(s.isTypeReferenceNode(d)&&d.typeArguments&&d.typeArguments.length===1){let C=d.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(C)){let f=d.typeArguments[0];if(s.isTypeQueryNode(f))return{typeName:f.exprName.getText(i),node:f.exprName};if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName}}}if(d.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return ne}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===ne)return u();let g=Ze(e,m.node);if(!g)return u();let p=He(e,g.symbol);return p?{kind:"schema",...p,array:m.isArray}:u()}function Ze(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=G(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function He(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>G(e,i)===t).map(i=>i.name);return s.length===0?null:{file:Ge(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var oe={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},Xe=new Set(["HttpError","PalError"]),Ye=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],et=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function Le(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=xt(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function tt(e,t,n){throw new h(`${O(e,t)} \u2014 ${n}`)}function U(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function ce(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function De(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function Pe(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function nt(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=Pe(n,D(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function q(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function $e(e,t,n){for(let r=q(e,t);r;r=q(e,r))if(r===n)return!0;return!1}function V(e,t,n,r){let s=e.ts;for(let i=t;i;i=q(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||ce(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function rt(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function Ce(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!De(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function Fe(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function st(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function re(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function J(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)J(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;De(r,a)||n.add(a);for(let l of Ce(e))$e(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of Ce(e)){let u=Fe(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function ae(e,t,n){let r=st(e,t);if(r){let s=rt(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&$e(e,o,r));if(i.length===1){n.add(i[0]);return}}J(e,t,n)}function it(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function Oe(e,t){return t.fn&&it(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function E(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(E(e,t.whenTrue,n,r)),a(E(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(E(e,t.left,n,r)),a(E(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(E(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of X(e,t,n))for(let l of H(s,c.fn))a(E(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=D(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(E(e,c.initializer,Oe(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&J(e,re(e,c),i),i;if(c&&s.isParameter(c)){let l=re(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?ae(e,l,i):J(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(E(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):ae(e,re(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of H(s,c))a(E(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(E(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return J(e,e.checker.getTypeAtLocation(t),i),i}function H(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function Re(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function ze(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function ot(e,t){let n=e.ts,r=Re(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(ze(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!te(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of Ye)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function at(e,t){let n=e.checker.getSymbolAtLocation(ze(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function je(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=q(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||ce(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function X(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&q(e,n.owner);return c?je(e,c,n.receiver):[]}let i=Re(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&q(e,n.owner),p=g&&V(e,g,i,!1);return p?[{fn:p.fn,ctx:{receiver:n.receiver,owner:p.owner,fn:p.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=V(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!at(e,c))return[];let m=[];for(let g of E(e,l,n)){let p=V(e,g,i,!1);p&&m.push({fn:p.fn,ctx:{receiver:g,owner:p.owner,fn:p.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!ce(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function Ne(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=D(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of E(e,s.expression,n)){let l=V(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=D(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function Ae(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function ct(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function ve(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Me(e,t,n,r,s){if(Xe.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(Ae(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:ve(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(oe,t)?oe[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!ct(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return Ae(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:ve(c),code:c,status:i.status}))}function le(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function Ie(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&tt(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function lt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Be(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(d=>d.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(d=>s.isConstructorDeclaration(d)&&!!d.body),c=n,l=r;if(a){let d=lt(s,a);if(!d)return[];c=d.arguments,l=d}let u=nt(s,t),m=I(e,o);if(m)return Me(e,m,c,l,u);let g=D(e,o);if(g&&s.isVariableDeclaration(g)){let d=le(e,g);return d?[{...Ie(e,g,d),name:u||g.name.getText()}]:[]}let p=_(e,o);if(p){let d=Be(e,p,c,l);return d.length===1&&u?[{...d[0],name:u}]:d}return[]}function ut(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Me(e,s,r,t);let i=T(n,t.expression),o=D(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=le(e,o);if(c)return[Ie(e,o,c)]}let a=Pe(n,o);return a&&v(e,a)?Be(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,ut(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of X(e,t,n))for(let u of H(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=D(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?Oe(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function se(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function ft(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function dt(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function mt(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=ft(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||dt(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function gt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(oe))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=le(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function St(e,t){let n=gt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new h(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)St(e,o);let i=mt(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function Ke(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function pt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?Ke(e,n.body,r.name.text):!1:!0:!1}return!0}function yt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=D(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&L(e,l.initializer,n,a);c.body&&L(e,c.body,n,a)}else L(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function ie(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function L(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;L(e,t.tryBlock,n,ie(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?Ke(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&L(e,a.block,n,r),t.finallyBlock&&L(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(yt(e,o,"allSettled")){L(e,t.expression,n,r);let u=ie(r,{kind:"settle",node:t});for(let m of t.arguments)L(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=pt(s,t.arguments[a]);L(e,u.expression,n,ie(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)L(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?et.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=ot(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of X(e,t,n))R(e,r,t,se(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of Ne(e,u,n))R(e,r,u,se(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of je(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of Ne(e,a,n))R(e,r,a,se(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=D(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of E(e,t.expression,n)){let c=V(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>L(e,o,i,r))}function _e(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of X(e,t,{receiver:null,owner:null,fn:null}))for(let o of H(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(..._e(e,a,n))}return s}function Tt(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of _e(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;ae(e,Fe(e,c),l);for(let u of l){let m=V(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function ht(e){return e.charAt(0).toLowerCase()+e.slice(1)}function bt(e,t,n){let r=new Map;for(let i of Tt(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=ht(i.name),a=s.get(o);if(a)throw new h(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function xt(e,t){let n=[];for(let{cls:r,routes:s}of Z(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=bt(e,r,o);n.push({className:r.name.text,ops:i})}return n}function _t(e,t,n={}){let r=n.typescript??wt,s=Ve(ue(e)),{options:i,ambient:o}=he(r,s);return kt(be(r,s,[Ve(ue(t)),...o],i))}function kt(e){let t=e.ts,n=ke(e),r=Le(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=Z(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ee(e,n,u.name.text,g))}catch(p){if(!(p instanceof h))throw p;o.push(p.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,p]of Object.entries(m))s.push({file:ue(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:p})}if(o.length===1)throw new h(o[0]);if(o.length>1)throw new h(`${o.length} routes have no contract:
5
5
  ${o.map(a=>`- ${a}`).join(`
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{lstat as j,mkdir as F,readdir as M,readFile as N,rename as J,rm as T,writeFile as v}from"node:fs/promises";import{join as E}from"node:path";var o="palbase/strings",f="_meta.json",p=3,y=2,$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function m(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function b(r,n){try{return JSON.parse(r)}catch(t){throw new Error(`${n} is not JSON: ${t.message}`)}}async function x(r){let n=E(r,o);try{if(!(await j(n)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let t=new Map;for(let e of await M(n,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);t.set(e.name,await N(E(n,e.name),"utf8"))}return t.size===0?void 0:t}async function R(r,n=[p,y]){let t=await x(r);if(t===void 0)return;let e=t.get(f);if(e===void 0)throw new Error(`${o}/${f} is missing: it names the source language, and without it the language files are not a table`);let u=b(e,`${o}/${f}`);if(!$(u))throw new Error(`${o}/${f}: not a JSON object`);let s=u.version;if(s===y&&!n.includes(y))throw new Error(`${o}/${f}: version 2 is the earlier format ({"value", "state"} for each sentence) \u2014 run \`npx palbase strings\` once, and it writes the table as version ${p}`);if(typeof s!="number"||!n.includes(s))throw new Error(`${o}/${f}: version ${JSON.stringify(s)} is not one this reads (${n.join(" or ")})`);let a=u.source;if(typeof a!="string"||m(a)!==a)throw new Error(`${o}/${f}: source ${JSON.stringify(a)} is not a language tag as it is written (${m(String(a))??"en, en-US, zh-Hans"})`);let S=new Map;for(let w of[...t.keys()].sort()){if(w===f)continue;let i=w.slice(0,-5),g=`${o}/${w}`,d=m(i);if(d===void 0)throw new Error(`${g}: ${JSON.stringify(i)} is not a language tag`);if(d!==i)throw new Error(`${g}: the language is written ${d} \u2014 name the file ${d}.json`);if(i===a)throw new Error(`${g}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${g}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let O=b(t.get(w),g);if(!$(O))throw new Error(`${g}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[l,c]of Object.entries(O))if(s===p){if(typeof c!="string")throw new Error(`${g}: the translation of ${JSON.stringify(l)} is not a string`);h.set(l,c)}else if(typeof c=="string")h.set(l,c);else{if(!$(c)||typeof c.value!="string")throw new Error(`${g}: key ${JSON.stringify(l)} is not {"value": string, "state": string}`);h.set(l,c.state==="missing"?"":c.value)}S.set(i,h)}return{format:s,source:a,languages:S}}async function A(r){let n=await R(r,[p]);if(n===void 0)return;let t={};Object.setPrototypeOf(t,null);for(let[e,u]of n.languages)for(let[s,a]of u)Object.hasOwn(t,s)||(t[s]={},Object.setPrototypeOf(t[s],null)),t[s][e]=a;return{source:n.source,locales:[n.source,...n.languages.keys()],strings:t}}export{A as a};
@@ -0,0 +1,6 @@
1
+ /*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as k,b as E}from"./2AT72FFB.js";async function*S(e,t={}){let n=e.getReader(),o=new TextDecoder,r="",i="",a=[],g,w=()=>{n.cancel().catch(()=>{})};t.signal?.addEventListener("abort",w,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:T,value:A}=await n.read();if(T||t.signal?.aborted)return;t.onBytes?.(),r+=o.decode(A,{stream:!0});for(let y=r.indexOf(`
3
+ `);y>=0;y=r.indexOf(`
4
+ `)){let s=r.slice(0,r[y-1]==="\r"?y-1:y);r=r.slice(y+1),s===""?(i!==""&&(yield g===void 0?{event:i,data:a.join(`
5
+ `)}:{event:i,data:a.join(`
6
+ `),id:g}),i="",a=[],g=void 0):s.startsWith("event:")?i=C(s,6):s.startsWith("data:")?a.push(C(s,5)):s.startsWith("id:")&&(g=C(s,3))}}}finally{t.signal?.removeEventListener("abort",w);try{await n.cancel()}catch{}}}function C(e,t){let n=e.slice(t);return n.startsWith(" ")?n.slice(1):n}function P(e){let t=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o<128?t+=1:o<2048?t+=2:o>=55296&&o<=56319&&n+1<e.length&&(e.charCodeAt(n+1)&64512)===56320?(t+=4,n++):t+=3}return t}function q(e,t){if(t<=0)return 0;let n=0;for(let o=0;o<e.length;o++){let r=e.charCodeAt(o),i=3,a=1;if(r<128?i=1:r<2048?i=2:r>=55296&&r<=56319&&o+1<e.length&&(e.charCodeAt(o+1)&64512)===56320&&(i=4,a=2),n+=i,n>=t)return o+a;o+=a-1}return e.length}function j(e,t){return e.slice(q(e,t))}var M={too_many_streams:()=>"too many chat streams are open at once (4 a user, 32 a project): close one \u2014 chat.close(), or leave a stream's loop \u2014 then follow again",too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:e=>`this user has sent as many messages this minute as the project allows${e.retryAfter!==void 0?`: write again in ${e.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:e=>`the project's storage did not answer when the model was to read a picture${e.retryAfter!==void 0?`: try again in ${e.retryAfter} s`:"; try again shortly"}`},O=new WeakSet;function R(e){if(!(e instanceof E)||O.has(e))return e;let t=M[e.code];if(!t)return e;let n=new E({op:e.op,status:e.status,code:e.code,message:`${t(e)} (${e.op}: ${e.status} ${e.code})`,requestId:e.requestId,retryAfter:e.retryAfter,body:e.body,cause:e});return O.add(n),n}function Y(e){return e.catch(t=>{throw R(t)})}var m=class extends Error{constructor(t){super(t),this.name="StreamCut"}};function z(e,t={}){let n=t.resumeFor??12e4,o=t.idleFor??45e3,r=t.signal,i=t.after,a=t.response,g=new Map;a!==void 0&&g.set(a,t.offset??0);let w=!1,T=()=>{let s={};return i!==void 0&&(s.after=i),a!==void 0&&(s.response=a,s.offset=g.get(a)??0),s};function A(s,_,h){let f=h!==void 0&&/^\d+$/.test(h)?Number(h):void 0;if(f!==void 0&&i!==void 0&&f<=i)return;let c;try{c=k(JSON.parse(_))}catch{throw new m(`a ${s} frame is not JSON`)}if(typeof c!="object"||c===null)throw new m(`a ${s} frame is not an object`);let p;switch(s){case"message":p={type:"message",seq:f??0,message:c};break;case"turn":{let d={...c,type:"turn",seq:f??0};d.waiting??=null,d.error??=null,(d.status==="running"||d.status==="waiting")&&(a=d.response_id),p=d;break}case"text":{let d=String(c.response_id),l=Number(c.offset),u=String(c.text??"");if(!Number.isInteger(l)||l<0)throw new m("a text frame names no offset");a=d;let b=g.get(d)??0,x=l+P(u);if(x<=b)return;let v=l>=b?u:j(u,b-l);g.set(d,x),p={type:"text",response_id:d,offset:Math.max(l,b),text:v};break}case"reset":{let d=String(c.response_id),l=Number(c.offset),u=g.get(d)??0;if(!Number.isInteger(l)||l<0||l>=u)return;g.set(d,l),p={type:"reset",response_id:d,offset:l};break}case"tool":case"agent":p={...c,type:s,seq:f??0};break;default:break}return f!==void 0&&(i=f),p}async function*y(){let s=Date.now()+n,_;for(let h=0;;h++){if(r?.aborted)throw r.reason;let f=new AbortController,c=()=>f.abort(r?.reason);r?.addEventListener("abort",c,{once:!0});let p,d=()=>{clearTimeout(p),p=setTimeout(()=>f.abort(new m(`no byte for ${o} ms`)),o)},l;try{let u=await e(T(),f.signal);if(!u.body)throw new m("the stream has no body");d();let b=S(u.body,{signal:f.signal,onBytes:()=>{d(),s=Date.now()+n,h=0}});for await(let x of b){let v=A(x.event,x.data,x.id);v&&(yield v)}_=new m("the stream ended")}catch(u){if(r?.aborted)throw r.reason;if(u instanceof E){if(u.status>0&&u.status<500&&u.status!==429||u.code==="too_many_streams")throw R(u);u.retryAfter!==void 0&&(l=u.retryAfter*1e3)}_=f.signal.aborted&&f.signal.reason instanceof m?f.signal.reason:u}finally{clearTimeout(p),r?.removeEventListener("abort",c),f.abort()}if(Date.now()+(l??0)>s)throw _;await L(l??Math.min(250*2**Math.min(h,4),4e3),r)}}return{get position(){return T()},[Symbol.asyncIterator](){if(w)throw new TypeError("a chat stream is read once: follow the chat again from its position for another reader");return w=!0,y()}}}function L(e,t){return new Promise((n,o)=>{if(t?.aborted)return o(t.reason);let i=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(i),o(t?.reason)};t?.addEventListener("abort",a,{once:!0})})}var N=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function K(e){return Array.isArray(e)&&e.length>0&&e.every(F)?e.map($):F(e)?[$(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function F(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.type==="text"?typeof t.text=="string":t.type==="image"?(typeof t.mediaType=="string"||typeof t.media_type=="string")&&(typeof t.data=="string"||t.data instanceof Uint8Array):t.type===void 0&&typeof t.mediaType=="string"&&t.bytes instanceof Uint8Array}function $(e){if("type"in e&&e.type==="text")return{type:"text",text:e.text};let t="bytes"in e||"mediaType"in e?e.mediaType:e.media_type;if(!N.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let n="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof n=="string"?n:B(n)}}function B(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}export{S as a,P as b,q as c,j as d,R as e,Y as f,z as g,K as h};