palbase 0.74.0 → 0.75.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 +2 -2
- package/dist/ai-sdk/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{53XWB3UV.js → 2SVWIAAD.js} +1 -1
- package/dist/chunks/3GR5ZPYK.js +18 -0
- package/dist/chunks/{SS3YF6MP.js → 5NZNKECX.js} +2 -2
- package/dist/chunks/{IIQ6QEL2.js → 7BSFT4SH.js} +1 -1
- package/dist/chunks/{U5LDOZB5.js → 7R5TMAGP.js} +2 -2
- package/dist/chunks/{YDHRQOAN.js → EFDYHDIB.js} +1 -1
- package/dist/chunks/{BBXGUP7G.js → FJVUDV4I.js} +2 -2
- package/dist/chunks/{ZRNXABQJ.js → G37YLKYL.js} +2 -2
- package/dist/chunks/{DFIAGTHU.js → GMCROKBB.js} +2 -2
- package/dist/chunks/{CVBLXV6M.js → GSY2E764.js} +2 -2
- package/dist/chunks/{OS567PDL.js → HT6TR6AZ.js} +2 -2
- package/dist/chunks/{AFO74GQQ.js → KWVOOFCB.js} +1 -1
- package/dist/chunks/{MKKBGO2H.js → LGXI36R6.js} +2 -2
- package/dist/chunks/{4DNFXRTX.js → MT22R56P.js} +2 -2
- package/dist/chunks/{FKDQMWI7.js → P6LK5BD6.js} +2 -2
- package/dist/chunks/{QJPQVLNV.js → POURMU7G.js} +2 -2
- package/dist/chunks/{IJBBBAXY.js → RBZI2C7M.js} +1 -1
- package/dist/chunks/{FYZAVXD4.js → SPMFD3LH.js} +2 -2
- package/dist/chunks/{7HDSHHGM.js → UKONQ2R4.js} +2 -2
- package/dist/chunks/{WNPRCDLR.js → UPJGT3BN.js} +1 -1
- package/dist/chunks/{5NLCEWSD.js → XUEBLD7V.js} +1 -1
- package/dist/chunks/{YOCX3MXN.js → XZSXLA3N.js} +2 -2
- package/dist/chunks/{AKM627JB.js → YEZCBT5I.js} +2 -2
- package/dist/chunks/{RK4CTF2F.js → ZWASHVNO.js} +2 -2
- package/dist/cli.js +2 -2
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.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/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/payments-ui.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/index.d.ts +1 -1
- package/types/ai/src/tools.d.ts +18 -0
- package/types/internal/src/modules/ai.d.ts +8 -0
- package/dist/chunks/PF52QMPW.js +0 -18
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a,b,c,d,e,f,g}from"../chunks/
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f,g}from"../chunks/3GR5ZPYK.js";import"../chunks/ZWASHVNO.js";import"../chunks/RBZI2C7M.js";import"../chunks/HT6TR6AZ.js";import"../chunks/GMCROKBB.js";import"../chunks/G37YLKYL.js";import"../chunks/XUEBLD7V.js";import"../chunks/7BSFT4SH.js";export{f as AIResponseError,b as AISchemaError,d as ToolError,e as WorkflowParkedError,g as createAI,a as partial,c as prepare};
|
package/dist/ai-sdk/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"../chunks/
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"../chunks/7BSFT4SH.js";function M(s){return typeof process<"u"&&process.env?process.env[s]??"":""}function j(s){let a=(s??M("PALBASE_URL")).trim().replace(/\/+$/,"");if(!a)throw new Error("@palbase/ai-sdk: url or PALBASE_URL is required");return a.endsWith("/ai/v1")?a:`${a}/ai/v1`}function N(s){let a=(s??M("PALBASE_SECRET_KEY")).trim();if(!a)throw new Error("@palbase/ai-sdk: apiKey or PALBASE_SECRET_KEY is required");return a}function x(s,a,t){let u={apikey:s,Authorization:`Bearer ${s}`,"Content-Type":"application/json",...a};return t?.sessionId&&(u["X-Palbase-Session-Id"]=t.sessionId),t?.agent&&(u["X-Palbase-Agent"]=t.agent),t?.userId&&(u["X-Palbase-User-Id"]=t.userId),t?.workspaceId&&(u["X-Palbase-Workspace-Id"]=t.workspaceId),t?.fallbacks?.length&&(u["X-Palbase-Fallbacks"]=t.fallbacks.join(",")),u}function I(s){let a=[];for(let t of s){if(typeof t.content=="string"){a.push({role:t.role,content:t.content});continue}if(t.role==="tool"){for(let g of t.content)a.push({role:"tool",tool_call_id:g.toolCallId??"",content:typeof g.output=="string"?g.output:JSON.stringify(g.output??"")});continue}let u=[],k=[];for(let g of t.content)g.type==="text"&&g.text&&u.push(g.text),g.type==="tool-call"&&k.push({id:g.toolCallId??"",type:"function",function:{name:g.toolName??"",arguments:typeof g.input=="string"?g.input:JSON.stringify(g.input??{})}});let T={role:t.role,content:u.join(`
|
|
3
3
|
`)};k.length>0&&(T.tool_calls=k),a.push(T)}return a}function R(s){switch(s){case"stop":return"stop";case"length":return"length";case"tool_calls":return"tool-calls";case"error":return"error";default:return"unknown"}}function L(s={}){let a=j(s.url),t=N(s.apiKey),u=s.fetch??globalThis.fetch,k=(l,c)=>({specificationVersion:"v2",provider:"palbase",modelId:l,async doGenerate(e){let n={model:l,messages:I(e.prompt),stream:!1};e.maxOutputTokens!==void 0&&(n.max_tokens=e.maxOutputTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.top_p=e.topP),e.tools?.length&&(n.tools=e.tools.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema??{type:"object",properties:{}}}})));let o=await u(`${a}/chat/completions`,{method:"POST",headers:x(t,{...s.headers,...e.headers},c),body:JSON.stringify(n),signal:e.abortSignal});if(!o.ok)throw new Error(`Palbase AI HTTP ${o.status}: ${await o.text()}`);let d=await o.json(),r=d.choices?.[0],p=[];r?.message?.content&&p.push({type:"text",text:r.message.content});for(let i of r?.message?.tool_calls??[])p.push({type:"tool-call",toolCallId:i.id,toolName:i.function.name,input:i.function.arguments});let m=d.usage?.prompt_tokens??0,f=d.usage?.completion_tokens??0;return{content:p,finishReason:R(r?.finish_reason),usage:{inputTokens:m,outputTokens:f,totalTokens:d.usage?.total_tokens??m+f},warnings:[]}},async doStream(e){let n={model:l,messages:I(e.prompt),stream:!0,stream_options:{include_usage:!0}};e.maxOutputTokens!==void 0&&(n.max_tokens=e.maxOutputTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.top_p=e.topP),e.tools?.length&&(n.tools=e.tools.map(b=>({type:"function",function:{name:b.name,description:b.description,parameters:b.inputSchema??{type:"object",properties:{}}}})));let o=await u(`${a}/chat/completions`,{method:"POST",headers:x(t,{...s.headers,...e.headers},c),body:JSON.stringify(n),signal:e.abortSignal});if(!o.ok||!o.body)throw new Error(`Palbase AI stream HTTP ${o.status}: ${await o.text()}`);let d=o.body.getReader(),r=new TextDecoder,p="",m="stop",f={inputTokens:0,outputTokens:0,totalTokens:0},i=new Map;return{stream:new ReadableStream({async pull(b){for(;;){let v=p.indexOf(`
|
|
4
4
|
`);if(v>=0){let S=p.slice(0,v).trim();if(p=p.slice(v+1),!S.startsWith("data:"))continue;let A=S.slice(5).trim();if(A==="[DONE]"){for(let P of i.values())b.enqueue({type:"tool-call",toolCallId:P.id,toolName:P.name,input:P.args});i.clear(),b.enqueue({type:"finish",finishReason:m,usage:f}),b.close();return}try{let P=JSON.parse(A);if(P.usage){let h=P.usage.prompt_tokens??0,y=P.usage.completion_tokens??0;f={inputTokens:h,outputTokens:y,totalTokens:P.usage.total_tokens??h+y}}for(let h of P.choices??[]){h.finish_reason&&(m=R(h.finish_reason)),h.delta?.content&&b.enqueue({type:"text-delta",id:P.id??"text_0",delta:h.delta.content});for(let y of h.delta?.tool_calls??[]){let _=i.get(y.index)??{id:"",name:"",args:""};y.id&&(_.id=y.id),y.function?.name&&(_.name=y.function.name),y.function?.arguments&&(_.args+=y.function.arguments),i.set(y.index,_)}}}catch{}continue}let{value:$,done:C}=await d.read();if(C){for(let S of i.values())b.enqueue({type:"tool-call",toolCallId:S.id,toolName:S.name,input:S.args});b.enqueue({type:"finish",finishReason:m,usage:f}),b.close();return}p+=r.decode($,{stream:!0})}}})}}}),T=l=>({specificationVersion:"v2",provider:"palbase",modelId:l,maxEmbeddingsPerCall:1024,async doEmbed({values:c,abortSignal:e}){let n=await u(`${a}/embeddings`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,input:c}),signal:e});if(!n.ok)throw new Error(`Palbase AI embeddings HTTP ${n.status}: ${await n.text()}`);let o=await n.json();return{embeddings:(o.data??[]).map(d=>d.embedding),usage:{tokens:o.usage?.prompt_tokens??o.usage?.total_tokens??0}}}}),g=l=>({specificationVersion:"v2",provider:"palbase",modelId:l,async doGenerate({prompt:c,n:e=1,size:n,abortSignal:o}){let d=await u(`${a}/images/generations`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,prompt:c,n:e,size:n,response_format:"b64_json"}),signal:o});if(!d.ok)throw new Error(`Palbase AI images HTTP ${d.status}: ${await d.text()}`);return{images:((await d.json()).data??[]).map(p=>p.b64_json??p.url??""),warnings:[]}}}),E=l=>({specificationVersion:"v1",provider:"palbase",modelId:l,async doGenerate({audio:c,mediaType:e,language:n,diarization:o,abortSignal:d}){let r=new FormData;r.set("model",l),n&&r.set("language",n),o&&r.set("diarization","true"),r.set("file",new Blob([new Uint8Array(c)],{type:e}),"audio.wav");let p=x(t,s.headers);delete p["Content-Type"];let m=await u(`${a}/audio/transcriptions`,{method:"POST",headers:p,body:r,signal:d});if(!m.ok)throw new Error(`Palbase AI transcription HTTP ${m.status}: ${await m.text()}`);let f=await m.json();return{text:f.text,language:f.language,durationInSeconds:f.duration_seconds,segments:(f.segments??[]).map(i=>({speaker:i.speaker,startSecond:i.start,endSecond:i.end,text:i.text}))}}}),O=l=>({specificationVersion:"v1",provider:"palbase",modelId:l,async doGenerate({text:c,voice:e,outputFormat:n,speed:o,abortSignal:d}){let r=await u(`${a}/audio/speech`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,input:c,voice:e,response_format:n??"mp3",speed:o}),signal:d});if(!r.ok)throw new Error(`Palbase AI speech HTTP ${r.status}: ${await r.text()}`);return{audio:new Uint8Array(await r.arrayBuffer()),mediaType:r.headers.get("content-type")??"audio/mpeg"}}}),w=((l,c)=>k(l,c));return w.languageModel=k,w.textEmbeddingModel=T,w.image=g,w.transcription=E,w.speech=O,w}export{L as createPalbase};
|
package/dist/backend/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{ha as w,la as h}from"../chunks/
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ha as w,la as h}from"../chunks/UKONQ2R4.js";import"../chunks/SPMFD3LH.js";import"../chunks/7R5TMAGP.js";import"../chunks/3GR5ZPYK.js";import"../chunks/ZWASHVNO.js";import"../chunks/MT22R56P.js";import"../chunks/KWVOOFCB.js";import"../chunks/RBZI2C7M.js";import"../chunks/HT6TR6AZ.js";import"../chunks/UPJGT3BN.js";import"../chunks/GMCROKBB.js";import"../chunks/G37YLKYL.js";import"../chunks/XUEBLD7V.js";import"../chunks/7BSFT4SH.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.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=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
|
package/dist/backend/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{$ as It,A as $,B as ut,C as dt,D as pt,E as gt,F as mt,G as ft,H as ht,I as bt,J as yt,K as wt,L as kt,M as Pt,N as St,O as vt,P as Rt,Q as At,R as Et,S as _t,T as Ot,U as xt,V as Tt,W as Ct,X as se,Y as Bt,Z as Ft,_ as Lt,a as Z,aa as $t,b as ee,ba as Mt,c as te,ca as Dt,d as Ne,da as Ut,e as qe,ea as jt,f as Ke,fa as M,g as We,ga as Wt,h as Ve,ha as D,i as Ge,ia as G,j as He,ja as Vt,k as ze,ka as Gt,l as Je,m as Ye,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as nt,t as rt,u as st,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/7HDSHHGM.js";import{a as Nt,b as qt}from"../chunks/FYZAVXD4.js";import{a as oe}from"../chunks/53XWB3UV.js";import{a as v,b as ne,c as re,f as c,g as V,h as p,j as ae,k as Kt}from"../chunks/U5LDOZB5.js";import"../chunks/PF52QMPW.js";import"../chunks/RK4CTF2F.js";import{F as Q,G as X,d as C,j as Ue,k as je,l as Y,m as I}from"../chunks/4DNFXRTX.js";import"../chunks/AFO74GQQ.js";import"../chunks/IJBBBAXY.js";import{t as De}from"../chunks/OS567PDL.js";import"../chunks/WNPRCDLR.js";import"../chunks/DFIAGTHU.js";import{b as O,c as W}from"../chunks/ZRNXABQJ.js";import"../chunks/5NLCEWSD.js";import"../chunks/IIQ6QEL2.js";import"reflect-metadata";import{existsSync as z,writeFileSync as $n,writeSync as Mn}from"node:fs";import{createServer as Dn}from"node:http";import{dirname as x,join as J,resolve as Oe}from"node:path";import{Readable as Un}from"node:stream";var Ht=2e3,zt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Yt=512,U=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,n={}){this.sink=e,this.linesPerSecond=n.linesPerSecond??10,this.batchSize=Math.min(100,n.batchSize??100),this.flushMs=n.flushMs??2e3,this.maxPending=n.maxPending??2e3,this.sendMs=n.sendMs??zt,this.shutdownMs=n.shutdownMs??Ht,this.now=n.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,n,r=new Promise(a=>n=a),s=setTimeout(()=>{e=!0,n()},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(s)}e&&this.letGo()}letGo(){let e=this.inFlight,n=(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`))),n>0&&p.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${n} dropped`)}log(e){let n=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(n-this.refilled)/1e3*this.linesPerSecond),this.refilled=n,this.unlogged>0&&n-this.unloggedSince>=6e4&&(p.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=n),this.tokens<1){this.unlogged===0&&(this.unloggedSince=n),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",s=Math.round(e.durationMs*10)/10;p[r](`${e.method} ${e.path} ${e.status} ${s}ms`,{route:e.endpoint,status:e.status,duration_ms:s,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Yt),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),n=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let s=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return s.unref?.(),this.sending=(async()=>{try{await n.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),d=a.retryAfter;this.pausedUntil=this.now()+(typeof d=="number"&&d>0?d*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),p.warn(`[palbase] request traces were not sent to analytics (${i}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(s),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 Qt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{bind as Zt,bunDriver as en,createDatabase as tn,pooledBinding as nn,sayRunning as rn,envBlock as sn,createSearchWorker as an,cutOff as on,forgetUserIn as ln,MigrationOpen as cn,MigrationRefused as un,Migrator as ue,VersionNotMigrated as dn}from"palgres";import{toModel as pn}from"palgres/dsl";var gn=["start","complete","rollback","plan","status","types"],mn=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!gn.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let n of e)if(n.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function ge(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Xt(e,"utf8")}catch(n){throw new Error(`[palbase] db.access: ${e.href} could not be read (${n instanceof Error?n.message:String(n)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=ge(t);return pn(pe(t),e===void 0?{}:{access:e})}function fn(t){return t.tables.some(e=>e.search!==void 0)}function N(t){return t.access!==void 0||t.tables.some(e=>!e.ignored&&e.columns.some(n=>n.user!==void 0&&!n.ignored))}function me(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let n=Number(e);if(!Number.isSafeInteger(n)||n<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 n}function hn(t,e){if(t.url!==void 0||t.driver!==void 0)return;let n=e.PALBASE_DB_POOLED_URL;return n===void 0||n===""?void 0:n}function bn(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let n=Number(e);if(!Number.isSafeInteger(n)||n<4)throw new Error(`[palbase] PALBASE_DB_POOLED_CONNECTIONS is how many pooled connections the app keeps open, 4 at least \u2014 not ${e}`);return n}var yn=2,wn=5e3;async function kn(t,e,n=wn){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let s=r,a=!1,l=!1,i=async()=>{if(s!==void 0)try{await s.unsafe("SELECT 1");return}catch{s.release(),s=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(g){throw o.release(),g}a?o.release():s=o},d=setInterval(()=>{l||a||(l=!0,i().catch(o=>p.warn(`[palbase] database: the session that says this version runs could not be opened again (${o instanceof Error?o.message:String(o)}) \u2014 tried again in ${n/1e3} s`)).finally(()=>{l=!1}))},n);return d.unref?.(),{stop(){a=!0,clearInterval(d),s?.release(),s=void 0}}}function Pn(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 ie=5;function H(t,e){if(t.driver)return t.driver;let n=globalThis.Bun;if(!n)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 s=>{let a=new n.SQL({url:s,prepare:!1,max:r}),l=new n.SQL({url:s,prepare:!1,max:1});return{pool:{reserve:()=>a.reserve(),unsafe:(i,d)=>a.unsafe(i,d),begin:i=>a.begin(i)},engine:en(a,l),poolSize:r,close:async()=>{await a.close({timeout:ie}),await l.close({timeout:ie})}}}}async function fe(t){return t==="rollback"?(p.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(p.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function he(t,e){if(!t)return p.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let n=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=ge(t);return await B("types",sn(n,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function be(t,e,n){let r=e.PALBASE_DB_OWNER_URL;if(!r)return p.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let s=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!mn.test(s))return p.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=H(t,me(e)),l=a(r),i,d=o=>p.error(`[palbase] migrate ${n}: ${o}`);try{let o=F(t),g=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),p.info(f)},shadow:f=>{let k=new URL(r);k.pathname=`/${f}`;let y=a(k.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:s,fields:()=>Sn(e)});if(n==="plan"){let f=await g.plan(o);return await B(n,f),f.refusals.length>0?1:0}if(n==="status")return await B(n,await g.status()),0;let m=n==="start"?await vn(g,o,s):n==="complete"?await g.complete():await g.rollback();return p.info(`[palbase] migrate ${n}: done`,{result:m}),await B(n,m),0}catch(o){return o instanceof un?(p.error(`[palbase] migrate ${n}: refused`,{refusals:o.refusals}),d(`refused \u2014 ${o.refusals.join("; ")}`),1):on(o)?(p.error(`[palbase] migrate ${n}: cut off; run again, it goes on from where it stopped`,{error:o}),d(`cut off \u2014 ${i??le(o)}`),75):(p.error(`[palbase] migrate ${n}: failed`,{error:o}),d(`failed \u2014 ${le(o)}`),1)}finally{await l.close().catch(()=>{})}}async function Sn(t){let e=t.PALBASE_URL,n=t.PALBASE_SECRET_KEY;if(!e||!n)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let r=C({url:e,secretKey:n}).fields;return await r.load(),r.close(),r}async function vn(t,e,n){try{return await t.start(e)}catch(r){if(!(r instanceof cn)||n!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return p.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)}}var Rn=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,n=Rn){return new Promise(r=>n(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as It,A as $,B as ut,C as dt,D as pt,E as gt,F as mt,G as ft,H as ht,I as bt,J as yt,K as wt,L as kt,M as Pt,N as St,O as vt,P as Rt,Q as At,R as Et,S as _t,T as Ot,U as xt,V as Tt,W as Ct,X as se,Y as Bt,Z as Ft,_ as Lt,a as Z,aa as $t,b as ee,ba as Mt,c as te,ca as Dt,d as Ne,da as Ut,e as qe,ea as jt,f as Ke,fa as M,g as We,ga as Wt,h as Ve,ha as D,i as Ge,ia as G,j as He,ja as Vt,k as ze,ka as Gt,l as Je,m as Ye,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as nt,t as rt,u as st,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/UKONQ2R4.js";import{a as Nt,b as qt}from"../chunks/SPMFD3LH.js";import{a as oe}from"../chunks/2SVWIAAD.js";import{a as v,b as ne,c as re,f as c,g as V,h as p,j as ae,k as Kt}from"../chunks/7R5TMAGP.js";import"../chunks/3GR5ZPYK.js";import"../chunks/ZWASHVNO.js";import{F as Q,G as X,d as C,j as Ue,k as je,l as Y,m as I}from"../chunks/MT22R56P.js";import"../chunks/KWVOOFCB.js";import"../chunks/RBZI2C7M.js";import{t as De}from"../chunks/HT6TR6AZ.js";import"../chunks/UPJGT3BN.js";import"../chunks/GMCROKBB.js";import{b as O,c as W}from"../chunks/G37YLKYL.js";import"../chunks/XUEBLD7V.js";import"../chunks/7BSFT4SH.js";import"reflect-metadata";import{existsSync as z,writeFileSync as $n,writeSync as Mn}from"node:fs";import{createServer as Dn}from"node:http";import{dirname as x,join as J,resolve as Oe}from"node:path";import{Readable as Un}from"node:stream";var Ht=2e3,zt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Yt=512,U=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,n={}){this.sink=e,this.linesPerSecond=n.linesPerSecond??10,this.batchSize=Math.min(100,n.batchSize??100),this.flushMs=n.flushMs??2e3,this.maxPending=n.maxPending??2e3,this.sendMs=n.sendMs??zt,this.shutdownMs=n.shutdownMs??Ht,this.now=n.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,n,r=new Promise(a=>n=a),s=setTimeout(()=>{e=!0,n()},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(s)}e&&this.letGo()}letGo(){let e=this.inFlight,n=(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`))),n>0&&p.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${n} dropped`)}log(e){let n=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(n-this.refilled)/1e3*this.linesPerSecond),this.refilled=n,this.unlogged>0&&n-this.unloggedSince>=6e4&&(p.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=n),this.tokens<1){this.unlogged===0&&(this.unloggedSince=n),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",s=Math.round(e.durationMs*10)/10;p[r](`${e.method} ${e.path} ${e.status} ${s}ms`,{route:e.endpoint,status:e.status,duration_ms:s,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Yt),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),n=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let s=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return s.unref?.(),this.sending=(async()=>{try{await n.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),d=a.retryAfter;this.pausedUntil=this.now()+(typeof d=="number"&&d>0?d*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),p.warn(`[palbase] request traces were not sent to analytics (${i}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(s),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 Qt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{bind as Zt,bunDriver as en,createDatabase as tn,pooledBinding as nn,sayRunning as rn,envBlock as sn,createSearchWorker as an,cutOff as on,forgetUserIn as ln,MigrationOpen as cn,MigrationRefused as un,Migrator as ue,VersionNotMigrated as dn}from"palgres";import{toModel as pn}from"palgres/dsl";var gn=["start","complete","rollback","plan","status","types"],mn=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!gn.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let n of e)if(n.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function ge(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Xt(e,"utf8")}catch(n){throw new Error(`[palbase] db.access: ${e.href} could not be read (${n instanceof Error?n.message:String(n)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=ge(t);return pn(pe(t),e===void 0?{}:{access:e})}function fn(t){return t.tables.some(e=>e.search!==void 0)}function N(t){return t.access!==void 0||t.tables.some(e=>!e.ignored&&e.columns.some(n=>n.user!==void 0&&!n.ignored))}function me(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let n=Number(e);if(!Number.isSafeInteger(n)||n<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 n}function hn(t,e){if(t.url!==void 0||t.driver!==void 0)return;let n=e.PALBASE_DB_POOLED_URL;return n===void 0||n===""?void 0:n}function bn(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let n=Number(e);if(!Number.isSafeInteger(n)||n<4)throw new Error(`[palbase] PALBASE_DB_POOLED_CONNECTIONS is how many pooled connections the app keeps open, 4 at least \u2014 not ${e}`);return n}var yn=2,wn=5e3;async function kn(t,e,n=wn){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let s=r,a=!1,l=!1,i=async()=>{if(s!==void 0)try{await s.unsafe("SELECT 1");return}catch{s.release(),s=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(g){throw o.release(),g}a?o.release():s=o},d=setInterval(()=>{l||a||(l=!0,i().catch(o=>p.warn(`[palbase] database: the session that says this version runs could not be opened again (${o instanceof Error?o.message:String(o)}) \u2014 tried again in ${n/1e3} s`)).finally(()=>{l=!1}))},n);return d.unref?.(),{stop(){a=!0,clearInterval(d),s?.release(),s=void 0}}}function Pn(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 ie=5;function H(t,e){if(t.driver)return t.driver;let n=globalThis.Bun;if(!n)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 s=>{let a=new n.SQL({url:s,prepare:!1,max:r}),l=new n.SQL({url:s,prepare:!1,max:1});return{pool:{reserve:()=>a.reserve(),unsafe:(i,d)=>a.unsafe(i,d),begin:i=>a.begin(i)},engine:en(a,l),poolSize:r,close:async()=>{await a.close({timeout:ie}),await l.close({timeout:ie})}}}}async function fe(t){return t==="rollback"?(p.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(p.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function he(t,e){if(!t)return p.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let n=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=ge(t);return await B("types",sn(n,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function be(t,e,n){let r=e.PALBASE_DB_OWNER_URL;if(!r)return p.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let s=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!mn.test(s))return p.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=H(t,me(e)),l=a(r),i,d=o=>p.error(`[palbase] migrate ${n}: ${o}`);try{let o=F(t),g=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),p.info(f)},shadow:f=>{let k=new URL(r);k.pathname=`/${f}`;let y=a(k.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:s,fields:()=>Sn(e)});if(n==="plan"){let f=await g.plan(o);return await B(n,f),f.refusals.length>0?1:0}if(n==="status")return await B(n,await g.status()),0;let m=n==="start"?await vn(g,o,s):n==="complete"?await g.complete():await g.rollback();return p.info(`[palbase] migrate ${n}: done`,{result:m}),await B(n,m),0}catch(o){return o instanceof un?(p.error(`[palbase] migrate ${n}: refused`,{refusals:o.refusals}),d(`refused \u2014 ${o.refusals.join("; ")}`),1):on(o)?(p.error(`[palbase] migrate ${n}: cut off; run again, it goes on from where it stopped`,{error:o}),d(`cut off \u2014 ${i??le(o)}`),75):(p.error(`[palbase] migrate ${n}: failed`,{error:o}),d(`failed \u2014 ${le(o)}`),1)}finally{await l.close().catch(()=>{})}}async function Sn(t){let e=t.PALBASE_URL,n=t.PALBASE_SECRET_KEY;if(!e||!n)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let r=C({url:e,secretKey:n}).fields;return await r.load(),r.close(),r}async function vn(t,e,n){try{return await t.start(e)}catch(r){if(!(r instanceof cn)||n!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return p.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)}}var Rn=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,n=Rn){return new Promise(r=>n(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,r))}function le(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
4
|
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function An(t,e){try{return await new ue(t).plan(e)}catch{return}}var ce="palbase.idempotency_keys.response_body";function En(t,e){let n=null,r=!1,s=async()=>{let i=e.currentKey();if(!(r||i===n)){r=!0;try{let d=await t.reseal();n=i;let o=d.reduce((g,m)=>g+m.resealed,0);o>0&&p.info(`[palbase] fields: ${o} value(s) sealed again with key ${i}`,{report:d})}catch(d){p.warn(`[palbase] fields: sealing again with key ${i} stopped; tried again in a minute`,{error:d})}finally{r=!1}}},a=setTimeout(s,1e4),l=setInterval(s,6e4);for(let i of[a,l])i.unref?.();return()=>{clearTimeout(a),clearInterval(l)}}var j=class extends Error{digest;plan;constructor(e,n){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>)`,...n?_n(n):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=n}};function _n(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 n of t.changes)e.push(` + ${n}`);for(let n of t.refusals)e.push(` \u2717 ${n}`);return e}var On=8e4;async function ye(t,e,n,r){let s=t.url??e.PALBASE_DB_URL;if(!s)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=pe(t),l=F(t),i=hn(t,e),d=H(t,i===void 0?me(e):yn)(s),o,g;try{let m=!1,f=b=>{m||(m=!0,p.warn(`[palbase] database: not answering yet (${b instanceof Error?b.message:String(b)}) \u2014 waiting for it, as one waking does`))},k=await Zt(d.engine,l,{waitMs:r.onPlatform?On:0,onUnreachable:f}).catch(async b=>{throw r.onPlatform||!(b instanceof dn)?b:new j(b.digest,await An(d.pool,l))});i!==void 0&&(g=await kn(d.pool,rn(k)),o=H(t,bn(e))(i));let y=o??d,R=Qt("sha256",n).update("palgres page cursor").digest("hex"),w=t.embed??r.embed,h=r.fields,A=await tn({sql:y.engine,schemas:a,binding:o===void 0?k:nn(k),...o===void 0?{}:{prepare:!1},cursorSecret:R,admission:Pn(y.poolSize),embed:w,log:b=>p.warn(`[palbase] ${b}`),fields:async()=>(await h.load(),h)}),E=h.loaded?En(A,h):()=>{},_=fn(l)?an({sql:y.engine,embed:w,log:b=>p.info(`[palbase] ${b}`)}):void 0;return{model:l,binding:k,app:A,requests:t.requests??"caller",forget:(b,P)=>ln({attempt:S=>P.$attempt(S)},k,l,b),..._?{search:_}:{},keptAnswers:{seal:b=>h.loaded?h.encrypt(ce,b):b,open:async b=>h.isEncrypted(b)?(h.loaded||await h.load(),h.decrypt(ce,b)):b},close:async()=>{E(),h.close(),await o?.close(),g?.stop(),await d.close()}}}catch(m){throw await o?.close().catch(()=>{}),g?.stop(),await d.close(),m}}function xn(t){let e=Buffer.from(t,"base64"),n=new Array(e.byteLength/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function we(t){return async({texts:e,model:n,dimensions:r})=>{let{data:s}=await t.ai.createEmbeddings({body:{input:e,model:n,dimensions:r}});return{model:s.model,vectors:s.vectors.map(xn)}}}var Tn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ke(t,e,n){let r=[],s=t.url??e.PALBASE_URL??"",a="";try{let g=new URL(s);a=g.origin,g.protocol!=="https:"&&g.hostname!=="localhost"&&g.hostname!=="127.0.0.1"&&r.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(g.pathname!=="/"||g.search||g.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??"";Tn.test(l)||r.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let i=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(i)||r.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let d=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;d!==void 0&&!/^[0-9a-f]{64}$/.test(d)&&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 o=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(n.needsWebhookSecret&&(d!==void 0||o!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(o??"")&&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:
|
|
@@ -9,4 +9,4 @@ ${r.join(`
|
|
|
9
9
|
`)}
|
|
10
10
|
`}async function ve(t,e,n=Bn){let r=Buffer.from(e,"utf8");for(let s=0;s<r.length;)try{s+=n(t,r,s,r.length-s)}catch(a){if(a.code!=="EAGAIN")throw a;await new Promise(l=>setTimeout(l,5))}}var Re=2e4,Ae=5e3,jn=15e3,Nn="/_palbase/health";function qn(t){let e=new Set,n=r=>{if(e.has(r))return!1;e.add(r);let s=$(r,Z);return s?s.providers.some(a=>$(a,ee)!==void 0&&$(a,te)===void 0)||s.imports.some(n):!1};return t.some(n)}var Kn={async create(t,e={}){let n=Array.isArray(t)?t:[t],r=e.env??process.env,s=de(r);if(s!==void 0){let P=s==="types"?await he(e.db):e.db?await be(e.db,r,s):await fe(s);throw process.exit(P),new q(P)}let a=r.PALBASE_CONTRACT_OUT;if(a){let P;try{await _e(Ee(r)),P=await Wn(n,e,r)}catch(S){throw Mn(2,`[palbase] the contract: ${S instanceof Error?S.message:String(S)}
|
|
11
11
|
`),process.exit(1),new L}throw a==="/dev/stdout"?await ve(1,Se(P)):$n(a,`${P}
|
|
12
|
-
`),process.exit(0),new L}let l=Ee(r),i=await _e(l);i&&p.info(`[palbase] strings: ${i.source} and ${i.locales.length-1} other language(s), ${Object.keys(i.strings).length} sentence(s), from ${l}/palbase/strings`),ae(i?void 0:l);let d=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&p.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&&p.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let g=qn(n)||d!==void 0&&N(d),m=ke(e.palbase??{},r,{needsWebhookSecret:g});g&&m.webhookSecret===void 0&&p.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 f=C({url:m.url,secretKey:m.secretKey}),k=e.port??Number(r.PORT??"8080");if(!Number.isInteger(k)||k<0||k>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let y=e.db?await ye(e.db,r,m.secretKey,{onPlatform:m.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&p.info(`[palbase] database: version ${y.binding.version}`);let R=y&&N(y.model)?{"user.deleted":[P=>Vn(y,P)]}:void 0,w=m.platformSecret===void 0?void 0:{secret:m.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),A=()=>D({modules:n,verifier:new I({issuer:m.url,projectId:m.projectId,standing:Y({url:m.url,secretKey:m.secretKey})}),server:f,webhookSecret:m.webhookSecret,env:r,projectId:m.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zn(e.cors,r.PALBASE_WEB_ORIGINS),platform:w,events:R,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:i}),E=A(),_=e.boot?.attempts??5,b=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(S){if(P>=_)throw p.error(`[palbase] the app did not start after ${_} attempts`,{error:S}),S;p.warn(`[palbase] the app did not start (attempt ${P} of ${_}); trying again in ${b} ms`,{error:S}),await new Promise(Me=>setTimeout(Me,b)),b*=2,E=A()}return Gn(E,f,k,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let n=x(Oe(e));for(;!z(J(n,"package.json"))&&x(n)!==n;)n=x(n);return z(J(n,"package.json"))?n:process.cwd()}async function _e(t){try{return await oe(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Wn(t,e,n){let r=Oe(n.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 s=x(r);for(;!z(J(s,"package.json"))&&x(s)!==s;)s=x(s);let{analyzeProject:a}=await import("../chunks/QJPQVLNV.js"),{routeContracts:l}=await import("../chunks/SS3YF6MP.js"),i=a(s,r);for(let g of i.warnings)p.warn(`[palbase] the contract: ${g}`);let d="https://contract.palbase.invalid",o=D({modules:t,verifier:new I({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:C({url:d,secretKey:"pb_contract_s"}),env:n,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(i.routes),errors:se()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var L=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},q=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Vn(t,e){let n=e.data?.user_id;if(typeof n!="string"||n==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(n,V.$asService());p.info(`[palbase] user ${n} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them${r.relationships===void 0?"":`, ${r.relationships} relationship(s) of the access schema taken back`}`)}async function Gn(t,e,n,r,s,a){let l,i={on:!1},d=(w,h)=>new URL(w.url).pathname===Nn&&w.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(w,h),o=Dn((w,h)=>{Hn(d,w,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((w,h)=>{o.once("error",h),o.listen(n,r,()=>w())})}catch(w){throw await t.stop(),await a?.close(),w}let g=o.address().port;p.info(`[palbase] serving ${t.routes.length} route(s) on :${g}`,{routes:t.routes}),a?.search?.start();let m=w=>l??=(async()=>{p.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let A=setTimeout(()=>o.closeAllConnections(),w);await h,clearTimeout(A),process.off("SIGINT",y),process.off("uncaughtException",R),process.off("unhandledRejection",R);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>m(Re),k=!1,y=()=>{if(k){p.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}k=!0;let w=setTimeout(()=>{p.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Re+jn);w.unref(),f().then(()=>{clearTimeout(w),process.exit(0)},h=>{clearTimeout(w),p.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},R=w=>{p.error("[palbase] the app crashed; stopping so the machine starts it again",{error:w});let h=setTimeout(()=>process.exit(1),Ae+1e3);m(Ae).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),s&&(process.on("uncaughtException",R),process.on("unhandledRejection",R)),{routes:t.routes,palbase:e,port:g,handle:d,close:f}}async function Hn(t,e,n,r){try{let s=e.url??"/",a;try{if(!s.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${s}`)}catch{n.statusCode=400,n.end();return}let l=new Headers;for(let[m,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let k of f)l.append(m,k);else l.set(m,f);let i=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;n.on("close",()=>{n.writableFinished||d.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Un.toWeb(e):void 0,duplex:"half",signal:d.signal}),g=await t(o,{remoteAddress:e.socket.remoteAddress,target:s});if(n.statusCode=g.status,g.headers.forEach((m,f)=>n.setHeader(f,m)),r.on&&n.setHeader("connection","close"),g.body)for await(let m of g.body)n.write(m);n.end()}catch(s){p.error("[palbase] the request could not be answered",{error:s}),n.headersSent||(n.statusCode=500),n.end()}}function zn(t,e,n=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let s=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&n(`[palbase] the project's web origins ${a.map(i=>JSON.stringify(i)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let l=[...new Set([...t?.origins??[],...s])];return l.length===0?t:{...t,origins:l}}import{bigint as cs,boolean as us,check as ds,date as ps,defineSchema as gs,defineTable as ms,enumType as fs,foreignKey as hs,index as bs,integer as ys,jsonb as ws,numeric as ks,ownedByUser as Ps,policy as Ss,raw as vs,sqlType as Rs,text as As,timestamp as Es,userRef as _s,uuid as Os}from"palgres/dsl";import{AccessRefused as Ts}from"palgres";import{increment as Bs,now as Fs}from"palgres";function T(t){if(t instanceof O)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function u(t,e){try{let n=await t();return{data:await e(n.data),error:null,status:n.status}}catch(n){return T(n)}}var Jn=v("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yn=100,Qn=1e3,Xn=168*3600,Zn={s:1,m:60,h:3600,d:86400};function er(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let n=0;for(let[,r,,s]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))n+=Math.round(Number(r)*Zn[s]*1e3);return Math.ceil(n/1e3)}function Ie(t,e,n){let r="getPublicUrl",s;try{s=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof O&&l.code==="invalid_path_parameter"?new O({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):l}let a=`${c.url}/storage/public/${W(r,"bucket",t)}/${s}`;return n?`${a}?variant=${encodeURIComponent(n)}`:a}function xe(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,Ie(t.bucket,t.path,e)]))}}function tr(t){return{async upload(e,n,r){let s=r?.contentType??(n instanceof Blob&&n.type!==""?n.type:void 0);try{let a=await c.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:n,contentType:s});return{data:xe(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}:T(a)}},async download(e){try{let n=await c.storage.getObject({path:{bucket:t,path:e}});if(n.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=n.data;try{return{data:await r.blob(),error:null,status:n.status}}catch(s){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${s instanceof Error?s.message:String(s)}`},status:0}}}catch(n){return T(n)}},getPublicUrl(e,n){return Ie(t,e,n?.variant)},async createSignedUrl(e,n){let r=er(n?.expiresIn);return r===void 0||r<1||r>Xn?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(n?.expiresIn)})`},status:400}:u(()=>c.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),s=>({signedUrl:s.url,expiresAt:s.expires_at}))},async list(e,n){let r=n?.limit??Yn,s=n?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(s)||s<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,i=200;try{for(;a.length<r;){let d=Math.max(1,Math.min(Qn,s+r-a.length)),o=await c.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...l?{cursor:l}:{}}});i=o.status;for(let g of o.data.objects)s>0?s--:a.length<r&&a.push(xe(g));if(l=o.data.next_cursor,!l)break}}catch(d){return T(d)}return{data:a,error:null,status:i}},async remove(e){let n=[];for(let r of e){try{await c.storage.deleteObject({path:{bucket:t,path:r}})}catch(s){return T(s)}n.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:n,error:null,status:200}},move(e,n){return u(()=>c.storage.moveObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})},copy(e,n){return u(()=>c.storage.copyObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})}}}var nr={bucket:tr},Te=t=>ne("Storage",t,nr),rr={bucket:t=>Te("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Te("buckets").bucket(e):void 0})},sr=v("Notifications",{push:{send(t){let{to:e,...n}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return u(()=>c.notify.sendPush({body:{...n,to:r}}),s=>({message_ids:s.message_ids,recipients:s.message_ids.length,skipped_user_ids:s.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:n,...r}=t,s={...r,...n!==void 0?{template:n}:{}};if(!Array.isArray(e))return u(()=>c.notify.sendEmail({body:{...s,to:e}}),i=>({...i.message_id!==void 0?{message_id:i.message_id}:{},...i.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let i of e)try{let d=await c.notify.sendEmail({body:{...s,to:i}});l=d.status,a.push(d.data.message_id??null)}catch(d){return T(d)}return{data:{message_ids:a},error:null,status:l}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function $e(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:$e();return u(()=>e?c.flags.getUserValues({path:{user_id:e}}):c.flags.getValues(),n=>n.values??{})}var Le={setOverrideForUser:(t,e,n)=>u(()=>c.flags.putUserValue({path:{user_id:t,key:e},body:{value:n}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>u(()=>c.flags.putUserValues({path:{user_id:t},body:{values:e}}),n=>({values:n.values??{}})),clearOverrideForUser:(t,e)=>u(()=>c.flags.deleteUserValue({path:{user_id:t,key:e}}),n=>({key:n.key,value:n.value,source:Fe(n.source)})),clearAllOverridesForUser:t=>u(()=>c.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>u(()=>c.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},or=v("Flags",{async isEnabled(t,e){let n=r=>(p.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?n(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return n(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let n=await K(e);return n.error?{data:null,error:n.error,status:n.status}:{data:Be(n.data[t]),error:null,status:n.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([n,r])=>{let s=Be(r);return{name:n,enabled:Ce(r),...s?{variant:s}:{}}}),error:null,status:e.status}},async get(t,e,n){let r,s=!1,a;n!==void 0?(r=e,s=!0,a=n):ar(e)?a=e:e!==void 0&&(r=e,s=!0);let l=await K(a);if(l.error)return s?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?r??null:i,error:null,status:l.status}},async setOverride(t,e){let n=$e();return n?Le.setOverrideForUser(n,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 Le}}),ir=v("Realtime",{broadcast(t,e,n){return u(()=>c.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:n??{}}]}}),()=>{})},state:{set(t,e,n){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,value:n}]}}),()=>{})},clear(t,e){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}}),lr=v("Commerce",{getSettings(){return u(()=>c.commerce.getCommerceSettings({}),t=>t)},listStores(t){return u(()=>c.commerce.listStores({query:t}),e=>e)},listProducts(t){return u(()=>c.commerce.listProducts({query:t}),e=>e)},createQuickProduct(t){return u(()=>c.commerce.createQuickProduct({body:t}),e=>e)},getOrder(t){return u(()=>c.commerce.getOrder({path:{order_id:t}}),e=>e)},listOrders(t){return u(()=>c.commerce.listOrders({query:t}),e=>e)},listStoreOrders(t){return u(()=>c.commerce.listStoreOrders({query:t}),e=>e)},adjustInventory(t){return u(()=>c.commerce.adjustInventory({body:t}),e=>e)},recomputeBuyBox(t){return u(()=>c.commerce.recomputeVariantBuyBox({path:{variant_id:t}}),e=>e)}}),cr=v("Promotions",{listRules(t){return u(()=>c.commerce.listPromotionRules({query:t}),e=>e)},createRule(t){return u(()=>c.commerce.createPromotionRule({body:t}),e=>e)},evaluate(t){return u(()=>c.commerce.evaluatePromotions({body:t}),e=>e)},hold(t){return u(()=>c.commerce.holdPromotions({body:t}),e=>e)},commitHold(t,e={}){return u(()=>c.commerce.commitPromotionHold({path:{hold_id:t},body:e}),n=>n)},releaseHold(t){return u(()=>c.commerce.releasePromotionHold({path:{hold_id:t}}),e=>e)},reverseRedemption(t){return u(()=>c.commerce.reversePromotionRedemption({path:{redemption_id:t}}),e=>e)}}),ur=v("Campaigns",{listBroadcasts(){return u(()=>c.campaigns.listBroadcasts({}),t=>t)},createBroadcast(t){return u(()=>c.campaigns.createBroadcast({body:t}),e=>e)},startBroadcast(t){return u(()=>c.campaigns.startBroadcast({path:{id:t}}),e=>e)},pauseBroadcast(t){return u(()=>c.campaigns.pauseBroadcast({path:{id:t}}),e=>e)},cancelBroadcast(t){return u(()=>c.campaigns.cancelBroadcast({path:{id:t}}),e=>e)},getBroadcastStats(t){return u(()=>c.campaigns.getBroadcastStats({path:{id:t}}),e=>e)},recordConversion(t){return u(()=>c.campaigns.recordBroadcastConversion({body:t}),e=>e)},listOnSite(){return u(()=>c.campaigns.listOnSiteCampaigns({}),t=>t)},createOnSite(t){return u(()=>c.campaigns.createOnSiteCampaign({body:t}),e=>e)},listTrackingLinks(){return u(()=>c.campaigns.listTrackingLinks({}),t=>t)},createTrackingLink(t){return u(()=>c.campaigns.createTrackingLink({body:t}),e=>e)},attributeLinkConversion(t){return u(()=>c.campaigns.attributeLinkConversion({body:t}),e=>e)}}),dr=v("Journeys",{list(t){return u(()=>c.journeys.listJourneys({query:t}),e=>e)},get(t){return u(()=>c.journeys.getJourney({path:{key:t}}),e=>e)},validate(t){return u(()=>c.journeys.validateJourney({body:{definition:t}}),e=>e)},publish(t){return u(()=>c.journeys.publishJourney({path:{key:t}}),e=>e)},stop(t){return u(()=>c.journeys.stopJourney({path:{key:t}}),e=>e)},listBlueprints(){return u(()=>c.journeys.listBlueprints({}),t=>t)},listStoreBlueprints(t){return u(()=>c.journeys.listStoreBlueprints({path:{store_id:t}}),e=>e)},activateStoreBlueprint(t,e){return u(()=>c.journeys.activateStoreBlueprint({path:{store_id:t},body:e}),n=>n)},deleteStoreBlueprint(t,e){return u(()=>c.journeys.deleteStoreBlueprint({path:{store_id:t,key:e}}),()=>{})}});import{z as Ns}from"zod";export{Ts as AccessRefused,rt as AttestedDevice,je as AuthUnavailable,Pt as Authorize,Ft as BadRequest,ze as Body,Vt as CACHE_MAX_TTL,Gt as Cache,ur as Campaigns,yt as ChatPart,nt as Client,lr as Commerce,Lt as Conflict,L as ContractRunEnded,Ne as Controller,lt as Cron,V as Database,It as DeadlockDetected,Ge as Delete,Ot as DiError,De as EVENT_TYPES,or as Flags,Ct as Forbidden,kt as Gateway,wt as GatewayRefusal,qe as Get,Ye as Headers,$t as HttpError,at as Injectable,dr as Journeys,p as Log,Wt as MAX_BODY_BYTES,q as MigrationRunEnded,ot as Module,Mt as NotFound,sr as Notifications,it as On,vt as OnConnect,Rt as OnDisconnect,At as OnEmpty,St as OnFirst,Ze as OptionalUser,xt as PalError,c as Palbase,O as PalbaseError,Kn as PalbaseFactory,Qe as Param,Ve as Patch,Ke as Post,cr as Promotions,We as Put,He as Query,Je as QueryParams,ir as Realtime,et as Req,tt as RequestId,st as Resolve,j as SchemaNotPushed,Jn as Secrets,Dt as SerializationFailure,rr as Storage,Et as Subscribe,gt as Task,pt as TaskFailure,mt as Tasks,ft as TestUserTemplate,Ue as TokenError,I as TokenVerifier,Ut as TooManyRequests,Tt as Unauthorized,jt as UniqueViolation,ht as Upload,bt as UploadedObject,Xe as User,ct as Webhook,cs as bigint,us as boolean,ds as check,D as createApp,ps as date,Bt as defineError,gs as defineSchema,ms as defineTable,qt as encrypt,Nt as encrypted,fs as enumType,hs as foreignKey,ut as getRegisteredControllers,dt as getRoutes,_t as getWebhookManifest,Bs as increment,bs as index,ys as integer,ws as jsonb,Fs as now,ks as numeric,Ps as ownedByUser,Ss as policy,vs as raw,Rs as sqlType,Kt as t,As as text,Es as timestamp,_s as userRef,Os as uuid,Ns as z};
|
|
12
|
+
`),process.exit(0),new L}let l=Ee(r),i=await _e(l);i&&p.info(`[palbase] strings: ${i.source} and ${i.locales.length-1} other language(s), ${Object.keys(i.strings).length} sentence(s), from ${l}/palbase/strings`),ae(i?void 0:l);let d=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&p.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&&p.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let g=qn(n)||d!==void 0&&N(d),m=ke(e.palbase??{},r,{needsWebhookSecret:g});g&&m.webhookSecret===void 0&&p.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 f=C({url:m.url,secretKey:m.secretKey}),k=e.port??Number(r.PORT??"8080");if(!Number.isInteger(k)||k<0||k>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let y=e.db?await ye(e.db,r,m.secretKey,{onPlatform:m.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&p.info(`[palbase] database: version ${y.binding.version}`);let R=y&&N(y.model)?{"user.deleted":[P=>Vn(y,P)]}:void 0,w=m.platformSecret===void 0?void 0:{secret:m.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),A=()=>D({modules:n,verifier:new I({issuer:m.url,projectId:m.projectId,standing:Y({url:m.url,secretKey:m.secretKey})}),server:f,webhookSecret:m.webhookSecret,env:r,projectId:m.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zn(e.cors,r.PALBASE_WEB_ORIGINS),platform:w,events:R,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:i}),E=A(),_=e.boot?.attempts??5,b=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(S){if(P>=_)throw p.error(`[palbase] the app did not start after ${_} attempts`,{error:S}),S;p.warn(`[palbase] the app did not start (attempt ${P} of ${_}); trying again in ${b} ms`,{error:S}),await new Promise(Me=>setTimeout(Me,b)),b*=2,E=A()}return Gn(E,f,k,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let n=x(Oe(e));for(;!z(J(n,"package.json"))&&x(n)!==n;)n=x(n);return z(J(n,"package.json"))?n:process.cwd()}async function _e(t){try{return await oe(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Wn(t,e,n){let r=Oe(n.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 s=x(r);for(;!z(J(s,"package.json"))&&x(s)!==s;)s=x(s);let{analyzeProject:a}=await import("../chunks/POURMU7G.js"),{routeContracts:l}=await import("../chunks/5NZNKECX.js"),i=a(s,r);for(let g of i.warnings)p.warn(`[palbase] the contract: ${g}`);let d="https://contract.palbase.invalid",o=D({modules:t,verifier:new I({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:C({url:d,secretKey:"pb_contract_s"}),env:n,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(i.routes),errors:se()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var L=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},q=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Vn(t,e){let n=e.data?.user_id;if(typeof n!="string"||n==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(n,V.$asService());p.info(`[palbase] user ${n} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them${r.relationships===void 0?"":`, ${r.relationships} relationship(s) of the access schema taken back`}`)}async function Gn(t,e,n,r,s,a){let l,i={on:!1},d=(w,h)=>new URL(w.url).pathname===Nn&&w.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(w,h),o=Dn((w,h)=>{Hn(d,w,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((w,h)=>{o.once("error",h),o.listen(n,r,()=>w())})}catch(w){throw await t.stop(),await a?.close(),w}let g=o.address().port;p.info(`[palbase] serving ${t.routes.length} route(s) on :${g}`,{routes:t.routes}),a?.search?.start();let m=w=>l??=(async()=>{p.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let A=setTimeout(()=>o.closeAllConnections(),w);await h,clearTimeout(A),process.off("SIGINT",y),process.off("uncaughtException",R),process.off("unhandledRejection",R);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>m(Re),k=!1,y=()=>{if(k){p.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}k=!0;let w=setTimeout(()=>{p.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Re+jn);w.unref(),f().then(()=>{clearTimeout(w),process.exit(0)},h=>{clearTimeout(w),p.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},R=w=>{p.error("[palbase] the app crashed; stopping so the machine starts it again",{error:w});let h=setTimeout(()=>process.exit(1),Ae+1e3);m(Ae).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),s&&(process.on("uncaughtException",R),process.on("unhandledRejection",R)),{routes:t.routes,palbase:e,port:g,handle:d,close:f}}async function Hn(t,e,n,r){try{let s=e.url??"/",a;try{if(!s.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${s}`)}catch{n.statusCode=400,n.end();return}let l=new Headers;for(let[m,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let k of f)l.append(m,k);else l.set(m,f);let i=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;n.on("close",()=>{n.writableFinished||d.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Un.toWeb(e):void 0,duplex:"half",signal:d.signal}),g=await t(o,{remoteAddress:e.socket.remoteAddress,target:s});if(n.statusCode=g.status,g.headers.forEach((m,f)=>n.setHeader(f,m)),r.on&&n.setHeader("connection","close"),g.body)for await(let m of g.body)n.write(m);n.end()}catch(s){p.error("[palbase] the request could not be answered",{error:s}),n.headersSent||(n.statusCode=500),n.end()}}function zn(t,e,n=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let s=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&n(`[palbase] the project's web origins ${a.map(i=>JSON.stringify(i)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let l=[...new Set([...t?.origins??[],...s])];return l.length===0?t:{...t,origins:l}}import{bigint as cs,boolean as us,check as ds,date as ps,defineSchema as gs,defineTable as ms,enumType as fs,foreignKey as hs,index as bs,integer as ys,jsonb as ws,numeric as ks,ownedByUser as Ps,policy as Ss,raw as vs,sqlType as Rs,text as As,timestamp as Es,userRef as _s,uuid as Os}from"palgres/dsl";import{AccessRefused as Ts}from"palgres";import{increment as Bs,now as Fs}from"palgres";function T(t){if(t instanceof O)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function u(t,e){try{let n=await t();return{data:await e(n.data),error:null,status:n.status}}catch(n){return T(n)}}var Jn=v("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yn=100,Qn=1e3,Xn=168*3600,Zn={s:1,m:60,h:3600,d:86400};function er(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let n=0;for(let[,r,,s]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))n+=Math.round(Number(r)*Zn[s]*1e3);return Math.ceil(n/1e3)}function Ie(t,e,n){let r="getPublicUrl",s;try{s=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof O&&l.code==="invalid_path_parameter"?new O({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):l}let a=`${c.url}/storage/public/${W(r,"bucket",t)}/${s}`;return n?`${a}?variant=${encodeURIComponent(n)}`:a}function xe(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,Ie(t.bucket,t.path,e)]))}}function tr(t){return{async upload(e,n,r){let s=r?.contentType??(n instanceof Blob&&n.type!==""?n.type:void 0);try{let a=await c.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:n,contentType:s});return{data:xe(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}:T(a)}},async download(e){try{let n=await c.storage.getObject({path:{bucket:t,path:e}});if(n.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=n.data;try{return{data:await r.blob(),error:null,status:n.status}}catch(s){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${s instanceof Error?s.message:String(s)}`},status:0}}}catch(n){return T(n)}},getPublicUrl(e,n){return Ie(t,e,n?.variant)},async createSignedUrl(e,n){let r=er(n?.expiresIn);return r===void 0||r<1||r>Xn?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(n?.expiresIn)})`},status:400}:u(()=>c.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),s=>({signedUrl:s.url,expiresAt:s.expires_at}))},async list(e,n){let r=n?.limit??Yn,s=n?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(s)||s<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,i=200;try{for(;a.length<r;){let d=Math.max(1,Math.min(Qn,s+r-a.length)),o=await c.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...l?{cursor:l}:{}}});i=o.status;for(let g of o.data.objects)s>0?s--:a.length<r&&a.push(xe(g));if(l=o.data.next_cursor,!l)break}}catch(d){return T(d)}return{data:a,error:null,status:i}},async remove(e){let n=[];for(let r of e){try{await c.storage.deleteObject({path:{bucket:t,path:r}})}catch(s){return T(s)}n.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:n,error:null,status:200}},move(e,n){return u(()=>c.storage.moveObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})},copy(e,n){return u(()=>c.storage.copyObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})}}}var nr={bucket:tr},Te=t=>ne("Storage",t,nr),rr={bucket:t=>Te("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Te("buckets").bucket(e):void 0})},sr=v("Notifications",{push:{send(t){let{to:e,...n}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return u(()=>c.notify.sendPush({body:{...n,to:r}}),s=>({message_ids:s.message_ids,recipients:s.message_ids.length,skipped_user_ids:s.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:n,...r}=t,s={...r,...n!==void 0?{template:n}:{}};if(!Array.isArray(e))return u(()=>c.notify.sendEmail({body:{...s,to:e}}),i=>({...i.message_id!==void 0?{message_id:i.message_id}:{},...i.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let i of e)try{let d=await c.notify.sendEmail({body:{...s,to:i}});l=d.status,a.push(d.data.message_id??null)}catch(d){return T(d)}return{data:{message_ids:a},error:null,status:l}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function $e(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:$e();return u(()=>e?c.flags.getUserValues({path:{user_id:e}}):c.flags.getValues(),n=>n.values??{})}var Le={setOverrideForUser:(t,e,n)=>u(()=>c.flags.putUserValue({path:{user_id:t,key:e},body:{value:n}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>u(()=>c.flags.putUserValues({path:{user_id:t},body:{values:e}}),n=>({values:n.values??{}})),clearOverrideForUser:(t,e)=>u(()=>c.flags.deleteUserValue({path:{user_id:t,key:e}}),n=>({key:n.key,value:n.value,source:Fe(n.source)})),clearAllOverridesForUser:t=>u(()=>c.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>u(()=>c.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},or=v("Flags",{async isEnabled(t,e){let n=r=>(p.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?n(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return n(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let n=await K(e);return n.error?{data:null,error:n.error,status:n.status}:{data:Be(n.data[t]),error:null,status:n.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([n,r])=>{let s=Be(r);return{name:n,enabled:Ce(r),...s?{variant:s}:{}}}),error:null,status:e.status}},async get(t,e,n){let r,s=!1,a;n!==void 0?(r=e,s=!0,a=n):ar(e)?a=e:e!==void 0&&(r=e,s=!0);let l=await K(a);if(l.error)return s?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?r??null:i,error:null,status:l.status}},async setOverride(t,e){let n=$e();return n?Le.setOverrideForUser(n,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 Le}}),ir=v("Realtime",{broadcast(t,e,n){return u(()=>c.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:n??{}}]}}),()=>{})},state:{set(t,e,n){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,value:n}]}}),()=>{})},clear(t,e){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}}),lr=v("Commerce",{getSettings(){return u(()=>c.commerce.getCommerceSettings({}),t=>t)},listStores(t){return u(()=>c.commerce.listStores({query:t}),e=>e)},listProducts(t){return u(()=>c.commerce.listProducts({query:t}),e=>e)},createQuickProduct(t){return u(()=>c.commerce.createQuickProduct({body:t}),e=>e)},getOrder(t){return u(()=>c.commerce.getOrder({path:{order_id:t}}),e=>e)},listOrders(t){return u(()=>c.commerce.listOrders({query:t}),e=>e)},listStoreOrders(t){return u(()=>c.commerce.listStoreOrders({query:t}),e=>e)},adjustInventory(t){return u(()=>c.commerce.adjustInventory({body:t}),e=>e)},recomputeBuyBox(t){return u(()=>c.commerce.recomputeVariantBuyBox({path:{variant_id:t}}),e=>e)}}),cr=v("Promotions",{listRules(t){return u(()=>c.commerce.listPromotionRules({query:t}),e=>e)},createRule(t){return u(()=>c.commerce.createPromotionRule({body:t}),e=>e)},evaluate(t){return u(()=>c.commerce.evaluatePromotions({body:t}),e=>e)},hold(t){return u(()=>c.commerce.holdPromotions({body:t}),e=>e)},commitHold(t,e={}){return u(()=>c.commerce.commitPromotionHold({path:{hold_id:t},body:e}),n=>n)},releaseHold(t){return u(()=>c.commerce.releasePromotionHold({path:{hold_id:t}}),e=>e)},reverseRedemption(t){return u(()=>c.commerce.reversePromotionRedemption({path:{redemption_id:t}}),e=>e)}}),ur=v("Campaigns",{listBroadcasts(){return u(()=>c.campaigns.listBroadcasts({}),t=>t)},createBroadcast(t){return u(()=>c.campaigns.createBroadcast({body:t}),e=>e)},startBroadcast(t){return u(()=>c.campaigns.startBroadcast({path:{id:t}}),e=>e)},pauseBroadcast(t){return u(()=>c.campaigns.pauseBroadcast({path:{id:t}}),e=>e)},cancelBroadcast(t){return u(()=>c.campaigns.cancelBroadcast({path:{id:t}}),e=>e)},getBroadcastStats(t){return u(()=>c.campaigns.getBroadcastStats({path:{id:t}}),e=>e)},recordConversion(t){return u(()=>c.campaigns.recordBroadcastConversion({body:t}),e=>e)},listOnSite(){return u(()=>c.campaigns.listOnSiteCampaigns({}),t=>t)},createOnSite(t){return u(()=>c.campaigns.createOnSiteCampaign({body:t}),e=>e)},listTrackingLinks(){return u(()=>c.campaigns.listTrackingLinks({}),t=>t)},createTrackingLink(t){return u(()=>c.campaigns.createTrackingLink({body:t}),e=>e)},attributeLinkConversion(t){return u(()=>c.campaigns.attributeLinkConversion({body:t}),e=>e)}}),dr=v("Journeys",{list(t){return u(()=>c.journeys.listJourneys({query:t}),e=>e)},get(t){return u(()=>c.journeys.getJourney({path:{key:t}}),e=>e)},validate(t){return u(()=>c.journeys.validateJourney({body:{definition:t}}),e=>e)},publish(t){return u(()=>c.journeys.publishJourney({path:{key:t}}),e=>e)},stop(t){return u(()=>c.journeys.stopJourney({path:{key:t}}),e=>e)},listBlueprints(){return u(()=>c.journeys.listBlueprints({}),t=>t)},listStoreBlueprints(t){return u(()=>c.journeys.listStoreBlueprints({path:{store_id:t}}),e=>e)},activateStoreBlueprint(t,e){return u(()=>c.journeys.activateStoreBlueprint({path:{store_id:t},body:e}),n=>n)},deleteStoreBlueprint(t,e){return u(()=>c.journeys.deleteStoreBlueprint({path:{store_id:t,key:e}}),()=>{})}});import{z as Ns}from"zod";export{Ts as AccessRefused,rt as AttestedDevice,je as AuthUnavailable,Pt as Authorize,Ft as BadRequest,ze as Body,Vt as CACHE_MAX_TTL,Gt as Cache,ur as Campaigns,yt as ChatPart,nt as Client,lr as Commerce,Lt as Conflict,L as ContractRunEnded,Ne as Controller,lt as Cron,V as Database,It as DeadlockDetected,Ge as Delete,Ot as DiError,De as EVENT_TYPES,or as Flags,Ct as Forbidden,kt as Gateway,wt as GatewayRefusal,qe as Get,Ye as Headers,$t as HttpError,at as Injectable,dr as Journeys,p as Log,Wt as MAX_BODY_BYTES,q as MigrationRunEnded,ot as Module,Mt as NotFound,sr as Notifications,it as On,vt as OnConnect,Rt as OnDisconnect,At as OnEmpty,St as OnFirst,Ze as OptionalUser,xt as PalError,c as Palbase,O as PalbaseError,Kn as PalbaseFactory,Qe as Param,Ve as Patch,Ke as Post,cr as Promotions,We as Put,He as Query,Je as QueryParams,ir as Realtime,et as Req,tt as RequestId,st as Resolve,j as SchemaNotPushed,Jn as Secrets,Dt as SerializationFailure,rr as Storage,Et as Subscribe,gt as Task,pt as TaskFailure,mt as Tasks,ft as TestUserTemplate,Ue as TokenError,I as TokenVerifier,Ut as TooManyRequests,Tt as Unauthorized,jt as UniqueViolation,ht as Upload,bt as UploadedObject,Xe as User,ct as Webhook,cs as bigint,us as boolean,ds as check,D as createApp,ps as date,Bt as defineError,gs as defineSchema,ms as defineTable,qt as encrypt,Nt as encrypted,fs as enumType,hs as foreignKey,ut as getRegisteredControllers,dt as getRoutes,_t as getWebhookManifest,Bs as increment,bs as index,ys as integer,ws as jsonb,Fs as now,ks as numeric,Ps as ownedByUser,Ss as policy,vs as raw,Rs as sqlType,Kt as t,As as text,Es as timestamp,_s as userRef,Os as uuid,Ns as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as l,c as g,d as f,e as m}from"../chunks/
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as l,c as g,d as f,e as m}from"../chunks/GSY2E764.js";import{a as u}from"../chunks/2SVWIAAD.js";import{c,i as p}from"../chunks/7R5TMAGP.js";import"../chunks/3GR5ZPYK.js";import"../chunks/ZWASHVNO.js";import"../chunks/KWVOOFCB.js";import"../chunks/RBZI2C7M.js";import"../chunks/HT6TR6AZ.js";import"../chunks/GMCROKBB.js";import"../chunks/G37YLKYL.js";import"../chunks/XUEBLD7V.js";import"../chunks/7BSFT4SH.js";import"reflect-metadata";import{randomUUID as y}from"node:crypto";import{createFakeClient as w,typedDatabase as h}from"palgres/testing";function b(s,t,e){if(e?.acceptLanguage!==void 0&&e.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:n,...o}=s,a=e?.strings;return c.run({requestId:`test_${y()}`,database:n===void 0?void 0:d(n),services:o,...a!==void 0?{strings:a,locales:p(e?.acceptLanguage??null,a.source),usedLocales:[]}:{}},t)}function T(){let s=new Map,t=new Map,e=[],n=a=>{if(s.has(a))return s.get(a);if(t.has(a))return t.get(a);if(e.includes(a)){let r=[...e.slice(e.indexOf(a)),a].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${r.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}e.push(a);try{let r=Reflect.getMetadata("design:paramtypes",a)??[],i=new a(...r.map(n));return t.set(a,i),i}finally{e.pop()}},o={with(a,r){return s.set(a,r),o},get:a=>n(a)};return o}var k="a database in memory keeps rows, not relationships, and answers no access question \u2014 give it the schema (fakeDatabase({ access: <the schema file's text> })), or test what asks Database.$access against Postgres; the schema itself is held to its expectations with `palbase access:test`";function d(s){let t=s.access;return h(s,t===void 0?{unanswered:k}:{access:t.names,via:t.via,as:"authenticated"})}function v(s={}){let t=w(s);return{db:d(t),raw:t,queries:t.queries,seed:(e,n)=>t.seed(e,n),inserted:e=>t.inserted(e),updated:e=>t.updated(e),deleted:e=>t.deleted(e),signedInAs(e){if(!t.access)throw new TypeError("fakeDatabase().signedInAs: this database was made without an access schema \u2014 fakeDatabase({ access: <the schema file's text> })");t.access.signedInAs(e)}}}export{l as TestApiError,m as api,g as createTestApi,v as fakeDatabase,T as isolated,u as loadStringsTable,f as testRun,b as withServices};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
import{lstat as E,mkdir as k,readdir as b,readFile as j,rename as F,rm as J,writeFile as R}from"node:fs/promises";import{join as $}from"node:path";var o="palbase/strings",g="_meta.json",m=3,S=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function w(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function O(r,t){try{return JSON.parse(r)}catch(n){throw new Error(`${t} is not JSON: ${n.message}`)}}async function M(r){let t=$(r,o);try{if(!(await E(t)).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 n=new Map;for(let e of await b(t,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);n.set(e.name,await j($(t,e.name),"utf8"))}return n.size===0?void 0:n}async function N(r){let t=await M(r);if(t===void 0)return;let n=t.get(g);if(n===void 0)throw new Error(`${o}/${g} is missing: it names the source language, and without it the language files are not a table`);let e=O(n,`${o}/${g}`);if(!S(e))throw new Error(`${o}/${g}: not a JSON object`);let c=e.version;if(c!==m)throw new Error(`${o}/${g}: version ${JSON.stringify(c)} is not one this reads (${m})`);let s=e.source;if(typeof s!="string"||w(s)!==s)throw new Error(`${o}/${g}: source ${JSON.stringify(s)} is not a language tag as it is written (${w(String(s))??"en, en-US, zh-Hans"})`);let f=new Map;for(let u of[...t.keys()].sort()){if(u===g)continue;let i=u.slice(0,-5),a=`${o}/${u}`,l=w(i);if(l===void 0)throw new Error(`${a}: ${JSON.stringify(i)} is not a language tag`);if(l!==i)throw new Error(`${a}: the language is written ${l} \u2014 name the file ${l}.json`);if(i===s)throw new Error(`${a}: ${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(`${a}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let d=O(t.get(u),a);if(!S(d))throw new Error(`${a}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[p,y]of Object.entries(d)){if(typeof y!="string")throw new Error(`${a}: the translation of ${JSON.stringify(p)} is not a string`);h.set(p,y)}f.set(i,h)}return{format:c,source:s,languages:f}}async function P(r){let t=await N(r);if(t===void 0)return;let n={};Object.setPrototypeOf(n,null);for(let[e,c]of t.languages)for(let[s,f]of c)Object.hasOwn(n,s)||(n[s]={},Object.setPrototypeOf(n[s],null)),n[s][e]=f;return{source:t.source,locales:[t.source,...t.languages.keys()],strings:n}}export{P as a};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as w,d as He,e as Ke,f as Je}from"./ZWASHVNO.js";import{a as ze}from"./RBZI2C7M.js";import{a as Ve}from"./HT6TR6AZ.js";import{a as Ge,b as Le,c as Fe}from"./GMCROKBB.js";import{b as I,d as Be}from"./G37YLKYL.js";async function*Qe(e,t={}){let i=e.getReader(),s=new TextDecoder,a="",d="",c=[],o,r=()=>{i.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:l}=await i.read();if(n||t.signal?.aborted)return;t.onBytes?.(),a+=s.decode(l,{stream:!0});for(let u=a.indexOf(`
|
|
3
|
+
`);u>=0;u=a.indexOf(`
|
|
4
|
+
`)){let f=a.slice(0,a[u-1]==="\r"?u-1:u);a=a.slice(u+1),f===""?(d!==""&&(yield o===void 0?{event:d,data:c.join(`
|
|
5
|
+
`)}:{event:d,data:c.join(`
|
|
6
|
+
`),id:o}),d="",c=[],o=void 0):f.startsWith("event:")?d=Se(f,6):f.startsWith("data:")?c.push(Se(f,5)):f.startsWith("id:")&&(o=Se(f,3))}}}finally{t.signal?.removeEventListener("abort",r);try{await i.cancel()}catch{}}}function Se(e,t){let i=e.slice(t);return i.startsWith(" ")?i.slice(1):i}var tn=/\s/;function de(e,t){for(;t<e.length&&tn.test(e[t]);)t++;return t}function Xe(e,t){let i="";for(let s=t+1;s<e.length;s++){let a=e[s];if(a==='"')return{value:i,complete:!0,empty:!1,at:s+1};if(a!=="\\"){i+=a;continue}let d=e[s+1];if(d===void 0)break;if(d==="u"){let c=e.slice(s+2,s+6);if(c.length<4)break;i+=String.fromCharCode(Number.parseInt(c,16)),s+=5;continue}i+={n:`
|
|
7
|
+
`,t:" ",r:"\r",b:"\b",f:"\f"}[d]??d,s++}return{value:i,complete:!1,empty:!1,at:e.length}}function ve(e,t){t=de(e,t);let i=e[t];if(i===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(i==='"')return Xe(e,t);if(i==="{")return nn(e,t);if(i==="[")return rn(e,t);let s=t;for(;s<e.length&&/[-+0-9.A-Za-z]/.test(e[s]);)s++;if(s===e.length)return{value:void 0,complete:!1,empty:!0,at:s};try{return{value:JSON.parse(e.slice(t,s)),complete:!0,empty:!1,at:s}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function nn(e,t){let i={},s=t+1;for(;;){if(s=de(e,s),e[s]==="}")return{value:i,complete:!0,empty:!1,at:s+1};if(e[s]===","){s++;continue}if(e[s]!=='"')return{value:i,complete:!1,empty:!1,at:e.length};let a=Xe(e,s);if(!a.complete)return{value:i,complete:!1,empty:!1,at:e.length};if(s=de(e,a.at),e[s]!==":")return{value:i,complete:!1,empty:!1,at:e.length};let d=ve(e,s+1);if(d.empty||Object.defineProperty(i,a.value,{value:d.value,enumerable:!0,writable:!0,configurable:!0}),!d.complete)return{value:i,complete:!1,empty:!1,at:e.length};s=d.at}}function rn(e,t){let i=[],s=t+1;for(;;){if(s=de(e,s),e[s]==="]")return{value:i,complete:!0,empty:!1,at:s+1};if(e[s]===","){s++;continue}if(s>=e.length)return{value:i,complete:!1,empty:!1,at:s};let a=ve(e,s);if(a.empty||i.push(a.value),!a.complete)return{value:i,complete:!1,empty:!1,at:e.length};s=a.at}}function Ae(e){let t=ve(e,0);return t.empty?void 0:t.value}var T=class extends Error{path;constructor(t,i){super(`${t}: ${i}`),this.name="AISchemaError",this.path=t}},sn=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),on=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),an=new Set(["object","array","string","integer","number","boolean"]),Ye=12,Ze=512,ln=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function H(e,t="answer"){if(!ln.test(t))throw new T(t||"(name)","a schema name starts with a letter and holds letters, digits, _ and -, 64 at most");let i=e?.["~standard"];if(!i||i.version!==1||typeof i.validate!="function")throw new T(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!i.jsonSchema||typeof i.jsonSchema.output!="function")throw new T(t,`${i.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let s;try{s=i.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(c){throw new T(t,`the schema has a part JSON Schema cannot say (${c.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(s.type!=="object")throw new T(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let d=xe(s,t,0,{properties:0});return{name:t,json:d,async check(c){let o=await i.validate(c);if(o.issues){let r=o.issues[0],n=(r?.path??[]).map(l=>String(typeof l=="object"?l.key:l)).join(".");throw new T(n?`${t}.${n}`:t,`the model's answer does not match the schema: ${r?.message??"invalid"}`)}return o.value}}}function xe(e,t,i,s){if(i>Ye)throw new T(t,`nests deeper than ${Ye} levels, the most the provider takes`);for(let c of["anyOf","oneOf","allOf"])if(c in e)throw new T(t,dn(e[c])??"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 c of["$ref","$defs","definitions","$dynamicRef"])if(c in e)throw new T(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 T(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 c of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(c in e)throw new T(t,`uses ${c}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new T(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 a=e.type;if(typeof a!="string"&&!("enum"in e))throw new T(t,"has no type: the provider holds a model only to a typed value");if(typeof a=="string"&&!an.has(a))throw new T(t,`is of type ${a}, which the provider does not take`);let d={};for(let[c,o]of Object.entries(e))if(!(c==="$schema"||c==="id"||c==="$id")&&!on.has(c)){if(!sn.has(c))throw new T(t,`uses ${c}, which the provider cannot hold a model to`);d[c]=o}if("enum"in e&&typeof a!="string"){let c=e.enum,o=new Set(c.map(r=>r===null?"null":typeof r));if(o.size!==1||o.has("null"))throw new T(t,"an enum of values of several types (or with null): one type per field");d.type=o.has("string")?"string":o.has("boolean")?"boolean":"number"}if(a==="object"){let c=e.properties??{},o=Object.keys(c);if(o.length===0)throw new T(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 T(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(s.properties+=o.length,s.properties>Ze)throw new T(t,`the schema has more than ${Ze} fields in all, the most the provider takes`);let r=new Set(e.required??[]),n={};for(let l of o){if(!r.has(l))throw new T(`${t}.${l}`,'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');n[l]=xe(c[l],`${t}.${l}`,i+1,s)}d.properties=n,d.required=o,d.additionalProperties=!1}if(a==="array"){let c=e.items;if(!c||typeof c!="object"||Array.isArray(c))throw new T(t,"is a list with no one shape for its items: the provider takes a list of one shape");d.items=xe(c,`${t}[]`,i+1,s)}return d}function dn(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 cn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function ne(e){return Array.isArray(e)&&e.length>0&&e.every(et)?e.map(tt):et(e)?[tt(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function et(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.type==="text"?typeof t.text=="string":t.type==="image"?(typeof t.mediaType=="string"||typeof t.media_type=="string")&&(typeof t.data=="string"||t.data instanceof Uint8Array):t.type===void 0&&typeof t.mediaType=="string"&&t.bytes instanceof Uint8Array}function tt(e){if("type"in e&&e.type==="text")return{type:"text",text:e.text};let t="bytes"in e||"mediaType"in e?e.mediaType:e.media_type;if(!cn.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let i="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof i=="string"?i:un(i)}}function un(e){let t="";for(let i=0;i<e.length;i+=32768)t+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(t)}var gt=Symbol.for("palbase.ai.deferred"),nt=60,rt=86400;function ft(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<nt||t>rt))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${nt} to ${rt} seconds (got ${String(t)})`);return Object.freeze({[gt]:!0,...t!==void 0?{expiresInSeconds:t}:{}})}function pn(e){return typeof e=="object"&&e!==null&&e[gt]===!0}var mt=Symbol.for("palbase.ai.reply"),gn=/^[A-Za-z0-9_.:-]{1,160}$/;function se(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: workspaceTree is the tree the tool's writes left the workspace at ({ manifestId, seq }), either or both`);let{manifestId:i,seq:s}=e,a={};if(i!==void 0){if(typeof i!="string"||!gn.test(i))throw new TypeError(`${t}: workspaceTree.manifestId is a tree's id (got ${JSON.stringify(i)})`);a.manifest_id=i}if(s!==void 0){if(!Number.isSafeInteger(s)||s<1)throw new TypeError(`${t}: workspaceTree.seq is a place in the workspace's history, a whole number from 1 (got ${String(s)})`);a.seq=s}if(a.manifest_id===void 0&&a.seq===void 0)throw new TypeError(`${t}: workspaceTree names the tree \u2014 its manifestId, its seq, or both`);return a}function ht(e,t){let i=se(t?.workspaceTree,"ai.answer");return Object.freeze({[mt]:!0,output:e,workspaceTree:Object.freeze({...i.manifest_id!==void 0?{manifestId:i.manifest_id}:{},...i.seq!==void 0?{seq:i.seq}:{}})})}function fn(e){return typeof e=="object"&&e!==null&&e[mt]===!0}var mn=Symbol.for("palbase.ai.declared"),hn=Symbol.for("palbase.ai.tool_error"),_e=class extends Error{workspaceTree;constructor(t,i){if(super(t),this.name="ToolError",Object.defineProperty(this,hn,{value:!0}),i?.workspaceTree!==void 0){let s=se(i.workspaceTree,"ToolError");this.workspaceTree=Object.freeze({...s.manifest_id!==void 0?{manifestId:s.manifest_id}:{},...s.seq!==void 0?{seq:s.seq}:{}})}}};function ce(){let e=globalThis,t=e[mn]??={tools:new Map,clientTools:new Map,agents:new Map,twice:new Set};return t.clientTools??=new Map,t}function Re(e,t,i,s,a=(d,c)=>d===c){let d=e.get(i);d===void 0?e.set(i,s):a(d,s)||ce().twice.add(`${t}:${i}`)}var yt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,j=/^[a-z][a-z0-9_-]{0,63}$/,ue=/^[A-Za-z0-9_.:-]{1,160}$/,wt=128,yn=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u,bt=`${wt} bytes at most, no control, format (bidi, zero-width) or line-separator character`;function Tt(e){return typeof e=="string"&&new TextEncoder().encode(e).byteLength<=wt&&!yn.test(e)}function kt(e,t){if(e===void 0)return{type:"object",properties:{}};let i=e?.["~standard"];if(!i||i.version!==1||typeof i.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!i.jsonSchema||typeof i.jsonSchema.output!="function")throw new TypeError(`${t}: ${i.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let s;try{s=i.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(s.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let a=JSON.stringify(s);if(/"\$(ref|defs|dynamicRef)"/.test(a))throw new TypeError(`${t}: the input refers to another schema (a recursive or shared type) \u2014 write the shape out`);let{$schema:d,...c}=s;return c}function St(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!yt.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&&!j.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 i=kt(e.input,t),s=e.input["~standard"],a=e.run,d={source:"backend",name:e.name,description:e.description,input:e.input,parameters:i,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(o,r){let n=await s.validate(o);if(n.issues){let u=n.issues[0],f=(u?.path??[]).map(C=>String(typeof C=="object"?C.key:C)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${f?` at ${f}`:""}: ${u?.message??"invalid"}`}],is_error:!0}}let l=await a(n.value,r);if(pn(l))return r.chatId===""?{output:[{type:"text",text:`${e.name} answers later, and a one-shot answer waits for no call: it answers at once, or in a chat`}],is_error:!0}:{deferred:!0,...l.expiresInSeconds!==void 0?{expires_in_seconds:l.expiresInSeconds}:{}};if(fn(l)){let u={output:ne(l.output),is_error:!1};return l.workspaceTree!==void 0&&(u.workspace_tree=se(l.workspaceTree,t)),u}return{output:ne(l),is_error:!1}}};Object.freeze(d);let c=ce();return c.clientTools.has(d.name)&&c.twice.add(`tool:${d.name}`),Re(c.tools,"tool",d.name,d),d}function vt(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!yt.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`);let i=Object.freeze({source:"client",name:e.name,description:e.description,parameters:kt(e.input,t),approval:e.approval===!0}),s=ce();return s.tools.has(i.name)&&s.twice.add(`tool:${i.name}`),Re(s.clientTools,"tool",i.name,i,(a,d)=>JSON.stringify(a)===JSON.stringify(d)),i}function At(e,t,i={}){let s=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!j.test(e))throw new TypeError(`${s}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${s}: the agent is a function of the turn's context that returns its definition`);let a=i??{};if(a.machine!==void 0&&!j.test(a.machine))throw new TypeError(`${s}: machine is the name of one of the project's machines`);let d=a.description===void 0?void 0:xt(a.description,s),c={kind:"agent",name:e,...d!==void 0?{description:d}:{},...a.machine!==void 0?{machine:a.machine}:{},async resolve(o){let r=await t(o),n=pe(r,`${s} for chat ${o.chatId}`);if(n.backend!==void 0)throw new TypeError(`${s}: a backend's agent is its definition \u2014 it names no other backend`);return n.description===void 0&&d!==void 0&&(n.description=d),{definition:n,tools:wn(r)}}};return Object.freeze(c),Re(ce().agents,"agent",e,c),c}function oe(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function wn(e){return[...e.tools??[],...(e.subagents??[]).flatMap(i=>i.tools??[])].filter(i=>i.source==="backend")}var st=["web.search","web.fetch","workspace.fetch_archive"];function re(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a tool is ai.tool(\u2026), ai.clientTool(\u2026), { source: 'https', name }, { source: 'mcp', name } or { source: 'platform', name }`);let i=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,...i,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...i};case"https":if(typeof e.name!="string"||!j.test(e.name))throw new TypeError(`${t}: { source: 'https', name } names an endpoint the project put`);return{source:"https",name:e.name,...i};case"mcp":if(typeof e.name!="string"||!j.test(e.name))throw new TypeError(`${t}: { source: 'mcp', name } names an MCP server the project put`);return{source:"mcp",name:e.name,...i,...e.only!==void 0?{only:[...e.only]}:{}};case"platform":{let s=Object.keys(e).filter(a=>a!=="source"&&a!=="name");if(typeof e.name!="string"||!st.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${st.join(", ")}`);if(s.length>0)throw new TypeError(`${t}: the platform's ${e.name} is given by its name alone (not ${s.join(", ")})`);return{source:"platform",name:e.name}}default:throw new TypeError(`${t}: a tool's source is backend, client, https, mcp or platform (got ${JSON.stringify(e.source)})`)}}var ot=1e4,at=["none","minimal","low","medium","high","xhigh","max"],bn=1e8,Tn=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/,it=1024,kn=/^[A-Z][A-Z0-9_]{0,127}$/,lt=64,K=32768,dt=65536;function Pe(e){return typeof e=="string"&&kn.test(e)&&!e.startsWith("PALAI_")}var ct=e=>new TextEncoder().encode(e).byteLength,ut=32,Sn=["header","query","body"];function Ce(e,t){let i={};if(e.hosts!==void 0){if(!Array.isArray(e.hosts)||e.hosts.length>ut)throw new TypeError(`${t}: hosts is a list of ${ut} hosts at most (api.stripe.com, *.stripe.com); [] takes them all away`);e.hosts.forEach((s,a)=>{if(typeof s!="string"||s==="")throw new TypeError(`${t}: hosts[${a}] is a host, as text (api.stripe.com, *.stripe.com)`)}),i.hosts=[...e.hosts]}if(e.inject!==void 0){if(!Array.isArray(e.inject)||e.inject.length===0)throw new TypeError(`${t}: inject is where in a request it may be put \u2014 header, query, body \u2014 at least one`);e.inject.forEach((s,a)=>{if(typeof s!="string"||!Sn.includes(s))throw new TypeError(`${t}: inject[${a}] is header, query or body (a secret never goes over plain http)`)}),i.inject=[...e.inject]}if(e.open!==void 0){if(typeof e.open!="boolean")throw new TypeError(`${t}: open is true (the agent reads it as it is) or false (sealed)`);i.open=e.open}if(e.secret!==void 0){if(typeof e.secret!="boolean")throw new TypeError(`${t}: secret is true (the default) or false (a plain variable the agent reads as it is)`);i.secret=e.secret}if(e.acknowledgeOpen!==void 0){if(typeof e.acknowledgeOpen!="boolean")throw new TypeError(`${t}: acknowledgeOpen is true, said with open: true or with secret: false`);i.acknowledge_open=e.acknowledgeOpen}if(e.acknowledgeGuessable!==void 0){if(typeof e.acknowledgeGuessable!="boolean")throw new TypeError(`${t}: acknowledgeGuessable is true, said with a sealed value a person may have chosen`);i.acknowledge_guessable=e.acknowledgeGuessable}return i}var vn={person_required:"where a secret goes \u2014 its hosts, inject, open, secret \u2014 is changed without its value by a person alone: an owner or an admin of the organization signed in to Studio (AI \u203A Secrets) or to the CLI as themselves (palbase login), never a key or a token, the project's secret key included. Or say it again with its value",secret_unusable:"a sealed secret's value is 8 bytes or more on one line \u2014 no CR, LF or NUL: a value that is no secret is { secret: false }, one the agent may read as it is { open: true, acknowledgeOpen: true }",secret_guessable:"the value looks like one a person chose (fewer than 16 characters, or one kind of character only), and the proxy hides a sealed value an allowed host echoes back, which lets an agent confirm a guess there: use a random key, say acknowledgeGuessable: true to keep it sealed anyway, or make it open",open_not_acknowledged:"an open secret, and a secret made no secret (secret: false), is read by the agent as it is \u2014 anyone who can drive the project's agents can get its value: say acknowledgeOpen: true to say you read this"};function An(e,t){if(!(e instanceof I))return e;let i=vn[e.code];return i?new I({op:e.op,status:e.status,code:e.code,message:`${t}: ${i} (the platform: ${e.message}; ${e.op}: ${e.status} ${e.code})`,requestId:e.requestId,retryAfter:e.retryAfter,body:e.body,cause:e}):e}function U(e,t){return e.catch(i=>{throw An(i,t)})}var pt=["value","hosts","inject","open","secret","acknowledgeOpen","acknowledgeGuessable"];function xn(e,t){let i={};if(e.env!==void 0){if(typeof e.env!="object"||e.env===null||Array.isArray(e.env))throw new TypeError(`${t}: env is the agent's own variables, { NAME: value }`);let s=Object.entries(e.env);if(s.length>lt)throw new TypeError(`${t}: env names ${lt} variables at most`);let a={},d=c=>typeof c=="string"&&ct(c)<=K&&!c.includes("\0");for(let[c,o]of s){if(!Pe(c))throw new TypeError(`${t}: env: ${JSON.stringify(c.slice(0,140))} is no variable's name \u2014 upper-case letters, digits and _, a letter first, at most 128, and not PALAI_\u2026, the engine's own`);if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let r=Object.keys(o).find(l=>!pt.includes(l));if(r!==void 0)throw new TypeError(`${t}: env.${c}: ${JSON.stringify(r.slice(0,64))} is not one of ${pt.join(", ")}`);let n=o;if(n.value!==void 0&&!d(n.value))throw new TypeError(`${t}: env.${c}.value is text of ${K} bytes at most, no NUL ('' keeps the value it has)`);a[c]={...n.value!==void 0?{value:n.value}:{},...Ce(n,`${t}: env.${c}`)};continue}if(!d(o))throw new TypeError(`${t}: env.${c} is text of ${K} bytes at most, no NUL ('' keeps the value it has), or { value, hosts, inject, open, secret, acknowledgeOpen, acknowledgeGuessable }`);a[c]=o}i.env=a}if(e.setup!==void 0){if(typeof e.setup!="string"||ct(e.setup)>dt||e.setup.includes("\0"))throw new TypeError(`${t}: setup is a shell script of ${dt} bytes at most, no NUL`);i.setup=e.setup}return i}function xt(e,t){if(typeof e!="string"||e.trim()===""||e.length>it)throw new TypeError(`${t}: description says what the agent is for, in a sentence or two (${it} characters at most)`);return e}function _n(e,t){let i=e?.prepared;if(i!==void 0&&typeof i=="object"&&i!==null&&typeof i.json=="object")return i.json;if(typeof e!="object"||e===null||!("~standard"in e))throw new TypeError(`${t}: output is the shape of its one-shot answers \u2014 a zod (valibot, arktype) object schema, or ai.schema(name, schema)`);return H(e,"output").json}function Ie(e,t){if(!Number.isInteger(e)||e<1||e>ot)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${ot} (got ${String(e)})`);return e}function Ee(e,t){let i={};if(e.effort!==void 0){if(typeof e.effort!="string"||!at.includes(e.effort))throw new TypeError(`${t}: effort is one of ${at.join(", ")} \u2014 which a model takes is its catalogue entry's (ai.models())`);i.effort=e.effort}if(e.contextWindow!==void 0){if(!Number.isInteger(e.contextWindow)||e.contextWindow<1||e.contextWindow>bn)throw new TypeError(`${t}: contextWindow is a number of tokens (got ${String(e.contextWindow)})`);i.context_window=e.contextWindow}if(e.thinking!==void 0){if(e.thinking!=="visible"&&e.thinking!=="hidden")throw new TypeError(`${t}: thinking is visible (the model's reasoning in the chat's stream) or hidden`);i.thinking=e.thinking}if(e.toolOutputs!==void 0){if(e.toolOutputs!=="aged"&&e.toolOutputs!=="window")throw new TypeError(`${t}: toolOutputs is aged (a tool's output is cut to its first and last lines once it is four messages old) or window (only once the conversation fills the turn's window)`);i.tool_outputs=e.toolOutputs}return i}function pe(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { description, instructions, model, tools, subagents, advisor, maxToolCalls, effort, contextWindow, thinking, toolOutputs, language, env, setup, output }`);let i={};if(e.description!==void 0&&(i.description=xt(e.description,t)),e.instructions!==void 0&&(i.instructions=e.instructions),e.model!==void 0&&(i.model=e.model),e.maxToolCalls!==void 0&&(i.max_tool_calls=Ie(e.maxToolCalls,t)),Object.assign(i,Ee(e,t)),e.language!==void 0){if(typeof e.language!="string"||e.language.length>35||!Tn.test(e.language))throw new TypeError(`${t}: language is the language of the person the turn works for, as a BCP 47 tag (tr, en-GB)`);i.language=e.language}if(Object.assign(i,xn(e,t)),e.output!==void 0&&(i.output=_n(e.output,t)),e.tools!==void 0&&(i.tools=e.tools.map(s=>re(s,t))),e.subagents!==void 0){for(let s of e.subagents){let a=(s?.tools??[]).find(d=>d?.source==="platform");if(a)throw new TypeError(`${t} subagent ${s.name}: the platform's ${a.name} is the agent's tool \u2014 its subagents work with the agent's`)}i.subagents=e.subagents.map(s=>({name:s.name,description:s.description,...s.instructions!==void 0?{instructions:s.instructions}:{},...s.model!==void 0?{model:s.model}:{},...s.required!==void 0?{required:s.required}:{},...Ee(s,`${t} subagent ${s.name}`),...s.tools!==void 0?{tools:s.tools.map(a=>re(a,`${t} subagent ${s.name}`))}:{}}))}return e.advisor!==void 0&&(i.advisor=En(e.advisor,`${t} advisor`)),i}function En(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: an advisor is { model, instructions, effort, tools }`);let i={};if(e.model!==void 0&&(i.model=e.model),e.instructions!==void 0){if(typeof e.instructions!="string"||new TextEncoder().encode(e.instructions).length>64*1024)throw new TypeError(`${t}: instructions is text, 64 KiB at most`);i.instructions=e.instructions}let{effort:s}=Ee({effort:e.effort},t);if(s!==void 0&&(i.effort=s),e.tools!==void 0){if(!Array.isArray(e.tools)||e.tools.length>32)throw new TypeError(`${t}: tools is 32 MCP servers at most`);i.tools=e.tools.map(a=>{if(a?.source!=="mcp")throw new TypeError(`${t}: the advisor reads; its tools are MCP servers' ({ source: 'mcp', name }), whose tools it is given when they say they only read`);if(a.approval===!0)throw new TypeError(`${t}: nothing the advisor reads waits for a person (approval)`);return re(a,t)})}return i}function N(e,t,i){if(typeof e!="string"||!ue.test(e))throw new TypeError(`${t}: ${i} (got ${JSON.stringify(e)})`);return e}var ge="the pool is one of the project's runner pools, by its id or its name",Oe="the machine is a pool's machine by its id (pools.state(pool).machines)";function _t(e){return{id:e.id,name:e.name,os:e.os,arch:e.arch,...e.created_at!==void 0?{createdAt:e.created_at}:{},...e.machines!==void 0?{machines:e.machines}:{},...e.capacity_total!==void 0?{capacityTotal:e.capacity_total}:{},...e.capacity_used!==void 0?{capacityUsed:e.capacity_used}:{},...e.waiting!==void 0?{waiting:e.waiting}:{}}}function Et(e){return{id:e.id,...e.label?{label:e.label}:{},...e.created_at!==void 0?{createdAt:e.created_at}:{},...e.expires_at!==void 0?{expiresAt:e.expires_at}:{},...e.last_used_at?{lastUsedAt:e.last_used_at}:{},...e.revoked_at?{revokedAt:e.revoked_at}:{}}}function Me(e){return{name:e.name,...e.acp_version!==void 0?{acpVersion:e.acp_version}:{},...e.cli_version!==void 0?{cliVersion:e.cli_version}:{},status:e.status}}function Rn(e){return{id:e.id,state:e.state,capacity:e.capacity,used:e.used,...e.label?{label:e.label}:{},...e.os?{os:e.os}:{},...e.arch?{arch:e.arch}:{},idleSince:e.idle_since??null,lastSeenAt:e.last_seen_at??null,registeredAt:e.registered_at??null,...e.harnesses!==void 0?{harnesses:e.harnesses.map(Me)}:{}}}var fe=e=>({key:e.key,secret:e.secret,hosts:e.hosts??[],inject:e.inject??[],open:e.open===!0,updatedAt:e.updated_at}),$e=e=>({requestId:e.request_id,key:e.key,agent:e.agent??null,origin:e.origin??null,host:e.host,domain:e.domain??e.host,status:e.status,asks:e.asks,firstAskedAt:e.first_asked_at,lastAskedAt:e.last_asked_at,decidedAt:e.decided_at??null}),Pn=e=>({allowanceId:e.allowance_id,origin:e.origin??"kept",agent:e.agent,key:e.key,host:e.host,domain:e.domain??e.host,allowedAt:e.allowed_at,allowedBy:e.allowed_by}),Rt="the ask is one env.hostRequests.list says, by its id (shr_\u2026)",Cn="an open secret is read by the agent as it is: anyone who can drive the project's agents \u2014 an app's user where the project lets them, a prompt the agent reads \u2014 can get its value. Say acknowledgeOpen: true with open: true to say you read this";function Pt(e,t,i){if(typeof t!="object"||t===null)throw new TypeError(`${i}(${JSON.stringify(e)}): options are { secret, hosts, inject, open, acknowledgeOpen, acknowledgeGuessable }`);let s=Ce(t,`${i}(${JSON.stringify(e)})`);if(t.open===!0&&t.acknowledgeOpen!==!0)throw new TypeError(`${i}(${JSON.stringify(e)}): ${Cn}`);return s}function me(e,t){if(!Pe(e))throw new TypeError(`${t}: ${JSON.stringify(typeof e=="string"?e.slice(0,140):e)} is no variable's name \u2014 upper-case letters, digits and _, a letter first, at most 128, and not PALAI_\u2026, the engine's own`);return e}function Ct(e){return{pools:{async create(a){if(typeof a?.name!="string"||!j.test(a.name))throw new TypeError("pools.create: name is lowercase letters, digits, _ and -, a letter first, at most 64 \u2014 the project's once");if(a.os!=="linux"&&a.os!=="macos")throw new TypeError("pools.create: os is its machines' operating system, linux or macos (a pool is of one type)");if(a.arch!=="amd64"&&a.arch!=="arm64")throw new TypeError("pools.create: arch is its machines' architecture, amd64 or arm64 (a pool is of one type)");return _t((await e.createPool({body:{name:a.name,os:a.os,arch:a.arch},signal:a.signal})).data)},async list(a={}){return(await e.listPools({signal:a.signal})).data.pools.map(_t)},async delete(a,d={}){await e.deletePool({path:{pool:N(a,"pools.delete",ge)},signal:d.signal})},async state(a,d={}){let c=(await e.getPoolState({path:{pool:N(a,"pools.state",ge)},signal:d.signal})).data;return{pool:{id:c.pool.id,name:c.pool.name,os:c.pool.os,arch:c.pool.arch},capacityTotal:c.capacity_total,capacityUsed:c.capacity_used,waiting:c.waiting,oldestWaitingSince:c.oldest_waiting_since??null,machines:c.machines.map(Rn)}},keys:{async create(a,d={}){let c={};if(d.label!==void 0){if(!Tt(d.label))throw new TypeError(`pools.keys.create: label is what the key is for, ${bt}`);c.label=d.label}let o=(await e.createPoolKey({path:{pool:N(a,"pools.keys.create",ge)},body:c,signal:d.signal})).data;if(typeof o.key!="string"||o.key==="")throw new I({op:"createPoolKey",status:502,code:"no_key",message:`the key ${o.id} was minted but not said: revoke it (pools.keys.revoke) and mint another`});return{...Et(o),key:o.key,...o.enroll_url?{enrollUrl:o.enroll_url}:{},...o.enroll?{enroll:{url:o.enroll.url,...o.enroll.server_name?{serverName:o.enroll.server_name}:{},...o.enroll.ca_certificate?{caCertificate:o.enroll.ca_certificate}:{}}}:{}}},async list(a,d={}){return(await e.listPoolKeys({path:{pool:N(a,"pools.keys.list",ge)},signal:d.signal})).data.keys.map(Et)},async revoke(a,d={}){await e.revokePoolKey({path:{key:N(a,"pools.keys.revoke","the key is a pool's key by its id (pools.keys.list)")},signal:d.signal})}}},machines:{async cordon(a,d={}){await e.cordonMachine({path:{machine:N(a,"machines.cordon",Oe)},signal:d.signal})},async resume(a,d={}){await e.resumeMachine({path:{machine:N(a,"machines.resume",Oe)},signal:d.signal})},async delete(a,d={}){await e.deleteMachine({path:{machine:N(a,"machines.delete",Oe)},signal:d.signal})}},env:{async set(a,d,c={}){me(a,"env.set");let o=`env.set(${JSON.stringify(a)})`;if(typeof d!="string"||d===""||new TextEncoder().encode(d).byteLength>K||d.includes("\0"))throw new TypeError(`${o}: the value is text of 1 to ${K} bytes, no NUL \u2014 to change what a variable says of itself and keep its value: env.update`);let r={value:d,...Pt(a,c,"env.set")};return fe((await U(e.putEnv({path:{key:a},body:r,signal:c.signal}),o)).data)},async update(a,d){me(a,"env.update");let c=Pt(a,d,"env.update");if(Object.keys(c).every(o=>o.startsWith("acknowledge_")))throw new TypeError(`env.update(${JSON.stringify(a)}): say what changes \u2014 secret, hosts, inject or open (its value: env.set)`);return fe((await U(e.putEnv({path:{key:a},body:c,signal:d.signal}),`env.update(${JSON.stringify(a)})`)).data)},async unset(a,d={}){await e.deleteEnv({path:{key:me(a,"env.unset")},signal:d.signal})},async list(a={}){return(await e.listEnv({signal:a.signal})).data.variables.map(fe)},async allowHost(a,d,c={}){if(me(a,"env.allowHost"),typeof d!="string"||d===""||d.length>253)throw new TypeError(`env.allowHost(${JSON.stringify(a)}): the host is an exact DNS name (api.stripe.com) or *. and one (*.stripe.com), as text`);return fe((await U(e.allowEnvHost({path:{key:a},body:{host:d},signal:c.signal}),`env.allowHost(${JSON.stringify(a)})`)).data)},hostRequests:{async list(a={}){if(a.status!==void 0&&!["asked","allowed","dismissed"].includes(a.status))throw new TypeError("env.hostRequests.list: status is asked (the default), allowed or dismissed");let d=a.status!==void 0?{status:a.status}:void 0;return(await e.listEnvHostRequests({...d?{query:d}:{},signal:a.signal})).data.requests.map($e)},async allow(a,d={}){let c=N(a,"env.hostRequests.allow",Rt);return $e((await U(e.allowEnvHostRequest({path:{request_id:c},signal:d.signal}),`env.hostRequests.allow(${JSON.stringify(c)})`)).data)},async dismiss(a,d={}){let c=N(a,"env.hostRequests.dismiss",Rt);return $e((await U(e.dismissEnvHostRequest({path:{request_id:c},signal:d.signal}),`env.hostRequests.dismiss(${JSON.stringify(c)})`)).data)}},allowances:{async list(a={}){return(await e.listEnvAllowances({signal:a.signal})).data.allowances.map(Pn)},async remove(a,d={}){let c=N(a,"env.allowances.remove","the allowance is one env.allowances.list says, by its id (sha_\u2026)");await U(e.deleteEnvAllowance({path:{allowance_id:c},signal:d.signal}),`env.allowances.remove(${JSON.stringify(c)})`)}}}}}function J(e,t){if(typeof e!="string"||!j.test(e))throw new TypeError(`${t}: an agent's name is lowercase letters, digits, _ and -, starting with a letter, at most 64 (got ${JSON.stringify(e)})`);return e}function It(e,t){if(!Number.isSafeInteger(e)||e<1)throw new TypeError(`${t}: revision is the draft's revision as it was read (Agent's revision), a whole number from 1 (got ${String(e)})`);return e}function Ot(e,t){let i={approve:e};return t.reason!==void 0&&(i.reason=t.reason),t.as!==void 0&&(i.as=t.as),i}var In=/^[a-z][a-z0-9-]{1,62}$/,$t=4,Mt=8;function On(e){let t={},i=(s,a)=>{if(typeof s?.bucket!="string"||!In.test(s.bucket))throw new TypeError(`chats.send: ${a}'s bucket is one of the project's buckets, by its name`);if(typeof s.path!="string"||s.path===""||s.path.length>1024)throw new TypeError(`chats.send: ${a}'s path is its path in the bucket (1024 characters at most)`);return{bucket:s.bucket,path:s.path}};if(e.images!==void 0){if(!Array.isArray(e.images)||e.images.length>$t)throw new TypeError(`chats.send: images are ${$t} at most \u2014 as many as the model is shown at once`);t.images=e.images.map((s,a)=>i(s,`images[${a}]`))}if(e.files!==void 0){if(!Array.isArray(e.files)||e.files.length>Mt)throw new TypeError(`chats.send: files are ${Mt} at most`);t.files=e.files.map((s,a)=>{let d=i(s,`files[${a}]`);if(s.filename!==void 0){if(typeof s.filename!="string"||s.filename===""||s.filename.length>255)throw new TypeError(`chats.send: files[${a}].filename is its name in the workspace (255 characters at most)`);d.filename=s.filename}if(s.contentType!==void 0){if(typeof s.contentType!="string"||s.contentType===""||s.contentType.length>128)throw new TypeError(`chats.send: files[${a}].contentType is a media type (application/pdf)`);d.content_type=s.contentType}return d})}return t}function $n(e){if(!e)return;let t={};return e.mode!==void 0&&(t.mode=e.mode),e.wake_phrases!==void 0&&(t.wakePhrases=e.wake_phrases),e.idle_close_seconds!==void 0&&(t.idleCloseSeconds=e.idle_close_seconds),t}function Mn(e){let t={type:e?.type??"webrtc"};e?.sdp!==void 0&&(t.sdp=e.sdp),e?.call_id!==void 0&&(t.callId=e.call_id),e?.identity!==void 0&&(t.identity=e.identity),e?.name!==void 0&&(t.name=e.name),e?.room!==void 0&&(t.room=e.room),e?.media_url!==void 0&&(t.mediaUrl=e.media_url);let i=$n(e?.activation);return i!==void 0&&(t.activation=i),e?.gate_open!==void 0&&(t.gateOpen=e.gate_open),t}function he(e){let t={id:e.id,chatId:e.chat_id,userId:e.user_id,transport:Mn(e.transport),delegation:e.delegation,status:e.status,seconds:e.seconds,startedAt:e.started_at,closedAt:e.closed_at,closeReason:e.close_reason??""};return e.model!==void 0&&(t.model=e.model),t}var qn=["speak","tell","know","instruct","activate","deactivate"];function qt(){return"cm_"+crypto.randomUUID()}async function ae(e,t,i=4){for(let s=1;;s++)try{return await e()}catch(a){if(s>=i||!(a instanceof I)||a.status===429||t?.aborted)throw a;let d=Fe(a,s,30);if(d===void 0)throw a;await new Promise((c,o)=>{let r=setTimeout(c,d*1e3);t?.addEventListener("abort",()=>(clearTimeout(r),o(t.reason)),{once:!0})})}}function qe(e){return{id:e.id,chatId:e.chat_id,objective:e.objective,rubric:e.rubric,status:e.status,stopCode:e.stop_code,stopReason:e.stop_reason,phase:e.phase,setBy:e.set_by,maxTurns:e.max_turns,budget:e.budget===null?null:{maxCostUsd:e.budget.max_cost_usd},usage:{turns:e.usage.turns,verifications:e.usage.verifications,costUsd:e.usage.cost_usd,costIsLowerBound:e.usage.cost_is_lower_bound,activeSeconds:e.usage.active_seconds},achievedAt:e.achieved_at,createdAt:e.created_at,updatedAt:e.updated_at}}var jt=e=>({user_id:e.userId,...e.name!==void 0?{name:e.name}:{},...e.email!==void 0?{email:e.email}:{},...e.owner!==void 0?{owner:e.owner}:{}}),jn=/^[a-z0-9][a-z0-9_-]{0,62}$/;function z(e,t){if(typeof e!="string"||!jn.test(e))throw new TypeError(`${t}: environment name must match ^[a-z0-9][a-z0-9_-]{0,62}$ (got ${JSON.stringify(e)})`);return e}function Un(e){return{runId:e.run_id,responseId:e.response_id,parentRunId:e.parent_run_id??null,subagent:e.subagent,model:e.model,state:e.state,inputTokens:e.input_tokens,outputTokens:e.output_tokens,cacheReadTokens:e.cache_read_tokens,cacheWriteTokens:e.cache_write_tokens,costNanoUsd:e.cost_nano_usd,usd:e.usd,unpriced:e.unpriced}}function je(e,t){if(typeof e!="object"||e===null||typeof e.compute!="object"||e.compute===null||typeof e.executor!="object"||e.executor===null)throw new TypeError(`${t}: target requires { compute, executor }`);let i=e.compute;if(!["serverless","cloud","pool","machine"].includes(i.kind))throw new TypeError(`${t}: target.compute.kind must be serverless, cloud, pool, or machine`);let s=e.executor;if(s.kind!=="palbase"&&s.kind!=="acp")throw new TypeError(`${t}: target.executor.kind must be palbase or acp`);if(s.kind==="acp"&&s.harness!=="claude-code"&&s.harness!=="codex"&&s.harness!=="gemini-cli")throw new TypeError(`${t}: target.executor.harness must be claude-code, codex, or gemini-cli when executor.kind is acp`);return{compute:{kind:i.kind,...i.poolId!==void 0?{pool_id:i.poolId}:{},...i.machineId!==void 0?{machine_id:i.machineId}:{},...i.environment!==void 0?{environment:i.environment}:{}},executor:{kind:s.kind,...s.harness!==void 0?{harness:s.harness}:{},...s.model!==void 0?{model:s.model}:{},...s.effort!==void 0?{effort:s.effort}:{}}}}function ye(e){return{compute:{kind:e.compute.kind,...e.compute.pool_id!==void 0?{poolId:e.compute.pool_id}:{},...e.compute.machine_id!==void 0?{machineId:e.compute.machine_id}:{},...e.compute.environment!==void 0?{environment:e.compute.environment}:{}},executor:{kind:e.executor.kind,...e.executor.harness!==void 0?{harness:e.executor.harness}:{},...e.executor.model!==void 0?{model:e.executor.model}:{},...e.executor.effort!==void 0?{effort:e.executor.effort}:{}}}}function Ut(e,t){if(!Number.isSafeInteger(e.afterOfflineSeconds)||e.afterOfflineSeconds<30||e.afterOfflineSeconds>86400)throw new TypeError(`${t}: autoFailover.afterOfflineSeconds must be an integer between 30 and 86400`);return{after_offline_seconds:e.afterOfflineSeconds,to:je(e.to,`${t}: autoFailover.to`),...e.requireWorkspaceCleanBeforeCut!==void 0?{require_workspace_clean_before_cut:e.requireWorkspaceCleanBeforeCut}:{}}}function Nn(e){return e?{afterOfflineSeconds:e.after_offline_seconds,to:ye(e.to),...e.require_workspace_clean_before_cut!==void 0?{requireWorkspaceCleanBeforeCut:e.require_workspace_clean_before_cut}:{}}:null}function Nt(e){return{chatId:e.chat_id,target:ye(e.target),targetGeneration:e.target_generation,...e.workspace_id!==void 0?{workspaceId:e.workspace_id}:{},workspaceSeq:e.workspace_seq,...e.machine_status!==void 0?{machineStatus:e.machine_status}:{},...e.machine_name!==void 0?{machineName:e.machine_name}:{},...e.harnesses!==void 0?{harnesses:e.harnesses.map(Me)}:{},autoFailover:Nn(e.auto_failover),failoverAt:e.failover_at??null,...e.pending_handoff!==void 0?{pendingHandoff:{to:ye(e.pending_handoff.to),reason:e.pending_handoff.reason,...e.pending_handoff.idempotency_key!==void 0?{idempotencyKey:e.pending_handoff.idempotency_key}:{},requestedAt:e.pending_handoff.requested_at}}:{}}}function Wn(e){return{chatId:e.chat_id,targetGeneration:e.target_generation,target:ye(e.target),workspaceSeq:e.workspace_seq,activeRunAction:e.active_run_action,...e.resumed_response_id!==void 0?{resumedResponseId:e.resumed_response_id}:{}}}function Wt(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes,monthlyBudgetUsd:e.monthly_budget_usd??null,openSecretsForAppUsers:e.open_secrets_for_app_users===!0,allowClientHandoff:e.allow_client_handoff===!0,autoPipeChats:e.auto_pipe_chats===!0}}function Dn(e){return new Proxy(e,{get(t,i){let s=t[i];return typeof s=="function"?(...a)=>w(s.apply(t,a)):s}})}function Dt(e){let t=Dn(e);return{chats:{async create(o){let r=typeof o.agent=="string"||o.agent===void 0?o.agent:oe(o.agent)?.name;if(o.agent!==void 0&&r===void 0)throw new TypeError("chats.create: agent is one of the project's agents by name (name@N for a version), or a backend's ai.agent");if(r===void 0&&o.definition===void 0)throw new TypeError("chats.create: an agent (one of the project's, by name) or a definition of the chat's own");let n={agent:r??"assistant"};if(o.definition!==void 0&&(n.definition=pe(o.definition,"chats.create")),o.title!==void 0&&(n.title=o.title),o.metadata!==void 0&&(n.metadata=o.metadata),o.members!==void 0&&(n.members=o.members.map(jt)),o.pool!==void 0){if(typeof o.pool!="string"||!ue.test(o.pool))throw new TypeError("chats.create: pool is one of the project's runner pools (ai.pools), by its id or its name");n.pool=o.pool}if(o.workspaceId!==void 0){if(typeof o.workspaceId!="string"||o.workspaceId==="")throw new TypeError("chats.create: workspaceId is a workspaces module id (ws_\u2026)");n.workspace_id=o.workspaceId}return o.target!==void 0&&(n.target=je(o.target,"chats.create")),o.autoFailover!==void 0&&(n.auto_failover=o.autoFailover===null?null:Ut(o.autoFailover,"chats.create")),o.live!==void 0&&(n.live=o.live),(await(o.definition!==void 0?U(t.createChat({body:n,signal:o.signal}),"chats.create"):t.createChat({body:n,signal:o.signal}))).data},async get(o,r={}){return(await t.getChat({path:{chat_id:o},signal:r.signal})).data},async list(o={}){let r=o.metadata===void 0?void 0:Object.entries(o.metadata).map(([l,u])=>`${l}:${u}`),n=(await t.listChats({query:{member:o.member,limit:o.limit,cursor:o.cursor,metadata:r,...o.status!==void 0?{status:o.status}:{}},signal:o.signal})).data;return n.next_cursor===void 0?{chats:n.chats}:{chats:n.chats,nextCursor:n.next_cursor}},async handoff(o,r){if(r?.when!==void 0&&r.when!=="idle"&&r.when!=="after_turn"&&r.when!=="now")throw new TypeError("chats.handoff: when must be idle, after_turn, or now");if(r?.graceSeconds!==void 0&&(!Number.isSafeInteger(r.graceSeconds)||r.graceSeconds<1||r.graceSeconds>60))throw new TypeError("chats.handoff: graceSeconds must be an integer between 1 and 60");let n={to:je(r.to,"chats.handoff"),...r.when!==void 0?{when:r.when}:{},...r.graceSeconds!==void 0?{grace_seconds:r.graceSeconds}:{},idempotency_key:r.idempotencyKey??`ho_${crypto.randomUUID()}`};return Wn((await ae(()=>t.handoffChat({path:{chat_id:o},body:n,signal:r.signal}),r.signal)).data)},async execution(o,r={}){return Nt((await t.getChatExecution({path:{chat_id:o},signal:r.signal})).data)},async updateExecution(o,r){let n={};return r.autoFailover!==void 0&&(n.auto_failover=r.autoFailover===null?null:Ut(r.autoFailover,"chats.updateExecution")),r.model!==void 0&&(n.model=r.model),r.effort!==void 0&&(n.effort=r.effort),Nt((await t.patchChatExecution({path:{chat_id:o},body:n,signal:r.signal})).data)},async delete(o){await t.deleteChat({path:{chat_id:o}})},members:{async put(o,r,n){let l={};return n.name!==void 0&&(l.name=n.name),n.email!==void 0&&(l.email=n.email),n.owner!==void 0&&(l.owner=n.owner),(await t.putChatMember({path:{chat_id:o,user_id:r},body:l})).data},async delete(o,r){await t.deleteChatMember({path:{chat_id:o,user_id:r}})}},async send(o,r){let n={client_id:r.clientId??qt(),text:r.text};return r.delivery!==void 0&&(n.delivery=r.delivery),r.as!==void 0&&(n.as=r.as),r.budget!==void 0&&(n.budget={max_cost_usd:r.budget.maxCostUsd}),r.metadata!==void 0&&(n.metadata=r.metadata),r.context!==void 0&&(n.context=r.context),Object.assign(n,On(r)),ae(async()=>(await t.sendChatMessage({path:{chat_id:o},body:n,signal:r.signal})).data,r.signal)},async turnCost(o,r,n={}){let l=(await t.getChatTurnCost({path:{chat_id:o,response_id:r},signal:n.signal})).data,u={chatId:l.chat_id,responseId:l.response_id,inputTokens:l.input_tokens,outputTokens:l.output_tokens,costNanoUsd:l.cost_nano_usd,usd:l.usd,unpriced:l.unpriced,final:l.final,runs:l.runs.map(Un)};return l.advisor&&(u.advisor={inputTokens:l.advisor.input_tokens,outputTokens:l.advisor.output_tokens,cacheReadTokens:l.advisor.cache_read_tokens,cacheWriteTokens:l.advisor.cache_write_tokens,costNanoUsd:l.advisor.cost_nano_usd,usd:l.advisor.usd,unpriced:l.advisor.unpriced}),u},async artifacts(o,r,n={}){return(await t.listChatTurnArtifacts({path:{chat_id:o,response_id:r},signal:n.signal})).data.artifacts.map(u=>({id:u.id,mediaType:u.media_type,...u.logical_type?{logicalType:u.logical_type}:{},sizeBytes:u.size_bytes,checksum:u.checksum,createdAt:u.created_at}))},async artifact(o,r,n,l={}){return(await t.getChatTurnArtifact({path:{chat_id:o,response_id:r,artifact_id:n},signal:l.signal})).data},async messages(o,r={}){let n=(await t.listChatMessages({path:{chat_id:o},query:{limit:r.limit,cursor:r.cursor},signal:r.signal})).data;return n.next_cursor===void 0?{messages:n.messages}:{messages:n.messages,nextCursor:n.next_cursor}},async parts(o,r={}){if(r.cursor!==void 0&&r.before!==void 0)throw new TypeError("chats.parts: cursor (where a page left off) or before (the oldest part the app's channel holds, by its id), not both");if(r.before!==void 0&&(!Number.isSafeInteger(r.before)||r.before<1))throw new TypeError(`chats.parts: before is a part's id \u2014 its journal sequence, a whole number from 1 (got ${String(r.before)})`);if(r.limit!==void 0&&r.turns!==void 0)throw new TypeError("chats.parts: limit (events) or turns (turns), not both");if(r.turns!==void 0&&(!Number.isSafeInteger(r.turns)||r.turns<1||r.turns>20))throw new TypeError(`chats.parts: turns is how many of the chat's turns a page reads back to, 1 to 20 (got ${String(r.turns)})`);let n=(await t.listChatParts({path:{chat_id:o},query:{limit:r.limit,turns:r.turns,cursor:r.cursor,before:r.before},signal:r.signal})).data;return{parts:n.parts.map(u=>({type:u.type,...u.id!==void 0?{id:u.id}:{},partId:u.part_id,data:u.data})),...n.next_cursor!==void 0?{nextCursor:n.next_cursor}:{},...n.turns!==void 0?{turns:n.turns}:{}}},async toolCall(o,r,n={}){let l=(await t.getChatToolCall({path:{chat_id:o,call_id:r},signal:n.signal})).data;return{callId:l.call_id,name:l.name,status:l.status,runId:l.run_id,responseId:l.response_id,input:l.input,output:l.output,outputBytes:l.output_bytes,imageCount:l.image_count,isError:l.is_error}},async toolCalls(o,r){if(typeof r?.turn!="string"||r.turn==="")throw new TypeError("chats.toolCalls: turn is the turn's responseId \u2014 a message's, or a turn's or an agent part's");let n=(await t.listTurnToolCalls({path:{chat_id:o},query:{turn:r.turn,limit:r.limit,cursor:r.cursor},signal:r.signal})).data,l=n.tool_calls.map(u=>({callId:u.call_id,name:u.name,state:u.state,createdAt:u.created_at,updatedAt:u.updated_at,arguments:u.arguments,...u.result!==void 0?{result:u.result}:{}}));return n.next_cursor===void 0?{toolCalls:l}:{toolCalls:l,nextCursor:n.next_cursor}},events(o){if(typeof o!="string"||!/^chat_[0-9a-f]{32}$/.test(o))throw new TypeError(`chats.events(id): a chat's id, chat_ and 32 hex digits (got ${JSON.stringify(o)})`);return Object.freeze({kind:"ai.chat",chatId:o,async pipe(r,n={}){await t.putChatPipe({path:{chat_id:o},body:{topic:r},signal:n.signal})},async unpipe(r={}){await t.deleteChatPipe({path:{chat_id:o},signal:r.signal})}})},async stop(o,r={}){return(await t.stopChat({path:{chat_id:o},...r.as!==void 0?{body:{as:r.as}}:{},signal:r.signal})).data.stopped},async approve(o,r,n={}){return(await t.decideChatApproval({path:{chat_id:o,approval_id:r},body:Ot(!0,n)})).data},async deny(o,r,n={}){return(await t.decideChatApproval({path:{chat_id:o,approval_id:r},body:Ot(!1,n)})).data},async answer(o,r,n,l={}){let u={output:ne(n)};l.isError&&(u.is_error=!0),l.as!==void 0&&(u.as=l.as),l.workspaceTree!==void 0&&(u.workspace_tree=se(l.workspaceTree,"chats.answer"));try{return await ae(()=>t.answerChatToolCall({path:{chat_id:o,call_id:r},body:u})),!0}catch(f){if(f instanceof I&&f.status===409)return!1;throw f}},async sendToSubagent(o,r,n,l={}){let u={client_id:l.clientId??qt(),text:n};l.as!==void 0&&(u.as=l.as);let f=await ae(async()=>(await t.sendSubagentMessage({path:{chat_id:o,run_id:r},body:u})).data);return{runId:f.run_id,clientId:f.client_id}},async stopSubagent(o,r,n={}){return{runId:(await ae(async()=>(await t.stopSubagent({path:{chat_id:o,run_id:r},body:n.as!==void 0?{as:n.as}:{},signal:n.signal})).data,n.signal)).run_id}},async fork(o,r){if(typeof r?.beforeMessage!="string"||r.beforeMessage==="")throw new TypeError("chats.fork: beforeMessage is the id of the message the fork is cut before (a message's id, msg_\u2026)");let n={before_message:r.beforeMessage};return r.title!==void 0&&(n.title=r.title),r.members!==void 0&&(n.members=r.members.map(jt)),(await t.forkChat({path:{chat_id:o},body:n,signal:r.signal})).data},goal:{async set(o,r){let n={objective:r.objective};return r.rubric!==void 0&&(n.rubric=r.rubric),r.maxTurns!==void 0&&(n.max_turns=r.maxTurns),r.budget!==void 0&&(n.budget={max_cost_usd:r.budget.maxCostUsd}),r.as!==void 0&&(n.as=r.as),qe((await t.setChatGoal({path:{chat_id:o},body:n,signal:r.signal})).data)},async get(o,r={}){return qe((await t.getChatGoal({path:{chat_id:o},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})).data)},async update(o,r){let n={};return r.status!==void 0&&(n.status=r.status),r.reason!==void 0&&(n.reason=r.reason),r.objective!==void 0&&(n.objective=r.objective),r.rubric!==void 0&&(n.rubric=r.rubric),r.maxTurns!==void 0&&(n.max_turns=r.maxTurns),r.budget!==void 0&&(n.budget=r.budget===null?null:{max_cost_usd:r.budget.maxCostUsd}),r.as!==void 0&&(n.as=r.as),qe((await t.updateChatGoal({path:{chat_id:o},body:n,signal:r.signal})).data)},async clear(o,r={}){await t.clearChatGoal({path:{chat_id:o},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})}},voice:{async start(o,r){if(r?.delegation!==void 0&&r.delegation!=="chat"&&r.delegation!=="events")throw new TypeError("chats.voice.start: delegation is chat (a turn of the chat) or events (ai.voice.delegated)");let n=r?.transport;if(!n||n.type!=="webrtc"&&n.type!=="call")throw new TypeError("chats.voice.start: transport is { type: 'webrtc', sdp } or { type: 'call', callId, ... }");let l;if(n.type==="webrtc"){if(typeof n.sdp!="string"||!n.sdp.startsWith("v="))throw new TypeError("chats.voice.start: transport.sdp is the app's WebRTC offer (an SDP, v=0 \u2026): its peer connection's localDescription.sdp");l={type:"webrtc",sdp:n.sdp}}else{if(typeof n.callId!="string"||n.callId.trim()==="")throw new TypeError("chats.voice.start: transport.callId is the Palbase Calls room ID to join");if(l={type:"call",call_id:n.callId},n.identity!==void 0&&(l.identity=n.identity),n.name!==void 0&&(l.name=n.name),n.activation!==void 0){let C={};n.activation.mode!==void 0&&(C.mode=n.activation.mode),n.activation.wakePhrases!==void 0&&(C.wake_phrases=n.activation.wakePhrases),n.activation.idleCloseSeconds!==void 0&&(C.idle_close_seconds=n.activation.idleCloseSeconds),l.activation=C}}let u={transport:l};r.model!==void 0&&(u.model=r.model),r.voice!==void 0&&(u.voice=r.voice),r.delegation!==void 0&&(u.delegation=r.delegation),r.as!==void 0&&(u.as=r.as),r.instructions!==void 0&&(u.instructions=r.instructions),r.context!==void 0&&(u.context=r.context);let f=(await t.startChatVoice({path:{chat_id:o},body:u,signal:r.signal})).data;if(n.type==="webrtc"&&(typeof f.transport?.sdp!="string"||f.transport.sdp===""))throw new I({op:"startChatVoice",status:502,code:"no_answer",message:"the voice was started but its WebRTC answer was not given"});return he(f)},async get(o,r,n={}){return he((await t.getChatVoice({path:{chat_id:o,voice_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)},async command(o,r,n){if(!qn.includes(n?.type))throw new TypeError("chats.voice.command: type is speak (say this exactly), tell (say it in your own words), know (keep it in mind), instruct (behave so), activate or deactivate");if(n.type!=="activate"&&n.type!=="deactivate"&&(typeof n.text!="string"||n.text===""))throw new TypeError("chats.voice.command: text is what the voice is given");if(n.delegationId!==void 0&&n.type!=="speak"&&n.type!=="tell")throw new TypeError("chats.voice.command: delegationId names the request a speak or a tell answers");if(n.interrupt!==void 0&&(typeof n.interrupt!="boolean"||n.type!=="speak"))throw new TypeError("chats.voice.command: interrupt is a speak's: it cuts what the voice is saying");let u={type:n.type};return n.text!==void 0&&(u.text=n.text),n.delegationId!==void 0&&(u.delegation_id=n.delegationId),n.interrupt===!0&&(u.interrupt=!0),n.as!==void 0&&(u.as=n.as),he((await t.commandChatVoice({path:{chat_id:o,voice_id:r},body:u,signal:n.signal})).data)},async close(o,r,n={}){return he((await t.closeChatVoice({path:{chat_id:o,voice_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)}}},agents:{async list(o={}){return(await t.listAgents({signal:o.signal})).data.agents},async get(o,r={}){return(await t.getAgent({path:{name:J(o,"agents.get")},signal:r.signal})).data},async saveDraft(o,r,n={}){let l=`agents.saveDraft(${JSON.stringify(o)})`;if(J(o,"agents.saveDraft"),oe(r))throw new TypeError(`${l}: a backend's ai.agent is its code's \u2014 its build's contract names it, and its chats ask its machine; it has no draft to save`);if(r===void 0)throw new TypeError(`${l}: its definition \u2014 { instructions, model, tools, \u2026 }`);let u=pe(r,l);return(await U(t.putAgent({path:{name:o},...n.revision!==void 0?{query:{revision:It(n.revision,l)}}:{},body:u,signal:n.signal}),l)).data},async publish(o,r={}){let n=`agents.publish(${JSON.stringify(o)})`;J(o,"agents.publish");let l=r.revision!==void 0?{revision:It(r.revision,n)}:{};return(await t.publishAgent({path:{name:o},body:l,signal:r.signal})).data},async rollback(o,r,n={}){if(J(o,"agents.rollback"),!Number.isSafeInteger(r)||r<1)throw new TypeError(`agents.rollback(${JSON.stringify(o)}): version is one it had \u2014 a whole number from 1 (got ${String(r)})`);return(await U(t.rollbackAgent({path:{name:o},body:{version:r},signal:n.signal}),`agents.rollback(${JSON.stringify(o)})`)).data},async versions(o,r={}){J(o,"agents.versions");let n=(await t.listAgentVersions({path:{name:o},query:{limit:r.limit,cursor:r.cursor},signal:r.signal})).data;return n.next_cursor===void 0?{versions:n.versions,publishedVersion:n.published_version}:{versions:n.versions,publishedVersion:n.published_version,nextCursor:n.next_cursor}},async delete(o,r={}){await t.deleteAgent({path:{name:J(o,"agents.delete")},signal:r.signal})},async tools(o={}){return(await t.listTools({signal:o.signal})).data.tools}},endpoints:{async put(o,r){let n={kind:r.kind,url:r.url};if(r.description!==void 0&&(n.description=r.description),r.parameters!==void 0&&(n.parameters=r.parameters),r.approval!==void 0&&(n.approval=r.approval),r.workspace!==void 0){if(typeof r.workspace!="boolean")throw new TypeError("endpoints.put: workspace is true for an endpoint of the project's own that reads or writes a chat's workspace, false (the default) for any other");n.workspace=r.workspace}return(await t.putEndpoint({path:{name:o},body:n})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(o){await t.deleteEndpoint({path:{name:o}})}},settings:{async get(){return Wt((await t.getSettings({})).data)},async put(o){let r={};if(o.clients!==void 0&&(r.clients=o.clients),o.userMessagesPerMinute!==void 0&&(r.user_messages_per_minute=o.userMessagesPerMinute),o.historyLimitBytes!==void 0&&(r.history_limit_bytes=o.historyLimitBytes),o.openSecretsForAppUsers!==void 0){if(typeof o.openSecretsForAppUsers!="boolean")throw new TypeError("settings.put: openSecretsForAppUsers is true (an app's users' work has the project's open secrets) or false");r.open_secrets_for_app_users=o.openSecretsForAppUsers}if(o.allowClientHandoff!==void 0){if(typeof o.allowClientHandoff!="boolean")throw new TypeError("settings.put: allowClientHandoff is true or false");r.allow_client_handoff=o.allowClientHandoff}if(o.autoPipeChats!==void 0){if(typeof o.autoPipeChats!="boolean")throw new TypeError("settings.put: autoPipeChats is true or false");r.auto_pipe_chats=o.autoPipeChats}try{return Wt((await t.putSettings({body:r})).data)}catch(n){throw o.openSecretsForAppUsers!==void 0&&n instanceof I&&n.code==="person_required"?new I({op:n.op,status:n.status,code:n.code,requestId:n.requestId,body:n.body,cause:n,message:`settings.put: whether an app's users' work has the project's open secrets is a person's to say \u2014 an owner or an admin of the organization signed in to Studio (AI \u203A Settings) or to the CLI as themselves (palbase ai:settings:set --open-secrets-for-app-users), never a key or a token, the project's secret key included (${n.op}: ${n.status} ${n.code})`}):o.allowClientHandoff!==void 0&&n instanceof I&&n.code==="person_required"?new I({op:n.op,status:n.status,code:n.code,requestId:n.requestId,body:n.body,cause:n,message:`settings.put: enabling client-triggered session handoffs is a person's to say \u2014 an owner or an admin of the organization signed in to Studio (AI \u203A Settings) or to the CLI as themselves, never a key or a token (${n.op}: ${n.status} ${n.code})`}):n}}},environments:{async list(o={}){return(await t.listEnvironments({signal:o.signal})).data.environments},async create(o,r={}){return z(o?.name,"environments.create"),(await t.createEnvironment({body:o,signal:r.signal})).data},async get(o,r={}){return(await t.getEnvironment({path:{name:z(o,"environments.get")},signal:r.signal})).data},async put(o,r,n={}){return(await t.putEnvironment({path:{name:z(o,"environments.put")},body:r,signal:n.signal})).data},async delete(o,r={}){await t.deleteEnvironment({path:{name:z(o,"environments.delete")},signal:r.signal})},async createBuild(o,r={}){return(await t.createEnvironmentBuild({path:{name:z(o,"environments.createBuild")},signal:r.signal})).data},async getBuild(o,r,n={}){if(typeof r!="string"||r==="")throw new TypeError("environments.getBuild: buildId is required");return(await t.getEnvironmentBuild({path:{name:z(o,"environments.getBuild"),build_id:r},signal:n.signal})).data}}}}var L=class extends Error{runId;stepKey;waitId;constructor(t,i,s){super(`workflow run ${t} parked on step ${i} (wait ${s})`),this.name="WorkflowParkedError",this.runId=t,this.stepKey=i,this.waitId=s}};function Bt(e){let t={async create(n,l={}){return(await w(e.createTrigger({body:n,signal:l.signal}))).data},async list(n={}){return(await w(e.listTriggers({signal:n.signal}))).data.triggers??[]},async get(n,l={}){return(await w(e.getTrigger({path:{trigger_id:n},signal:l.signal}))).data},async update(n,l,u={}){return(await w(e.updateTrigger({path:{trigger_id:n},body:l,signal:u.signal}))).data},async delete(n,l={}){await w(e.deleteTrigger({path:{trigger_id:n},signal:l.signal}))},async test(n,l={},u={}){return(await w(e.testTrigger({path:{trigger_id:n},body:l,signal:u.signal}))).data}},i={async list(n={}){return(await w(e.listWaits({query:{status:n.status,owner_id:n.ownerId},signal:n.signal}))).data.waits??[]},async get(n,l={}){return(await w(e.getWait({path:{wait_id:n},signal:l.signal}))).data},async signal(n,l={},u={}){return(await w(e.signalWait({path:{wait_id:n},body:{payload:l},signal:u.signal}))).data},async cancel(n,l={}){return(await w(e.cancelWait({path:{wait_id:n},signal:l.signal}))).data}},s={async create(n,l={}){return(await w(e.createWorkflowRun({body:n,signal:l.signal}))).data},async list(n={}){return(await w(e.listWorkflowRuns({query:{workflow_name:n.workflowName,status:n.status},signal:n.signal}))).data.runs??[]},async get(n,l={}){return(await w(e.getWorkflowRun({path:{run_id:n},signal:l.signal}))).data},async recordStep(n,l,u,f={}){return(await w(e.recordWorkflowStep({path:{run_id:n,step_key:l},body:u,signal:f.signal}))).data},async complete(n,l,u={}){return(await w(e.completeWorkflowRun({path:{run_id:n},body:l,signal:u.signal}))).data},async replay(n,l={}){return(await w(e.replayWorkflowRun({path:{run_id:n},body:{from_step:l.fromStep},signal:l.signal}))).data},async stopTree(n,l={}){return(await w(e.stopRunTree({path:{root_id:n},signal:l.signal}))).data}},a={async put(n,l,u,f={}){return(await w(e.putMemory({path:{namespace:n,key:l},body:u,signal:f.signal}))).data},async get(n,l,u={}){return(await w(e.getMemory({path:{namespace:n,key:l},signal:u.signal}))).data},async delete(n,l,u={}){await w(e.deleteMemory({path:{namespace:n,key:l},signal:u.signal}))},async search(n,l={}){return(await w(e.searchMemory({body:n,signal:l.signal}))).data.results??[]}},d={async members(n,l={}){return(await w(e.listActorGroupMembers({path:{group_id:n},signal:l.signal}))).data.members??[]},async addMember(n,l,u={}){return(await w(e.addActorGroupMember({path:{group_id:n},body:{chat_id:l,role:u.role},signal:u.signal}))).data.members??[]},async broadcast(n,l,u={}){return(await w(e.broadcastActorGroup({path:{group_id:n},body:l,signal:u.signal}))).data}},c={async setUserCredential(n,l,u,f={}){return(await w(e.putMcpUserCredential({path:{name:n,user_id:l},body:u,signal:f.signal}))).data},async deleteUserCredential(n,l,u={}){await w(e.deleteMcpUserCredential({path:{name:n,user_id:l},signal:u.signal}))},async startOAuth(n,l,u={}){return(await w(e.startMcpoAuth({path:{name:n},query:{user_id:l,redirect_uri:u.redirectUri},signal:u.signal}))).data}};function o(n,l){return{name:n,async run(u,f={}){let C=f.runId?await s.get(f.runId,{signal:f.signal}):await s.create({workflow_name:n,root_run_id:f.rootRunId,parent_run_id:f.parentRunId,depth:f.depth,input:u??{},metadata:f.metadata,root_budget_usd:f.rootBudgetUsd,max_depth:f.maxDepth,max_concurrent_children:f.maxConcurrentChildren,max_total_steps:f.maxTotalSteps},{signal:f.signal}),R=C.id,k=new Map;for(let m of C.steps??[])m.step_key&&k.set(m.step_key,m);let M={runId:R,async do(m,$){let _=k.get(m);if(_&&_.status==="completed")return _.output;let A=await $(),q=await s.recordStep(R,m,{kind:"do",status:"completed",output:A},{signal:f.signal});return k.set(m,q),q.output},async parallel(m,$){let _=k.get(m);if(_&&_.status==="completed")return _.output;let A=Object.entries($),q=await Promise.all(A.map(async([be,Te])=>[be,await Te()])),we=Object.fromEntries(q),le=await s.recordStep(R,m,{kind:"parallel",status:"completed",output:we},{signal:f.signal});return k.set(m,le),le.output},async sleep(m,$){let _=k.get(m);if(_&&_.status==="completed")return;let A=await s.recordStep(R,m,{kind:"sleep",sleep_seconds:$},{signal:f.signal});if(k.set(m,A),A.status!=="completed")throw new L(R,m,A.wait_id??"")},async waitForEvent(m,$,_={}){let A=k.get(m);if(A&&A.status==="completed")return A.output;let q=await s.recordStep(R,m,{kind:"wait_event",match_topic:$,match_filter:_.filter,timeout_seconds:_.timeoutSeconds},{signal:f.signal});if(k.set(m,q),q.status!=="completed")throw new L(R,m,q.wait_id??"");return q.output},async waitForApproval(m,$={}){let _=k.get(m);if(_&&_.status==="completed")return _.output;let A=await s.recordStep(R,m,{kind:"wait_approval",approval_id:$.approvalId,timeout_seconds:$.timeoutSeconds},{signal:f.signal});if(k.set(m,A),A.status!=="completed")throw new L(R,m,A.wait_id??"");return A.output}};try{let m=await l(u,M);return await s.complete(R,{status:"completed",output:m??{}},{signal:f.signal}),{runId:R,status:"completed",output:m}}catch(m){if(m instanceof L)return{runId:R,status:"waiting",waitId:m.waitId};throw await s.complete(R,{status:"failed",error:m instanceof Error?m.message:String(m)},{signal:f.signal}).catch(()=>{}),m}}}}function r(n,l){let u=l.maxSteps??100,f=o(n,async(C,R)=>{let k={...C},M=l.start;for(let m=0;m<u&&M&&M!=="END";m++){let $=l.nodes[M];if(!$)throw new Error(`graph ${n}: unknown node "${M}"`);let _=await R.do(`${m}:${M}`,()=>$(k,R));k={...k,..._};let A=l.edges[M];if(!A)break;M=typeof A=="function"?A(k):A}return k});return{name:n,async run(C,R){let k=await f.run(C,R);return{runId:k.runId,status:k.status,state:k.output,waitId:k.waitId}}}}return{triggers:t,waits:i,workflows:s,memory:a,groups:d,mcpAuth:c,workflow:o,graph:r}}function Vt(e){return{templates:{async list(s={}){return(await e.listTemplates({signal:s.signal})).data.templates},async get(s,a={}){return(await e.getTemplate({path:{name:s},signal:a.signal})).data},async save(s,a,d={}){return(await e.putTemplate({path:{name:s},body:a,signal:d.signal})).data},async publish(s,a={}){return(await e.publishTemplate({path:{name:s},body:a.version!==void 0?{version:a.version}:{},signal:a.signal})).data},async rollback(s,a={}){return(await e.rollbackTemplate({path:{name:s},body:a.version!==void 0?{version:a.version}:{},signal:a.signal})).data},async versions(s,a={}){return(await e.listTemplateVersions({path:{name:s},signal:a.signal})).data.versions},async delete(s,a={}){await e.deleteTemplate({path:{name:s},signal:a.signal})}},userQuotas:{async listSpend(s={}){let a=(await e.listUserSpend({query:{user_id:s.userId,template_name:s.templateName,period_kind:s.periodKind,period_key:s.periodKey},signal:s.signal})).data;return{periodKind:a.period_kind,periodKey:a.period_key,items:a.items}},async get(s,a={}){return(await e.getUserQuota({path:{user_id:s},signal:a.signal})).data},async set(s,a,d={}){return(await e.putUserQuota({path:{user_id:s},body:a,signal:d.signal})).data},async delete(s,a={}){await e.deleteUserQuota({path:{user_id:s},signal:a.signal})}}}}var Bn=/^pb_[a-z0-9]+_s/;function Gt(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function Ue(){return"ai_"+crypto.randomUUID()}function Ne(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:H(t,"answer")}}var Lt=4,Vn=/^[a-z][a-z0-9-]{1,62}$/,Ft=["image/png","image/jpeg","image/webp","image/gif"],Ht=5<<20,Kt=6<<20;function Xt(e){let t="";for(let i=0;i<e.length;i+=32768)t+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(t)}function Gn(e){return e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)?-1:e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}function Ln(e){if(!Array.isArray(e))throw new TypeError("images is a list of { bucket, path } (a file of the project's storage), { url } (an https address) or { mediaType, data } (its bytes)");if(e.length>Lt)throw new TypeError(`a question takes ${Lt} pictures at most (got ${e.length})`);let t=0;return e.map((i,s)=>{let a=i??{};if("bytes"in a||i instanceof Uint8Array)throw new TypeError(`images[${s}]: a picture's bytes are { mediaType, data } \u2014 or, in the project's storage, { bucket, path }`);if("data"in a||"mediaType"in a){if(a.bucket!==void 0||a.path!==void 0||a.url!==void 0)throw new TypeError(`images[${s}] is { bucket, path }, { url } or { mediaType, data }: one of them`);if(typeof a.mediaType!="string"||!Ft.includes(a.mediaType))throw new TypeError(`images[${s}].mediaType is the picture's type: ${Ft.join(", ")}`);let d=a.data instanceof Uint8Array?Xt(a.data):a.data,c=typeof d=="string"?Gn(d):-1;if(c<0)throw new TypeError(`images[${s}].data is the picture's bytes: base64, or a Uint8Array`);if(c===0||c>Ht)throw new TypeError(`images[${s}] is ${c} bytes: a picture given by its bytes is 1 byte to ${Ht>>20} MiB`);if(t+=c,t>Kt)throw new TypeError(`the pictures given by their bytes are ${Kt>>20} MiB at most together: put a larger one in the project's storage and give { bucket, path }`);return{media_type:a.mediaType,data:d}}if(typeof a.url=="string"){if(a.bucket!==void 0||a.path!==void 0)throw new TypeError(`images[${s}] is { bucket, path } or { url }, not both`);let d;try{d=new URL(a.url)}catch{throw new TypeError(`images[${s}].url is not an address: ${JSON.stringify(a.url.slice(0,80))}`)}if(d.protocol!=="https:"||a.url.length>2048)throw new TypeError(`images[${s}].url is an https address of 2048 characters at most`);return{url:a.url}}if(typeof a.bucket!="string"||!Vn.test(a.bucket)||typeof a.path!="string"||a.path==="")throw new TypeError(`images[${s}] is { bucket, path } \u2014 a file of the project's storage \u2014 { url } or { mediaType, data }`);return{bucket:a.bucket,path:a.path}})}var Fn=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/;function Yt(e){let t=typeof e=="string"?e:oe(e)?.name;if(typeof t!="string"||!Fn.test(t))throw new TypeError(`agent is one of the project's agents by name (support), name@N for its version N (support@3), or a backend's ai.agent (got ${JSON.stringify(typeof e=="string"?e:typeof e)})`);return t}function ie(e,t={},i){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let s={...t};if(e.agent!==void 0&&(s.agent=Yt(e.agent)),e.prompt!==void 0&&(s.input=e.prompt),e.messages!==void 0&&(s.messages=e.messages),e.instructions!==void 0&&(s.instructions=e.instructions),e.model!==void 0&&(s.model=e.model),e.metadata!==void 0&&(s.metadata=e.metadata),e.images!==void 0&&(s.images=Ln(e.images)),e.tools!==void 0&&(s.tools=e.tools.map((a,d)=>{if(a?.source==="client")throw new TypeError(`tools[${d}]: ${a.name} is a client tool \u2014 an app answers it, in a chat; a one-shot answer has no app to wait for`);if(a?.source==="platform")throw new TypeError(`tools[${d}]: the platform's ${a.name} is a chat's agent's tool \u2014 a one-shot answer is given none`);let c=re(a,`tools[${d}]`);return c.source==="backend"&&c.machine===void 0&&i!==void 0&&(c.machine=i),c})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");s.max_tool_calls=Ie(e.maxToolCalls,"ask")}return s}function Jt(e,t){if(e.output===null||e.output===void 0)throw new T(t,"the answer is text, not a document: the agent has no output (the shape of its one-shot answers) \u2014 give it one, give generate a schema, or ask() it");return e.output}var B=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 Hn(e){let t=Uint8Array.from(atob(e),a=>a.charCodeAt(0)),i=new DataView(t.buffer,t.byteOffset,t.byteLength),s=new Array(t.byteLength/4);for(let a=0;a<s.length;a++)s[a]=i.getFloat32(a*4,!0);return s}async function zt(e){let t,i;return e instanceof Uint8Array?(t=e,i=Qt(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),i=e.type||Qt(t)):(t=e.bytes,i=e.mediaType),{media_type:i,data:Xt(t)}}function Qt(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 Kn(e){let t=e.url??Gt("PALBASE_URL"),i=e.secretKey??Gt("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 i!="string"||!Bn.test(i))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 s=Le(Be({baseUrl:t,credentials:{secretKey:i},fetch:e.fetch}),e.retry??Ge);return Ve.client(s)}function Jn(e){return new Proxy({},{get:(t,i)=>e.ai[i]})}function zn(e={}){if(ze())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&&!j.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?Jn(e.server):Kn(e),i=e.resumeFor??12e4;async function s(p,g,y=Ue()){return w(t.createResponse({headers:{"Idempotency-Key":y},body:p,signal:g}))}async function a(p,g={}){return(await t.getResponse({path:{response_id:p},signal:g.signal})).data}async function d(p,g,y,E,b){let S=0,P=p,W=Ue(),Q=()=>Date.now()+i,X=Q();for(let Y=0;;Y++)try{if(P||(g===null?P=(await s({...b,stream:!0},E,W)).data:P=(await t.followResponse({path:{response_id:g},query:{offset:S},signal:E})).data),!P.body)throw new Error("the stream has no body");for await(let v of Qe(P.body)){let O=JSON.parse(v.data);switch(v.event){case"response":g===null&&(g=O.id,y.admitted(O));break;case"delta":{let F=O.offset+He(O.text);if(F>S){let ke=O.offset>=S?O.text:Je(O.text,S-O.offset);y.delta(S,ke),S=F}X=Q();break}case"reset":O.offset<S&&(S=O.offset,y.reset(S));break;case"terminal":return O}}throw new Error("the stream ended before its answer did")}catch(v){if(P=null,E?.aborted||v instanceof I&&v.status>0&&v.status<500&&v.status!==429||g===null&&!(v instanceof I)||Date.now()>X)throw v;await new Promise(O=>setTimeout(O,Math.min(250*2**Math.min(Y,4),4e3)))}}function c(p){if(p.status!=="completed")throw new B(p);return p.text??""}function o(p,g){let y=ie(p,g?{schema:g.prepared.json,schema_name:g.name}:{},e.machine),E=[],b=!1,S,P=null,W=()=>{let h=P;P=null,h?.()},Q,X,Y=new Promise((h,x)=>{Q=h,X=x});Y.catch(()=>{});let v="",O=d(null,null,{admitted:h=>Q(h.id),delta:(h,x)=>{v+=x,E.push(x),W()},reset:h=>{let x=Ke(v,h);v=v.slice(0,x),E.push("\0reset:"+x),W()}},p.signal,y).then(h=>{let x=h.status==="completed"?h.text??"":"";return x.length>v.length&&x.startsWith(v)&&(E.push(x.slice(v.length)),v=x),b=!0,W(),h},h=>{throw b=!0,S=h,X(h),W(),h});O.catch(()=>{});async function*F(){for(let h=0;;h++){for(;h>=E.length;){if(b){if(S)throw S;return}await new Promise(x=>P=x)}yield E[h]}}async function*ke(){for await(let h of F())h.startsWith("\0reset:")||(yield h)}async function*en(){let h="",x="";for await(let ee of F()){ee.startsWith("\0reset:")?h=h.slice(0,Number(ee.slice(7))):h+=ee;let V=Ae(h);if(V===void 0)continue;let G=JSON.stringify(V);G!==x&&(x=G,yield V)}}let Z=O.then(h=>{if(h.status!=="completed")throw new B(h);return h});Z.catch(()=>{});let We=g?Z.then(h=>g.prepared.check(h.output)):Promise.reject(new TypeError("object is a schema stream's"));We.catch(()=>{});let De=Z.then(h=>h.text??v);return De.catch(()=>{}),{id:Y,response:Z,text:De,get textStream(){return ke()},get partialObjectStream(){return en()},object:We,toResponse(h={}){let x=new TextEncoder,ee=new ReadableStream({async start(G){try{for await(let te of F())te.startsWith("\0reset:")?G.enqueue(x.encode(`event: reset
|
|
8
|
+
data: ${JSON.stringify({offset:Number(te.slice(7))})}
|
|
9
|
+
|
|
10
|
+
`)):G.enqueue(x.encode(`data: ${JSON.stringify({text:te})}
|
|
11
|
+
|
|
12
|
+
`));let D=await Z;G.enqueue(x.encode(`event: done
|
|
13
|
+
data: ${JSON.stringify({id:D.id,text:D.text,output:D.output,usage:D.usage})}
|
|
14
|
+
|
|
15
|
+
`))}catch(D){let te=D instanceof B||D instanceof I?D.code:"stream_failed";G.enqueue(x.encode(`event: error
|
|
16
|
+
data: ${JSON.stringify({code:te})}
|
|
17
|
+
|
|
18
|
+
`))}finally{G.close()}}}),V=new Headers(h.headers);return V.set("content-type","text/event-stream"),V.set("cache-control","no-store"),V.set("x-accel-buffering","no"),new globalThis.Response(ee,{...h,headers:V})}}}async function r(p,g){return d(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},p.signal,ie(p,g,e.machine))}let{chats:n,agents:l,endpoints:u,settings:f,environments:C}=Dt(t),{pools:R,machines:k,env:M}=Ct(t),{triggers:m,waits:$,workflows:_,memory:A,groups:q,mcpAuth:we,workflow:le,graph:be}=Bt(t),{templates:Te,userQuotas:Zt}=Vt(t);return{module:t,chats:n,agents:l,endpoints:u,settings:f,environments:C,pools:R,machines:k,env:M,triggers:m,waits:$,workflows:_,memory:A,groups:q,mcpAuth:we,workflow:le,graph:be,templates:Te,userQuotas:Zt,tool:St,clientTool:vt,deferred:ft,answer:ht,agent:At,async ask(p,g={}){let y=typeof p=="string"?{...g,prompt:p}:p;return c(await r(y,{}))},async generate(p){if(p.schema===void 0){if(p.agent===void 0)throw new TypeError("generate: a schema \u2014 the answer's shape \u2014 or an agent whose output is");if(p.background){let P=(await s(ie(p,{background:!0},e.machine),p.signal)).data;return{id:P.id,status:P.status}}let b=await r(p,{});if(b.status!=="completed")throw new B(b);return Jt(b,Yt(p.agent))}let g=Ne(p.schema),y={schema:g.prepared.json,schema_name:g.name};if(p.background){let S=(await s(ie(p,{...y,background:!0},e.machine),p.signal)).data;return{id:S.id,status:S.status}}let E=await r(p,y);if(E.status!=="completed")throw new B(E);return g.prepared.check(E.output)},stream(p){return o(p,p.schema?Ne(p.schema):void 0)},async start(p){let g=(await s(ie(p,{background:!0},e.machine),p.signal)).data;return{id:g.id,status:g.status}},schema(p,g){return{name:p,schema:g,prepared:H(g,p)}},response:a,async result(p,g){let y=await a(p);if(y.status!=="completed")throw new B(y);return g===void 0?Jt(y,"the response"):Ne(g).prepared.check(y.output)},async cancel(p){return(await t.cancelResponse({path:{response_id:p}})).data},async embed(p,g={}){let y=Array.isArray(p)?p:[p],E=[];for(let b=0;b<y.length;b+=1024){let S=await w(t.createEmbeddings({body:{input:y.slice(b,b+1024),model:g.model,dimensions:g.dimensions},signal:g.signal}));for(let P of S.data.vectors)E.push(Hn(P))}return Array.isArray(p)?E:E[0]},async image(p){let g={prompt:p.prompt};for(let b of["model","size","quality","background","format","count"])p[b]!==void 0&&(g[b]=p[b]);p.references?.length&&(g.references=await Promise.all(p.references.map(zt))),p.mask&&(g.mask=await zt(p.mask));let y=(await w(t.createImage({headers:{"Idempotency-Key":Ue()},body:g,signal:p.signal}))).data;for(let b=0;y.status==="running";b++){if(await new Promise(S=>setTimeout(S,Math.min(500+b*250,3e3))),p.signal?.aborted)throw p.signal.reason;y=(await t.getImage({path:{image_id:y.id},signal:p.signal})).data}if(y.status!=="completed")throw new Error(`the image failed: ${y.error?.code??"image_failed"}: ${y.error?.message??""}`);let E=await Promise.all(y.files.map(async b=>{let P=(await t.getImageFile({path:{image_id:y.id,position:b.position},signal:p.signal})).data;return{mediaType:b.media_type,bytes:new Uint8Array(await P.arrayBuffer())}}));return{id:y.id,model:y.model,pictures:E,costNanoUSD:y.usage?.cost_nano_usd??0,save(b,S,P=0){let W=E[P];if(!W)throw new RangeError(`the job made ${E.length} picture(s)`);return b.upload(S,W.bytes,{contentType:W.mediaType})}}},videos:{async create(p,g={}){return(await w(t.createVideo({body:p,signal:g.signal}))).data},async get(p,g={}){return(await t.getVideo({path:{video_id:p},signal:g.signal})).data},async cancel(p,g={}){return(await t.cancelVideo({path:{video_id:p},signal:g.signal})).data}},audio:{async transcribe(p,g={}){return(await w(t.createAudioTranscription({body:p,signal:g.signal}))).data},async speak(p,g={}){let y=(await w(t.createAudioSpeech({body:p,signal:g.signal}))).data;return{mediaType:y.headers.get("content-type")??"audio/mpeg",bytes:new Uint8Array(await y.arrayBuffer())}},async speakStream(p,g={}){return(await w(t.createAudioSpeech({body:p,signal:g.signal}))).data}},async models(){return(await t.listModels({})).data},async usage(p={}){let g=p.metadata===void 0?void 0:JSON.stringify(p.metadata),y=(await t.listUsage({query:{kind:p.kind,limit:p.limit,cursor:p.cursor,metadata:g}})).data;return{usage:y.usage,nextCursor:y.next_cursor}},async spend(p={}){return(await t.getSpend({signal:p.signal})).data},async connectProvider(p,g){return(await t.connectProvider({path:{provider:p},body:{key:g}})).data},async disconnectProvider(p){await t.disconnectProvider({path:{provider:p}})}}}export{Ae as a,T as b,H as c,_e as d,L as e,B as f,zn as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as g,f as y,g as w}from"./
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,f as y,g as w}from"./SPMFD3LH.js";import"./UPJGT3BN.js";import"./7BSFT4SH.js";import{pathToFileURL as z}from"node:url";import{z as c}from"zod";async function S(r){let l=new Map,t=new Map;for(let s of r){let o=`${s.className}.${s.method}`,i=t.get(s.className);if(i!==void 0&&i!==s.file)throw new Error(`two controllers are named ${s.className} (${i}, ${s.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(s.className,s.file),l.set(o,{returns:await x(s),throws:s.throws})}return s=>l.get(`${s.controller.name}.${s.fn}`)}async function x(r){let l=`${r.file} \u2014 ${r.className}.${r.method}`;switch(r.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let s=(await import(z(r.returns.file).href))[r.returns.exportName];if(!k(s))throw new Error(`${l}: its return type names ${r.returns.exportName}, which ${r.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(w(y(s)))throw new Error(`${l}: ${r.returns.exportName} marks an encrypted field (encrypted()) \u2014 an answer's is encrypt(value) in what the handler returns, its type Encrypted<T>, which the contract reads`);return{kind:"json",schema:s,array:r.returns.array}}case"expression":{let t=$(r.returns.expression,l);if(!k(t))throw new Error(`${l}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function $(r,l){let t=0,s=()=>{for(;t<r.length&&/\s/.test(r[t]);)t++},o=e=>{throw new Error(`${l}: invalid inferred return schema (${e}) at offset ${t}`)},i=e=>(s(),r.startsWith(e,t)?(t+=e.length,!0):!1),n=e=>{i(e)||o(`expected ${JSON.stringify(e)}`)},f=()=>{s(),r[t]!=='"'&&o("expected string literal");let e=t+1;for(;e<r.length;){let d=r[e];if(d==="\\"){e+=2;continue}if(d==='"'){let h=r.slice(t,e+1);return t=e+1,JSON.parse(h)}e++}return o("unterminated string literal")},p=()=>{if(s(),r[t]==='"')return f();if(r.startsWith("true",t)&&!/[A-Za-z0-9_$]/.test(r[t+4]??""))return t+=4,!0;if(r.startsWith("false",t)&&!/[A-Za-z0-9_$]/.test(r[t+5]??""))return t+=5,!1;let e=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(r.slice(t));return e?(t+=e[0].length,Number(e[0])):o("expected literal value")},u=()=>{s();let e;if(i("encrypted(")){let d=u();n(")"),e=g(d)}else if(i("z.")){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"string":n(")"),e=c.string();break;case"number":n(")"),e=c.number();break;case"boolean":n(")"),e=c.boolean();break;case"null":n(")"),e=c.null();break;case"undefined":n(")"),e=c.undefined();break;case"literal":{let a=p();n(")"),e=c.literal(a);break}case"array":{let a=u();n(")"),e=c.array(a);break}case"union":{n("[");let a=[];if(!i("]")){do a.push(u());while(i(","));n("]")}n(")"),a.length<2&&o("z.union requires at least two alternatives"),e=c.union(a);break}case"record":{let a=u();n(",");let m=u();n(")"),e=c.record(a,m);break}case"object":{n("{");let a={};if(!i("}")){do{let m=f();n(":"),a[m]=u()}while(i(","));n("}")}n(")"),e=c.object(a);break}default:return o(`unsupported z.${h}`)}}else return o("expected z.* or encrypted(...)");for(;i(".");){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"strict":n(")"),e=e.strict();break;case"nullable":n(")"),e=e.nullable();break;case"optional":n(")"),e=e.optional();break;case"length":{let a=p();if(typeof a!="number"||!Number.isInteger(a)||a<0)return o("expected non-negative integer for .length()");n(")"),e=e.length(a);break}case"regex":{n("new RegExp(");let a=f();n(")"),n(")"),e=e.regex(new RegExp(a));break}default:return o(`unsupported modifier .${h}()`)}}return e},b=u();return s(),t!==r.length&&o("unexpected trailing tokens"),b}function k(r){return typeof r=="object"&&r!==null&&typeof r["~standard"]?.validate=="function"}export{S as routeContracts};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{g as m}from"./
|
|
1
|
+
/*! palbase 0.75.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{g as m}from"./3GR5ZPYK.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
|
|
3
3
|
`):process.stdout.write(`${o}
|
|
4
4
|
`)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
|