palbase 0.9.1 → 0.10.1
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/README.md +72 -1
- 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 +5 -5
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{OV2D7HYG.js → 6N3E2XHZ.js} +1 -1
- package/dist/chunks/{CNUOWB6T.js → APTIATSC.js} +2 -2
- package/dist/chunks/{KUFTU2AJ.js → EUI3Y3LO.js} +3 -3
- package/dist/chunks/{4DDSGFFD.js → FHXGE2MX.js} +1 -1
- package/dist/chunks/{CJPHHWRE.js → INRWHOEW.js} +2 -2
- package/dist/chunks/{6RX5KVMR.js → IVJCGBYG.js} +2 -2
- package/dist/chunks/MFMA46HN.js +2 -0
- package/dist/chunks/{MALOKTVW.js → NBI5LPMS.js} +2 -2
- package/dist/chunks/{BKOIWNJP.js → NGS4ALOE.js} +1 -1
- package/dist/chunks/{WPE6J77U.js → PG7BO4MR.js} +1 -1
- package/dist/chunks/{5UI3Q5JO.js → QC2SDBJD.js} +2 -2
- package/dist/chunks/{2DWAHEYE.js → QD3SPM7D.js} +2 -2
- package/dist/chunks/{SE3MXMQD.js → QW3V2NBT.js} +2 -2
- package/dist/chunks/{ZRV54HT6.js → R4OLJRMH.js} +2 -2
- package/dist/chunks/{I56MGYTD.js → RO7ERCT3.js} +2 -2
- package/dist/chunks/{XGWTZGWR.js → RWGEPDRQ.js} +2 -2
- package/dist/chunks/{YSTCOQFT.js → UDAWSJMT.js} +2 -2
- package/dist/chunks/{2GF6TA4C.js → XYXBDSXW.js} +1 -1
- package/dist/chunks/{ZHHMA7V4.js → YQEM4H7U.js} +2 -2
- package/dist/chunks/{XSPSDUZA.js → Z4A62VQR.js} +2 -2
- package/dist/cli.js +124 -130
- 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 +21 -2
- package/types/backend/src/decorators.d.ts +9 -6
- package/types/backend/src/errors.d.ts +1 -1
- package/types/backend/src/gateways.d.ts +1 -1
- package/types/backend/src/runtime.d.ts +5 -5
- package/types/backend/src/services.d.ts +2 -8
- package/types/backend/src/upload.d.ts +1 -1
- package/types/backend/src/webhooks.d.ts +2 -2
- package/types/server/src/testing.d.ts +0 -6
- package/types/web/src/backends.d.ts +2 -2
- package/dist/chunks/PUILCUFX.js +0 -2
package/README.md
CHANGED
|
@@ -1,3 +1,74 @@
|
|
|
1
1
|
# palbase
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The JavaScript SDK and CLI of [Palbase](https://palbase.studio) — the backend for web, iOS and Android apps. Every project has auth, storage, realtime, feature flags, notifications, secrets, analytics, AI and in-app purchases; your own TypeScript backend runs on a machine built from a GitHub branch on every push, beside a Postgres database of its own.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install palbase
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
| Import | What it is |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `palbase/web` | The client for browsers and Next.js, made with the project's publishable key: auth, flags, analytics, consent, web push, purchases, the realtime socket, and your backend's typed clients |
|
|
12
|
+
| `palbase/web/ssr` | The signed-in session in cookies, for server-rendered apps |
|
|
13
|
+
| `palbase/web/paywall` | Rendering the project's paywalls on the web |
|
|
14
|
+
| `palbase/server` | The server SDK, made with the secret key: every module's server calls |
|
|
15
|
+
| `palbase/backend` | The framework a Palbase machine runs: modules, controllers, validation, gateways, cron, tasks, webhooks, the database |
|
|
16
|
+
| `palbase/ai` | The project's models, tools, agents and chats |
|
|
17
|
+
| `npx palbase` | The CLI: projects, environments, client apps, the purchase catalog, databases, tokens for CI and AI agents |
|
|
18
|
+
|
|
19
|
+
The typed Postgres layer, [`palgres`](https://www.npmjs.com/package/palgres), comes with `palbase/backend`.
|
|
20
|
+
|
|
21
|
+
## In a web app
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { createClient } from "palbase/web";
|
|
25
|
+
|
|
26
|
+
const pb = createClient({
|
|
27
|
+
url: "https://<ref>.palbase.studio", // the environment's address
|
|
28
|
+
publishableKey: "pb_<ref>_c…", // Studio › Settings › API keys
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
await pb.auth.signUp({ email, password });
|
|
32
|
+
const session = await pb.auth.signIn(email, password);
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## A backend
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
// src/main.ts
|
|
39
|
+
import { PalbaseFactory } from "palbase/backend";
|
|
40
|
+
import { AppModule } from "./app.module";
|
|
41
|
+
|
|
42
|
+
await PalbaseFactory.create(AppModule);
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
// src/me.controller.ts
|
|
47
|
+
import { Controller, Get, User, type UserT } from "palbase/backend";
|
|
48
|
+
|
|
49
|
+
@Controller("/me")
|
|
50
|
+
export class MeController {
|
|
51
|
+
@Get("")
|
|
52
|
+
me(@User() user: UserT) {
|
|
53
|
+
return { id: user.id }; // every route needs a signed-in user unless it says otherwise
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Push it to the GitHub branch a machine is connected to, and the machine builds and serves it — a machine named `backend` at `https://<ref>.app.palbase.studio`.
|
|
59
|
+
|
|
60
|
+
## The CLI
|
|
61
|
+
|
|
62
|
+
```sh
|
|
63
|
+
npx palbase login
|
|
64
|
+
npx palbase use <project>/<environment>
|
|
65
|
+
npx palbase init --db # a backend on palbase/backend, with a schema
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Documentation
|
|
69
|
+
|
|
70
|
+
- Docs: https://palbase.studio/docs — [Quickstart](https://palbase.studio/docs/getting-started/quickstart), [Web SDK](https://palbase.studio/docs/web/overview), [Backend SDK](https://palbase.studio/docs/backend/overview), [CLI](https://palbase.studio/docs/cli/overview)
|
|
71
|
+
- For AI coding assistants: https://palbase.studio/llms.txt (the index) and https://palbase.studio/llms-full.txt (every page in one file)
|
|
72
|
+
- iOS: [palbase-swift](https://github.com/palgroup/palbase-swift) · Android: [palbase-android](https://github.com/palgroup/palbase-android)
|
|
73
|
+
|
|
74
|
+
Distributed compiled; licensed under the Palbase SDK License (`LICENSE`).
|
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a,b,c,d,e,f}from"../chunks/
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f}from"../chunks/QW3V2NBT.js";import"../chunks/IVJCGBYG.js";import"../chunks/6N3E2XHZ.js";import"../chunks/YQEM4H7U.js";import"../chunks/RO7ERCT3.js";import"../chunks/RWGEPDRQ.js";import"../chunks/PG7BO4MR.js";import"../chunks/XYXBDSXW.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.
|
|
2
|
-
import{ga as h,ka as d}from"../chunks/
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ga as h,ka as d}from"../chunks/EUI3Y3LO.js";import"../chunks/Z4A62VQR.js";import"../chunks/INRWHOEW.js";import"../chunks/QW3V2NBT.js";import"../chunks/IVJCGBYG.js";import"../chunks/6N3E2XHZ.js";import"../chunks/YQEM4H7U.js";import"../chunks/RO7ERCT3.js";import"../chunks/RWGEPDRQ.js";import"../chunks/PG7BO4MR.js";import"../chunks/XYXBDSXW.js";import{binding as R,createDatabase as v}from"palgres";var b=new WeakMap;function q(l,e,n){if(!n?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=n.schemas,s=b.get(l);s||b.set(l,s=new Map);let r=s.get(u);r||s.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",f=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},g=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(g);i||(i=v({sql:l,schemas:u,binding:R(0,!0),roles:f}),r.set(g,i));let w=JSON.parse(e.claimsJson),m=i.then(a=>a.request({role:o,claims:w},{diagnostics:n.diagnostics,signal:n.signal})),y=a=>new Proxy(()=>{},{apply:async(t,D,c)=>{let p=(await m).client;return a(p).apply(p,c)}});return{client:new Proxy({},{get(a,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:y(p=>p.asService()[c])}):y(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async a=>(await m).rollback(a)}}export{h as createApp,q as createRequestDatabase,d as makeMemoryCache};
|
package/dist/backend/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{$ as $t,A as B,B as ct,C as dt,D as pt,E as ht,F as gt,G as bt,H as ft,I as mt,J as yt,K as wt,L as Pt,M as St,N as vt,O as At,P as kt,Q as Et,R as xt,S as
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as $t,A as B,B as ct,C as dt,D as pt,E as ht,F as gt,G as bt,H as ft,I as mt,J as yt,K as wt,L as Pt,M as St,N as vt,O as At,P as kt,Q as Et,R as xt,S as _t,T as Ot,U as Rt,V as Tt,W as re,X as Ct,Y as Bt,Z as Ft,_ as Mt,a as Q,aa as It,b as X,ba as Lt,c as Z,ca as Dt,d as je,da as Ut,e as Ne,ea as F,f as qe,fa as Nt,g as We,ga as M,h as Ve,ha as G,i as Ge,ia as qt,j as Ke,ja as Wt,k as ze,l as He,m as Ye,n as Je,o as Qe,p as Xe,q as Ze,r as et,s as tt,t as rt,u as st,v as nt,w as at,x as ot,y as it,z as lt}from"../chunks/EUI3Y3LO.js";import{a as ne}from"../chunks/NGS4ALOE.js";import{a as _,b as ee,c as te,f as g,g as ut,h as c,j as se,k as jt}from"../chunks/Z4A62VQR.js";import{a as V,g as De,h as Ue,i as H,j as C,q as Y,r as J}from"../chunks/INRWHOEW.js";import"../chunks/QW3V2NBT.js";import"../chunks/IVJCGBYG.js";import"../chunks/6N3E2XHZ.js";import{m as Le}from"../chunks/YQEM4H7U.js";import"../chunks/RO7ERCT3.js";import{b as A,c as W}from"../chunks/RWGEPDRQ.js";import"../chunks/PG7BO4MR.js";import"../chunks/XYXBDSXW.js";import"reflect-metadata";import{existsSync as K,writeFileSync as Sr,writeSync as vr}from"node:fs";import{createServer as Ar}from"node:http";import{dirname as k,join as z,resolve as _e}from"node:path";import{Readable as kr}from"node:stream";var Vt=2e3,Gt=1e4,Kt=/^[A-Za-z0-9_-]{1,64}$/,zt=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??Gt,this.shutdownMs=r.shutdownMs??Vt,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&&c.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&&(c.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;c[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:Kt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,zt),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,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),d=a.retryAfter;this.pausedUntil=this.now()+(typeof d=="number"&&d>0?d*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),c.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 Ht}from"node:crypto";import{bind as Yt,bunDriver as Jt,createDatabase as Qt,envBlock as Xt,createSearchWorker as Zt,cutOff as er,forgetUser as tr,MigrationOpen as rr,MigrationRefused as sr,Migrator as le,renewingBunPool as ae,VersionNotMigrated as nr}from"palgres";import{toModel as ce}from"palgres/dsl";var ar=["start","complete","rollback","plan","status","types"],or=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!ar.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function ue(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===F.name)throw new Error(`[palbase] db.schemas: the ${F.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,F]}function L(t){return ce(ue(t))}function ir(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function pe(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 lr(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 he(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=ae(()=>new r.SQL({url:n,prepare:!1,max:s})),i=ae(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,d)=>a.unsafe(o,d),begin:o=>a.current.begin(o)},engine:Jt(a,i),poolSize:s,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(c.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await O(t,{state:"none"}),0):(c.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return c.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 O("types",Xt(r,{module:"palbase/backend/env"}),e),0}async function fe(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return c.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(!or.test(n))return c.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=he(t,pe(e)),i=a(s),o,d=l=>c.error(`[palbase] migrate ${r}: ${l}`);try{let l=L(t),u=new le(i.pool,{log:h=>{/ is held by others | held by writers/.test(h)&&(o=h.trim()),c.info(h)},shadow:h=>{let y=new URL(s);y.pathname=`/${h}`;let b=a(y.toString());return{reserve:()=>b.pool.reserve(),end:()=>b.close()}},openedBy:n});if(r==="plan"){let h=await u.plan(l);return await O(r,h),h.refusals.length>0?1:0}if(r==="status")return await O(r,await u.status()),0;let p=r==="start"?await cr(u,l,n):r==="complete"?await u.complete():await u.rollback();return c.info(`[palbase] migrate ${r}: done`,{result:p}),await O(r,p),0}catch(l){return l instanceof sr?(c.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),d(`refused \u2014 ${l.refusals.join("; ")}`),1):er(l)?(c.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),d(`cut off \u2014 ${o??ie(l)}`),75):(c.error(`[palbase] migrate ${r}: failed`,{error:l}),d(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function cr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof rr)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return c.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 dr=(t,e)=>{process.stdout.write(t,()=>e())};function O(t,e,r=dr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,s))}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 ur(t,e){try{return await new le(t).plan(e)}catch{return}}var I=class extends Error{digest;plan;constructor(e,r){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...r?pr(r):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function pr(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 hr=8e4;async function me(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=ue(t),i=ce(a),o=he(t,pe(e))(n);try{let d=!1,l=f=>{d||(d=!0,c.warn(`[palbase] database: not answering yet (${f instanceof Error?f.message:String(f)}) \u2014 waiting for it, as one waking does`))},u=await Yt(o.engine,i,{waitMs:s.onPlatform?hr:0,onUnreachable:l}).catch(async f=>{throw s.onPlatform||!(f instanceof nr)?f:new I(f.digest,await ur(o.pool,i))}),p=Ht("sha256",r).update("palgres page cursor").digest("hex"),h=t.embed??s.embed,y=await Qt({sql:o.engine,schemas:a,binding:u,cursorSecret:p,admission:lr(o.poolSize),embed:h,log:f=>c.warn(`[palbase] ${f}`)}),b=ir(i)?Zt({sql:o.engine,embed:h,log:f=>c.info(`[palbase] ${f}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:f=>tr(o.engine,u,i,f),...b?{search:b}:{},close:()=>o.close()}}catch(d){throw await o.close(),d}}function gr(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 ye(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(gr)}}}var br=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function we(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??"";br.test(i)||s.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let d=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;d!==void 0&&!/^[0-9a-f]{64}$/.test(d)&&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 l=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(d!==void 0||l!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(l??"")&&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:
|
|
@@ -7,6 +7,6 @@ import{$ as $t,A as B,B as ct,C as dt,D as pt,E as ht,F as gt,G as bt,H as ft,I
|
|
|
7
7
|
- `)}`);return{url:a,projectId:i,secretKey:o,webhookSecret:r.needsWebhookSecret?l:void 0,platformSecret:d}}import{createHash as fr}from"node:crypto";import{writeSync as mr}from"node:fs";import{gzipSync as yr}from"node:zlib";var wr="palbase-contract-v1 begin",Pr="palbase-contract-v1 end",Pe=76;function Se(t){let e=Buffer.from(t,"utf8"),r=yr(e).toString("base64"),s=[`${wr} ${fr("sha256").update(e).digest("hex")} ${e.length}`];for(let n=0;n<r.length;n+=Pe)s.push(r.slice(n,n+Pe));return s.push(Pr),`
|
|
8
8
|
${s.join(`
|
|
9
9
|
`)}
|
|
10
|
-
`}function ve(t,e,r=mr){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 Ae=2e4,ke=5e3,Er=15e3,xr="/_palbase/health";function
|
|
11
|
-
`),process.exit(1),new
|
|
12
|
-
`),process.exit(0),new O}let i=Ee(s),o=await xe(i);o&&c.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),se(o?void 0:i);let d=e.db?L(e.db):void 0,l=await J({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&c.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&&c.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=Rr(r)||d!==void 0&&D(d),p=we(e.palbase??{},s,{needsWebhookSecret:u});u&&p.webhookSecret===void 0&&c.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let h=V({url:p.url,secretKey:p.secretKey}),y=e.port??Number(s.PORT??"8080");if(!Number.isInteger(y)||y<0||y>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let b=e.db?await me(e.db,s,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:ye(h)}):void 0;b&&c.info(`[palbase] database: version ${b.binding.version}`);let f=b&&D(b.model)?{"user.deleted":[w=>Tr(b,w)]}:void 0,m=p.platformSecret===void 0?void 0:{secret:p.platformSecret},S=e.requestTelemetry===!1?void 0:new $(h.analytics),T=()=>M({modules:r,verifier:new C({issuer:p.url,projectId:p.projectId,standing:H({url:p.url,secretKey:p.secretKey})}),server:h,webhookSecret:p.webhookSecret,env:s,projectId:p.projectId,telemetry:S,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Fr(e.cors,s.PALBASE_WEB_ORIGINS),platform:m,events:f,database:b&&{app:b.app,requests:b.requests},strings:o}),x=T(),N=e.boot?.attempts??5,q=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await x.start();break}catch(v){if(w>=N)throw c.error(`[palbase] the app did not start after ${N} attempts`,{error:v}),v;c.warn(`[palbase] the app did not start (attempt ${w} of ${N}); trying again in ${q} ms`,{error:v}),await new Promise(Ie=>setTimeout(Ie,q)),q*=2,x=T()}return Cr(x,h,y,e.host??"0.0.0.0",e.exitOnFatal??!0,b)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=k(Re(e));for(;!K(z(r,"package.json"))&&k(r)!==r;)r=k(r);return K(z(r,"package.json"))?r:process.cwd()}async function xe(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 Or(t,e,r){let s=Re(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=k(s);for(;!K(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/CNUOWB6T.js"),{routeContracts:i}=await import("../chunks/5UI3Q5JO.js"),o=a(n,s);for(let u of o.warnings)c.warn(`[palbase] the contract: ${u}`);let d="https://contract.palbase.invalid",l=M({modules:t,verifier:new C({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:V({url:d,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(o.routes),errors:re()},events:e.db&&D(L(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"}},U=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Tr(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);c.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Cr(t,e,r,s,n,a){let i,o={on:!1},d=(m,S)=>new URL(m.url).pathname===xr&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,S),l=Ar((m,S)=>{Br(d,m,S,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,S)=>{l.once("error",S),l.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;c.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=m=>i??=(async()=>{c.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let S=new Promise(x=>l.close(()=>x()));l.closeIdleConnections();let T=setTimeout(()=>l.closeAllConnections(),m);await S,clearTimeout(T),process.off("SIGINT",b),process.off("uncaughtException",f),process.off("unhandledRejection",f);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",b)}})(),h=()=>p(Ae),y=!1,b=()=>{if(y){c.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}y=!0;let m=setTimeout(()=>{c.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ae+Er);m.unref(),h().then(()=>{clearTimeout(m),process.exit(0)},S=>{clearTimeout(m),c.error("[palbase] stopping failed; the process ends",{error:S}),process.exit(1)})},f=m=>{c.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let S=setTimeout(()=>process.exit(1),ke+1e3);p(ke).finally(()=>{clearTimeout(S),process.exit(1)})};return process.on("SIGTERM",b),process.once("SIGINT",b),n&&(process.on("uncaughtException",f),process.on("unhandledRejection",f)),{routes:t.routes,palbase:e,port:u,handle:d,close:h}}async function Br(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,h]of Object.entries(e.headers))if(h!==void 0)if(Array.isArray(h))for(let y of h)i.append(p,y);else i.set(p,h);let o=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;r.on("close",()=>{r.writableFinished||d.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?kr.toWeb(e):void 0,duplex:"half",signal:d.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((p,h)=>r.setHeader(h,p)),s.on&&r.setHeader("connection","close"),u.body)for await(let p of u.body)r.write(p);r.end()}catch(n){c.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function Fr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>G(o)),a=s.filter(o=>!G(o));a.length>0&&r(`[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 Ns,boolean as qs,check as Ws,date as Vs,defineSchema as Gs,defineTable as Ks,enumType as zs,foreignKey as Hs,index as Ys,integer as Js,jsonb as Qs,numeric as Xs,ownedByUser as Zs,policy as en,raw as tn,sqlType as rn,text as sn,timestamp as nn,userRef as an,uuid as on}from"palgres/dsl";import{increment as cn,now as dn}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 r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return E(r)}}var Mr=R("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),$r=100,Ir=1e3,Lr=168*3600,Dr={s:1,m:60,h:3600,d:86400};function Ur(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)*Dr[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 A&&i.code==="invalid_path_parameter"?new A({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=`${g.url}/storage/public/${W(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function _e(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 jr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:_e(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 r=await g.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return E(r)}},getPublicUrl(e,r){return Me(t,e,r?.variant)},async createSignedUrl(e,r){let s=Ur(r?.expiresIn);return s===void 0||s<1||s>Lr?{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}:P(()=>g.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??$r,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,o=200;try{for(;a.length<s;){let d=Math.max(1,Math.min(Ir,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(_e(u));if(i=l.data.next_cursor,!i)break}}catch(d){return E(d)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await g.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return E(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 P(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Nr={bucket:jr},Oe=t=>ee("Storage",t,Nr),qr={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},Wr=R("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 P(()=>g.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>g.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 d=await g.notify.sendEmail({body:{...n,to:o}});i=d.status,a.push(d.data.message_id??null)}catch(d){return E(d)}return{data:{message_ids:a},error:null,status:i}}}}),Te=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Ce=t=>typeof t=="string"?{name:t}:null,Be=t=>t==="override"?"user":t,Vr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&("userId"in t||"properties"in t);function $e(){return te.getStore()?.userId}function j(t){let e=t&&"userId"in t?t.userId??void 0:$e();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Fe={setOverrideForUser:(t,e,r)=>P(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Be(s.source)})),setOverridesForUser:(t,e)=>P(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Be(r.source)})),clearAllOverridesForUser:t=>P(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Gr=R("Flags",{async isEnabled(t,e){let r=s=>(c.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await j(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Te(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await j(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Ce(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await j(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Ce(s);return{name:r,enabled:Te(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):Vr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await j(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=$e();return r?Fe.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 Fe}}),Kr=R("Realtime",{broadcast(t,e,r){return P(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as yn}from"zod";export{Ue as AuthUnavailable,Pt as Authorize,Bt as BadRequest,ze as Body,qt as CACHE_MAX_TTL,Wt as Cache,mt as ChatPart,rt as Client,Ft as Conflict,O as ContractRunEnded,je as Controller,it as Cron,ut as Database,Mt as DeadlockDetected,Ge as Delete,Rt as DiError,Le as EVENT_TYPES,Gr as Flags,Tt as Forbidden,wt as Gateway,yt as GatewayRefusal,Ne as Get,Ye as Headers,$t as HttpError,nt as Injectable,c as Log,Nt as MAX_BODY_BYTES,U as MigrationRunEnded,at as Module,It as NotFound,Wr as Notifications,ot as On,vt as OnConnect,At as OnDisconnect,kt as OnEmpty,St as OnFirst,Xe as OptionalUser,_t as PalError,g as Palbase,A as PalbaseError,_r as PalbaseFactory,Je as Param,Ve as Patch,qe as Post,We as Put,Ke as Query,He as QueryParams,Kr as Realtime,Ze as Req,et as RequestId,st as Resolve,I as SchemaNotPushed,Mr as Secrets,Lt as SerializationFailure,qr as Storage,Et as Subscribe,ht as Task,pt as TaskFailure,gt as Tasks,De as TokenError,C as TokenVerifier,Dt as TooManyRequests,tt as TraceId,Ot as Unauthorized,Ut as UniqueViolation,bt as Upload,ft as UploadedObject,Qe as User,lt as Webhook,Ns as bigint,qs as boolean,Ws as check,M as createApp,Vs as date,Ct as defineError,Gs as defineSchema,Ks as defineTable,zs as enumType,Hs as foreignKey,ct as getRegisteredControllers,dt as getRoutes,xt as getWebhookManifest,cn as increment,Ys as index,Js as integer,Qs as jsonb,dn as now,Xs as numeric,Zs as ownedByUser,en as policy,tn as raw,rn as sqlType,jt as t,sn as text,nn as timestamp,an as userRef,on as uuid,yn as z};
|
|
10
|
+
`}function ve(t,e,r=mr){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 Ae=2e4,ke=5e3,Er=15e3,xr="/_palbase/health";function _r(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=B(s,Q);return n?n.providers.some(a=>B(a,X)!==void 0&&B(a,Z)===void 0)||n.imports.some(r):!1};return t.some(r)}var Or={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=de(s);if(n!==void 0){let w=n==="types"?await be(e.db):e.db?await fe(e.db,s,n):await ge(n);throw process.exit(w),new U(w)}let a=s.PALBASE_CONTRACT_OUT;if(a){let w;try{await xe(Ee(s)),w=await Rr(r,e,s)}catch(v){throw vr(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
|
|
11
|
+
`),process.exit(1),new R}throw a==="/dev/stdout"?ve(1,Se(w)):Sr(a,`${w}
|
|
12
|
+
`),process.exit(0),new R}let i=Ee(s),o=await xe(i);o&&c.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),se(o?void 0:i);let d=e.db?L(e.db):void 0,l=await J({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&c.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&&c.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=_r(r)||d!==void 0&&D(d),p=we(e.palbase??{},s,{needsWebhookSecret:u});u&&p.webhookSecret===void 0&&c.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let h=V({url:p.url,secretKey:p.secretKey}),y=e.port??Number(s.PORT??"8080");if(!Number.isInteger(y)||y<0||y>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let b=e.db?await me(e.db,s,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:ye(h)}):void 0;b&&c.info(`[palbase] database: version ${b.binding.version}`);let f=b&&D(b.model)?{"user.deleted":[w=>Tr(b,w)]}:void 0,m=p.platformSecret===void 0?void 0:{secret:p.platformSecret},S=e.requestTelemetry===!1?void 0:new $(h.analytics),T=()=>M({modules:r,verifier:new C({issuer:p.url,projectId:p.projectId,standing:H({url:p.url,secretKey:p.secretKey})}),server:h,webhookSecret:p.webhookSecret,env:s,projectId:p.projectId,telemetry:S,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Fr(e.cors,s.PALBASE_WEB_ORIGINS),platform:m,events:f,database:b&&{app:b.app,requests:b.requests},strings:o}),x=T(),N=e.boot?.attempts??5,q=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await x.start();break}catch(v){if(w>=N)throw c.error(`[palbase] the app did not start after ${N} attempts`,{error:v}),v;c.warn(`[palbase] the app did not start (attempt ${w} of ${N}); trying again in ${q} ms`,{error:v}),await new Promise(Ie=>setTimeout(Ie,q)),q*=2,x=T()}return Cr(x,h,y,e.host??"0.0.0.0",e.exitOnFatal??!0,b)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=k(_e(e));for(;!K(z(r,"package.json"))&&k(r)!==r;)r=k(r);return K(z(r,"package.json"))?r:process.cwd()}async function xe(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 Rr(t,e,r){let s=_e(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=k(s);for(;!K(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/APTIATSC.js"),{routeContracts:i}=await import("../chunks/QC2SDBJD.js"),o=a(n,s);for(let u of o.warnings)c.warn(`[palbase] the contract: ${u}`);let d="https://contract.palbase.invalid",l=M({modules:t,verifier:new C({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:V({url:d,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(o.routes),errors:re()},events:e.db&&D(L(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var R=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},U=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Tr(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);c.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Cr(t,e,r,s,n,a){let i,o={on:!1},d=(m,S)=>new URL(m.url).pathname===xr&&m.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(m,S),l=Ar((m,S)=>{Br(d,m,S,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((m,S)=>{l.once("error",S),l.listen(r,s,()=>m())})}catch(m){throw await t.stop(),await a?.close(),m}let u=l.address().port;c.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=m=>i??=(async()=>{c.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let S=new Promise(x=>l.close(()=>x()));l.closeIdleConnections();let T=setTimeout(()=>l.closeAllConnections(),m);await S,clearTimeout(T),process.off("SIGINT",b),process.off("uncaughtException",f),process.off("unhandledRejection",f);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",b)}})(),h=()=>p(Ae),y=!1,b=()=>{if(y){c.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}y=!0;let m=setTimeout(()=>{c.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ae+Er);m.unref(),h().then(()=>{clearTimeout(m),process.exit(0)},S=>{clearTimeout(m),c.error("[palbase] stopping failed; the process ends",{error:S}),process.exit(1)})},f=m=>{c.error("[palbase] the app crashed; stopping so the machine starts it again",{error:m});let S=setTimeout(()=>process.exit(1),ke+1e3);p(ke).finally(()=>{clearTimeout(S),process.exit(1)})};return process.on("SIGTERM",b),process.once("SIGINT",b),n&&(process.on("uncaughtException",f),process.on("unhandledRejection",f)),{routes:t.routes,palbase:e,port:u,handle:d,close:h}}async function Br(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,h]of Object.entries(e.headers))if(h!==void 0)if(Array.isArray(h))for(let y of h)i.append(p,y);else i.set(p,h);let o=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;r.on("close",()=>{r.writableFinished||d.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?kr.toWeb(e):void 0,duplex:"half",signal:d.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(r.statusCode=u.status,u.headers.forEach((p,h)=>r.setHeader(h,p)),s.on&&r.setHeader("connection","close"),u.body)for await(let p of u.body)r.write(p);r.end()}catch(n){c.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function Fr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>G(o)),a=s.filter(o=>!G(o));a.length>0&&r(`[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 Ns,boolean as qs,check as Ws,date as Vs,defineSchema as Gs,defineTable as Ks,enumType as zs,foreignKey as Hs,index as Ys,integer as Js,jsonb as Qs,numeric as Xs,ownedByUser as Zs,policy as en,raw as tn,sqlType as rn,text as sn,timestamp as nn,userRef as an,uuid as on}from"palgres/dsl";import{increment as cn,now as dn}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 r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return E(r)}}var Mr=_("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),$r=100,Ir=1e3,Lr=168*3600,Dr={s:1,m:60,h:3600,d:86400};function Ur(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)*Dr[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 A&&i.code==="invalid_path_parameter"?new A({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=`${g.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 jr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(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 r=await g.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return E(r)}},getPublicUrl(e,r){return Me(t,e,r?.variant)},async createSignedUrl(e,r){let s=Ur(r?.expiresIn);return s===void 0||s<1||s>Lr?{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}:P(()=>g.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??$r,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,o=200;try{for(;a.length<s;){let d=Math.max(1,Math.min(Ir,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=l.data.next_cursor,!i)break}}catch(d){return E(d)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await g.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return E(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 P(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Nr={bucket:jr},Re=t=>ee("Storage",t,Nr),qr={bucket:t=>Re("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Re("buckets").bucket(e):void 0})},Wr=_("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 P(()=>g.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>g.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 d=await g.notify.sendEmail({body:{...n,to:o}});i=d.status,a.push(d.data.message_id??null)}catch(d){return E(d)}return{data:{message_ids:a},error:null,status:i}}}}),Te=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Ce=t=>typeof t=="string"?{name:t}:null,Be=t=>t==="override"?"user":t,Vr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function $e(){return te.getStore()?.userId}function j(t){let e=t&&"userId"in t?t.userId??void 0:$e();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Fe={setOverrideForUser:(t,e,r)=>P(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Be(s.source)})),setOverridesForUser:(t,e)=>P(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Be(r.source)})),clearAllOverridesForUser:t=>P(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Gr=_("Flags",{async isEnabled(t,e){let r=s=>(c.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await j(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Te(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await j(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Ce(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await j(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Ce(s);return{name:r,enabled:Te(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):Vr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await j(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=$e();return r?Fe.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 Fe}}),Kr=_("Realtime",{broadcast(t,e,r){return P(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as yn}from"zod";export{Ue as AuthUnavailable,Pt as Authorize,Bt as BadRequest,ze as Body,qt as CACHE_MAX_TTL,Wt as Cache,mt as ChatPart,rt as Client,Ft as Conflict,R as ContractRunEnded,je as Controller,it as Cron,ut as Database,Mt as DeadlockDetected,Ge as Delete,_t as DiError,Le as EVENT_TYPES,Gr as Flags,Tt as Forbidden,wt as Gateway,yt as GatewayRefusal,Ne as Get,Ye as Headers,$t as HttpError,nt as Injectable,c as Log,Nt as MAX_BODY_BYTES,U as MigrationRunEnded,at as Module,It as NotFound,Wr as Notifications,ot as On,vt as OnConnect,At as OnDisconnect,kt as OnEmpty,St as OnFirst,Xe as OptionalUser,Ot as PalError,g as Palbase,A as PalbaseError,Or as PalbaseFactory,Je as Param,Ve as Patch,qe as Post,We as Put,Ke as Query,He as QueryParams,Kr as Realtime,Ze as Req,et as RequestId,st as Resolve,I as SchemaNotPushed,Mr as Secrets,Lt as SerializationFailure,qr as Storage,Et as Subscribe,ht as Task,pt as TaskFailure,gt as Tasks,De as TokenError,C as TokenVerifier,Dt as TooManyRequests,tt as TraceId,Rt as Unauthorized,Ut as UniqueViolation,bt as Upload,ft as UploadedObject,Qe as User,lt as Webhook,Ns as bigint,qs as boolean,Ws as check,M as createApp,Vs as date,Ct as defineError,Gs as defineSchema,Ks as defineTable,zs as enumType,Hs as foreignKey,ct as getRegisteredControllers,dt as getRoutes,xt as getWebhookManifest,cn as increment,Ys as index,Js as integer,Qs as jsonb,dn as now,Xs as numeric,Zs as ownedByUser,en as policy,tn as raw,rn as sqlType,jt as t,sn as text,nn as timestamp,an as userRef,on as uuid,yn as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as u}from"../chunks/
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u}from"../chunks/NGS4ALOE.js";import{c as p,i as c}from"../chunks/Z4A62VQR.js";import{a as l,b as g,c as f,d as y}from"../chunks/UDAWSJMT.js";import"../chunks/QW3V2NBT.js";import"../chunks/IVJCGBYG.js";import"../chunks/6N3E2XHZ.js";import"../chunks/YQEM4H7U.js";import"../chunks/RO7ERCT3.js";import"../chunks/RWGEPDRQ.js";import"../chunks/PG7BO4MR.js";import"../chunks/XYXBDSXW.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.
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"./
|
|
1
|
+
/*! palbase 0.10.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"./XYXBDSXW.js";import{realpathSync as Ue}from"node:fs";import{resolve as de}from"node:path";import Nt from"typescript";import{existsSync as Se,readFileSync as ye}from"node:fs";import{createRequire as qe}from"node:module";import{dirname as ne,join as W,relative as Je,resolve as Te,sep as te}from"node:path";var h=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},G=new Set(["palbase/backend","@palbase/backend","palgres"]),Qe=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function he(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new h(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var We={bun:"bun-types",node:"@types/node"},Ge=qe(import.meta.url);function Ze(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=We[i],a=e.resolveTypeReferenceDirective(i,W(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=Ge.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(ye(c,"utf8"));s.push(W(ne(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function be(e,t){he(e);let n=W(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(Se(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new h(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
|
|
3
3
|
`)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Ze(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function xe(e,t,n,r,s){he(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=Te(t);return!n.includes(`${te}node_modules${te}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+te))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function we(e,t){let n=[],r=ne(Te(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=W(r,"package.json");if(Se(o)){try{let c=JSON.parse(ye(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=ne(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function re(e,t){if($(e,t))return!1;let n=we(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):G.has(n)}function ke(e,t){if($(e,t))return!1;let n=we(e,t)??"";return G.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${Je(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function Z(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=Z(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ge(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&G.has(ge(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&G.has(ge(n,i)??""))return(i.propertyName||i.name).text;if(re(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function pe(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function H(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>pe(e,o)==="Controller"))continue;if(!s.name)throw new h(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Qe.has(pe(e,a)??""))){if(P(n,o.name)===null)throw new h(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var He=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function Xe(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ee(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=f=>{throw new h(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${f}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let f=[];for(let p of n.getSourceFiles()){if(f.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ke(e,p.fileName)||f.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!He.has(x.code)))}f.length&&u(t.formatDiagnostics(f.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
|
|
4
4
|
`})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(Xe(g))return{kind:"raw"};let S=new Set,d=0;function C(f,p){if(++d>2e3||S.size>24)return u(`${p}: contract is too large; name its schema`);let x=f.flags,y=t.TypeFlags;if(x&(y.Any|y.Unknown|y.Never|y.TypeParameter))return u(`${p}: ${r.typeToString(f)}`);let me=b=>{let w=r.getPropertiesOfType(b);if(!(b.flags&y.Object)||w.length!==1||w[0].name!=="__pg"||!(w[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(b).length)return!1;let N=r.getTypeOfSymbolAtLocation(w[0],o);return(N.isUnion()?N.types:[N]).every(k=>k.flags&(y.StringLiteral|y.Undefined))};if(f.isIntersection()){let b=f.types.filter(w=>!me(w));if(b.length===1&&b.length<f.types.length)return C(b[0],p)}if(me(f))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&y.StringLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.NumberLiteral)return`z.literal(${JSON.stringify(f.value)})`;if(x&y.BooleanLiteral)return`z.literal(${r.typeToString(f)==="true"})`;if(x&y.String)return"z.string()";if(x&y.TemplateLiteral){let b=f;if(b.types.length>8||!b.types.every(k=>k.flags&y.String))return u(`${p}: template literal requires an explicit schema`);let w=k=>k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+w(b.texts[0]);for(let k of b.texts.slice(1,-1))if(k){let ee=w(k);N+=`(?:(?!${ee})[\\s\\S])*${ee}`}return N+="[\\s\\S]*"+w(b.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&y.Number)return"z.number().finite()";if(x&y.Boolean)return"z.boolean()";if(x&y.Null)return"z.null()";if(x&y.Undefined)return"z.undefined()";if(S.has(f))return u(`${p}: recursive response`);S.add(f);try{if(f.isUnion()){if(f.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=f.types.some(M=>M.flags&y.Null),Q=f.types.some(M=>M.flags&y.Undefined),j=f.types.filter(M=>!(M.flags&(y.Null|y.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?C(j[0],p):`z.union([${j.map(M=>C(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(Q?".optional()":"")}if(r.isTupleType(f))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(f)){let A=r.getTypeArguments(f)[0];return A.flags&y.Never?"z.array(z.string()).length(0)":`z.array(${C(A,`${p}[]`)})`}let b=f.isIntersection()&&f.types.every(A=>A.flags&y.Object);if(!(x&y.Object)&&!b||f.getCallSignatures().length||f.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(f)}`);let w=f.symbol?.declarations?.[0];if(w&&(t.isClassDeclaration(w)||t.isClassExpression(w)))return u(`${p}: class instance ${r.typeToString(f)}`);let N=r.getPropertiesOfType(f),k=r.getIndexInfosOfType(f);return k.length?k.length!==1||!(k[0].keyType.flags&y.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${C(k[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let Q=A.getName(),j=C(r.getTypeOfSymbolAtLocation(A,o),`${p}.${Q}`);return`${JSON.stringify(Q)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{S.delete(f)}}return{kind:"expression",expression:C(g,"return")}}}import{resolve as Ye}from"node:path";var se=Symbol("not a named schema");function Ce(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=d=>new h(`${i.fileName} \u2014 ${n}.${o}: ${d}`);function c(d){if(s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Promise"&&d.typeArguments&&d.typeArguments.length===1)return c(d.typeArguments[0]);if(d.kind===s.SyntaxKind.VoidKeyword||d.kind===s.SyntaxKind.UndefinedKeyword)return null;let C=s.isArrayTypeNode(d)?d.elementType:s.isTypeReferenceNode(d)&&d.typeName.getText(i)==="Array"&&d.typeArguments&&d.typeArguments.length===1?d.typeArguments[0]:void 0,f=l(C??d);return f===se?f:{...f,isArray:C!==void 0}}function l(d){if(s.isTypeReferenceNode(d)&&!d.typeArguments)return{typeName:d.typeName.getText(i),node:d.typeName};if(s.isTypeReferenceNode(d)&&d.typeArguments&&d.typeArguments.length===1){let C=d.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(C)){let f=d.typeArguments[0];if(s.isTypeQueryNode(f))return{typeName:f.exprName.getText(i),node:f.exprName};if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName}}}if(d.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return se}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===se)return u();let g=et(e,m.node);if(!g)return u();let S=tt(e,g.symbol);return S?{kind:"schema",...S,array:m.isArray}:u()}function et(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=Z(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function tt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>Z(e,i)===t).map(i=>i.name);return s.length===0?null:{file:Ye(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ce={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},nt=new Set(["HttpError","PalError"]),rt=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],st=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function Le(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=Ct(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function it(e,t,n){throw new h(`${O(e,t)} \u2014 ${n}`)}function U(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function ue(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Pe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function $e(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ot(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=$e(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function q(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Fe(e,t,n){for(let r=q(e,t);r;r=q(e,r))if(r===n)return!0;return!1}function V(e,t,n,r){let s=e.ts;for(let i=t;i;i=q(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||ue(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function at(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function Ne(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Pe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function Oe(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ct(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ie(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function J(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)J(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Pe(r,a)||n.add(a);for(let l of Ne(e))Fe(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of Ne(e)){let u=Oe(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function le(e,t,n){let r=ct(e,t);if(r){let s=at(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Fe(e,o,r));if(i.length===1){n.add(i[0]);return}}J(e,t,n)}function lt(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function Re(e,t){return t.fn&<(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function E(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(E(e,t.whenTrue,n,r)),a(E(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(E(e,t.left,n,r)),a(E(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(E(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of Y(e,t,n))for(let l of X(s,c.fn))a(E(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(E(e,c.initializer,Re(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&J(e,ie(e,c),i),i;if(c&&s.isParameter(c)){let l=ie(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?le(e,l,i):J(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(E(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):le(e,ie(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of X(s,c))a(E(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(E(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return J(e,e.checker.getTypeAtLocation(t),i),i}function X(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function ze(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function je(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function ut(e,t){let n=e.ts,r=ze(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(je(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!re(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of rt)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function ft(e,t){let n=e.checker.getSymbolAtLocation(je(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Me(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=q(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||ue(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function Y(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&q(e,n.owner);return c?Me(e,c,n.receiver):[]}let i=ze(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&q(e,n.owner),S=g&&V(e,g,i,!1);return S?[{fn:S.fn,ctx:{receiver:n.receiver,owner:S.owner,fn:S.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=V(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!ft(e,c))return[];let m=[];for(let g of E(e,l,n)){let S=V(e,g,i,!1);S&&m.push({fn:S.fn,ctx:{receiver:g,owner:S.owner,fn:S.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!ue(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function Ae(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of E(e,s.expression,n)){let l=V(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function ve(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function dt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function De(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ie(e,t,n,r,s){if(nt.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(ve(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:De(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ce,t)?ce[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!dt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return ve(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:De(c),code:c,status:i.status}))}function fe(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function Be(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&it(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function mt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ke(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(d=>d.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(d=>s.isConstructorDeclaration(d)&&!!d.body),c=n,l=r;if(a){let d=mt(s,a);if(!d)return[];c=d.arguments,l=d}let u=ot(s,t),m=I(e,o);if(m)return Ie(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let d=fe(e,g);return d?[{...Be(e,g,d),name:u||g.name.getText()}]:[]}let S=_(e,o);if(S){let d=Ke(e,S,c,l);return d.length===1&&u?[{...d[0],name:u}]:d}return[]}function gt(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ie(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=fe(e,o);if(c)return[Be(e,o,c)]}let a=$e(n,o);return a&&v(e,a)?Ke(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,gt(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of Y(e,t,n))for(let u of X(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?Re(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function oe(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function pt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function St(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function yt(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=pt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||St(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function Tt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ce))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=fe(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function ht(e,t){let n=Tt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new h(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)ht(e,o);let i=yt(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function _e(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function bt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?_e(e,n.body,r.name.text):!1:!0:!1}return!0}function xt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${U(e,t)}@${n.receiver?U(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function ae(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,ae(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?_e(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(xt(e,o,"allSettled")){D(e,t.expression,n,r);let u=ae(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=bt(s,t.arguments[a]);D(e,u.expression,n,ae(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?st.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=ut(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of Y(e,t,n))R(e,r,t,oe(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of Ae(e,u,n))R(e,r,u,oe(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Me(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of Ae(e,a,n))R(e,r,a,oe(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of E(e,t.expression,n)){let c=V(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function Ve(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of Y(e,t,{receiver:null,owner:null,fn:null}))for(let o of X(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...Ve(e,a,n))}return s}function wt(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of Ve(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;le(e,Oe(e,c),l);for(let u of l){let m=V(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function kt(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Et(e,t,n){let r=new Map;for(let i of wt(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=kt(i.name),a=s.get(o);if(a)throw new h(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function Ct(e,t){let n=[];for(let{cls:r,routes:s}of H(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Et(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Qt(e,t,n={}){let r=n.typescript??Nt,s=Ue(de(e)),{options:i,ambient:o}=be(r,s);return At(xe(r,s,[Ue(de(t)),...o],i))}function At(e){let t=e.ts,n=Ee(e),r=Le(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=H(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ce(e,n,u.name.text,g))}catch(S){if(!(S instanceof h))throw S;o.push(S.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,S]of Object.entries(m))s.push({file:de(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:S})}if(o.length===1)throw new h(o[0]);if(o.length>1)throw new h(`${o.length} routes have no contract:
|
|
5
5
|
${o.map(a=>`- ${a}`).join(`
|