palbase 0.11.0 → 0.11.2
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/{KXY2SF4N.js → 4NC6D3AY.js} +2 -2
- package/dist/chunks/{AEAFASN2.js → 4OASGT7Q.js} +2 -2
- package/dist/chunks/{7JE4KOPN.js → 5FJNJOWL.js} +2 -2
- package/dist/chunks/{5D7BAVO5.js → 6FV2T52H.js} +1 -1
- package/dist/chunks/{2MS22NJC.js → 6S6MUPJA.js} +2 -2
- package/dist/chunks/{GUFHH4DP.js → BPFIGT6G.js} +2 -2
- package/dist/chunks/{D6RL5OCI.js → D5A6USBN.js} +2 -2
- package/dist/chunks/{LJ3VOTHH.js → E765DY7Q.js} +2 -2
- package/dist/chunks/{BAOQMZPI.js → FIWWCA6S.js} +2 -2
- package/dist/chunks/{476DZPIV.js → MWKPDZHT.js} +2 -2
- package/dist/chunks/{2CQIOY2Z.js → NT7K4S2X.js} +1 -1
- package/dist/chunks/{QX7E6TNL.js → NZRVCF6B.js} +1 -1
- package/dist/chunks/{NHNXW6EK.js → PF3S7VGN.js} +1 -1
- package/dist/chunks/{CQBT2Z2T.js → QNJK2UIR.js} +2 -2
- package/dist/chunks/{S4GBHZOR.js → SI2TXLYT.js} +1 -1
- package/dist/chunks/{GCVVMTWI.js → VPFDS7G7.js} +2 -2
- package/dist/chunks/{XBT3QJRS.js → W6LUHPMU.js} +2 -2
- package/dist/chunks/{DAYQLOBB.js → W7UOMPUA.js} +2 -2
- package/dist/chunks/{63TWL4SB.js → WUPBDP6G.js} +2 -2
- package/dist/chunks/{WYUC5N2T.js → XOPSQEWX.js} +1 -1
- package/dist/chunks/{52DZTUF7.js → XQUWS373.js} +2 -2
- package/dist/cli.js +102 -102
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/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/purchases.d.ts +1 -1
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
2
|
-
import{a,b,c,d,e,f}from"../chunks/
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f}from"../chunks/4OASGT7Q.js";import"../chunks/W6LUHPMU.js";import"../chunks/SI2TXLYT.js";import"../chunks/4NC6D3AY.js";import"../chunks/FIWWCA6S.js";import"../chunks/5FJNJOWL.js";import"../chunks/NT7K4S2X.js";import"../chunks/PF3S7VGN.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.11.
|
|
2
|
-
import{ha as w,la as h}from"../chunks/
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ha as w,la as h}from"../chunks/QNJK2UIR.js";import"../chunks/BPFIGT6G.js";import"../chunks/VPFDS7G7.js";import"../chunks/XOPSQEWX.js";import"../chunks/4OASGT7Q.js";import"../chunks/W6LUHPMU.js";import"../chunks/SI2TXLYT.js";import"../chunks/4NC6D3AY.js";import"../chunks/FIWWCA6S.js";import"../chunks/5FJNJOWL.js";import"../chunks/NT7K4S2X.js";import"../chunks/PF3S7VGN.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.11.
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
2
|
-
import{$ as It,A as F,B as dt,C as ut,D as ht,E as ft,F as gt,G as bt,H as mt,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 Tt,R as _t,S as xt,T as Rt,U as Ot,V as Ct,W as Bt,X as se,Y as Ft,Z as Mt,_ as $t,a as Q,aa as Lt,b as X,ba as Ut,c as Z,ca as Dt,d as Ne,da as jt,e as qe,ea as Nt,f as We,fa as M,g as Ke,ga as Wt,h as Ve,ha as $,i as Ge,ia as V,j as ze,ja as Kt,k as He,ka as Vt,l as Ye,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as st,t as rt,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/CQBT2Z2T.js";import{a as ne}from"../chunks/QX7E6TNL.js";import{a as x,b as ee,c as te,f as b,g as pt,h as d,j as re,k as qt}from"../chunks/GUFHH4DP.js";import{a as _,g as De,h as je,i as H,j as B,q as Y,r as J}from"../chunks/GCVVMTWI.js";import"../chunks/WYUC5N2T.js";import"../chunks/AEAFASN2.js";import"../chunks/XBT3QJRS.js";import"../chunks/S4GBHZOR.js";import{m as Ue}from"../chunks/KXY2SF4N.js";import"../chunks/BAOQMZPI.js";import{b as A,c as K}from"../chunks/7JE4KOPN.js";import"../chunks/2CQIOY2Z.js";import"../chunks/NHNXW6EK.js";import"reflect-metadata";import{existsSync as G,writeFileSync as Es,writeSync as Ts}from"node:fs";import{createServer as _s}from"node:http";import{dirname as k,join as z,resolve as xe}from"node:path";import{Readable as xs}from"node:stream";var Gt=2e3,zt=1e4,Ht=/^[A-Za-z0-9_-]{1,64}$/,Yt=512,I=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,s={}){this.sink=e,this.linesPerSecond=s.linesPerSecond??10,this.batchSize=Math.min(100,s.batchSize??100),this.flushMs=s.flushMs??2e3,this.maxPending=s.maxPending??2e3,this.sendMs=s.sendMs??zt,this.shutdownMs=s.shutdownMs??Gt,this.now=s.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,s,r=new Promise(a=>s=a),n=setTimeout(()=>{e=!0,s()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,s=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),s>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${s} dropped`)}log(e){let s=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(s-this.refilled)/1e3*this.linesPerSecond),this.refilled=s,this.unlogged>0&&s-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=s),this.tokens<1){this.unlogged===0&&(this.unloggedSince=s),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[r](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Ht.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Yt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),s=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let n=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await s.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let i=a.status,o=i??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Jt}from"node:crypto";import{bind as Qt,bunDriver as Xt,createDatabase as Zt,envBlock as es,createSearchWorker as ts,cutOff as ss,forgetUser as rs,MigrationOpen as ns,MigrationRefused as as,Migrator as ce,renewingBunPool as ae,VersionNotMigrated as os}from"palgres";import{toModel as de}from"palgres/dsl";var is=["start","complete","rollback","plan","status","types"],ls=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!is.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let s of e)if(s.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 U(t){return de(pe(t))}function cs(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(s=>s.user!==void 0&&!s.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let s=Number(e);if(!Number.isSafeInteger(s)||s<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return s}function ds(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 oe=5;function fe(t,e){if(t.driver)return t.driver;let s=globalThis.Bun;if(!s)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let r=e-1;return n=>{let a=ae(()=>new s.SQL({url:n,prepare:!1,max:r})),i=ae(()=>new s.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:Xt(a,i),poolSize:r,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await R(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 s=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await R("types",es(s,{module:"palbase/backend/env"}),e),0}async function me(t,e,s){let r=e.PALBASE_DB_OWNER_URL;if(!r)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!ls.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=fe(t,he(e)),i=a(r),o,c=l=>d.error(`[palbase] migrate ${s}: ${l}`);try{let l=U(t),u=new ce(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let g=new URL(r);g.pathname=`/${f}`;let y=a(g.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>us(e)});if(s==="plan"){let f=await u.plan(l);return await R(s,f),f.refusals.length>0?1:0}if(s==="status")return await R(s,await u.status()),0;let h=s==="start"?await ps(u,l,n):s==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${s}: done`,{result:h}),await R(s,h),0}catch(l){return l instanceof as?(d.error(`[palbase] migrate ${s}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):ss(l)?(d.error(`[palbase] migrate ${s}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??ie(l)}`),75):(d.error(`[palbase] migrate ${s}: failed`,{error:l}),c(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function us(t){let e=t.PALBASE_URL,s=t.PALBASE_SECRET_KEY;if(!e||!s)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let r=_({url:e,secretKey:s}).fields;return await r.load(),r.close(),r}async function ps(t,e,s){try{return await t.start(e)}catch(r){if(!(r instanceof ns)||s!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return d.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var hs=(t,e)=>{process.stdout.write(t,()=>e())};function R(t,e,s=hs){return new Promise(r=>s(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as It,A as F,B as dt,C as ut,D as ht,E as ft,F as gt,G as bt,H as mt,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 Tt,R as _t,S as xt,T as Rt,U as Ot,V as Ct,W as Bt,X as se,Y as Ft,Z as Mt,_ as $t,a as Q,aa as Lt,b as X,ba as Ut,c as Z,ca as Dt,d as Ne,da as jt,e as qe,ea as Nt,f as We,fa as M,g as Ke,ga as Wt,h as Ve,ha as $,i as Ge,ia as V,j as ze,ja as Kt,k as He,ka as Vt,l as Ye,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as st,t as rt,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/QNJK2UIR.js";import{a as ne}from"../chunks/NZRVCF6B.js";import{a as x,b as ee,c as te,f as b,g as pt,h as d,j as re,k as qt}from"../chunks/BPFIGT6G.js";import{a as _,g as De,h as je,i as H,j as B,q as Y,r as J}from"../chunks/VPFDS7G7.js";import"../chunks/XOPSQEWX.js";import"../chunks/4OASGT7Q.js";import"../chunks/W6LUHPMU.js";import"../chunks/SI2TXLYT.js";import{m as Ue}from"../chunks/4NC6D3AY.js";import"../chunks/FIWWCA6S.js";import{b as A,c as K}from"../chunks/5FJNJOWL.js";import"../chunks/NT7K4S2X.js";import"../chunks/PF3S7VGN.js";import"reflect-metadata";import{existsSync as G,writeFileSync as Es,writeSync as Ts}from"node:fs";import{createServer as _s}from"node:http";import{dirname as k,join as z,resolve as xe}from"node:path";import{Readable as xs}from"node:stream";var Gt=2e3,zt=1e4,Ht=/^[A-Za-z0-9_-]{1,64}$/,Yt=512,I=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,s={}){this.sink=e,this.linesPerSecond=s.linesPerSecond??10,this.batchSize=Math.min(100,s.batchSize??100),this.flushMs=s.flushMs??2e3,this.maxPending=s.maxPending??2e3,this.sendMs=s.sendMs??zt,this.shutdownMs=s.shutdownMs??Gt,this.now=s.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,s,r=new Promise(a=>s=a),n=setTimeout(()=>{e=!0,s()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,s=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),s>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${s} dropped`)}log(e){let s=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(s-this.refilled)/1e3*this.linesPerSecond),this.refilled=s,this.unlogged>0&&s-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=s),this.tokens<1){this.unlogged===0&&(this.unloggedSince=s),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[r](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Ht.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Yt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),s=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let n=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await s.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let i=a.status,o=i??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Jt}from"node:crypto";import{bind as Qt,bunDriver as Xt,createDatabase as Zt,envBlock as es,createSearchWorker as ts,cutOff as ss,forgetUser as rs,MigrationOpen as ns,MigrationRefused as as,Migrator as ce,renewingBunPool as ae,VersionNotMigrated as os}from"palgres";import{toModel as de}from"palgres/dsl";var is=["start","complete","rollback","plan","status","types"],ls=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!is.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let s of e)if(s.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 U(t){return de(pe(t))}function cs(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(s=>s.user!==void 0&&!s.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let s=Number(e);if(!Number.isSafeInteger(s)||s<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return s}function ds(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 oe=5;function fe(t,e){if(t.driver)return t.driver;let s=globalThis.Bun;if(!s)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let r=e-1;return n=>{let a=ae(()=>new s.SQL({url:n,prepare:!1,max:r})),i=ae(()=>new s.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:Xt(a,i),poolSize:r,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await R(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 s=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await R("types",es(s,{module:"palbase/backend/env"}),e),0}async function me(t,e,s){let r=e.PALBASE_DB_OWNER_URL;if(!r)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!ls.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=fe(t,he(e)),i=a(r),o,c=l=>d.error(`[palbase] migrate ${s}: ${l}`);try{let l=U(t),u=new ce(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let g=new URL(r);g.pathname=`/${f}`;let y=a(g.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>us(e)});if(s==="plan"){let f=await u.plan(l);return await R(s,f),f.refusals.length>0?1:0}if(s==="status")return await R(s,await u.status()),0;let h=s==="start"?await ps(u,l,n):s==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${s}: done`,{result:h}),await R(s,h),0}catch(l){return l instanceof as?(d.error(`[palbase] migrate ${s}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):ss(l)?(d.error(`[palbase] migrate ${s}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??ie(l)}`),75):(d.error(`[palbase] migrate ${s}: failed`,{error:l}),c(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function us(t){let e=t.PALBASE_URL,s=t.PALBASE_SECRET_KEY;if(!e||!s)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let r=_({url:e,secretKey:s}).fields;return await r.load(),r.close(),r}async function ps(t,e,s){try{return await t.start(e)}catch(r){if(!(r instanceof ns)||s!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return d.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var hs=(t,e)=>{process.stdout.write(t,()=>e())};function R(t,e,s=hs){return new Promise(r=>s(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,r))}function ie(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
4
|
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function fs(t,e){try{return await new ce(t).plan(e)}catch{return}}var le="palbase.idempotency_keys.response_body";function gs(t,e){let s=null,r=!1,n=async()=>{let o=e.currentKey();if(!(r||o===s)){r=!0;try{let c=await t.reseal();s=o;let l=c.reduce((u,h)=>u+h.resealed,0);l>0&&d.info(`[palbase] fields: ${l} value(s) sealed again with key ${o}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${o} stopped; tried again in a minute`,{error:c})}finally{r=!1}}},a=setTimeout(n,1e4),i=setInterval(n,6e4);for(let o of[a,i])o.unref?.();return()=>{clearTimeout(a),clearInterval(i)}}var L=class extends Error{digest;plan;constructor(e,s){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...s?bs(s):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=s}};function bs(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let s of t.changes)e.push(` + ${s}`);for(let s of t.refusals)e.push(` \u2717 ${s}`);return e}var ms=8e4;async function ye(t,e,s,r){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=pe(t),i=de(a),o=fe(t,he(e))(n);try{let c=!1,l=p=>{c||(c=!0,d.warn(`[palbase] database: not answering yet (${p instanceof Error?p.message:String(p)}) \u2014 waiting for it, as one waking does`))},u=await Qt(o.engine,i,{waitMs:r.onPlatform?ms:0,onUnreachable:l}).catch(async p=>{throw r.onPlatform||!(p instanceof os)?p:new L(p.digest,await fs(o.pool,i))}),h=Jt("sha256",s).update("palgres page cursor").digest("hex"),f=t.embed??r.embed,g=r.fields,y=await Zt({sql:o.engine,schemas:a,binding:u,cursorSecret:h,admission:ds(o.poolSize),embed:f,log:p=>d.warn(`[palbase] ${p}`),fields:async()=>(await g.load(),g)}),S=g.loaded?gs(y,g):()=>{},m=cs(i)?ts({sql:o.engine,embed:f,log:p=>d.info(`[palbase] ${p}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:p=>rs(o.engine,u,i,p),...m?{search:m}:{},keptAnswers:{seal:p=>g.loaded?g.encrypt(le,p):p,open:async p=>g.isEncrypted(p)?(g.loaded||await g.load(),g.decrypt(le,p)):p},close:async()=>{S(),g.close(),await o.close()}}}catch(c){throw await o.close(),c}}function ys(t){let e=Buffer.from(t,"base64"),s=new Array(e.byteLength/4);for(let r=0;r<s.length;r++)s[r]=e.readFloatLE(r*4);return s}function we(t){return async({texts:e,model:s,dimensions:r})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:s,dimensions:r}});return{model:n.model,vectors:n.vectors.map(ys)}}}var ws=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Pe(t,e,s){let r=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&r.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&r.push("palbase.url / PALBASE_URL is the project origin alone")}catch{r.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let i=t.projectId??e.PALBASE_PROJECT_ID??"";ws.test(i)||r.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||r.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&r.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let l=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(s.needsWebhookSecret&&(c!==void 0||l!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(l??"")&&r.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),r.length>0)throw new Error(`[palbase] the app cannot start:
|
|
@@ -9,4 +9,4 @@ ${r.join(`
|
|
|
9
9
|
`)}
|
|
10
10
|
`}function Ae(t,e,s=Ss){let r=Buffer.from(e,"utf8"),n=new Int32Array(new SharedArrayBuffer(4));for(let a=0;a<r.length;)try{a+=s(t,r,a,r.length-a)}catch(i){if(i.code!=="EAGAIN")throw i;Atomics.wait(n,0,0,5)}}var ke=2e4,Ee=5e3,Rs=15e3,Os="/_palbase/health";function Cs(t){let e=new Set,s=r=>{if(e.has(r))return!1;e.add(r);let n=F(r,Q);return n?n.providers.some(a=>F(a,X)!==void 0&&F(a,Z)===void 0)||n.imports.some(s):!1};return t.some(s)}var Bs={async create(t,e={}){let s=Array.isArray(t)?t:[t],r=e.env??process.env,n=ue(r);if(n!==void 0){let w=n==="types"?await be(e.db):e.db?await me(e.db,r,n):await ge(n);throw process.exit(w),new j(w)}let a=r.PALBASE_CONTRACT_OUT;if(a){let w;try{await _e(Te(r)),w=await Fs(s,e,r)}catch(v){throw Ts(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
|
|
11
11
|
`),process.exit(1),new O}throw a==="/dev/stdout"?Ae(1,ve(w)):Es(a,`${w}
|
|
12
|
-
`),process.exit(0),new O}let i=Te(r),o=await _e(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),re(o?void 0:i);let c=e.db?U(e.db):void 0,l=await J({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Cs(s)||c!==void 0&&D(c),h=Pe(e.palbase??{},r,{needsWebhookSecret:u});u&&h.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=_({url:h.url,secretKey:h.secretKey}),g=e.port??Number(r.PORT??"8080");if(!Number.isInteger(g)||g<0||g>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let y=e.db?await ye(e.db,r,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&D(y.model)?{"user.deleted":[w=>Ms(y,w)]}:void 0,m=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new I(f.analytics),C=()=>$({modules:s,verifier:new B({issuer:h.url,projectId:h.projectId,standing:H({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:r,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Ls(e.cors,r.PALBASE_WEB_ORIGINS),platform:m,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),T=C(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await T.start();break}catch(v){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:v}),await new Promise(Le=>setTimeout(Le,W)),W*=2,T=C()}return $s(T,f,g,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Te(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let s=k(xe(e));for(;!G(z(s,"package.json"))&&k(s)!==s;)s=k(s);return G(z(s,"package.json"))?s:process.cwd()}async function _e(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Fs(t,e,s){let r=xe(s.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(r);for(;!G(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/D6RL5OCI.js"),{routeContracts:i}=await import("../chunks/2MS22NJC.js"),o=a(n,r);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=$({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:_({url:c,secretKey:"pb_contract_s"}),env:s,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&D(U(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Ms(t,e){let s=e.data?.user_id;if(typeof s!="string"||s==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(s);d.info(`[palbase] user ${s} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them`)}async function $s(t,e,s,r,n,a){let i,o={on:!1},c=(m,p)=>new URL(m.url).pathname===Os&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,p),l=_s((m,p)=>{Is(c,m,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,p)=>{l.once("error",p),l.listen(s,r,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=m=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(T=>l.close(()=>T()));l.closeIdleConnections();let C=setTimeout(()=>l.closeAllConnections(),m);await p,clearTimeout(C),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(ke),g=!1,y=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let m=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Rs);m.unref(),f().then(()=>{clearTimeout(m),process.exit(0)},p=>{clearTimeout(m),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=m=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let p=setTimeout(()=>process.exit(1),Ee+1e3);h(Ee).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Is(t,e,s,r){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{s.statusCode=400,s.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let g of f)i.append(h,g);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;s.on("close",()=>{s.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?xs.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(s.statusCode=u.status,u.headers.forEach((h,f)=>s.setHeader(f,h)),r.on&&s.setHeader("connection","close"),u.body)for await(let h of u.body)s.write(h);s.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),s.headersSent||(s.statusCode=500),s.end()}}function Ls(t,e,s=r=>console.warn(r)){let r=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(r.length===0||t?.origins==="*")return t;let n=r.filter(o=>V(o)),a=r.filter(o=>!V(o));a.length>0&&s(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).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 zr,boolean as Hr,check as Yr,date as Jr,defineSchema as Qr,defineTable as Xr,enumType as Zr,foreignKey as en,index as tn,integer as sn,jsonb as rn,numeric as nn,ownedByUser as an,policy as on,raw as ln,sqlType as cn,text as dn,timestamp as un,userRef as pn,uuid as hn}from"palgres/dsl";import{increment as gn,now as bn}from"palgres";function E(t){if(t instanceof A)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let s=await t();return{data:await e(s.data),error:null,status:s.status}}catch(s){return E(s)}}var Us=x("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Ds=100,js=1e3,Ns=168*3600,qs={s:1,m:60,h:3600,d:86400};function Ws(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let s=0;for(let[,r,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))s+=Math.round(Number(r)*qs[n]*1e3);return Math.ceil(s/1e3)}function $e(t,e,s){let r="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(r,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${b.url}/storage/public/${K(r,"bucket",t)}/${n}`;return s?`${a}?variant=${encodeURIComponent(s)}`:a}function Re(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function Ks(t){return{async upload(e,s,r){let n=r?.contentType??(s instanceof Blob&&s.type!==""?s.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:s,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&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}:E(a)}},async download(e){try{let s=await b.storage.getObject({path:{bucket:t,path:e}});if(s.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=s.data;try{return{data:await r.blob(),error:null,status:s.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(s){return E(s)}},getPublicUrl(e,s){return $e(t,e,s?.variant)},async createSignedUrl(e,s){let r=Ws(s?.expiresIn);return r===void 0||r<1||r>Ns?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(s?.expiresIn)})`},status:400}:P(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,s){let r=s?.limit??Ds,n=s?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<r;){let c=Math.max(1,Math.min(js,n+r-a.length)),l=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<r&&a.push(Re(u));if(i=l.data.next_cursor,!i)break}}catch(c){return E(c)}return{data:a,error:null,status:o}},async remove(e){let s=[];for(let r of e){try{await b.storage.deleteObject({path:{bucket:t,path:r}})}catch(n){return E(n)}s.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:s,error:null,status:200}},move(e,s){return P(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})},copy(e,s){return P(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})}}}var Vs={bucket:Ks},Oe=t=>ee("Storage",t,Vs),Gs={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},zs=x("Notifications",{push:{send(t){let{to:e,...s}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>b.notify.sendPush({body:{...s,to:r}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:s,...r}=t,n={...r,...s!==void 0?{template:s}:{}};if(!Array.isArray(e))return P(()=>b.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await b.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return E(c)}return{data:{message_ids:a},error:null,status:i}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,Hs=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return te.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return P(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),s=>s.values??{})}var Me={setOverrideForUser:(t,e,s)=>P(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:s}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>P(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),s=>({values:s.values??{}})),clearOverrideForUser:(t,e)=>P(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),clearAllOverridesForUser:t=>P(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Ys=x("Flags",{async isEnabled(t,e){let s=r=>(d.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await N(e);return r.error?s(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return s(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let s=await N(e);return s.error?{data:null,error:s.error,status:s.status}:{data:Be(s.data[t]),error:null,status:s.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([s,r])=>{let n=Be(r);return{name:s,enabled:Ce(r),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,s){let r,n=!1,a;s!==void 0?(r=e,n=!0,a=s):Hs(e)?a=e:e!==void 0&&(r=e,n=!0);let i=await N(a);if(i.error)return n?{data:r??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?r??null:o,error:null,status:i.status}},async setOverride(t,e){let s=Ie();return s?Me.setOverrideForUser(s,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Me}}),Js=x("Realtime",{broadcast(t,e,s){return P(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:s??{}}]}}),()=>{})},state:{set(t,e,s){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:s}]}}),()=>{})},clear(t,e){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as kn}from"zod";export{je as AuthUnavailable,vt as Authorize,Mt as BadRequest,He as Body,Kt as CACHE_MAX_TTL,Vt as Cache,wt as ChatPart,rt as Client,$t as Conflict,O as ContractRunEnded,Ne as Controller,lt as Cron,pt as Database,It as DeadlockDetected,Ge as Delete,Rt as DiError,Ue as EVENT_TYPES,Ys as Flags,Bt as Forbidden,St as Gateway,Pt as GatewayRefusal,qe as Get,Je as Headers,Lt as HttpError,at as Injectable,d as Log,Wt as MAX_BODY_BYTES,j as MigrationRunEnded,ot as Module,Ut as NotFound,zs as Notifications,it as On,kt as OnConnect,Et as OnDisconnect,Tt as OnEmpty,At as OnFirst,Ze as OptionalUser,Ot as PalError,b as Palbase,A as PalbaseError,Bs as PalbaseFactory,Qe as Param,Ve as Patch,We as Post,Ke as Put,ze as Query,Ye as QueryParams,Js as Realtime,et as Req,tt as RequestId,nt as Resolve,L as SchemaNotPushed,Us as Secrets,Dt as SerializationFailure,Gs as Storage,_t as Subscribe,ft as Task,ht as TaskFailure,gt as Tasks,bt as TestUserTemplate,De as TokenError,B as TokenVerifier,jt as TooManyRequests,st as TraceId,Ct as Unauthorized,Nt as UniqueViolation,mt as Upload,yt as UploadedObject,Xe as User,ct as Webhook,zr as bigint,Hr as boolean,Yr as check,$ as createApp,Jr as date,Ft as defineError,Qr as defineSchema,Xr as defineTable,Zr as enumType,en as foreignKey,dt as getRegisteredControllers,ut as getRoutes,xt as getWebhookManifest,gn as increment,tn as index,sn as integer,rn as jsonb,bn as now,nn as numeric,an as ownedByUser,on as policy,ln as raw,cn as sqlType,qt as t,dn as text,un as timestamp,pn as userRef,hn as uuid,kn as z};
|
|
12
|
+
`),process.exit(0),new O}let i=Te(r),o=await _e(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),re(o?void 0:i);let c=e.db?U(e.db):void 0,l=await J({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Cs(s)||c!==void 0&&D(c),h=Pe(e.palbase??{},r,{needsWebhookSecret:u});u&&h.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=_({url:h.url,secretKey:h.secretKey}),g=e.port??Number(r.PORT??"8080");if(!Number.isInteger(g)||g<0||g>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let y=e.db?await ye(e.db,r,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&D(y.model)?{"user.deleted":[w=>Ms(y,w)]}:void 0,m=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new I(f.analytics),C=()=>$({modules:s,verifier:new B({issuer:h.url,projectId:h.projectId,standing:H({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:r,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Ls(e.cors,r.PALBASE_WEB_ORIGINS),platform:m,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),T=C(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await T.start();break}catch(v){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:v}),await new Promise(Le=>setTimeout(Le,W)),W*=2,T=C()}return $s(T,f,g,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Te(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let s=k(xe(e));for(;!G(z(s,"package.json"))&&k(s)!==s;)s=k(s);return G(z(s,"package.json"))?s:process.cwd()}async function _e(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Fs(t,e,s){let r=xe(s.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(r);for(;!G(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/D5A6USBN.js"),{routeContracts:i}=await import("../chunks/6S6MUPJA.js"),o=a(n,r);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=$({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:_({url:c,secretKey:"pb_contract_s"}),env:s,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&D(U(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Ms(t,e){let s=e.data?.user_id;if(typeof s!="string"||s==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(s);d.info(`[palbase] user ${s} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them`)}async function $s(t,e,s,r,n,a){let i,o={on:!1},c=(m,p)=>new URL(m.url).pathname===Os&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,p),l=_s((m,p)=>{Is(c,m,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,p)=>{l.once("error",p),l.listen(s,r,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=m=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(T=>l.close(()=>T()));l.closeIdleConnections();let C=setTimeout(()=>l.closeAllConnections(),m);await p,clearTimeout(C),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(ke),g=!1,y=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let m=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Rs);m.unref(),f().then(()=>{clearTimeout(m),process.exit(0)},p=>{clearTimeout(m),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=m=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let p=setTimeout(()=>process.exit(1),Ee+1e3);h(Ee).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Is(t,e,s,r){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{s.statusCode=400,s.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let g of f)i.append(h,g);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;s.on("close",()=>{s.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?xs.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(s.statusCode=u.status,u.headers.forEach((h,f)=>s.setHeader(f,h)),r.on&&s.setHeader("connection","close"),u.body)for await(let h of u.body)s.write(h);s.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),s.headersSent||(s.statusCode=500),s.end()}}function Ls(t,e,s=r=>console.warn(r)){let r=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(r.length===0||t?.origins==="*")return t;let n=r.filter(o=>V(o)),a=r.filter(o=>!V(o));a.length>0&&s(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).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 zr,boolean as Hr,check as Yr,date as Jr,defineSchema as Qr,defineTable as Xr,enumType as Zr,foreignKey as en,index as tn,integer as sn,jsonb as rn,numeric as nn,ownedByUser as an,policy as on,raw as ln,sqlType as cn,text as dn,timestamp as un,userRef as pn,uuid as hn}from"palgres/dsl";import{increment as gn,now as bn}from"palgres";function E(t){if(t instanceof A)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let s=await t();return{data:await e(s.data),error:null,status:s.status}}catch(s){return E(s)}}var Us=x("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Ds=100,js=1e3,Ns=168*3600,qs={s:1,m:60,h:3600,d:86400};function Ws(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let s=0;for(let[,r,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))s+=Math.round(Number(r)*qs[n]*1e3);return Math.ceil(s/1e3)}function $e(t,e,s){let r="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(r,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${b.url}/storage/public/${K(r,"bucket",t)}/${n}`;return s?`${a}?variant=${encodeURIComponent(s)}`:a}function Re(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function Ks(t){return{async upload(e,s,r){let n=r?.contentType??(s instanceof Blob&&s.type!==""?s.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:s,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&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}:E(a)}},async download(e){try{let s=await b.storage.getObject({path:{bucket:t,path:e}});if(s.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=s.data;try{return{data:await r.blob(),error:null,status:s.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(s){return E(s)}},getPublicUrl(e,s){return $e(t,e,s?.variant)},async createSignedUrl(e,s){let r=Ws(s?.expiresIn);return r===void 0||r<1||r>Ns?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(s?.expiresIn)})`},status:400}:P(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,s){let r=s?.limit??Ds,n=s?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<r;){let c=Math.max(1,Math.min(js,n+r-a.length)),l=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<r&&a.push(Re(u));if(i=l.data.next_cursor,!i)break}}catch(c){return E(c)}return{data:a,error:null,status:o}},async remove(e){let s=[];for(let r of e){try{await b.storage.deleteObject({path:{bucket:t,path:r}})}catch(n){return E(n)}s.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:s,error:null,status:200}},move(e,s){return P(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})},copy(e,s){return P(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})}}}var Vs={bucket:Ks},Oe=t=>ee("Storage",t,Vs),Gs={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},zs=x("Notifications",{push:{send(t){let{to:e,...s}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>b.notify.sendPush({body:{...s,to:r}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:s,...r}=t,n={...r,...s!==void 0?{template:s}:{}};if(!Array.isArray(e))return P(()=>b.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await b.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return E(c)}return{data:{message_ids:a},error:null,status:i}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,Hs=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return te.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return P(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),s=>s.values??{})}var Me={setOverrideForUser:(t,e,s)=>P(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:s}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>P(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),s=>({values:s.values??{}})),clearOverrideForUser:(t,e)=>P(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),clearAllOverridesForUser:t=>P(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Ys=x("Flags",{async isEnabled(t,e){let s=r=>(d.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await N(e);return r.error?s(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return s(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let s=await N(e);return s.error?{data:null,error:s.error,status:s.status}:{data:Be(s.data[t]),error:null,status:s.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([s,r])=>{let n=Be(r);return{name:s,enabled:Ce(r),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,s){let r,n=!1,a;s!==void 0?(r=e,n=!0,a=s):Hs(e)?a=e:e!==void 0&&(r=e,n=!0);let i=await N(a);if(i.error)return n?{data:r??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?r??null:o,error:null,status:i.status}},async setOverride(t,e){let s=Ie();return s?Me.setOverrideForUser(s,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Me}}),Js=x("Realtime",{broadcast(t,e,s){return P(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:s??{}}]}}),()=>{})},state:{set(t,e,s){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:s}]}}),()=>{})},clear(t,e){return P(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as kn}from"zod";export{je as AuthUnavailable,vt as Authorize,Mt as BadRequest,He as Body,Kt as CACHE_MAX_TTL,Vt as Cache,wt as ChatPart,rt as Client,$t as Conflict,O as ContractRunEnded,Ne as Controller,lt as Cron,pt as Database,It as DeadlockDetected,Ge as Delete,Rt as DiError,Ue as EVENT_TYPES,Ys as Flags,Bt as Forbidden,St as Gateway,Pt as GatewayRefusal,qe as Get,Je as Headers,Lt as HttpError,at as Injectable,d as Log,Wt as MAX_BODY_BYTES,j as MigrationRunEnded,ot as Module,Ut as NotFound,zs as Notifications,it as On,kt as OnConnect,Et as OnDisconnect,Tt as OnEmpty,At as OnFirst,Ze as OptionalUser,Ot as PalError,b as Palbase,A as PalbaseError,Bs as PalbaseFactory,Qe as Param,Ve as Patch,We as Post,Ke as Put,ze as Query,Ye as QueryParams,Js as Realtime,et as Req,tt as RequestId,nt as Resolve,L as SchemaNotPushed,Us as Secrets,Dt as SerializationFailure,Gs as Storage,_t as Subscribe,ft as Task,ht as TaskFailure,gt as Tasks,bt as TestUserTemplate,De as TokenError,B as TokenVerifier,jt as TooManyRequests,st as TraceId,Ct as Unauthorized,Nt as UniqueViolation,mt as Upload,yt as UploadedObject,Xe as User,ct as Webhook,zr as bigint,Hr as boolean,Yr as check,$ as createApp,Jr as date,Ft as defineError,Qr as defineSchema,Xr as defineTable,Zr as enumType,en as foreignKey,dt as getRegisteredControllers,ut as getRoutes,xt as getWebhookManifest,gn as increment,tn as index,sn as integer,rn as jsonb,bn as now,nn as numeric,an as ownedByUser,on as policy,ln as raw,cn as sqlType,qt as t,dn as text,un as timestamp,pn as userRef,hn as uuid,kn as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.11.
|
|
2
|
-
import{a as u}from"../chunks/
|
|
1
|
+
/*! palbase 0.11.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u}from"../chunks/NZRVCF6B.js";import{c as p,i as c}from"../chunks/BPFIGT6G.js";import{b as l,c as g,d as f,e as y}from"../chunks/MWKPDZHT.js";import"../chunks/XOPSQEWX.js";import"../chunks/4OASGT7Q.js";import"../chunks/W6LUHPMU.js";import"../chunks/SI2TXLYT.js";import"../chunks/4NC6D3AY.js";import"../chunks/FIWWCA6S.js";import"../chunks/5FJNJOWL.js";import"../chunks/NT7K4S2X.js";import"../chunks/PF3S7VGN.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};
|