palbase 0.3.3 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +10 -13
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +11 -11
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{4AQYBTIN.js → 2GGJKIKT.js} +2 -2
- package/dist/chunks/2S5VK2PA.js +2 -0
- package/dist/chunks/{NK54UVDI.js → 6SXSYK4S.js} +2 -2
- package/dist/chunks/{IXHR57QC.js → 73WBTWOK.js} +2 -2
- package/dist/chunks/{4YD2XCGF.js → ABBUC5HE.js} +1 -1
- package/dist/chunks/{PB7UKHCY.js → C627JALV.js} +2 -2
- package/dist/chunks/{YWOS5WH2.js → CC36MKWZ.js} +2 -2
- package/dist/chunks/{TJ5SQTW5.js → COCND66P.js} +3 -3
- package/dist/chunks/{PRM2UXWG.js → FEHN6AHI.js} +1 -1
- package/dist/chunks/{P5JIZEPB.js → GUR3A4M7.js} +2 -2
- package/dist/chunks/HNMC2RJ7.js +20 -0
- package/dist/chunks/{OKZJIY6F.js → IOIQM4QO.js} +1 -1
- package/dist/chunks/OROMWNJD.js +6 -0
- package/dist/chunks/{47V66C2X.js → R5BCF2YW.js} +2 -2
- package/dist/chunks/RBUTW6OM.js +4 -0
- package/dist/chunks/{UXRIXHHY.js → RQFK2F3Q.js} +2 -2
- package/dist/cli.js +132 -125
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/ai.d.ts +63 -2
- package/types/ai/src/chats.d.ts +147 -0
- package/types/ai/src/index.d.ts +6 -1
- package/types/ai/src/tools.d.ts +167 -0
- package/types/backend/src/container.d.ts +4 -2
- package/types/backend/src/decorators.d.ts +32 -17
- package/types/backend/src/engine.d.ts +21 -5
- package/types/backend/src/env.d.ts +1 -1
- package/types/backend/src/i18n.d.ts +8 -7
- package/types/backend/src/index.d.ts +2 -1
- package/types/backend/src/strings-files.d.ts +28 -1
- package/types/backend/src/tasks.d.ts +168 -0
- package/types/internal/src/chat.d.ts +117 -0
- package/types/internal/src/modules/auth.d.ts +64 -47
- package/types/internal/src/modules/machines.d.ts +320 -79
- package/types/internal/src/modules/notify.d.ts +3 -3
- package/types/internal/src/modules/purchases.d.ts +562 -3
- package/types/internal/src/modules/storage.d.ts +31 -2
- package/types/internal/src/tool-output.d.ts +20 -0
- package/types/web/src/ai.d.ts +201 -0
- package/types/web/src/client.d.ts +10 -0
- package/types/web/src/index.d.ts +1 -0
- package/types/web/src/paywall/placement.d.ts +2 -0
- package/types/web/src/purchases.d.ts +3 -1
- package/dist/chunks/CJCMQ73A.js +0 -20
- package/dist/chunks/CZQ7KIRM.js +0 -2
- package/dist/chunks/M5B52IE6.js +0 -4
package/dist/ai/index.js
CHANGED
|
@@ -1,17 +1,14 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as
|
|
3
|
-
`);for(let b=r.indexOf(`
|
|
4
|
-
|
|
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.5.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/OROMWNJD.js";import{a as pe}from"../chunks/ABBUC5HE.js";import{a as re}from"../chunks/6SXSYK4S.js";import{a as ae,b as oe,c as se}from"../chunks/73WBTWOK.js";import{b as I,d as ne}from"../chunks/RQFK2F3Q.js";import"../chunks/IOIQM4QO.js";import"../chunks/FEHN6AHI.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
|
-
`)):
|
|
6
|
+
`)):E.enqueue(S.encode(`data: ${JSON.stringify({text:D})}
|
|
10
7
|
|
|
11
|
-
`));let
|
|
12
|
-
data: ${JSON.stringify({id:
|
|
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(
|
|
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{
|
|
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};
|
package/dist/backend/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{
|
|
1
|
+
/*! palbase 0.5.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ea as h,ha as d}from"../chunks/HNMC2RJ7.js";import"../chunks/RBUTW6OM.js";import"../chunks/C627JALV.js";import"../chunks/ABBUC5HE.js";import"../chunks/6SXSYK4S.js";import"../chunks/73WBTWOK.js";import"../chunks/RQFK2F3Q.js";import"../chunks/IOIQM4QO.js";import"../chunks/FEHN6AHI.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};
|
package/dist/backend/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.5.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{$ as
|
|
3
|
-
`)}function
|
|
4
|
-
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function
|
|
5
|
-
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=
|
|
6
|
-
- ${
|
|
7
|
-
- `)}`);return{url:a,projectId:l,secretKey:o,webhookSecret:
|
|
8
|
-
${
|
|
1
|
+
/*! palbase 0.5.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as Bt,A as C,B as ot,C as it,D as ct,E as dt,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 kt,S as At,T as Rt,U as ee,V as Et,W as xt,X as _t,Y as Ot,Z as Tt,_ as Ct,a as Y,aa as Ft,b as J,ba as Mt,c as Q,ca as B,d as Le,da as $t,e as De,ea as F,f as Ue,fa as Lt,g as je,ga as Dt,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 Ye,q as Je,r as Qe,s as Xe,t as Ze,u as et,v as tt,w as st,x as rt,y as nt,z as at}from"../chunks/HNMC2RJ7.js";import{a as se}from"../chunks/2S5VK2PA.js";import{a as E,b as X,c as Z,e as g,f as lt,g as d,i as te,j as It}from"../chunks/RBUTW6OM.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/C627JALV.js";import"../chunks/ABBUC5HE.js";import{m as Me}from"../chunks/6SXSYK4S.js";import"../chunks/73WBTWOK.js";import{b as O}from"../chunks/RQFK2F3Q.js";import"../chunks/IOIQM4QO.js";import"../chunks/FEHN6AHI.js";import"reflect-metadata";import{existsSync as W,writeFileSync as ps,writeSync as we}from"node:fs";import{createServer as hs}from"node:http";import{dirname as k,join as K,resolve as Ae}from"node:path";import{Readable as gs}from"node:stream";var Ut=2e3,jt=1e4,Nt=/^[A-Za-z0-9_-]{1,64}$/,qt=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,s={}){this.sink=e,this.linesPerSecond=s.linesPerSecond??10,this.batchSize=Math.min(100,s.batchSize??100),this.flushMs=s.flushMs??2e3,this.maxPending=s.maxPending??2e3,this.sendMs=s.sendMs??jt,this.shutdownMs=s.shutdownMs??Ut,this.now=s.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,s,r=new Promise(a=>s=a),n=setTimeout(()=>{e=!0,s()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,s=(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`))),s>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${s} dropped`)}log(e){let s=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(s-this.refilled)/1e3*this.linesPerSecond),this.refilled=s,this.unlogged>0&&s-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=s),this.tokens<1){this.unlogged===0&&(this.unloggedSince=s),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[r](`${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:Nt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,qt),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),s=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let n=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await s.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,o=l??(r.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 Vt}from"node:crypto";import{bind as Wt,bunDriver as Kt,createDatabase as zt,createSearchWorker as Gt,cutOff as Ht,forgetUser as Yt,MigrationOpen as Jt,MigrationRefused as Qt,Migrator as oe,renewingBunPool as re,VersionNotMigrated as Xt}from"palgres";import{toModel as ie}from"palgres/dsl";var Zt=["start","complete","rollback","plan","status"],es=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function le(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!Zt.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 s of e)if(s.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 ts(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(s=>s.user!==void 0&&!s.ignored))}function de(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let s=Number(e);if(!Number.isSafeInteger(s)||s<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 s}function ss(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 s=globalThis.Bun;if(!s)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 r=e-1;return n=>{let a=re(()=>new s.SQL({url:n,prepare:!1,max:r})),l=re(()=>new s.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:Kt(a,l),poolSize:r,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,s){let r=e.PALBASE_DB_OWNER_URL;if(!r)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(!es.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=ue(t,de(e)),l=a(r),o,c=i=>d.error(`[palbase] migrate ${s}: ${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(r);b.pathname=`/${h}`;let f=a(b.toString());return{reserve:()=>f.pool.reserve(),end:()=>f.close()}},openedBy:n});if(s==="plan"){let h=await u.plan(i);return I(s,h),h.refusals.length>0?1:0}if(s==="status")return I(s,await u.status()),0;let p=s==="start"?await rs(u,i,n):s==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${s}: done`,{result:p}),I(s,p),0}catch(i){return i instanceof Qt?(d.error(`[palbase] migrate ${s}: refused`,{refusals:i.refusals}),c(`refused \u2014 ${i.refusals.join("; ")}`),1):Ht(i)?(d.error(`[palbase] migrate ${s}: 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 ${s}: failed`,{error:i}),c(`failed \u2014 ${ae(i)}`),1)}finally{await l.close().catch(()=>{})}}async function rs(t,e,s){try{return await t.start(e)}catch(r){if(!(r instanceof Jt)||s!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return d.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.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 ns(t,e){try{return await new oe(t).plan(e)}catch{return}}var $=class extends Error{digest;plan;constructor(e,s){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>)`,...s?as(s):[" palbase db:plan says what it would change"]].join(`
|
|
5
|
+
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=s}};function as(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 s of t.changes)e.push(` + ${s}`);for(let s of t.refusals)e.push(` \u2717 ${s}`);return e}async function ge(t,e,s,r){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 Wt(o.engine,l,{waitMs:r.onPlatform?6e4:0}).catch(async b=>{throw r.onPlatform||!(b instanceof Xt)?b:new $(b.digest,await ns(o.pool,l))}),i=Vt("sha256",s).update("palgres page cursor").digest("hex"),u=t.embed??r.embed,p=await zt({sql:o.engine,schemas:a,binding:c,cursorSecret:i,admission:ss(o.poolSize),embed:u,log:b=>d.warn(`[palbase] ${b}`)}),h=ts(l)?Gt({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=>Yt(o.engine,c,l,b),...h?{search:h}:{},close:()=>o.close()}}catch(c){throw await o.close(),c}}function os(t){let e=Buffer.from(t,"base64"),s=new Array(e.byteLength/4);for(let r=0;r<s.length;r++)s[r]=e.readFloatLE(r*4);return s}function be(t){return async({texts:e,model:s,dimensions:r})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:s,dimensions:r}});return{model:n.model,vectors:n.vectors.map(os)}}}var is=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function me(t,e,s){let r=[],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"&&r.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&r.push("palbase.url / PALBASE_URL is the project origin alone")}catch{r.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let l=t.projectId??e.PALBASE_PROJECT_ID??"";is.test(l)||r.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)||r.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)&&r.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(s.needsWebhookSecret&&(c!==void 0||i!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(i??"")&&r.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"),r.length>0)throw new Error(`[palbase] the app cannot start:
|
|
6
|
+
- ${r.join(`
|
|
7
|
+
- `)}`);return{url:a,projectId:l,secretKey:o,webhookSecret:s.needsWebhookSecret?i:void 0,platformSecret:c}}import{createHash as ls}from"node:crypto";import{gzipSync as cs}from"node:zlib";var ds="palbase-contract-v1 begin",us="palbase-contract-v1 end",fe=76;function ye(t){let e=Buffer.from(t,"utf8"),s=cs(e).toString("base64"),r=[`${ds} ${ls("sha256").update(e).digest("hex")} ${e.length}`];for(let n=0;n<s.length;n+=fe)r.push(s.slice(n,n+fe));return r.push(us),`
|
|
8
|
+
${r.join(`
|
|
9
9
|
`)}
|
|
10
|
-
`}var
|
|
11
|
-
`),process.exit(1),new x}throw a==="/dev/stdout"?
|
|
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,bs=15e3,ms="/_palbase/health";function fs(t){let e=new Set,s=r=>{if(e.has(r))return!1;e.add(r);let n=C(r,Y);return n?n.providers.some(a=>C(a,J)!==void 0&&C(a,Q)===void 0)||n.imports.some(s):!1};return t.some(s)}var ys={async create(t,e={}){let s=Array.isArray(t)?t:[t],r=e.env??process.env,n=le(r);if(n!==void 0){let y=e.db?await he(e.db,r,n):pe(n);throw process.exit(y),new U(y)}let a=r.PALBASE_CONTRACT_OUT;if(a){let y;try{await ke(ve(r)),y=await ws(s,e,r)}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)):ps(a,`${y}
|
|
12
|
+
`),process.exit(0),new x}let l=ve(r),o=await ke(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:r,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=fs(s)||c!==void 0&&D(c),p=me(e.palbase??{},r,{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(r.PORT??"8080");if(!Number.isInteger(b)||b<0||b>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let f=e.db?await ge(e.db,r,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=>Ps(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:s,verifier:new T({issuer:p.url,projectId:p.projectId,standing:z({url:p.url,secretKey:p.secretKey})}),server:h,webhookSecret:p.webhookSecret,env:r,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 Ss(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 s=k(Ae(e));for(;!W(K(s,"package.json"))&&k(s)!==s;)s=k(s);return W(K(s,"package.json"))?s:process.cwd()}async function ke(t){try{return await se(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function ws(t,e,s){let r=Ae(s.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(r);for(;!W(K(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/GUR3A4M7.js"),{routeContracts:l}=await import("../chunks/R5BCF2YW.js"),o=a(n,r);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:s,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 Ps(t,e){let s=e.data?.user_id;if(typeof s!="string"||s==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(s);d.info(`[palbase] user ${s} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them`)}async function Ss(t,e,s,r,n,a){let l,o={on:!1},c=(m,P)=>new URL(m.url).pathname===ms&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,P),i=hs((m,P)=>{vs(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(s,r,()=>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+bs);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 vs(t,e,s,r){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{s.statusCode=400,s.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;s.on("close",()=>{s.writableFinished||c.abort(new Error("the client closed the connection"))});let i=new Request(a,{method:e.method,headers:l,body:o?gs.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(i,{remoteAddress:e.socket.remoteAddress});if(s.statusCode=u.status,u.headers.forEach((p,h)=>s.setHeader(h,p)),r.on&&s.setHeader("connection","close"),u.body)for await(let p of u.body)s.write(p);s.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),s.headersSent||(s.statusCode=500),s.end()}}import{bigint as _r,boolean as Or,check as Tr,date as Cr,defineSchema as Br,defineTable as Fr,enumType as Mr,foreignKey as Ir,index as $r,integer as Lr,jsonb as Dr,numeric as Ur,ownedByUser as jr,policy as Nr,raw as qr,sqlType as Vr,text as Wr,timestamp as Kr,userRef as zr,uuid as Gr}from"palgres/dsl";import{increment as Yr,now as Jr}from"palgres";function A(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 s=await t();return{data:await e(s.data),error:null,status:s.status}}catch(s){return A(s)}}var ks=E("Secrets",{async get(t){if(G(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),As=100,Rs=1e3,Es=168*3600,xs={s:1,m:60,h:3600,d:86400};function _s(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let s=0;for(let[,r,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))s+=Math.round(Number(r)*xs[n]*1e3);return Math.ceil(s/1e3)}function Ce(t,e,s){let r=`${g.url}/storage/public/${encodeURIComponent(t)}/${encodeURIComponent(e)}`;return s?`${r}?variant=${encodeURIComponent(s)}`:r}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 Os(t){return{async upload(e,s,r){let n=r?.contentType??(s instanceof Blob&&s.type!==""?s.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:s,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}:A(a)}},async download(e){try{let s=await g.storage.getObject({path:{bucket:t,path:e}});if(s.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=s.data;try{return{data:await r.blob(),error:null,status:s.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(s){return A(s)}},getPublicUrl(e,s){return Ce(t,e,s?.variant)},async createSignedUrl(e,s){let r=_s(s?.expiresIn);return r===void 0||r<1||r>Es?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(s?.expiresIn)})`},status:400}:w(()=>g.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,s){let r=s?.limit??As,n=s?.offset??0;if(!Number.isInteger(r)||r<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<r;){let c=Math.max(1,Math.min(Rs,n+r-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<r&&a.push(Re(u));if(l=i.data.next_cursor,!l)break}}catch(c){return A(c)}return{data:a,error:null,status:o}},async remove(e){let s=[];for(let r of e){try{await g.storage.deleteObject({path:{bucket:t,path:r}})}catch(n){return A(n)}s.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:s,error:null,status:200}},move(e,s){return w(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})},copy(e,s){return w(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})}}}var Ts={bucket:Os},Ee=t=>X("Storage",t,Ts),Cs={bucket:t=>Ee("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ee("buckets").bucket(e):void 0})},Bs=E("Notifications",{push:{send(t){let{to:e,...s}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return w(()=>g.notify.sendPush({body:{...s,to:r}}),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:s,...r}=t,n={...r,...s!==void 0?{template:s}:{}};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 A(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",Fs=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(),s=>s.values??{})}var Te={setOverrideForUser:(t,e,s)=>w(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:s}}),r=>({key:r.key,value:r.value,source:Oe(r.source)})),setOverridesForUser:(t,e)=>w(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),s=>({values:s.values??{}})),clearOverrideForUser:(t,e)=>w(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),s=>({key:s.key,value:s.value,source:Oe(s.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}))},Ms=E("Flags",{async isEnabled(t,e){let s=r=>(d.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await j(e);return r.error?s(`${r.error.code}: ${r.error.message}`):xe(r.data[t])}catch(r){return s(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let s=await j(e);return s.error?{data:null,error:s.error,status:s.status}:{data:_e(s.data[t]),error:null,status:s.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(([s,r])=>{let n=_e(r);return{name:s,enabled:xe(r),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,s){let r,n=!1,a;s!==void 0?(r=e,n=!0,a=s):Fs(e)?a=e:e!==void 0&&(r=e,n=!0);let l=await j(a);if(l.error)return n?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let o=l.data[t];return{data:o===void 0?r??null:o,error:null,status:l.status}},async setOverride(t,e){let s=Be();return s?Te.setOverrideForUser(s,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}}),Is=E("Realtime",{broadcast(t,e,s){return w(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:s??{}}]}}),()=>{})},state:{set(t,e,s){return w(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:s}]}}),()=>{})},clear(t,e){return w(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as nn}from"zod";export{$e as AuthUnavailable,xt as BadRequest,We as Body,Lt as CACHE_MAX_TTL,Dt as Cache,Ze as Client,_t as Conflict,x as ContractRunEnded,Le as Controller,nt as Cron,lt as Database,Ot as DeadlockDetected,qe as Delete,vt as DiError,Me as EVENT_TYPES,Ms as Flags,Rt as Forbidden,De as Get,ze as Headers,Tt as HttpError,tt as Injectable,d as Log,$t as MAX_BODY_BYTES,U as MigrationRunEnded,st as Module,Ct as NotFound,Bs as Notifications,rt as On,bt as OnAuthorize,wt as OnEmpty,mt as OnFirst,ft as OnJoin,yt as OnLeave,Pt as OnMessage,Ye as OptionalUser,kt as PalError,g as Palbase,O as PalbaseError,ys as PalbaseFactory,Ge as Param,Ne as Patch,Ue as Post,je as Put,Ve as Query,Ke as QueryParams,Is as Realtime,Je as Req,Qe as RequestId,et as Resolve,gt as Room,$ as SchemaNotPushed,ks as Secrets,Bt as SerializationFailure,Cs as Storage,dt as Task,ct as TaskFailure,ut as Tasks,Ie as TokenError,T as TokenVerifier,Ft as TooManyRequests,Xe as TraceId,At as Unauthorized,Mt as UniqueViolation,pt as Upload,ht as UploadedObject,He as User,at as Webhook,_r as bigint,Or as boolean,Tr as check,F as createApp,Cr as date,Et as defineError,Br as defineSchema,Fr as defineTable,Mr as enumType,Ir as foreignKey,ot as getRegisteredControllers,it as getRoutes,St as getWebhookManifest,Yr as increment,$r as index,Lr as integer,Dr as jsonb,Jr as now,Ur as numeric,jr as ownedByUser,Nr as policy,qr as raw,Vr as sqlType,It as t,Wr as text,Kr as timestamp,zr as userRef,Gr as uuid,nn as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.5.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as
|
|
1
|
+
/*! palbase 0.5.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as l,b as g,c as f,d as m}from"../chunks/CC36MKWZ.js";import{a as u}from"../chunks/2S5VK2PA.js";import{c as p,h as c}from"../chunks/RBUTW6OM.js";import"../chunks/IOIQM4QO.js";import"../chunks/FEHN6AHI.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,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{
|
|
1
|
+
/*! palbase 0.5.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{d as O}from"./73WBTWOK.js";import{a as E,b as T,e as _}from"./RQFK2F3Q.js";var a=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(n,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=n,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function D(e){return e instanceof a||typeof e=="object"&&e!==null&&e.name==="BackendError"&&typeof e.kind=="string"}function $(e){let n=e.body,t={code:e.code,message:e.message,status:e.status,requestId:e.requestId??se(n,"request_id"),data:b(n,"data"),cause:e};if(e.code==="network_error")return new a("network",t);if(e.status===401)return new a("unauthorized",t);if(e.status===429)return new a("rateLimited",{...t,retryAfter:oe(n)??e.retryAfter});let r=re(n);return e.status===400&&r?new a("validation",{...t,fields:r}):new a("server",t)}function P(e){return e instanceof T||e instanceof Error&&e.name==="PalbaseError"}function j(e){return Array.isArray(e)&&e.length>0&&e.every(n=>typeof n=="object"&&n!==null&&typeof n.field=="string"&&typeof n.message=="string")}function re(e){let n=b(b(e,"data"),"fields");if(j(n))return n;let t=b(e,"fields");return j(t)?t:void 0}function oe(e){return N(e,"retry_after")??N(b(e,"data"),"retryAfter")}function b(e,n){if(typeof e=="object"&&e!==null)return e[n]}function N(e,n){let t=b(e,n);return typeof t=="number"?t:void 0}function se(e,n){let t=b(e,n);return typeof t=="string"?t:void 0}var ie=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ae=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ce=new Set(ae),de=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function S(e){return e==="then"||e==="toJSON"||de.has(e)}function A(e){return e==="call"||e==="join"||S(e)}function C(e){return typeof e=="string"&&ie.test(e)&&!ce.has(e)&&!S(e)}function B(e){return typeof e=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(e)}function I(e){_(e)}function J(e){return _(e).origin}var R=class extends Error{reason;constructor(n,t){super(n),this.name="RoomError",this.reason=t}},q=new WeakMap;async function U(e,n,t){let{pattern:r,events:o,messages:s}=pe(n),i=ue(r,t),c=q.get(e);c||q.set(e,c=new Map);let p=c;p.set(i,(p.get(i)??0)+1);let u=e.channel(i),l=()=>{let d=(p.get(i)??1)-1;d>0?p.set(i,d):(p.delete(i),u.leave())};try{await u.join()}catch{let d=u.state==="refused"?K(u.refusal,"unavailable"):"socket closed";throw l(),new R(`room ${JSON.stringify(i)} was not joined: ${d}`,d)}let m=!1,w=new Set,k=()=>{if(!m){m=!0,h();for(let d of[...w])d();l()}},h=u.onClosed(k),y=d=>{if(m)return()=>{};let v=u.on("broadcast",f=>{typeof f.event=="string"&&o.has(f.event)&&d(f.event,E(f.payload))}),g=()=>{w.delete(g),v()};return w.add(g),g};return{topic:i,on(d,v){if(typeof d=="function")return y((g,f)=>d({event:g,payload:f}));if(!o.has(d))throw new TypeError(`room ${JSON.stringify(r)} declares no event ${JSON.stringify(String(d))}`);if(typeof v!="function")throw new TypeError(`room ${JSON.stringify(r)}: on(${JSON.stringify(d)}, \u2026) takes the function the event is handed to`);return y((g,f)=>{g===d&&v(f)})},off(d){w.has(d)&&d()},async send(d,v){if(!s.has(d))throw new TypeError(`room ${JSON.stringify(r)} declares no message ${JSON.stringify(String(d))}`);let g=m?{status:"error",response:{reason:"not joined"}}:await u.push("broadcast",{type:"broadcast",event:d,payload:v});if(g.status==="ok")return;let f=K(g.response,"unavailable");throw new R(`room ${JSON.stringify(i)} did not take ${JSON.stringify(d)}: ${f}`,f)},leave:k}}function pe(e){let n=typeof e=="object"&&e!==null?e:{},t=r=>Array.isArray(r)&&r.every(o=>typeof o=="string");if(typeof n.pattern!="string"||n.pattern===""||!t(n.events)||!t(n.messages))throw new TypeError("join takes a room of the backend's generated module: its pattern, its events and its messages");return{pattern:n.pattern,events:new Set(n.events),messages:new Set(n.messages)}}function ue(e,n){let t=typeof n=="object"&&n!==null?n:{};return e.split(":").map(r=>{if(!(r.startsWith("{")&&r.endsWith("}")&&r.length>2))return r;let o=r.slice(1,-1),s=Object.hasOwn(t,o)?t[o]:void 0;if(typeof s!="string"||s==="")throw new TypeError(`room ${JSON.stringify(e)} needs a value for ${JSON.stringify(o)}`);if(s.includes(":"))throw new TypeError(`room ${JSON.stringify(e)}: the value of ${JSON.stringify(o)} is one segment of the channel's name and cannot hold ":"`);return s}).join(":")}function K(e,n){let t=e?.reason;return typeof t=="string"&&t!==""?t:n}var x=class{pending="";dataLines=[];eventName;consume(n){this.pending+=n.replace(/\r\n/g,`
|
|
3
3
|
`);let t=[],r=this.pending.indexOf(`
|
|
4
4
|
`);for(;r!==-1;){let o=this.pending.slice(0,r);this.pending=this.pending.slice(r+1);let s=o.endsWith("\r")?o.slice(0,-1):o;if(s==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
5
|
`)}),this.dataLines=[],this.eventName=void 0;else if(!s.startsWith(":")){if(s.startsWith("data:")){let i=s.slice(5);this.dataLines.push(i.startsWith(" ")?i.slice(1):i)}else if(s.startsWith("event:")){let i=s.slice(6);this.eventName=i.startsWith(" ")?i.slice(1):i}}r=this.pending.indexOf(`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! palbase 0.5.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};
|