palbase 0.52.3 → 0.52.4
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/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/{UH5Q63EN.js → 2JWR4TOH.js} +2 -2
- package/dist/chunks/{ZAR57AMM.js → 2YNLJAG5.js} +1 -1
- package/dist/chunks/{2PCDSIWJ.js → 4NILQCHQ.js} +1 -1
- package/dist/chunks/{JJC4IE3C.js → 6CQFSNLY.js} +2 -2
- package/dist/chunks/{CLFVU67I.js → 7GD3L3PE.js} +2 -2
- package/dist/chunks/{N7ZEBHXL.js → C64DV7YH.js} +2 -2
- package/dist/chunks/{57HMBEZC.js → DXBUBVLA.js} +3 -3
- package/dist/chunks/{DOOOEV6B.js → HI5LYPKI.js} +2 -2
- package/dist/chunks/{LHOFBMBZ.js → IAOUEMQZ.js} +2 -2
- package/dist/chunks/{P2IYCDCP.js → IRNNGVIR.js} +1 -1
- package/dist/chunks/{MFQQUKVA.js → KYM3FOIG.js} +2 -2
- package/dist/chunks/{OPXS5CYY.js → NWSACFNU.js} +1 -1
- package/dist/chunks/{XHTOI77Q.js → OVBMWRJE.js} +1 -1
- package/dist/chunks/{VNMRZXZM.js → OX35EL23.js} +2 -2
- package/dist/chunks/{TGML3Y7W.js → P7KXATI4.js} +2 -2
- package/dist/chunks/{6EWQSD7D.js → PKKXILGV.js} +1 -1
- package/dist/chunks/{IMY77ULI.js → RFO74P2O.js} +1 -1
- package/dist/chunks/{JL542ZSC.js → SER5LGIQ.js} +2 -2
- package/dist/chunks/SXRHHF3J.js +2 -0
- package/dist/chunks/{5ASDRQ76.js → T3VXSKEG.js} +2 -2
- package/dist/chunks/{QBER5HWP.js → WSPAP2CG.js} +2 -2
- package/dist/chunks/{3OXYHLPZ.js → WZHBF3BR.js} +2 -2
- package/dist/chunks/{7ZMRJPD5.js → Y5QCPCHW.js} +2 -2
- package/dist/cli.js +55 -55
- package/dist/cloud/index.js +2 -2
- 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/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/internal/src/modules/auth.d.ts +71 -5
- package/types/web/src/auth.d.ts +2 -2
- package/dist/chunks/IAEVNAIO.js +0 -2
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
2
|
-
import{a,b,c,d,e,f}from"../chunks/
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f}from"../chunks/Y5QCPCHW.js";import"../chunks/OX35EL23.js";import"../chunks/OVBMWRJE.js";import"../chunks/SXRHHF3J.js";import"../chunks/7GD3L3PE.js";import"../chunks/2JWR4TOH.js";import"../chunks/4NILQCHQ.js";import"../chunks/IRNNGVIR.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
|
package/dist/backend/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
2
|
-
import{ia as w,ma as h}from"../chunks/
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ia as w,ma as h}from"../chunks/SER5LGIQ.js";import"../chunks/HI5LYPKI.js";import"../chunks/WZHBF3BR.js";import"../chunks/Y5QCPCHW.js";import"../chunks/OX35EL23.js";import"../chunks/WSPAP2CG.js";import"../chunks/PKKXILGV.js";import"../chunks/NWSACFNU.js";import"../chunks/OVBMWRJE.js";import"../chunks/SXRHHF3J.js";import"../chunks/7GD3L3PE.js";import"../chunks/2JWR4TOH.js";import"../chunks/4NILQCHQ.js";import"../chunks/IRNNGVIR.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.52.
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
2
|
-
import{$ as Mt,A as ut,B as L,C as pt,D as ft,E as ht,F as gt,G as mt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as _t,R as Rt,S as Tt,T as xt,U as Ot,V as Ct,W as Bt,X as Ft,Y as ne,Z as It,_ as Lt,a as Z,aa as Dt,b as ee,ba as $t,c as te,ca as Ut,d as qe,da as Nt,e as Ke,ea as jt,f as We,fa as qt,g as Ve,ga as M,h as Ge,ha as Gt,i as ze,ia as D,j as He,ja as G,k as Ye,ka as zt,l as Je,la as Ht,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as rt,s as st,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/JL542ZSC.js";import{a as Kt,b as Wt}from"../chunks/DOOOEV6B.js";import{a as oe}from"../chunks/IMY77ULI.js";import{a as C,b as re,c as se,f as m,g as V,h as d,j as ae,k as Vt}from"../chunks/3OXYHLPZ.js";import"../chunks/7ZMRJPD5.js";import"../chunks/VNMRZXZM.js";import{d as O,j as Ne,k as je,l as J,m as I,t as Q,u as X}from"../chunks/QBER5HWP.js";import"../chunks/6EWQSD7D.js";import"../chunks/OPXS5CYY.js";import"../chunks/XHTOI77Q.js";import{p as Ue}from"../chunks/IAEVNAIO.js";import"../chunks/CLFVU67I.js";import{b as R,c as W}from"../chunks/UH5Q63EN.js";import"../chunks/2PCDSIWJ.js";import"../chunks/P2IYCDCP.js";import"reflect-metadata";import{existsSync as H,writeFileSync as Lr,writeSync as Mr}from"node:fs";import{createServer as Dr}from"node:http";import{dirname as T,join as Y,resolve as xe}from"node:path";import{Readable as $r}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,$=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Jt,this.shutdownMs=r.shutdownMs??Yt,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,l=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${l}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as er,bunDriver as tr,createDatabase as rr,pooledBinding as sr,sayRunning as nr,envBlock as ar,createSearchWorker as or,cutOff as ir,forgetUserIn as lr,MigrationOpen as cr,MigrationRefused as dr,Migrator as ue,renewingBunPool as ie,VersionNotMigrated as ur}from"palgres";import{toModel as pe}from"palgres/dsl";var pr=["start","complete","rollback","plan","status","types"],fr=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function fe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!pr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function he(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.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 N(t){return pe(he(t))}function hr(t){return t.tables.some(e=>e.search!==void 0)}function j(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function ge(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function gr(t,e){if(t.url!==void 0||t.driver!==void 0)return;let r=e.PALBASE_DB_POOLED_URL;return r===void 0||r===""?void 0:r}function mr(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let r=Number(e);if(!Number.isSafeInteger(r)||r<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 r}var br=2,yr=5e3;async function wr(t,e,r=yr){let s=await t.reserve();try{await s.unsafe(e)}catch(o){throw s.release(),o}let n=s,a=!1,i=!1,l=async()=>{if(n!==void 0)try{await n.unsafe("SELECT 1");return}catch{n.release(),n=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(u){throw o.release(),u}a?o.release():n=o},c=setInterval(()=>{i||a||(i=!0,l().catch(o=>d.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 ${r/1e3} s`)).finally(()=>{i=!1}))},r);return c.unref?.(),{stop(){a=!0,clearInterval(c),n?.release(),n=void 0}}}function Pr(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 le=5;function z(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=ie(()=>new r.SQL({url:n,prepare:!1,max:s})),i=ie(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(l,c)=>a.unsafe(l,c),begin:l=>a.current.begin(l)},engine:tr(a,i),poolSize:s,close:async()=>{await a.close({timeout:le}),await i.close({timeout:le})}}}}async function me(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await B("types",ar(r,{module:"palbase/backend/env"}),e),0}async function ye(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!fr.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=z(t,ge(e)),i=a(s),l,c=o=>d.error(`[palbase] migrate ${r}: ${o}`);try{let o=N(t),u=new ue(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(l=f.trim()),d.info(f)},shadow:f=>{let w=new URL(s);w.pathname=`/${f}`;let b=a(w.toString());return{reserve:()=>b.pool.reserve(),end:()=>b.close()}},openedBy:n,fields:()=>Sr(e)});if(r==="plan"){let f=await u.plan(o);return await B(r,f),f.refusals.length>0?1:0}if(r==="status")return await B(r,await u.status()),0;let p=r==="start"?await vr(u,o,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:p}),await B(r,p),0}catch(o){return o instanceof dr?(d.error(`[palbase] migrate ${r}: refused`,{refusals:o.refusals}),c(`refused \u2014 ${o.refusals.join("; ")}`),1):ir(o)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:o}),c(`cut off \u2014 ${l??ce(o)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:o}),c(`failed \u2014 ${ce(o)}`),1)}finally{await i.close().catch(()=>{})}}async function Sr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)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 s=O({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function vr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof cr)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var Ar=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,r=Ar){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as Mt,A as ut,B as L,C as pt,D as ft,E as ht,F as gt,G as mt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as _t,R as Rt,S as Tt,T as xt,U as Ot,V as Ct,W as Bt,X as Ft,Y as ne,Z as It,_ as Lt,a as Z,aa as Dt,b as ee,ba as $t,c as te,ca as Ut,d as qe,da as Nt,e as Ke,ea as jt,f as We,fa as qt,g as Ve,ga as M,h as Ge,ha as Gt,i as ze,ia as D,j as He,ja as G,k as Ye,ka as zt,l as Je,la as Ht,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as rt,s as st,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/SER5LGIQ.js";import{a as Kt,b as Wt}from"../chunks/HI5LYPKI.js";import{a as oe}from"../chunks/RFO74P2O.js";import{a as C,b as re,c as se,f as m,g as V,h as d,j as ae,k as Vt}from"../chunks/WZHBF3BR.js";import"../chunks/Y5QCPCHW.js";import"../chunks/OX35EL23.js";import{d as O,j as Ne,k as je,l as J,m as I,t as Q,u as X}from"../chunks/WSPAP2CG.js";import"../chunks/PKKXILGV.js";import"../chunks/NWSACFNU.js";import"../chunks/OVBMWRJE.js";import{p as Ue}from"../chunks/SXRHHF3J.js";import"../chunks/7GD3L3PE.js";import{b as R,c as W}from"../chunks/2JWR4TOH.js";import"../chunks/4NILQCHQ.js";import"../chunks/IRNNGVIR.js";import"reflect-metadata";import{existsSync as H,writeFileSync as Lr,writeSync as Mr}from"node:fs";import{createServer as Dr}from"node:http";import{dirname as T,join as Y,resolve as xe}from"node:path";import{Readable as $r}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,$=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Jt,this.shutdownMs=r.shutdownMs??Yt,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,l=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${l}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as er,bunDriver as tr,createDatabase as rr,pooledBinding as sr,sayRunning as nr,envBlock as ar,createSearchWorker as or,cutOff as ir,forgetUserIn as lr,MigrationOpen as cr,MigrationRefused as dr,Migrator as ue,renewingBunPool as ie,VersionNotMigrated as ur}from"palgres";import{toModel as pe}from"palgres/dsl";var pr=["start","complete","rollback","plan","status","types"],fr=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function fe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!pr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function he(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.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 N(t){return pe(he(t))}function hr(t){return t.tables.some(e=>e.search!==void 0)}function j(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function ge(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function gr(t,e){if(t.url!==void 0||t.driver!==void 0)return;let r=e.PALBASE_DB_POOLED_URL;return r===void 0||r===""?void 0:r}function mr(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let r=Number(e);if(!Number.isSafeInteger(r)||r<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 r}var br=2,yr=5e3;async function wr(t,e,r=yr){let s=await t.reserve();try{await s.unsafe(e)}catch(o){throw s.release(),o}let n=s,a=!1,i=!1,l=async()=>{if(n!==void 0)try{await n.unsafe("SELECT 1");return}catch{n.release(),n=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(u){throw o.release(),u}a?o.release():n=o},c=setInterval(()=>{i||a||(i=!0,l().catch(o=>d.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 ${r/1e3} s`)).finally(()=>{i=!1}))},r);return c.unref?.(),{stop(){a=!0,clearInterval(c),n?.release(),n=void 0}}}function Pr(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 le=5;function z(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=ie(()=>new r.SQL({url:n,prepare:!1,max:s})),i=ie(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(l,c)=>a.unsafe(l,c),begin:l=>a.current.begin(l)},engine:tr(a,i),poolSize:s,close:async()=>{await a.close({timeout:le}),await i.close({timeout:le})}}}}async function me(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await B("types",ar(r,{module:"palbase/backend/env"}),e),0}async function ye(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!fr.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=z(t,ge(e)),i=a(s),l,c=o=>d.error(`[palbase] migrate ${r}: ${o}`);try{let o=N(t),u=new ue(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(l=f.trim()),d.info(f)},shadow:f=>{let w=new URL(s);w.pathname=`/${f}`;let b=a(w.toString());return{reserve:()=>b.pool.reserve(),end:()=>b.close()}},openedBy:n,fields:()=>Sr(e)});if(r==="plan"){let f=await u.plan(o);return await B(r,f),f.refusals.length>0?1:0}if(r==="status")return await B(r,await u.status()),0;let p=r==="start"?await vr(u,o,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:p}),await B(r,p),0}catch(o){return o instanceof dr?(d.error(`[palbase] migrate ${r}: refused`,{refusals:o.refusals}),c(`refused \u2014 ${o.refusals.join("; ")}`),1):ir(o)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:o}),c(`cut off \u2014 ${l??ce(o)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:o}),c(`failed \u2014 ${ce(o)}`),1)}finally{await i.close().catch(()=>{})}}async function Sr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)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 s=O({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function vr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof cr)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var Ar=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,r=Ar){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,s))}function ce(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
4
|
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function kr(t,e){try{return await new ue(t).plan(e)}catch{return}}var de="palbase.idempotency_keys.response_body";function Er(t,e){let r=null,s=!1,n=async()=>{let l=e.currentKey();if(!(s||l===r)){s=!0;try{let c=await t.reseal();r=l;let o=c.reduce((u,p)=>u+p.resealed,0);o>0&&d.info(`[palbase] fields: ${o} value(s) sealed again with key ${l}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${l} stopped; tried again in a minute`,{error:c})}finally{s=!1}}},a=setTimeout(n,1e4),i=setInterval(n,6e4);for(let l of[a,i])l.unref?.();return()=>{clearTimeout(a),clearInterval(i)}}var U=class extends Error{digest;plan;constructor(e,r){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...r?_r(r):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function _r(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let r of t.changes)e.push(` + ${r}`);for(let r of t.refusals)e.push(` \u2717 ${r}`);return e}var Rr=8e4;async function we(t,e,r,s){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=he(t),i=pe(a),l=gr(t,e),c=z(t,l===void 0?ge(e):br)(n),o,u;try{let p=!1,f=g=>{p||(p=!0,d.warn(`[palbase] database: not answering yet (${g instanceof Error?g.message:String(g)}) \u2014 waiting for it, as one waking does`))},w=await er(c.engine,i,{waitMs:s.onPlatform?Rr:0,onUnreachable:f}).catch(async g=>{throw s.onPlatform||!(g instanceof ur)?g:new U(g.digest,await kr(c.pool,i))});l!==void 0&&(u=await wr(c.pool,nr(w)),o=z(t,mr(e))(l));let b=o??c,A=Zt("sha256",r).update("palgres page cursor").digest("hex"),y=t.embed??s.embed,h=s.fields,k=await rr({sql:b.engine,schemas:a,binding:o===void 0?w:sr(w),...o===void 0?{}:{prepare:!1},cursorSecret:A,admission:Pr(b.poolSize),embed:y,log:g=>d.warn(`[palbase] ${g}`),fields:async()=>(await h.load(),h)}),E=h.loaded?Er(k,h):()=>{},_=hr(i)?or({sql:b.engine,embed:y,log:g=>d.info(`[palbase] ${g}`)}):void 0;return{model:i,binding:w,app:k,requests:t.requests??"caller",forget:(g,P)=>lr({attempt:v=>P.$attempt(v)},w,i,g),..._?{search:_}:{},keptAnswers:{seal:g=>h.loaded?h.encrypt(de,g):g,open:async g=>h.isEncrypted(g)?(h.loaded||await h.load(),h.decrypt(de,g)):g},close:async()=>{E(),h.close(),await o?.close(),u?.stop(),await c.close()}}}catch(p){throw await o?.close().catch(()=>{}),u?.stop(),await c.close(),p}}function Tr(t){let e=Buffer.from(t,"base64"),r=new Array(e.byteLength/4);for(let s=0;s<r.length;s++)r[s]=e.readFloatLE(s*4);return r}function Pe(t){return async({texts:e,model:r,dimensions:s})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:r,dimensions:s}});return{model:n.model,vectors:n.vectors.map(Tr)}}}var xr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Se(t,e,r){let s=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&s.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&s.push("palbase.url / PALBASE_URL is the project origin alone")}catch{s.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let i=t.projectId??e.PALBASE_PROJECT_ID??"";xr.test(i)||s.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let l=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(l)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&s.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let o=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(c!==void 0||o!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(o??"")&&s.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),s.length>0)throw new Error(`[palbase] the app cannot start:
|
|
@@ -9,4 +9,4 @@ ${s.join(`
|
|
|
9
9
|
`)}
|
|
10
10
|
`}function ke(t,e,r=Cr){let s=Buffer.from(e,"utf8"),n=new Int32Array(new SharedArrayBuffer(4));for(let a=0;a<s.length;)try{a+=r(t,s,a,s.length-a)}catch(i){if(i.code!=="EAGAIN")throw i;Atomics.wait(n,0,0,5)}}var Ee=2e4,_e=5e3,Ur=15e3,Nr="/_palbase/health";function jr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=L(s,Z);return n?n.providers.some(a=>L(a,ee)!==void 0&&L(a,te)===void 0)||n.imports.some(r):!1};return t.some(r)}var qr={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=fe(s);if(n!==void 0){let P=n==="types"?await be(e.db):e.db?await ye(e.db,s,n):await me(n);throw process.exit(P),new q(P)}let a=s.PALBASE_CONTRACT_OUT;if(a){let P;try{await Te(Re(s)),P=await Kr(r,e,s)}catch(v){throw Mr(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
|
|
11
11
|
`),process.exit(1),new F}throw a==="/dev/stdout"?ke(1,Ae(P)):Lr(a,`${P}
|
|
12
|
-
`),process.exit(0),new F}let i=Re(s),l=await Te(i);l&&d.info(`[palbase] strings: ${l.source} and ${l.locales.length-1} other language(s), ${Object.keys(l.strings).length} sentence(s), from ${i}/palbase/strings`),ae(l?void 0:i);let c=e.db?N(e.db):void 0,o=await X({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&d.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let u=jr(r)||c!==void 0&&j(c),p=Se(e.palbase??{},s,{needsWebhookSecret:u});u&&p.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=O({url:p.url,secretKey:p.secretKey}),w=e.port??Number(s.PORT??"8080");if(!Number.isInteger(w)||w<0||w>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let b=e.db?await we(e.db,s,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;b&&d.info(`[palbase] database: version ${b.binding.version}`);let A=b&&j(b.model)?{"user.deleted":[P=>Wr(b,P)]}:void 0,y=p.platformSecret===void 0?void 0:{secret:p.platformSecret},h=e.requestTelemetry===!1?void 0:new $(f.analytics),k=()=>D({modules:r,verifier:new I({issuer:p.url,projectId:p.projectId,standing:J({url:p.url,secretKey:p.secretKey})}),server:f,webhookSecret:p.webhookSecret,env:s,projectId:p.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zr(e.cors,s.PALBASE_WEB_ORIGINS),platform:y,events:A,database:b&&{app:b.app,requests:b.requests,keptAnswers:b.keptAnswers},strings:l}),E=k(),_=e.boot?.attempts??5,g=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(v){if(P>=_)throw d.error(`[palbase] the app did not start after ${_} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${P} of ${_}); trying again in ${g} ms`,{error:v}),await new Promise($e=>setTimeout($e,g)),g*=2,E=k()}return Vr(E,f,w,e.host??"0.0.0.0",e.exitOnFatal??!0,b)}};function Re(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=T(xe(e));for(;!H(Y(r,"package.json"))&&T(r)!==r;)r=T(r);return H(Y(r,"package.json"))?r:process.cwd()}async function Te(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 Kr(t,e,r){let s=xe(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=T(s);for(;!H(Y(n,"package.json"))&&T(n)!==n;)n=T(n);let{analyzeProject:a}=await import("../chunks/N7ZEBHXL.js"),{routeContracts:i}=await import("../chunks/TGML3Y7W.js"),l=a(n,s);for(let u of l.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",o=D({modules:t,verifier:new I({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:O({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(l.routes),errors:ne()},events:e.db&&j(N(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var F=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 Wr(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r,V.$asService());d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Vr(t,e,r,s,n,a){let i,l={on:!1},c=(y,h)=>new URL(y.url).pathname===Nr&&y.method==="GET"?Promise.resolve(l.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(y,h),o=Dr((y,h)=>{Gr(c,y,h,l).finally(()=>{l.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((y,h)=>{o.once("error",h),o.listen(r,s,()=>y())})}catch(y){throw await t.stop(),await a?.close(),y}let u=o.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=y=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),l.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let k=setTimeout(()=>o.closeAllConnections(),y);await h,clearTimeout(k),process.off("SIGINT",b),process.off("uncaughtException",A),process.off("unhandledRejection",A);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",b)}})(),f=()=>p(Ee),w=!1,b=()=>{if(w){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}w=!0;let y=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+Ur);y.unref(),f().then(()=>{clearTimeout(y),process.exit(0)},h=>{clearTimeout(y),d.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},A=y=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:y});let h=setTimeout(()=>process.exit(1),_e+1e3);p(_e).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",b),process.once("SIGINT",b),n&&(process.on("uncaughtException",A),process.on("unhandledRejection",A)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Gr(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[p,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let w of f)i.append(p,w);else i.set(p,f);let l=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:i,body:l?$r.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(o,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=u.status,u.headers.forEach((p,f)=>r.setHeader(f,p)),s.on&&r.setHeader("connection","close"),u.body)for await(let p of u.body)r.write(p);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function zr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(l=>l.trim()).filter(l=>l!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(l=>G(l)),a=s.filter(l=>!G(l));a.length>0&&r(`[palbase] the project's web origins ${a.map(l=>JSON.stringify(l)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as sn,boolean as nn,check as an,date as on,defineSchema as ln,defineTable as cn,enumType as dn,foreignKey as un,index as pn,integer as fn,jsonb as hn,numeric as gn,ownedByUser as mn,policy as bn,raw as yn,sqlType as wn,text as Pn,timestamp as Sn,userRef as vn,uuid as An}from"palgres/dsl";import{increment as En,now as _n}from"palgres";function x(t){if(t instanceof R)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function S(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return x(r)}}var Hr=C("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yr=100,Jr=1e3,Qr=168*3600,Xr={s:1,m:60,h:3600,d:86400};function Zr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Xr[n]*1e3);return Math.ceil(r/1e3)}function Me(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>W(s,"path",i)).join("%2F")}catch(i){throw i instanceof R&&i.code==="invalid_path_parameter"?new R({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${m.url}/storage/public/${W(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Oe(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,Me(t.bucket,t.path,e)]))}}function es(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await m.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof R&&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}:x(a)}},async download(e){try{let r=await m.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return x(r)}},getPublicUrl(e,r){return Me(t,e,r?.variant)},async createSignedUrl(e,r){let s=Zr(r?.expiresIn);return s===void 0||s<1||s>Qr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:S(()=>m.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??Yr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,l=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Jr,n+s-a.length)),o=await m.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});l=o.status;for(let u of o.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=o.data.next_cursor,!i)break}}catch(c){return x(c)}return{data:a,error:null,status:l}},async remove(e){let r=[];for(let s of e){try{await m.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return x(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return S(()=>m.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return S(()=>m.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var ts={bucket:es},Ce=t=>re("Storage",t,ts),rs={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},ss=C("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return S(()=>m.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return S(()=>m.notify.sendEmail({body:{...n,to:e}}),l=>({...l.message_id!==void 0?{message_id:l.message_id}:{},...l.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let l of e)try{let c=await m.notify.sendEmail({body:{...n,to:l}});i=c.status,a.push(c.data.message_id??null)}catch(c){return x(c)}return{data:{message_ids:a},error:null,status:i}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Ie=t=>t==="override"?"user":t,ns=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function De(){return se.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:De();return S(()=>e?m.flags.getUserValues({path:{user_id:e}}):m.flags.getValues(),r=>r.values??{})}var Le={setOverrideForUser:(t,e,r)=>S(()=>m.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Ie(s.source)})),setOverridesForUser:(t,e)=>S(()=>m.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>S(()=>m.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Ie(r.source)})),clearAllOverridesForUser:t=>S(()=>m.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>S(()=>m.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},as=C("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await K(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Be(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await K(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Fe(r.data[t]),error:null,status:r.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(([r,s])=>{let n=Fe(s);return{name:r,enabled:Be(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):ns(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await K(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let l=i.data[t];return{data:l===void 0?s??null:l,error:null,status:i.status}},async setOverride(t,e){let r=De();return r?Le.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Le}}),os=C("Realtime",{broadcast(t,e,r){return S(()=>m.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return S(()=>m.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return S(()=>m.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as In}from"zod";export{at as AttestedDevice,je as AuthUnavailable,At as Authorize,Lt as BadRequest,Ye as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,nt as Client,Mt as Conflict,F as ContractRunEnded,qe as Controller,dt as Cron,V as Database,Dt as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,as as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,Ke as Get,Qe as Headers,$t as HttpError,it as Injectable,d as Log,Gt as MAX_BODY_BYTES,q as MigrationRunEnded,lt as Module,Ut as NotFound,ss as Notifications,ct as On,Et as OnConnect,_t as OnDisconnect,Rt as OnEmpty,kt as OnFirst,et as OptionalUser,Ct as PalError,m as Palbase,R as PalbaseError,qr as PalbaseFactory,Xe as Param,Ge as Patch,We as Post,Ve as Put,He as Query,Je as QueryParams,os as Realtime,tt as Req,rt as RequestId,ot as Resolve,U as SchemaNotPushed,Hr as Secrets,Nt as SerializationFailure,rs as Storage,Tt as Subscribe,gt as Task,ht as TaskFailure,mt as Tasks,bt as TestUserTemplate,Ne as TokenError,I as TokenVerifier,jt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Ze as User,ut as Webhook,sn as bigint,nn as boolean,an as check,D as createApp,on as date,It as defineError,ln as defineSchema,cn as defineTable,Wt as encrypt,Kt as encrypted,dn as enumType,un as foreignKey,pt as getRegisteredControllers,ft as getRoutes,xt as getWebhookManifest,En as increment,pn as index,fn as integer,hn as jsonb,_n as now,gn as numeric,mn as ownedByUser,bn as policy,yn as raw,wn as sqlType,Vt as t,Pn as text,Sn as timestamp,vn as userRef,An as uuid,In as z};
|
|
12
|
+
`),process.exit(0),new F}let i=Re(s),l=await Te(i);l&&d.info(`[palbase] strings: ${l.source} and ${l.locales.length-1} other language(s), ${Object.keys(l.strings).length} sentence(s), from ${i}/palbase/strings`),ae(l?void 0:i);let c=e.db?N(e.db):void 0,o=await X({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&d.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let u=jr(r)||c!==void 0&&j(c),p=Se(e.palbase??{},s,{needsWebhookSecret:u});u&&p.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=O({url:p.url,secretKey:p.secretKey}),w=e.port??Number(s.PORT??"8080");if(!Number.isInteger(w)||w<0||w>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let b=e.db?await we(e.db,s,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;b&&d.info(`[palbase] database: version ${b.binding.version}`);let A=b&&j(b.model)?{"user.deleted":[P=>Wr(b,P)]}:void 0,y=p.platformSecret===void 0?void 0:{secret:p.platformSecret},h=e.requestTelemetry===!1?void 0:new $(f.analytics),k=()=>D({modules:r,verifier:new I({issuer:p.url,projectId:p.projectId,standing:J({url:p.url,secretKey:p.secretKey})}),server:f,webhookSecret:p.webhookSecret,env:s,projectId:p.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zr(e.cors,s.PALBASE_WEB_ORIGINS),platform:y,events:A,database:b&&{app:b.app,requests:b.requests,keptAnswers:b.keptAnswers},strings:l}),E=k(),_=e.boot?.attempts??5,g=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(v){if(P>=_)throw d.error(`[palbase] the app did not start after ${_} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${P} of ${_}); trying again in ${g} ms`,{error:v}),await new Promise($e=>setTimeout($e,g)),g*=2,E=k()}return Vr(E,f,w,e.host??"0.0.0.0",e.exitOnFatal??!0,b)}};function Re(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=T(xe(e));for(;!H(Y(r,"package.json"))&&T(r)!==r;)r=T(r);return H(Y(r,"package.json"))?r:process.cwd()}async function Te(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 Kr(t,e,r){let s=xe(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=T(s);for(;!H(Y(n,"package.json"))&&T(n)!==n;)n=T(n);let{analyzeProject:a}=await import("../chunks/C64DV7YH.js"),{routeContracts:i}=await import("../chunks/P7KXATI4.js"),l=a(n,s);for(let u of l.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",o=D({modules:t,verifier:new I({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:O({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(l.routes),errors:ne()},events:e.db&&j(N(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var F=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 Wr(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r,V.$asService());d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Vr(t,e,r,s,n,a){let i,l={on:!1},c=(y,h)=>new URL(y.url).pathname===Nr&&y.method==="GET"?Promise.resolve(l.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(y,h),o=Dr((y,h)=>{Gr(c,y,h,l).finally(()=>{l.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((y,h)=>{o.once("error",h),o.listen(r,s,()=>y())})}catch(y){throw await t.stop(),await a?.close(),y}let u=o.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=y=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),l.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let k=setTimeout(()=>o.closeAllConnections(),y);await h,clearTimeout(k),process.off("SIGINT",b),process.off("uncaughtException",A),process.off("unhandledRejection",A);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",b)}})(),f=()=>p(Ee),w=!1,b=()=>{if(w){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}w=!0;let y=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+Ur);y.unref(),f().then(()=>{clearTimeout(y),process.exit(0)},h=>{clearTimeout(y),d.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},A=y=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:y});let h=setTimeout(()=>process.exit(1),_e+1e3);p(_e).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",b),process.once("SIGINT",b),n&&(process.on("uncaughtException",A),process.on("unhandledRejection",A)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Gr(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[p,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let w of f)i.append(p,w);else i.set(p,f);let l=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:i,body:l?$r.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(o,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=u.status,u.headers.forEach((p,f)=>r.setHeader(f,p)),s.on&&r.setHeader("connection","close"),u.body)for await(let p of u.body)r.write(p);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function zr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(l=>l.trim()).filter(l=>l!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(l=>G(l)),a=s.filter(l=>!G(l));a.length>0&&r(`[palbase] the project's web origins ${a.map(l=>JSON.stringify(l)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as sn,boolean as nn,check as an,date as on,defineSchema as ln,defineTable as cn,enumType as dn,foreignKey as un,index as pn,integer as fn,jsonb as hn,numeric as gn,ownedByUser as mn,policy as bn,raw as yn,sqlType as wn,text as Pn,timestamp as Sn,userRef as vn,uuid as An}from"palgres/dsl";import{increment as En,now as _n}from"palgres";function x(t){if(t instanceof R)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function S(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return x(r)}}var Hr=C("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yr=100,Jr=1e3,Qr=168*3600,Xr={s:1,m:60,h:3600,d:86400};function Zr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Xr[n]*1e3);return Math.ceil(r/1e3)}function Me(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>W(s,"path",i)).join("%2F")}catch(i){throw i instanceof R&&i.code==="invalid_path_parameter"?new R({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${m.url}/storage/public/${W(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Oe(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,Me(t.bucket,t.path,e)]))}}function es(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await m.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof R&&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}:x(a)}},async download(e){try{let r=await m.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return x(r)}},getPublicUrl(e,r){return Me(t,e,r?.variant)},async createSignedUrl(e,r){let s=Zr(r?.expiresIn);return s===void 0||s<1||s>Qr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:S(()=>m.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??Yr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,l=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Jr,n+s-a.length)),o=await m.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});l=o.status;for(let u of o.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=o.data.next_cursor,!i)break}}catch(c){return x(c)}return{data:a,error:null,status:l}},async remove(e){let r=[];for(let s of e){try{await m.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return x(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return S(()=>m.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return S(()=>m.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var ts={bucket:es},Ce=t=>re("Storage",t,ts),rs={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},ss=C("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return S(()=>m.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return S(()=>m.notify.sendEmail({body:{...n,to:e}}),l=>({...l.message_id!==void 0?{message_id:l.message_id}:{},...l.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let l of e)try{let c=await m.notify.sendEmail({body:{...n,to:l}});i=c.status,a.push(c.data.message_id??null)}catch(c){return x(c)}return{data:{message_ids:a},error:null,status:i}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Ie=t=>t==="override"?"user":t,ns=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function De(){return se.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:De();return S(()=>e?m.flags.getUserValues({path:{user_id:e}}):m.flags.getValues(),r=>r.values??{})}var Le={setOverrideForUser:(t,e,r)=>S(()=>m.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Ie(s.source)})),setOverridesForUser:(t,e)=>S(()=>m.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>S(()=>m.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Ie(r.source)})),clearAllOverridesForUser:t=>S(()=>m.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>S(()=>m.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},as=C("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await K(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Be(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await K(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Fe(r.data[t]),error:null,status:r.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(([r,s])=>{let n=Fe(s);return{name:r,enabled:Be(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):ns(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await K(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let l=i.data[t];return{data:l===void 0?s??null:l,error:null,status:i.status}},async setOverride(t,e){let r=De();return r?Le.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Le}}),os=C("Realtime",{broadcast(t,e,r){return S(()=>m.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return S(()=>m.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return S(()=>m.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as In}from"zod";export{at as AttestedDevice,je as AuthUnavailable,At as Authorize,Lt as BadRequest,Ye as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,nt as Client,Mt as Conflict,F as ContractRunEnded,qe as Controller,dt as Cron,V as Database,Dt as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,as as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,Ke as Get,Qe as Headers,$t as HttpError,it as Injectable,d as Log,Gt as MAX_BODY_BYTES,q as MigrationRunEnded,lt as Module,Ut as NotFound,ss as Notifications,ct as On,Et as OnConnect,_t as OnDisconnect,Rt as OnEmpty,kt as OnFirst,et as OptionalUser,Ct as PalError,m as Palbase,R as PalbaseError,qr as PalbaseFactory,Xe as Param,Ge as Patch,We as Post,Ve as Put,He as Query,Je as QueryParams,os as Realtime,tt as Req,rt as RequestId,ot as Resolve,U as SchemaNotPushed,Hr as Secrets,Nt as SerializationFailure,rs as Storage,Tt as Subscribe,gt as Task,ht as TaskFailure,mt as Tasks,bt as TestUserTemplate,Ne as TokenError,I as TokenVerifier,jt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Ze as User,ut as Webhook,sn as bigint,nn as boolean,an as check,D as createApp,on as date,It as defineError,ln as defineSchema,cn as defineTable,Wt as encrypt,Kt as encrypted,dn as enumType,un as foreignKey,pt as getRegisteredControllers,ft as getRoutes,xt as getWebhookManifest,En as increment,pn as index,fn as integer,hn as jsonb,_n as now,gn as numeric,mn as ownedByUser,bn as policy,yn as raw,wn as sqlType,Vt as t,Pn as text,Sn as timestamp,vn as userRef,An as uuid,In as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
2
|
-
import{a as u}from"../chunks/
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u}from"../chunks/RFO74P2O.js";import{c as p,i as c}from"../chunks/WZHBF3BR.js";import"../chunks/Y5QCPCHW.js";import{b as l,c as g,d as f,e as y}from"../chunks/IAOUEMQZ.js";import"../chunks/OX35EL23.js";import"../chunks/PKKXILGV.js";import"../chunks/OVBMWRJE.js";import"../chunks/SXRHHF3J.js";import"../chunks/7GD3L3PE.js";import"../chunks/2JWR4TOH.js";import"../chunks/4NILQCHQ.js";import"../chunks/IRNNGVIR.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
2
|
-
import{a as g,b}from"./
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,b}from"./4NILQCHQ.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),At=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let a={},l=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await l(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let w=_t(c.kind,new Uint8Array(g));if(w===void 0)return;let y=await Et(c,g,w,t);y&&(a[c.id]=y)}catch{}})),a}var C=(d,t,a=0)=>d.length>=a+t.length&&t.every((l,c)=>d[a+c]===l),W=d=>[...d].map(t=>t.charCodeAt(0));function _t(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,a,l){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:a}))};case"font":{let c=At(d.id),p=globalThis.FontFace,g=l.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),a=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){a=h;break}if(a<0)throw new Error("not a zip");let l=t.getUint16(a+10,!0),c=t.getUint32(a+16,!0),p=new Map,g=0;for(let h=0;h<l;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let w=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),_=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+_+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(w===0)p.set(x,O);else if(w===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function qe(d,t){let a=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",l="";for(let c=0;c<t.length;c+=32768)l+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${a};base64,${btoa(l)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let a=new TextDecoder().decode(t),l=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,_)=>{let P=c(_);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(a,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(l(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let _=c(v);_?y.setAttribute(m,qe(_,d.get(_))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let w=h.createElement("meta");return w.setAttribute("http-equiv","Content-Security-Policy"),w.setAttribute("content",$t),h.head.prepend(w),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,a)=>`M${d-a} ${t}a${a} ${a} 0 1 0 ${2*a} 0a${a} ${a} 0 1 0 ${-2*a} 0`,de={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[K(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",K(6,18,3),K(17,16,3)],people:[K(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var Be="http://www.w3.org/2000/svg";function pe(d,t,a){let l=d.createElementNS(Be,"svg");l.setAttribute("viewBox","0 0 24 24"),l.setAttribute("width",String(a)),l.setAttribute("height",String(a)),l.setAttribute("fill","none"),l.setAttribute("stroke","currentColor"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("aria-hidden","true"),l.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),l.append(p)}return l}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),X=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:X(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:X(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:X()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:X(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:X(!0),text:X(),color:j("")},feature:{icon:f(void 0,!0),text:X(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],G=(d,t)=>d??t;function It(d){let t="";for(let a of new TextEncoder().encode(d)){let l=String.fromCharCode(a);t+=/^[A-Za-z0-9._~-]$/.test(l)?l:`%${a.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),a=Math.floor(d%86400/3600),l=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(a)}:${p(l)}:${p(c)}`:a>0?`${a}:${p(l)}:${p(c)}`:`${p(l)}:${p(c)}`,days:String(t),hours:p(a),minutes:p(l),seconds:p(c)}}function fn(d){let t=[],a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer"])a(l[c]);for(let c of Object.keys(M(l.sheets)).sort())a(M(M(l.sheets)[c]).root);return t}function Ut(d){let t=new Map,a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer","sheets"])a(l[c]);return t}function gn(d,t){return _e(d,t).tree}function _e(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:a,...l}=t;return new ue("message",d,{...l,packages:{"":{...a}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,a,l){this.kind=t,this.d=a,this.opts=l,this.offers=Ut(a);let c={};for(let[y,m]of Object.entries(l.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=l.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let w=M(this.d.theme);this.palette=M(M(w.colors)[l.appearance]);for(let[y,m]of Object.entries(M(w.typography))){let v={};for(let[_,P]of Object.entries(this.objectFields("typography"))){let R=G(M(m)[_],P.def);R!=null&&(v[_]=R)}this.typography[y]=v}this.radii=M(w.radii),this.spacing=M(w.spacing)}open(t){let a=this.offers.get(t);return a!==void 0&&(this.opts.offers??[]).includes(a)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,a]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?a:"";let l={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(l.selected=a);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let w of Object.keys(g))h.includes(w)||delete g[w];l.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let w=this.component(M(h),g,"",!1);w&&(l[g]=w)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,w]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(w).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(w).title,this.packages[this.selected]);m!==null&&(p[h]=m)}l.sheets=g}return{tree:l,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,a){return this.opts.switches&&Object.hasOwn(this.opts.switches,a)?this.opts.switches[a]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,a){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[a];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",a="",l="",c="",p=(h,w)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${w}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;l===""&&(l=m),y.selected===!0&&a===""&&(a=m);break}case"switch":{let m=this.switchOn(y,w),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${w}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,w);t===""&&(t=m),I(y.tabs).forEach((v,_)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${w}.tabs[${_}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],w===""?m:`${w}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||a||l;return[t,g]}holds(t,a){let l=a||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(l)!==p)return!1;break;case"offer_open":if(this.open(l)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,a,l,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),l))return null;let p=String(t.type),g=l,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let w={type:p};this.paths.set(w,a),Q(t,"id")&&(w.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(w.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(w.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,w,a,g);case"switch":return this.switchOf(t,w,a,g,h);case"countdown":return this.countdown(t,w,a,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;w.package=v,this.open(v)&&(w.offer=this.offers.get(v));let _=this.component(M(t.content),`${a}.content`,v,h);return _?(w.content=_,w):null}case"package":w.product=t.product,w.plan=t.plan,w.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(w.offer=t.offer)}for(let[v,_]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(_.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${a}.${v}`,g,h);if(!x&&_.required)return null;x&&(w[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${a}.${v}[${O}]`,g,h);V&&x.push(V)}),w[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)w[v]=x;else if(_.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(_.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(w[v]=x);break}case"object":{if(R){let x=this.object(M(P),_.item,m);if(x===null&&_.required)return null;w[v]=x}else v==="indicator"&&(w[v]=this.object({},_.item,m));break}case"value":{let x=this.value(G(P,_.def),_);x!=null&&x!==""&&(w[v]=x);break}}}return p==="text"&&this.typeStyle(w),w}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let a=this.typography[t.size];for(let l of["font","weight","line_height","letter_spacing","text_style"])!Q(t,l)&&a?.[l]!==void 0&&a?.[l]!==null&&(t[l]=a[l]);t.size=a?.size??null}tabs(t,a,l,c){let p=this.tabShown(t,l);this.tabsShown[l]=p;let g=[];return I(t.tabs).forEach((h,w)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${l}.tabs[${w}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let _=this.component(M(y.content),`${l}.tabs[${w}].content`,c,!1);_&&(a.content=_)}}),a.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(a.bar=this.style(M(t.bar))),a}switchOf(t,a,l,c,p){let g=this.switchOn(t,l);this.switchesOn[l]=g,a.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(a.label=h),a.tint=this.color(String(G(t.tint,"accent")));let w=g?"on":"off",y=this.component(M(t[w]),`${l}.${w}`,c,p);return y&&(a.content=y),a}countdown(t,a,l,c,p){let g=M(t.target),h=this.opts.now??Date.now(),w;if(typeof g.after_open_seconds=="number"?w=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):w=Math.trunc((Date.parse(String(g.at))-h)/1e3),w>0){a.state="counting",a.remaining_seconds=w,this.countdowns[l]=w;let y=this.packages,m={};for(let[_,P]of Object.entries(y))m[_]={...P,...Vt(w)};this.packages=m;let v=this.component(M(t.counting),`${l}.counting`,c,p);return v&&(a.content=v),this.packages=y,a}if(a.state="ended",a.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${l}.ended`,c,p);y&&(a.content=y)}return a}item(t,a,l){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=a[p];if(g.kind==="text"){let w=this.text(h,l);if(w!==null)c[p]=w;else if(g.required)return null}else{let w=g.def,y=this.value(G(h,w),g);y!=null&&(Q(a,p)||w!=null&&w!=="")&&(c[p]=y)}}return c}object(t,a,l){if(a==="style")return this.style(t);let c=this.item(a,t,l)??{};if(a==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],l);if(g===null)return null;c[p]=g}return c}defaults(t,a){let l={};for(let[c,p]of Object.entries(a)){let g=G(t[c],p.def);g!=null&&g!==""&&(l[c]=g)}return l}style(t){let a={};for(let[l,c]of Object.entries(t)){let p=this.objectFields("style")[l];if(!p){a[l]=c;continue}switch(p.kind){case"edges":a[l]=this.sides(c,Nt,this.spacing);break;case"corners":a[l]=this.sides(c,Dt,this.radii);break;case"fill":a[l]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[w,y]of Object.entries(this.objectFields(p.item))){let m=G(g[w],y.def);m!=null&&m!==""&&(h[w]=this.value(m,y))}a[l]=h;break}default:a[l]=c}}return a}sides(t,a,l){let c={};for(let p of a){let g=typeof t=="object"&&t!==null?G(M(t)[p],0):t;c[p]=Ae(g,l)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let a=M(t),l=this.defaults(a,this.objectFields(Ft[String(a.type)]??""));return Array.isArray(a.stops)&&(l.stops=a.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),l}value(t,a){if(a.kind!=="value")return t;switch(a.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return Ae(t,this.spacing);case"radius":return Ae(t,this.radii);default:return t}}color(t){let a=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof a=="string"?a:t}text(t,a){let l;if(typeof t=="string")l=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;l=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return l=l.replace(Ye,(p,g)=>{let h=a&&Object.hasOwn(a,g)?a[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||l.trim()===""?null:l}};function qt(d,t){let a=!1,l=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(a=!0,""):It(g)});return a?null:l}function Ae(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
|
|
3
3
|
:host{display:block;height:100%}
|
|
4
4
|
.pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
2
|
-
import{b as q,c as P,d as S}from"./VNMRZXZM.js";import{a as Y,f as Z,g as X,j as ee,k as te,l as ne,o as N,p as se,q as re}from"./OPXS5CYY.js";import{d as G}from"./CLFVU67I.js";import{a as E,b as Q,c as _,e as A}from"./UH5Q63EN.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function ae(t){return t instanceof p||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function D(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??We(e,"request_id"),data:x(e,"data"),cause:t};if(t.code==="network_error")return new p("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new p("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new p("attestationRequired",n);if(t.status===401)return new p("unauthorized",n);if(t.status===429)return new p("rateLimited",{...n,retryAfter:Je(e)??t.retryAfter});let s=Le(e);return t.status===400&&s?new p("validation",{...n,fields:s}):new p("server",n)}function I(t){return t instanceof Q||t instanceof Error&&t.name==="PalbaseError"}function oe(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Le(t){let e=x(x(t,"data"),"fields");if(oe(e))return e;let n=x(t,"fields");return oe(n)?n:void 0}function Je(t){return ie(t,"retry_after")??ie(x(t,"data"),"retryAfter")}function x(t,e){if(typeof t=="object"&&t!==null)return t[e]}function ie(t,e){let n=x(t,e);return typeof n=="number"?n:void 0}function We(t,e){let n=x(t,e);return typeof n=="string"?n:void 0}var He=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ve=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Ue=new Set(Ve),ze=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(t){return t==="then"||t==="toJSON"||ze.has(t)}function de(t){return t==="call"||t==="join"||$(t)}function le(t){return typeof t=="string"&&He.test(t)&&!Ue.has(t)&&!$(t)}function ue(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function ce(t){A(t)}function pe(t){return A(t).origin}var O=class t{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},n,s,r=!0){this.me=e,this.reader=n,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let n=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...n!==void 0?{turns:n}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let h=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(h,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(h=>q(h)).filter(h=>h!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),n===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;n-=a.turns}while(n>0);return this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let c=v(i);c<=0||(this.paged.add(c),(this.pagedFrom===void 0||c<this.pagedFrom)&&(this.pagedFrom=c),(this.pagedTo===void 0||c>this.pagedTo)&&(this.pagedTo=c))}let n=new t(this.me);n.thoughts=this.thoughts,n.lowest=this.lowest-e.length;let s=n.lowest;for(let i of e)n.at=s++,n.fold(i);this.folded+=n.folded,this.lowest=n.lowest,this.chatId??=n.chatId;let r=new Map;for(let[i,c]of n.messages){let y=this.told.get(i)??[],f=c;if(y.length>0)for(let C of y)f=me(f,C);else f=this.messages.get(i)??c;r.set(i,f);let m=[...n.told.get(i)??[],...y];m.length>0&&this.told.set(i,m)}for(let[i,c]of this.messages)r.has(i)||r.set(i,c);this.messages.clear();for(let[i,c]of r)this.messages.set(i,c);let o=new Map;for(let[i,c]of n.responses){let y=this.responses.get(i);o.set(i,y?Ye(c,y):c)}for(let[i,c]of this.responses)o.has(i)||o.set(i,c);this.responses.clear();for(let[i,c]of o)this.responses.set(i,c);let d=new Set;for(let i of n.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...n.order],l=new Set([...n.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&n.goalWords.has(i.event.seq))&&!(i.type==="voice"&&n.voiceWords.has(F(i.event)))){if(i.type==="message"&&i.began&&i.turn!==null){let c=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:c&&c.at<i.arrived?c.at-.5:i.arrived});continue}a.push(i)}a.sort((i,c)=>i.at-c.at),this.order=a;for(let i of n.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of n.voiceWords)this.voiceWords.add(i);let h=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=ye(this.voice,i.event,h));this.turn??=n.turn;let u=new Map([...n.calls,...this.calls]);this.calls.clear();for(let[i,c]of u)this.calls.set(i,c);for(let[i,c]of n.history)this.history.has(i)||this.history.set(i,c);this.forkedFrom??=n.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let n=q(e);n&&this.take(n)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let n=v(e);n>0&&this.pagedTo!==void 0&&n>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=ge(setTimeout(()=>this.quiet(),he)));return}this.takeNow(e)}}quiet(){let e=this.held.map(v).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Qe?this.heldTimer=ge(setTimeout(()=>this.quiet(),he)):this.sortHeld()}takeNow(e){let n=v(e);n>0&&this.paged.has(n)||(n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),n=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(v(a))),d=o<0?-1:n.findIndex(a=>v(a)===v(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],n[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<n.length&&fe(e[o+l],n[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(h=>v(h)>0),l=a!==void 0&&this.pagedFrom!==void 0&&v(a)<this.pagedFrom;for(let h of e){let u=v(h);u>0&&!(this.pagedFrom!==void 0&&u<this.pagedFrom)&&(l=!1),(l?s:r).push(h)}}if(s.length>0){let a=Math.min(...s.map(v).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:n.from+P(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:n.from+P(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let n=F(e);if(this.voiceWords.has(n))return!1;this.voice=ye(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);et(n,e.offset,e.text),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"reset":{let n=this.response(e.response_id);e.offset<=n.from?(n.text="",n.from=Math.max(0,e.offset)):n.text=n.text.slice(0,S(n.text,e.offset-n.from)),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);n.runId=e.run_id,n.agent=e.name,n.named=!0,n.parentId??=e.parent_response_id;break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Xe(e),s=this.messages.get(n);this.messages.set(n,me(s,e));let r=this.told.get(n);r?r.push(e):this.told.set(n,[e]),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,n){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,h])=>l!==n&&h.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:n,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,n),this.order.push({type:"response",key:e,at:this.at})),n}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=u=>e!==void 0&&u.startedBy===e,s=new Map;for(let u of this.responses.values()){let i=u.parentId!==null?this.responses.get(u.parentId)??u:u;s.set(u.id,tt(u,i.startedBy??null,n(i),u.goal??i.goal))}let r=new Map([...this.messages].map(([u,i])=>[u,e!==void 0&&i.author===e?{...i,mine:!0}:i])),o=[...this.history.entries()].sort(([u],[i])=>u-i).flatMap(([u,i])=>i.map((c,y)=>nt(c,`${u}:${y}`,e))),d=[...o];for(let u of this.order)u.type==="goal"?d.push({type:"goal",goal:u.event}):u.type==="voice"?d.push({type:"voice",voice:u.event}):u.type==="message"?d.push({type:"message",message:r.get(u.key)}):this.responses.get(u.key).parentId===null&&d.push({type:"response",response:s.get(u.key)});let a=o.flatMap(u=>u.type==="message"?[u.message]:[]),l=o.flatMap(u=>u.type==="response"?[u.response]:[]),h=[...this.calls.values()].filter(u=>s.get(u.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:h.filter(u=>u.status==="awaiting_approval"),outputs:h.filter(u=>u.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Ze(this.voice,e):null}}},he=150,Qe=2e3;function fe(t,e){let n=v(t);return n>0||v(e)>0?n===v(e):JSON.stringify(t)===JSON.stringify(e)}function v(t){let e=t.seq;return typeof e=="number"&&e>0?e:0}function ge(t){return t.unref?.(),t}function F(t){return`${t.voice_id}\0${t.status}`}function ye(t,e,n){return n.add(F(e)),(e.status==="closed"?t===null||t.voice_id===e.voice_id:!n.has(`${e.voice_id}\0closed`))?e:t}function me(t,e){let n=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??t?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:t?.status==="delivered"?"delivered":n,error:e.error??null,responseId:e.response_id??t?.responseId??null,createdAt:e.created_at??t?.createdAt??"",mine:!1,metadata:e.metadata??t?.metadata??{},history:!1,truncated:!1,kind:e.kind??t?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:t?.voice??null,attachments:e.attachments?we(e.attachments):t?.attachments??[]}}function Ye(t,e){let n={...t,marks:new Map(t.marks)};e.status!==null&&(n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=e.end),e.startedBy!==void 0&&(n.startedBy=e.startedBy),e.goal&&(n.goal=e.goal),e.named&&(n.runId=e.runId,n.agent=e.agent,n.named=!0),n.parentId=t.parentId??e.parentId,e.cut!==null&&(t.text===""||e.cut<=t.from?(n.text=e.text,n.from=e.text===""?Math.max(0,e.cut):e.from):n.text=t.text.slice(0,S(t.text,e.cut-t.from))+e.text,n.cut=t.cut===null?e.cut:Math.min(t.cut,e.cut));let s=r=>{if(t.text==="")return null;if(r!==null&&r<=t.from)return r;let o=P(t.text);return t.from+(r===null?o:Math.min(o,r-t.from))};for(let[r,o]of e.marks){let d=n.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")n.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);n.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?t.cut:t.cut===null?o.cutAt:Math.min(o.cutAt,t.cut)})}else n.marks.set(r,o)}return n}function Ze(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function we(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Xe(t){return`${t.author??""}\0${t.client_id}`}function et(t,e,n){if(t.text===""||e<=t.from){t.from=Math.max(0,e),t.text=n;return}t.text=t.text.slice(0,S(t.text,e-t.from))+n}function tt(t,e,n,s){let r=[...t.marks.values()].map((l,h)=>({m:l,i:h,at:S(t.text,Math.max(0,(Number(l.text_offset)||0)-t.from))}));r.sort((l,h)=>l.at-h.at||l.i-h.i);let o=[],d=[],a=0;for(let{m:l,at:h}of r)h>a&&o.push({type:"text",text:t.text.slice(a,h)}),a=Math.max(a,h),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<t.text.length&&o.push({type:"text",text:t.text.slice(a)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:d,goal:s,history:!1,truncated:!1}}function nt(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var B=[["ApiKeyAuth","userJWT"]];function ve(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.turns!==void 0&&(s.turns=n.turns),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:B,answers:{200:"json"},query:s,signal:n.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:B,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:B,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var M=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},be=new WeakMap;async function Ee(t,e,n,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:h,chat:u}=st(e),i=rt(d,n),c=be.get(t);c||be.set(t,c=new Map);let y=c,f=y.get(i)??{count:0};y.set(i,f),f.count++;let m=t.channel(i,h&&s.history!==!1?{after:0}:{});if(u&&!f.chat){let g=n.chatId,k=new O(r,o,typeof g=="string"&&g!==""?g:void 0,h&&s.history!==!1);f.chat=k,f.unchat=m.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let C=()=>{--f.count>0||(y.delete(i),f.unchat?.(),f.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?ke(m.refusal,"unavailable"):"socket closed";throw C(),new M(`gateway ${JSON.stringify(i)} was not joined: ${g}`,g)}let T=!1,R=new Set,V=()=>{if(!T){T=!0,Ke();for(let g of[...R])g();C()}},Ke=m.onClosed(V),U=g=>{if(T)return()=>{};let k=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),w=()=>{R.delete(w),k()};return R.add(w),w},z={topic:i,get seq(){return m.logSeq},on(g,k){if(typeof g=="function")return U((w,b)=>g({event:w,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return U((w,b)=>{w===g&&k(b)})},off(g){R.has(g)&&g()},async send(g,k){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let w=T?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:k});if(w.status==="ok")return E(w.response.reply);let b=ke(w.response,"unavailable");throw new M(`gateway ${JSON.stringify(i)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:V};return u&&Object.defineProperty(z,"chat",{value:f.chat,enumerable:!0}),z}function st(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function rt(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ke(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ot=3600*1e3,j=new Map;function it(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!n&&r&&Date.now()-r.at<ot)return r.list;let o=(async()=>{let d=se(),a;try{a=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await re(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function _e(t,e,n,s,r,o){let a=(await it(t,e,o)).keys[0];return X(a.kid,a.key,Z(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):N(e,n,s,(r,o)=>ee(t.key,r,o))}function xe(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):N(e,"/response",n,async(r,o)=>{if(!te(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ne(t.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(t){return t instanceof p&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var L=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as q,c as P,d as S}from"./OX35EL23.js";import{a as Y,f as Z,g as X,j as ee,k as te,l as ne,o as N,p as se,q as re}from"./NWSACFNU.js";import{d as G}from"./7GD3L3PE.js";import{a as E,b as Q,c as _,e as A}from"./2JWR4TOH.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function ae(t){return t instanceof p||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function D(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??We(e,"request_id"),data:x(e,"data"),cause:t};if(t.code==="network_error")return new p("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new p("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new p("attestationRequired",n);if(t.status===401)return new p("unauthorized",n);if(t.status===429)return new p("rateLimited",{...n,retryAfter:Je(e)??t.retryAfter});let s=Le(e);return t.status===400&&s?new p("validation",{...n,fields:s}):new p("server",n)}function I(t){return t instanceof Q||t instanceof Error&&t.name==="PalbaseError"}function oe(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Le(t){let e=x(x(t,"data"),"fields");if(oe(e))return e;let n=x(t,"fields");return oe(n)?n:void 0}function Je(t){return ie(t,"retry_after")??ie(x(t,"data"),"retryAfter")}function x(t,e){if(typeof t=="object"&&t!==null)return t[e]}function ie(t,e){let n=x(t,e);return typeof n=="number"?n:void 0}function We(t,e){let n=x(t,e);return typeof n=="string"?n:void 0}var He=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ve=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Ue=new Set(Ve),ze=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(t){return t==="then"||t==="toJSON"||ze.has(t)}function de(t){return t==="call"||t==="join"||$(t)}function le(t){return typeof t=="string"&&He.test(t)&&!Ue.has(t)&&!$(t)}function ue(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function ce(t){A(t)}function pe(t){return A(t).origin}var O=class t{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},n,s,r=!0){this.me=e,this.reader=n,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let n=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...n!==void 0?{turns:n}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let h=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(h,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(h=>q(h)).filter(h=>h!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),n===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;n-=a.turns}while(n>0);return this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let c=v(i);c<=0||(this.paged.add(c),(this.pagedFrom===void 0||c<this.pagedFrom)&&(this.pagedFrom=c),(this.pagedTo===void 0||c>this.pagedTo)&&(this.pagedTo=c))}let n=new t(this.me);n.thoughts=this.thoughts,n.lowest=this.lowest-e.length;let s=n.lowest;for(let i of e)n.at=s++,n.fold(i);this.folded+=n.folded,this.lowest=n.lowest,this.chatId??=n.chatId;let r=new Map;for(let[i,c]of n.messages){let y=this.told.get(i)??[],f=c;if(y.length>0)for(let C of y)f=me(f,C);else f=this.messages.get(i)??c;r.set(i,f);let m=[...n.told.get(i)??[],...y];m.length>0&&this.told.set(i,m)}for(let[i,c]of this.messages)r.has(i)||r.set(i,c);this.messages.clear();for(let[i,c]of r)this.messages.set(i,c);let o=new Map;for(let[i,c]of n.responses){let y=this.responses.get(i);o.set(i,y?Ye(c,y):c)}for(let[i,c]of this.responses)o.has(i)||o.set(i,c);this.responses.clear();for(let[i,c]of o)this.responses.set(i,c);let d=new Set;for(let i of n.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...n.order],l=new Set([...n.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&n.goalWords.has(i.event.seq))&&!(i.type==="voice"&&n.voiceWords.has(F(i.event)))){if(i.type==="message"&&i.began&&i.turn!==null){let c=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:c&&c.at<i.arrived?c.at-.5:i.arrived});continue}a.push(i)}a.sort((i,c)=>i.at-c.at),this.order=a;for(let i of n.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of n.voiceWords)this.voiceWords.add(i);let h=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=ye(this.voice,i.event,h));this.turn??=n.turn;let u=new Map([...n.calls,...this.calls]);this.calls.clear();for(let[i,c]of u)this.calls.set(i,c);for(let[i,c]of n.history)this.history.has(i)||this.history.set(i,c);this.forkedFrom??=n.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let n=q(e);n&&this.take(n)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let n=v(e);n>0&&this.pagedTo!==void 0&&n>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=ge(setTimeout(()=>this.quiet(),he)));return}this.takeNow(e)}}quiet(){let e=this.held.map(v).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Qe?this.heldTimer=ge(setTimeout(()=>this.quiet(),he)):this.sortHeld()}takeNow(e){let n=v(e);n>0&&this.paged.has(n)||(n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),n=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(v(a))),d=o<0?-1:n.findIndex(a=>v(a)===v(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],n[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<n.length&&fe(e[o+l],n[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(h=>v(h)>0),l=a!==void 0&&this.pagedFrom!==void 0&&v(a)<this.pagedFrom;for(let h of e){let u=v(h);u>0&&!(this.pagedFrom!==void 0&&u<this.pagedFrom)&&(l=!1),(l?s:r).push(h)}}if(s.length>0){let a=Math.min(...s.map(v).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:n.from+P(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:n.from+P(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let n=F(e);if(this.voiceWords.has(n))return!1;this.voice=ye(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);et(n,e.offset,e.text),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"reset":{let n=this.response(e.response_id);e.offset<=n.from?(n.text="",n.from=Math.max(0,e.offset)):n.text=n.text.slice(0,S(n.text,e.offset-n.from)),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);n.runId=e.run_id,n.agent=e.name,n.named=!0,n.parentId??=e.parent_response_id;break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Xe(e),s=this.messages.get(n);this.messages.set(n,me(s,e));let r=this.told.get(n);r?r.push(e):this.told.set(n,[e]),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,n){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,h])=>l!==n&&h.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:n,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,n),this.order.push({type:"response",key:e,at:this.at})),n}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=u=>e!==void 0&&u.startedBy===e,s=new Map;for(let u of this.responses.values()){let i=u.parentId!==null?this.responses.get(u.parentId)??u:u;s.set(u.id,tt(u,i.startedBy??null,n(i),u.goal??i.goal))}let r=new Map([...this.messages].map(([u,i])=>[u,e!==void 0&&i.author===e?{...i,mine:!0}:i])),o=[...this.history.entries()].sort(([u],[i])=>u-i).flatMap(([u,i])=>i.map((c,y)=>nt(c,`${u}:${y}`,e))),d=[...o];for(let u of this.order)u.type==="goal"?d.push({type:"goal",goal:u.event}):u.type==="voice"?d.push({type:"voice",voice:u.event}):u.type==="message"?d.push({type:"message",message:r.get(u.key)}):this.responses.get(u.key).parentId===null&&d.push({type:"response",response:s.get(u.key)});let a=o.flatMap(u=>u.type==="message"?[u.message]:[]),l=o.flatMap(u=>u.type==="response"?[u.response]:[]),h=[...this.calls.values()].filter(u=>s.get(u.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:h.filter(u=>u.status==="awaiting_approval"),outputs:h.filter(u=>u.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Ze(this.voice,e):null}}},he=150,Qe=2e3;function fe(t,e){let n=v(t);return n>0||v(e)>0?n===v(e):JSON.stringify(t)===JSON.stringify(e)}function v(t){let e=t.seq;return typeof e=="number"&&e>0?e:0}function ge(t){return t.unref?.(),t}function F(t){return`${t.voice_id}\0${t.status}`}function ye(t,e,n){return n.add(F(e)),(e.status==="closed"?t===null||t.voice_id===e.voice_id:!n.has(`${e.voice_id}\0closed`))?e:t}function me(t,e){let n=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??t?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:t?.status==="delivered"?"delivered":n,error:e.error??null,responseId:e.response_id??t?.responseId??null,createdAt:e.created_at??t?.createdAt??"",mine:!1,metadata:e.metadata??t?.metadata??{},history:!1,truncated:!1,kind:e.kind??t?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:t?.voice??null,attachments:e.attachments?we(e.attachments):t?.attachments??[]}}function Ye(t,e){let n={...t,marks:new Map(t.marks)};e.status!==null&&(n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=e.end),e.startedBy!==void 0&&(n.startedBy=e.startedBy),e.goal&&(n.goal=e.goal),e.named&&(n.runId=e.runId,n.agent=e.agent,n.named=!0),n.parentId=t.parentId??e.parentId,e.cut!==null&&(t.text===""||e.cut<=t.from?(n.text=e.text,n.from=e.text===""?Math.max(0,e.cut):e.from):n.text=t.text.slice(0,S(t.text,e.cut-t.from))+e.text,n.cut=t.cut===null?e.cut:Math.min(t.cut,e.cut));let s=r=>{if(t.text==="")return null;if(r!==null&&r<=t.from)return r;let o=P(t.text);return t.from+(r===null?o:Math.min(o,r-t.from))};for(let[r,o]of e.marks){let d=n.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")n.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);n.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?t.cut:t.cut===null?o.cutAt:Math.min(o.cutAt,t.cut)})}else n.marks.set(r,o)}return n}function Ze(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function we(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Xe(t){return`${t.author??""}\0${t.client_id}`}function et(t,e,n){if(t.text===""||e<=t.from){t.from=Math.max(0,e),t.text=n;return}t.text=t.text.slice(0,S(t.text,e-t.from))+n}function tt(t,e,n,s){let r=[...t.marks.values()].map((l,h)=>({m:l,i:h,at:S(t.text,Math.max(0,(Number(l.text_offset)||0)-t.from))}));r.sort((l,h)=>l.at-h.at||l.i-h.i);let o=[],d=[],a=0;for(let{m:l,at:h}of r)h>a&&o.push({type:"text",text:t.text.slice(a,h)}),a=Math.max(a,h),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<t.text.length&&o.push({type:"text",text:t.text.slice(a)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:d,goal:s,history:!1,truncated:!1}}function nt(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var B=[["ApiKeyAuth","userJWT"]];function ve(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.turns!==void 0&&(s.turns=n.turns),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:B,answers:{200:"json"},query:s,signal:n.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:B,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:B,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var M=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},be=new WeakMap;async function Ee(t,e,n,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:h,chat:u}=st(e),i=rt(d,n),c=be.get(t);c||be.set(t,c=new Map);let y=c,f=y.get(i)??{count:0};y.set(i,f),f.count++;let m=t.channel(i,h&&s.history!==!1?{after:0}:{});if(u&&!f.chat){let g=n.chatId,k=new O(r,o,typeof g=="string"&&g!==""?g:void 0,h&&s.history!==!1);f.chat=k,f.unchat=m.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let C=()=>{--f.count>0||(y.delete(i),f.unchat?.(),f.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?ke(m.refusal,"unavailable"):"socket closed";throw C(),new M(`gateway ${JSON.stringify(i)} was not joined: ${g}`,g)}let T=!1,R=new Set,V=()=>{if(!T){T=!0,Ke();for(let g of[...R])g();C()}},Ke=m.onClosed(V),U=g=>{if(T)return()=>{};let k=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),w=()=>{R.delete(w),k()};return R.add(w),w},z={topic:i,get seq(){return m.logSeq},on(g,k){if(typeof g=="function")return U((w,b)=>g({event:w,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return U((w,b)=>{w===g&&k(b)})},off(g){R.has(g)&&g()},async send(g,k){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let w=T?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:k});if(w.status==="ok")return E(w.response.reply);let b=ke(w.response,"unavailable");throw new M(`gateway ${JSON.stringify(i)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:V};return u&&Object.defineProperty(z,"chat",{value:f.chat,enumerable:!0}),z}function st(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function rt(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ke(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ot=3600*1e3,j=new Map;function it(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!n&&r&&Date.now()-r.at<ot)return r.list;let o=(async()=>{let d=se(),a;try{a=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await re(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function _e(t,e,n,s,r,o){let a=(await it(t,e,o)).keys[0];return X(a.kid,a.key,Z(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):N(e,n,s,(r,o)=>ee(t.key,r,o))}function xe(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):N(e,"/response",n,async(r,o)=>{if(!te(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ne(t.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(t){return t instanceof p&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var L=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
3
3
|
`);let n=[],s=this.pending.indexOf(`
|
|
4
4
|
`);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
5
|
`)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let d=o.slice(5);this.dataLines.push(d.startsWith(" ")?d.slice(1):d)}else if(o.startsWith("event:")){let d=o.slice(6);this.eventName=d.startsWith(" ")?d.slice(1):d}}s=this.pending.indexOf(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.52.
|
|
2
|
-
import{b as c,f as u}from"./
|
|
1
|
+
/*! palbase 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as c,f as u}from"./2JWR4TOH.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
|