@palbase/backend 0.10.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-7N5ICXCB.js +88 -0
- package/dist/chunk-7N5ICXCB.js.map +1 -0
- package/dist/db/index.d.cts +2 -2
- package/dist/db/index.d.ts +2 -2
- package/dist/{endpoint-BbbU1hE1.d.ts → endpoint-knNIeovM.d.ts} +166 -131
- package/dist/{endpoint-6LeBP-eb.d.cts → endpoint-yn2xcrWu.d.cts} +166 -131
- package/dist/index.cjs +104 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +195 -22
- package/dist/index.d.ts +195 -22
- package/dist/index.js +34 -29
- package/dist/index.js.map +1 -1
- package/dist/{schema-zk-a0Dv7.d.cts → schema-BqfEhIC0.d.cts} +1 -1
- package/dist/{schema-zk-a0Dv7.d.ts → schema-BqfEhIC0.d.ts} +1 -1
- package/dist/test/index.cjs +62 -7
- package/dist/test/index.cjs.map +1 -1
- package/dist/test/index.d.cts +28 -5
- package/dist/test/index.d.ts +28 -5
- package/dist/test/index.js +34 -7
- package/dist/test/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,27 +1,200 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { A as AuthConfig,
|
|
3
|
-
|
|
1
|
+
import { D as DBClient, C as CacheClient, P as PalbaseDocsClient, a as PalbaseFlagsClient, L as Logger, b as PalbaseNotificationsClient, Q as QueueClient, c as PalbaseStorageClient, d as PalbaseModuleClients, U as User, E as ErrorThrowers } from './endpoint-yn2xcrWu.cjs';
|
|
2
|
+
export { A as AuthConfig, e as ClientInfo, f as EndpointConfig, g as ErrorDef, h as ErrorMap, F as FileContext, H as HttpError, i as HttpMethod, M as Middleware, j as MiddlewareContext, k as MiddlewareHandler, l as PBRequest, m as PalbaseAnalyticsClient, n as PalbaseAnalyticsManagementNamespace, o as PalbaseAnalyticsProperties, p as PalbaseAnalyticsQueryNamespace, q as PalbaseAttestAndroidParams, r as PalbaseAttestAndroidResult, s as PalbaseAttestiOSParams, t as PalbaseAttestiOSResult, u as PalbaseAuthClient, v as PalbaseBindDeviceParams, w as PalbaseBucketClient, x as PalbaseCmsClient, y as PalbaseCmsFindOneOptions, z as PalbaseCmsFindOptions, B as PalbaseCohortQueryInput, G as PalbaseCohortResult, I as PalbaseCollectionRef, J as PalbaseCountQueryInput, K as PalbaseCountResult, N as PalbaseCreateLinkParams, O as PalbaseDeviceInfo, R as PalbaseDeviceTokenView, S as PalbaseDocumentRef, T as PalbaseDocumentSnapshot, V as PalbaseEmailClient, W as PalbaseEmailSendParams, X as PalbaseEmailSendResponse, Y as PalbaseEventNamesResult, Z as PalbaseEventsQueryInput, _ as PalbaseEventsResult, $ as PalbaseFileObject, a0 as PalbaseFlag, a1 as PalbaseFlagContext, a2 as PalbaseFlagVariant, a3 as PalbaseFunctionsClient, a4 as PalbaseFunnelQueryInput, a5 as PalbaseFunnelResult, a6 as PalbaseIdentifyTraits, a7 as PalbaseInboxClient, a8 as PalbaseInboxListOptions, a9 as PalbaseInboxListResult, aa as PalbaseInboxMessage, ab as PalbaseInboxSendParams, ac as PalbaseInboxSendResponse, ad as PalbaseInitialLink, ae as PalbaseInvokeOptions, af as PalbaseLink, ag as PalbaseLinkAnalytics, ah as PalbaseLinkDetails, ai as PalbaseLinksClient, aj as PalbaseListLinksOptions, ak as PalbaseListLinksResult, al as PalbaseListOptions, am as PalbaseMatchParams, an as PalbaseMultiChannelResponse, ao as PalbaseOverviewResult, ap as PalbasePreferences, aq as PalbasePreferencesClient, ar as PalbasePublicUrlResponse, as as PalbasePushClient, at as PalbasePushSendParams, au as PalbasePushSendResponse, av as PalbaseQrCodeOptions, aw as PalbaseQuerySnapshot, ax as PalbaseRealtimeChannel, ay as PalbaseRealtimeClient, az as PalbaseRealtimeMessage, aA as PalbaseRegisterDeviceParams, aB as PalbaseResult, aC as PalbaseRetentionQueryInput, aD as PalbaseRetentionResult, aE as PalbaseSession, aF as PalbaseSignedUrlResponse, aG as PalbaseSmsClient, aH as PalbaseSmsSendParams, aI as PalbaseSmsSendResponse, aJ as PalbaseTransformOptions, aK as PalbaseUpdateLinkParams, aL as PalbaseUploadOptions, aM as PalbaseUser, aN as PalbaseUserDetailResult, aO as PalbaseUsersQueryInput, aP as PalbaseUsersResult, aQ as PalbaseVerifyRequestSignatureParams, aR as PalbaseWhereOperator, aS as RateLimitConfig, aT as TxClient, aU as defineEndpoint, aV as defineMiddleware } from './endpoint-yn2xcrWu.cjs';
|
|
3
|
+
import { T as TableDef, C as ColIsOptionalOnInsert, a as ColValue, S as SchemaDef } from './schema-BqfEhIC0.cjs';
|
|
4
|
+
export { b as ColumnBuilder, c as ColumnDef, d as ColumnType, O as OnDeleteAction, e as boolean, f as defineSchema, g as enumType, i as integer, j as jsonb, t as table, h as text, k as timestamp, u as uuid } from './schema-BqfEhIC0.cjs';
|
|
4
5
|
export { z } from 'zod';
|
|
5
6
|
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
7
|
+
/**
|
|
8
|
+
* typed-db.ts — Task 2: TypedDB schema-derived insert/row shapes.
|
|
9
|
+
*
|
|
10
|
+
* Derives INSERT and full-row TypeScript types from a `defineSchema()` result
|
|
11
|
+
* and wraps the untyped runtime `DBClient` with a typed facade.
|
|
12
|
+
*
|
|
13
|
+
* No value-any. No `as unknown as X`. The two narrow `as` casts in
|
|
14
|
+
* `makeTypedTable` are safe because:
|
|
15
|
+
* - `data as Record<string, unknown>`: InsertShape<T> maps string keys to
|
|
16
|
+
* typed values; all value types are subsets of `unknown`, so the cast is
|
|
17
|
+
* structurally sound.
|
|
18
|
+
* - `result as RowShape<T>`: The runtime DBClient returns `Record<string,
|
|
19
|
+
* unknown>` which is the erased form of the typed row; we're narrowing back
|
|
20
|
+
* to the precise shape that the schema declared.
|
|
21
|
+
* Both casts are narrowing only (not widening) and correctness is guaranteed
|
|
22
|
+
* by the schema the caller provides.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** Keys of C whose columns are required on INSERT (not nullable, no default). */
|
|
26
|
+
type RequiredKeys<C> = {
|
|
27
|
+
[K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? never : K;
|
|
28
|
+
}[keyof C];
|
|
29
|
+
/** Keys of C whose columns are optional on INSERT (nullable or has a default). */
|
|
30
|
+
type OptionalKeys<C> = {
|
|
31
|
+
[K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? K : never;
|
|
32
|
+
}[keyof C];
|
|
33
|
+
/**
|
|
34
|
+
* The TypeScript type for an INSERT payload for table `T`.
|
|
35
|
+
* - Required: columns that are NOT NULL and have no DB-level default.
|
|
36
|
+
* - Optional: columns that are nullable or carry a default.
|
|
37
|
+
*
|
|
38
|
+
* When all columns are optional, `RequiredKeys<C>` resolves to `never` and
|
|
39
|
+
* the first part becomes `{}`, which is a neutral element for `&`.
|
|
40
|
+
*/
|
|
41
|
+
type InsertShape<T extends TableDef> = {
|
|
42
|
+
[K in RequiredKeys<T["columns"]>]: ColValue<T["columns"][K]>;
|
|
43
|
+
} & {
|
|
44
|
+
[K in OptionalKeys<T["columns"]>]?: ColValue<T["columns"][K]>;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* The TypeScript type for a full row returned by the DB for table `T`.
|
|
48
|
+
* Every column is present; nullable columns resolve to `T | null`.
|
|
49
|
+
*/
|
|
50
|
+
type RowShape<T extends TableDef> = {
|
|
51
|
+
[K in keyof T["columns"]]: ColValue<T["columns"][K]>;
|
|
52
|
+
};
|
|
53
|
+
/** A typed table accessor that mirrors the runtime DBClient surface. */
|
|
54
|
+
interface TypedTable<T extends TableDef> {
|
|
55
|
+
insert(data: InsertShape<T>): Promise<RowShape<T>>;
|
|
56
|
+
update(id: string, data: Partial<InsertShape<T>>): Promise<RowShape<T>>;
|
|
57
|
+
delete(id: string): Promise<void>;
|
|
58
|
+
findById(id: string): Promise<RowShape<T> | null>;
|
|
59
|
+
findMany(query?: Partial<RowShape<T>>): Promise<RowShape<T>[]>;
|
|
60
|
+
}
|
|
61
|
+
/** A typed DB facade covering all tables declared in schema `S`. */
|
|
62
|
+
interface TypedDB<S extends SchemaDef> {
|
|
63
|
+
tables: {
|
|
64
|
+
[K in keyof S["tables"]]: TypedTable<S["tables"][K]>;
|
|
65
|
+
};
|
|
66
|
+
transaction<T>(fn: (tx: TypedTx<S>) => Promise<T>): Promise<T>;
|
|
67
|
+
}
|
|
68
|
+
/** Transaction-scoped typed facade: same typed tables, no nested transaction. */
|
|
69
|
+
interface TypedTx<S extends SchemaDef> {
|
|
70
|
+
tables: {
|
|
71
|
+
[K in keyof S["tables"]]: TypedTable<S["tables"][K]>;
|
|
22
72
|
};
|
|
23
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Wraps a raw `DBClient` with the type-safe `TypedDB<S>` facade derived from
|
|
76
|
+
* the provided schema. No behavior change — all calls delegate to `raw` with
|
|
77
|
+
* the table name as a plain string.
|
|
78
|
+
*
|
|
79
|
+
* `buildTables` is the reusable factory that wraps any op-bearing client
|
|
80
|
+
* (`TxClient` — the surface shared by `DBClient` and the transaction-scoped
|
|
81
|
+
* client) into the typed tables map. It is used both for the top-level db
|
|
82
|
+
* (wrapping `raw`) and inside `transaction`, where it wraps the raw `TxClient`
|
|
83
|
+
* the runtime yields so the callback sees the same typed `.tables` API.
|
|
84
|
+
*
|
|
85
|
+
* `transaction` delegates straight to `raw.transaction`; the two narrow
|
|
86
|
+
* `as TypedTx<S>` / `as TypedDB<S>` casts are single structural narrowings
|
|
87
|
+
* from the dynamically-built tables object to the precise mapped type (TS
|
|
88
|
+
* cannot infer through `Object.keys` iteration) — see module-level doc comment.
|
|
89
|
+
*/
|
|
90
|
+
declare function makeTypedDB<S extends SchemaDef>(schema: S, raw: DBClient): TypedDB<S>;
|
|
24
91
|
|
|
92
|
+
/**
|
|
93
|
+
* runtime.ts — request-scoped service singletons.
|
|
94
|
+
*
|
|
95
|
+
* The backend SDK no longer threads a `ctx` god-object through every handler.
|
|
96
|
+
* Instead, endpoint authors import PascalCase service singletons directly:
|
|
97
|
+
*
|
|
98
|
+
* import { Database, Documents, Cache } from "@palbase/backend";
|
|
99
|
+
*
|
|
100
|
+
* export default defineEndpoint({
|
|
101
|
+
* method: "POST",
|
|
102
|
+
* handler: async (req) => {
|
|
103
|
+
* const row = await Database.insert("todos", { title: req.input.title });
|
|
104
|
+
* return row;
|
|
105
|
+
* },
|
|
106
|
+
* });
|
|
107
|
+
*
|
|
108
|
+
* The singletons are thin Proxies. Every property access forwards to the live
|
|
109
|
+
* client held in a per-process mutable slot, which the runtime sets with
|
|
110
|
+
* {@link __setRuntime} BEFORE invoking the handler and (today) leaves in place
|
|
111
|
+
* for the lifetime of that fresh Node subprocess. Because each `br-<ref>` pod
|
|
112
|
+
* is single-tenant and every request runs in a fresh Node subprocess
|
|
113
|
+
* (node_executor.go), there is no cross-tenant leakage risk.
|
|
114
|
+
*
|
|
115
|
+
* The seam that makes `import { Database } from "@palbase/backend"` resolve to
|
|
116
|
+
* the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL
|
|
117
|
+
* when the tenant bundle is built, and the package is installed globally in the
|
|
118
|
+
* pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's
|
|
119
|
+
* `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared
|
|
120
|
+
* module instance — calling `__setRuntime` on that instance is visible to the
|
|
121
|
+
* singletons the bundle imported.
|
|
122
|
+
*/
|
|
123
|
+
|
|
124
|
+
/** The set of live clients the runtime injects per request scope.
|
|
125
|
+
*
|
|
126
|
+
* EXCLUDED on purpose: Realtime, Functions, CMS, Links, Analytics, Auth. They
|
|
127
|
+
* are not exposed as backend handler singletons (auth lives on the client SDK;
|
|
128
|
+
* the rest are out of scope for backend endpoints). */
|
|
129
|
+
interface RuntimeServices {
|
|
130
|
+
Database: DBClient;
|
|
131
|
+
Documents: PalbaseDocsClient;
|
|
132
|
+
Storage: PalbaseStorageClient;
|
|
133
|
+
Cache: CacheClient;
|
|
134
|
+
Queue: QueueClient;
|
|
135
|
+
Log: Logger;
|
|
136
|
+
Notifications: PalbaseNotificationsClient;
|
|
137
|
+
Flags: PalbaseFlagsClient;
|
|
138
|
+
}
|
|
139
|
+
/** Install the live clients for the current request scope.
|
|
140
|
+
*
|
|
141
|
+
* Called by the Palbase runtime (worker.js / dev-server.js) immediately before
|
|
142
|
+
* invoking a handler. NOT part of the public author-facing API — exported with
|
|
143
|
+
* a `__` prefix so the runtime can reach it across the shared module instance.
|
|
144
|
+
*/
|
|
145
|
+
declare function __setRuntime(services: RuntimeServices): void;
|
|
146
|
+
/** Read the live clients, throwing if accessed outside a request scope.
|
|
147
|
+
*
|
|
148
|
+
* NOT part of the public author-facing API — exported with a `__` prefix for
|
|
149
|
+
* the runtime and the singleton Proxies. */
|
|
150
|
+
declare function __getRuntime(): RuntimeServices;
|
|
151
|
+
/** The project's own Postgres (pgx, schema `env_<envId>`). Typed CRUD +
|
|
152
|
+
* `query`/`transaction`. For a typed `.tables.<name>` API, wrap with
|
|
153
|
+
* {@link typedDatabase}. */
|
|
154
|
+
declare const Database: DBClient;
|
|
155
|
+
/** Firestore-like document client (PalDocs). */
|
|
156
|
+
declare const Documents: PalbaseDocsClient;
|
|
157
|
+
/** Object storage client (buckets, signed URLs). */
|
|
158
|
+
declare const Storage: PalbaseStorageClient;
|
|
159
|
+
/** JSON-typed cache (get/set/incr/getOrSet). */
|
|
160
|
+
declare const Cache: CacheClient;
|
|
161
|
+
/** Background job queue. */
|
|
162
|
+
declare const Queue: QueueClient;
|
|
163
|
+
/** Structured logger. */
|
|
164
|
+
declare const Log: Logger;
|
|
165
|
+
/** Push / email / SMS / in-app notifications. */
|
|
166
|
+
declare const Notifications: PalbaseNotificationsClient;
|
|
167
|
+
/** Feature flags. */
|
|
168
|
+
declare const Flags: PalbaseFlagsClient;
|
|
169
|
+
/**
|
|
170
|
+
* Type the `Database` singleton against a `defineSchema()` result, returning a
|
|
171
|
+
* facade with a typed `.tables.<name>.insert(...)` API alongside the raw
|
|
172
|
+
* `query`/`transaction` ops.
|
|
173
|
+
*
|
|
174
|
+
* const Db = typedDatabase(schema);
|
|
175
|
+
* const todo = await Db.tables.todos.insert({ title: "x" });
|
|
176
|
+
*
|
|
177
|
+
* This is per-endpoint (not global module augmentation), so one endpoint's
|
|
178
|
+
* tables never leak into another's `Database` type.
|
|
179
|
+
*/
|
|
180
|
+
declare function typedDatabase<TSchema extends SchemaDef>(schema: TSchema): TypedDB<TSchema> & DBClient;
|
|
181
|
+
|
|
182
|
+
/** Context injected into worker handlers — the non-request-scoped service
|
|
183
|
+
* surface (db/log/cache/queue + module clients), plus correlation ids. Workers
|
|
184
|
+
* are not part of the Phase 1 `ctx → PBRequest` redesign, so they keep their
|
|
185
|
+
* own `ctx`; the job payload arrives as the handler's second argument. */
|
|
186
|
+
interface WorkerContext extends PalbaseModuleClients {
|
|
187
|
+
user: User | null;
|
|
188
|
+
db: DBClient;
|
|
189
|
+
env: Record<string, string>;
|
|
190
|
+
log: Logger;
|
|
191
|
+
cache: CacheClient;
|
|
192
|
+
queue: QueueClient;
|
|
193
|
+
errors: ErrorThrowers<undefined>;
|
|
194
|
+
requestId: string;
|
|
195
|
+
projectId: string;
|
|
196
|
+
environmentId: string;
|
|
197
|
+
}
|
|
25
198
|
/** Backoff strategy for worker retries. */
|
|
26
199
|
type BackoffStrategy = "exponential" | "linear" | "fixed";
|
|
27
200
|
/** Configuration for a background worker. */
|
|
@@ -35,7 +208,7 @@ interface WorkerConfig<TPayload = unknown> {
|
|
|
35
208
|
/** Backoff strategy between retries. Defaults to "exponential". */
|
|
36
209
|
backoff?: BackoffStrategy;
|
|
37
210
|
/** Handler function that processes the job payload. */
|
|
38
|
-
handler: (ctx:
|
|
211
|
+
handler: (ctx: WorkerContext, payload: TPayload) => Promise<void>;
|
|
39
212
|
}
|
|
40
213
|
/** Resolved worker configuration with defaults applied. */
|
|
41
214
|
interface ResolvedWorkerConfig<TPayload = unknown> {
|
|
@@ -43,7 +216,7 @@ interface ResolvedWorkerConfig<TPayload = unknown> {
|
|
|
43
216
|
retry: number;
|
|
44
217
|
timeout: number;
|
|
45
218
|
backoff: BackoffStrategy;
|
|
46
|
-
handler: (ctx:
|
|
219
|
+
handler: (ctx: WorkerContext, payload: TPayload) => Promise<void>;
|
|
47
220
|
}
|
|
48
221
|
/**
|
|
49
222
|
* Define a background worker that processes jobs from the queue.
|
|
@@ -370,4 +543,4 @@ declare const documents: {
|
|
|
370
543
|
onDocumentDeleted(handler: HookHandler<DocumentDeletedEvent>): ResolvedHook<DocumentDeletedEvent>;
|
|
371
544
|
};
|
|
372
545
|
|
|
373
|
-
export { type BackoffStrategy, CacheClient, type CustomWebhookConfig, DBClient, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent,
|
|
546
|
+
export { type BackoffStrategy, Cache, CacheClient, type CustomWebhookConfig, DBClient, Database, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, Documents, type EnvSecretRef, ErrorThrowers, type FileDeletedEvent, type FileUploadedEvent, Flags, type HookContext, type HookHandler, type InsertShape, type JobConfig, type JobContext, Log, Logger, Notifications, PalbaseDocsClient, PalbaseFlagsClient, PalbaseNotificationsClient, PalbaseStorageClient, type PasswordResetEvent, type ProviderEventMap, type ProviderWebhookConfig, Queue, QueueClient, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, type RowShape, type RuntimeServices, SchemaDef, type SignInEvent, type SignOutEvent, Storage, TableDef, type TypedDB, type TypedTable, type TypedTx, User, type UserCreatedEvent, type WebhookContext, type WebhookEventHandler, type WebhookProvider, type WebhookRequest, type WorkerConfig, type WorkerContext, __getRuntime, __setRuntime, auth, defineJob, defineWebhook, defineWorker, documents, makeTypedDB, storage, typedDatabase };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,27 +1,200 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { A as AuthConfig,
|
|
3
|
-
|
|
1
|
+
import { D as DBClient, C as CacheClient, P as PalbaseDocsClient, a as PalbaseFlagsClient, L as Logger, b as PalbaseNotificationsClient, Q as QueueClient, c as PalbaseStorageClient, d as PalbaseModuleClients, U as User, E as ErrorThrowers } from './endpoint-knNIeovM.js';
|
|
2
|
+
export { A as AuthConfig, e as ClientInfo, f as EndpointConfig, g as ErrorDef, h as ErrorMap, F as FileContext, H as HttpError, i as HttpMethod, M as Middleware, j as MiddlewareContext, k as MiddlewareHandler, l as PBRequest, m as PalbaseAnalyticsClient, n as PalbaseAnalyticsManagementNamespace, o as PalbaseAnalyticsProperties, p as PalbaseAnalyticsQueryNamespace, q as PalbaseAttestAndroidParams, r as PalbaseAttestAndroidResult, s as PalbaseAttestiOSParams, t as PalbaseAttestiOSResult, u as PalbaseAuthClient, v as PalbaseBindDeviceParams, w as PalbaseBucketClient, x as PalbaseCmsClient, y as PalbaseCmsFindOneOptions, z as PalbaseCmsFindOptions, B as PalbaseCohortQueryInput, G as PalbaseCohortResult, I as PalbaseCollectionRef, J as PalbaseCountQueryInput, K as PalbaseCountResult, N as PalbaseCreateLinkParams, O as PalbaseDeviceInfo, R as PalbaseDeviceTokenView, S as PalbaseDocumentRef, T as PalbaseDocumentSnapshot, V as PalbaseEmailClient, W as PalbaseEmailSendParams, X as PalbaseEmailSendResponse, Y as PalbaseEventNamesResult, Z as PalbaseEventsQueryInput, _ as PalbaseEventsResult, $ as PalbaseFileObject, a0 as PalbaseFlag, a1 as PalbaseFlagContext, a2 as PalbaseFlagVariant, a3 as PalbaseFunctionsClient, a4 as PalbaseFunnelQueryInput, a5 as PalbaseFunnelResult, a6 as PalbaseIdentifyTraits, a7 as PalbaseInboxClient, a8 as PalbaseInboxListOptions, a9 as PalbaseInboxListResult, aa as PalbaseInboxMessage, ab as PalbaseInboxSendParams, ac as PalbaseInboxSendResponse, ad as PalbaseInitialLink, ae as PalbaseInvokeOptions, af as PalbaseLink, ag as PalbaseLinkAnalytics, ah as PalbaseLinkDetails, ai as PalbaseLinksClient, aj as PalbaseListLinksOptions, ak as PalbaseListLinksResult, al as PalbaseListOptions, am as PalbaseMatchParams, an as PalbaseMultiChannelResponse, ao as PalbaseOverviewResult, ap as PalbasePreferences, aq as PalbasePreferencesClient, ar as PalbasePublicUrlResponse, as as PalbasePushClient, at as PalbasePushSendParams, au as PalbasePushSendResponse, av as PalbaseQrCodeOptions, aw as PalbaseQuerySnapshot, ax as PalbaseRealtimeChannel, ay as PalbaseRealtimeClient, az as PalbaseRealtimeMessage, aA as PalbaseRegisterDeviceParams, aB as PalbaseResult, aC as PalbaseRetentionQueryInput, aD as PalbaseRetentionResult, aE as PalbaseSession, aF as PalbaseSignedUrlResponse, aG as PalbaseSmsClient, aH as PalbaseSmsSendParams, aI as PalbaseSmsSendResponse, aJ as PalbaseTransformOptions, aK as PalbaseUpdateLinkParams, aL as PalbaseUploadOptions, aM as PalbaseUser, aN as PalbaseUserDetailResult, aO as PalbaseUsersQueryInput, aP as PalbaseUsersResult, aQ as PalbaseVerifyRequestSignatureParams, aR as PalbaseWhereOperator, aS as RateLimitConfig, aT as TxClient, aU as defineEndpoint, aV as defineMiddleware } from './endpoint-knNIeovM.js';
|
|
3
|
+
import { T as TableDef, C as ColIsOptionalOnInsert, a as ColValue, S as SchemaDef } from './schema-BqfEhIC0.js';
|
|
4
|
+
export { b as ColumnBuilder, c as ColumnDef, d as ColumnType, O as OnDeleteAction, e as boolean, f as defineSchema, g as enumType, i as integer, j as jsonb, t as table, h as text, k as timestamp, u as uuid } from './schema-BqfEhIC0.js';
|
|
4
5
|
export { z } from 'zod';
|
|
5
6
|
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
7
|
+
/**
|
|
8
|
+
* typed-db.ts — Task 2: TypedDB schema-derived insert/row shapes.
|
|
9
|
+
*
|
|
10
|
+
* Derives INSERT and full-row TypeScript types from a `defineSchema()` result
|
|
11
|
+
* and wraps the untyped runtime `DBClient` with a typed facade.
|
|
12
|
+
*
|
|
13
|
+
* No value-any. No `as unknown as X`. The two narrow `as` casts in
|
|
14
|
+
* `makeTypedTable` are safe because:
|
|
15
|
+
* - `data as Record<string, unknown>`: InsertShape<T> maps string keys to
|
|
16
|
+
* typed values; all value types are subsets of `unknown`, so the cast is
|
|
17
|
+
* structurally sound.
|
|
18
|
+
* - `result as RowShape<T>`: The runtime DBClient returns `Record<string,
|
|
19
|
+
* unknown>` which is the erased form of the typed row; we're narrowing back
|
|
20
|
+
* to the precise shape that the schema declared.
|
|
21
|
+
* Both casts are narrowing only (not widening) and correctness is guaranteed
|
|
22
|
+
* by the schema the caller provides.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** Keys of C whose columns are required on INSERT (not nullable, no default). */
|
|
26
|
+
type RequiredKeys<C> = {
|
|
27
|
+
[K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? never : K;
|
|
28
|
+
}[keyof C];
|
|
29
|
+
/** Keys of C whose columns are optional on INSERT (nullable or has a default). */
|
|
30
|
+
type OptionalKeys<C> = {
|
|
31
|
+
[K in keyof C]: ColIsOptionalOnInsert<C[K]> extends true ? K : never;
|
|
32
|
+
}[keyof C];
|
|
33
|
+
/**
|
|
34
|
+
* The TypeScript type for an INSERT payload for table `T`.
|
|
35
|
+
* - Required: columns that are NOT NULL and have no DB-level default.
|
|
36
|
+
* - Optional: columns that are nullable or carry a default.
|
|
37
|
+
*
|
|
38
|
+
* When all columns are optional, `RequiredKeys<C>` resolves to `never` and
|
|
39
|
+
* the first part becomes `{}`, which is a neutral element for `&`.
|
|
40
|
+
*/
|
|
41
|
+
type InsertShape<T extends TableDef> = {
|
|
42
|
+
[K in RequiredKeys<T["columns"]>]: ColValue<T["columns"][K]>;
|
|
43
|
+
} & {
|
|
44
|
+
[K in OptionalKeys<T["columns"]>]?: ColValue<T["columns"][K]>;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* The TypeScript type for a full row returned by the DB for table `T`.
|
|
48
|
+
* Every column is present; nullable columns resolve to `T | null`.
|
|
49
|
+
*/
|
|
50
|
+
type RowShape<T extends TableDef> = {
|
|
51
|
+
[K in keyof T["columns"]]: ColValue<T["columns"][K]>;
|
|
52
|
+
};
|
|
53
|
+
/** A typed table accessor that mirrors the runtime DBClient surface. */
|
|
54
|
+
interface TypedTable<T extends TableDef> {
|
|
55
|
+
insert(data: InsertShape<T>): Promise<RowShape<T>>;
|
|
56
|
+
update(id: string, data: Partial<InsertShape<T>>): Promise<RowShape<T>>;
|
|
57
|
+
delete(id: string): Promise<void>;
|
|
58
|
+
findById(id: string): Promise<RowShape<T> | null>;
|
|
59
|
+
findMany(query?: Partial<RowShape<T>>): Promise<RowShape<T>[]>;
|
|
60
|
+
}
|
|
61
|
+
/** A typed DB facade covering all tables declared in schema `S`. */
|
|
62
|
+
interface TypedDB<S extends SchemaDef> {
|
|
63
|
+
tables: {
|
|
64
|
+
[K in keyof S["tables"]]: TypedTable<S["tables"][K]>;
|
|
65
|
+
};
|
|
66
|
+
transaction<T>(fn: (tx: TypedTx<S>) => Promise<T>): Promise<T>;
|
|
67
|
+
}
|
|
68
|
+
/** Transaction-scoped typed facade: same typed tables, no nested transaction. */
|
|
69
|
+
interface TypedTx<S extends SchemaDef> {
|
|
70
|
+
tables: {
|
|
71
|
+
[K in keyof S["tables"]]: TypedTable<S["tables"][K]>;
|
|
22
72
|
};
|
|
23
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Wraps a raw `DBClient` with the type-safe `TypedDB<S>` facade derived from
|
|
76
|
+
* the provided schema. No behavior change — all calls delegate to `raw` with
|
|
77
|
+
* the table name as a plain string.
|
|
78
|
+
*
|
|
79
|
+
* `buildTables` is the reusable factory that wraps any op-bearing client
|
|
80
|
+
* (`TxClient` — the surface shared by `DBClient` and the transaction-scoped
|
|
81
|
+
* client) into the typed tables map. It is used both for the top-level db
|
|
82
|
+
* (wrapping `raw`) and inside `transaction`, where it wraps the raw `TxClient`
|
|
83
|
+
* the runtime yields so the callback sees the same typed `.tables` API.
|
|
84
|
+
*
|
|
85
|
+
* `transaction` delegates straight to `raw.transaction`; the two narrow
|
|
86
|
+
* `as TypedTx<S>` / `as TypedDB<S>` casts are single structural narrowings
|
|
87
|
+
* from the dynamically-built tables object to the precise mapped type (TS
|
|
88
|
+
* cannot infer through `Object.keys` iteration) — see module-level doc comment.
|
|
89
|
+
*/
|
|
90
|
+
declare function makeTypedDB<S extends SchemaDef>(schema: S, raw: DBClient): TypedDB<S>;
|
|
24
91
|
|
|
92
|
+
/**
|
|
93
|
+
* runtime.ts — request-scoped service singletons.
|
|
94
|
+
*
|
|
95
|
+
* The backend SDK no longer threads a `ctx` god-object through every handler.
|
|
96
|
+
* Instead, endpoint authors import PascalCase service singletons directly:
|
|
97
|
+
*
|
|
98
|
+
* import { Database, Documents, Cache } from "@palbase/backend";
|
|
99
|
+
*
|
|
100
|
+
* export default defineEndpoint({
|
|
101
|
+
* method: "POST",
|
|
102
|
+
* handler: async (req) => {
|
|
103
|
+
* const row = await Database.insert("todos", { title: req.input.title });
|
|
104
|
+
* return row;
|
|
105
|
+
* },
|
|
106
|
+
* });
|
|
107
|
+
*
|
|
108
|
+
* The singletons are thin Proxies. Every property access forwards to the live
|
|
109
|
+
* client held in a per-process mutable slot, which the runtime sets with
|
|
110
|
+
* {@link __setRuntime} BEFORE invoking the handler and (today) leaves in place
|
|
111
|
+
* for the lifetime of that fresh Node subprocess. Because each `br-<ref>` pod
|
|
112
|
+
* is single-tenant and every request runs in a fresh Node subprocess
|
|
113
|
+
* (node_executor.go), there is no cross-tenant leakage risk.
|
|
114
|
+
*
|
|
115
|
+
* The seam that makes `import { Database } from "@palbase/backend"` resolve to
|
|
116
|
+
* the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL
|
|
117
|
+
* when the tenant bundle is built, and the package is installed globally in the
|
|
118
|
+
* pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's
|
|
119
|
+
* `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared
|
|
120
|
+
* module instance — calling `__setRuntime` on that instance is visible to the
|
|
121
|
+
* singletons the bundle imported.
|
|
122
|
+
*/
|
|
123
|
+
|
|
124
|
+
/** The set of live clients the runtime injects per request scope.
|
|
125
|
+
*
|
|
126
|
+
* EXCLUDED on purpose: Realtime, Functions, CMS, Links, Analytics, Auth. They
|
|
127
|
+
* are not exposed as backend handler singletons (auth lives on the client SDK;
|
|
128
|
+
* the rest are out of scope for backend endpoints). */
|
|
129
|
+
interface RuntimeServices {
|
|
130
|
+
Database: DBClient;
|
|
131
|
+
Documents: PalbaseDocsClient;
|
|
132
|
+
Storage: PalbaseStorageClient;
|
|
133
|
+
Cache: CacheClient;
|
|
134
|
+
Queue: QueueClient;
|
|
135
|
+
Log: Logger;
|
|
136
|
+
Notifications: PalbaseNotificationsClient;
|
|
137
|
+
Flags: PalbaseFlagsClient;
|
|
138
|
+
}
|
|
139
|
+
/** Install the live clients for the current request scope.
|
|
140
|
+
*
|
|
141
|
+
* Called by the Palbase runtime (worker.js / dev-server.js) immediately before
|
|
142
|
+
* invoking a handler. NOT part of the public author-facing API — exported with
|
|
143
|
+
* a `__` prefix so the runtime can reach it across the shared module instance.
|
|
144
|
+
*/
|
|
145
|
+
declare function __setRuntime(services: RuntimeServices): void;
|
|
146
|
+
/** Read the live clients, throwing if accessed outside a request scope.
|
|
147
|
+
*
|
|
148
|
+
* NOT part of the public author-facing API — exported with a `__` prefix for
|
|
149
|
+
* the runtime and the singleton Proxies. */
|
|
150
|
+
declare function __getRuntime(): RuntimeServices;
|
|
151
|
+
/** The project's own Postgres (pgx, schema `env_<envId>`). Typed CRUD +
|
|
152
|
+
* `query`/`transaction`. For a typed `.tables.<name>` API, wrap with
|
|
153
|
+
* {@link typedDatabase}. */
|
|
154
|
+
declare const Database: DBClient;
|
|
155
|
+
/** Firestore-like document client (PalDocs). */
|
|
156
|
+
declare const Documents: PalbaseDocsClient;
|
|
157
|
+
/** Object storage client (buckets, signed URLs). */
|
|
158
|
+
declare const Storage: PalbaseStorageClient;
|
|
159
|
+
/** JSON-typed cache (get/set/incr/getOrSet). */
|
|
160
|
+
declare const Cache: CacheClient;
|
|
161
|
+
/** Background job queue. */
|
|
162
|
+
declare const Queue: QueueClient;
|
|
163
|
+
/** Structured logger. */
|
|
164
|
+
declare const Log: Logger;
|
|
165
|
+
/** Push / email / SMS / in-app notifications. */
|
|
166
|
+
declare const Notifications: PalbaseNotificationsClient;
|
|
167
|
+
/** Feature flags. */
|
|
168
|
+
declare const Flags: PalbaseFlagsClient;
|
|
169
|
+
/**
|
|
170
|
+
* Type the `Database` singleton against a `defineSchema()` result, returning a
|
|
171
|
+
* facade with a typed `.tables.<name>.insert(...)` API alongside the raw
|
|
172
|
+
* `query`/`transaction` ops.
|
|
173
|
+
*
|
|
174
|
+
* const Db = typedDatabase(schema);
|
|
175
|
+
* const todo = await Db.tables.todos.insert({ title: "x" });
|
|
176
|
+
*
|
|
177
|
+
* This is per-endpoint (not global module augmentation), so one endpoint's
|
|
178
|
+
* tables never leak into another's `Database` type.
|
|
179
|
+
*/
|
|
180
|
+
declare function typedDatabase<TSchema extends SchemaDef>(schema: TSchema): TypedDB<TSchema> & DBClient;
|
|
181
|
+
|
|
182
|
+
/** Context injected into worker handlers — the non-request-scoped service
|
|
183
|
+
* surface (db/log/cache/queue + module clients), plus correlation ids. Workers
|
|
184
|
+
* are not part of the Phase 1 `ctx → PBRequest` redesign, so they keep their
|
|
185
|
+
* own `ctx`; the job payload arrives as the handler's second argument. */
|
|
186
|
+
interface WorkerContext extends PalbaseModuleClients {
|
|
187
|
+
user: User | null;
|
|
188
|
+
db: DBClient;
|
|
189
|
+
env: Record<string, string>;
|
|
190
|
+
log: Logger;
|
|
191
|
+
cache: CacheClient;
|
|
192
|
+
queue: QueueClient;
|
|
193
|
+
errors: ErrorThrowers<undefined>;
|
|
194
|
+
requestId: string;
|
|
195
|
+
projectId: string;
|
|
196
|
+
environmentId: string;
|
|
197
|
+
}
|
|
25
198
|
/** Backoff strategy for worker retries. */
|
|
26
199
|
type BackoffStrategy = "exponential" | "linear" | "fixed";
|
|
27
200
|
/** Configuration for a background worker. */
|
|
@@ -35,7 +208,7 @@ interface WorkerConfig<TPayload = unknown> {
|
|
|
35
208
|
/** Backoff strategy between retries. Defaults to "exponential". */
|
|
36
209
|
backoff?: BackoffStrategy;
|
|
37
210
|
/** Handler function that processes the job payload. */
|
|
38
|
-
handler: (ctx:
|
|
211
|
+
handler: (ctx: WorkerContext, payload: TPayload) => Promise<void>;
|
|
39
212
|
}
|
|
40
213
|
/** Resolved worker configuration with defaults applied. */
|
|
41
214
|
interface ResolvedWorkerConfig<TPayload = unknown> {
|
|
@@ -43,7 +216,7 @@ interface ResolvedWorkerConfig<TPayload = unknown> {
|
|
|
43
216
|
retry: number;
|
|
44
217
|
timeout: number;
|
|
45
218
|
backoff: BackoffStrategy;
|
|
46
|
-
handler: (ctx:
|
|
219
|
+
handler: (ctx: WorkerContext, payload: TPayload) => Promise<void>;
|
|
47
220
|
}
|
|
48
221
|
/**
|
|
49
222
|
* Define a background worker that processes jobs from the queue.
|
|
@@ -370,4 +543,4 @@ declare const documents: {
|
|
|
370
543
|
onDocumentDeleted(handler: HookHandler<DocumentDeletedEvent>): ResolvedHook<DocumentDeletedEvent>;
|
|
371
544
|
};
|
|
372
545
|
|
|
373
|
-
export { type BackoffStrategy, CacheClient, type CustomWebhookConfig, DBClient, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent,
|
|
546
|
+
export { type BackoffStrategy, Cache, CacheClient, type CustomWebhookConfig, DBClient, Database, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentUpdatedEvent, Documents, type EnvSecretRef, ErrorThrowers, type FileDeletedEvent, type FileUploadedEvent, Flags, type HookContext, type HookHandler, type InsertShape, type JobConfig, type JobContext, Log, Logger, Notifications, PalbaseDocsClient, PalbaseFlagsClient, PalbaseNotificationsClient, PalbaseStorageClient, type PasswordResetEvent, type ProviderEventMap, type ProviderWebhookConfig, Queue, QueueClient, type ResolvedCustomWebhook, type ResolvedHook, type ResolvedJobConfig, type ResolvedProviderWebhook, type ResolvedWebhookConfig, type ResolvedWorkerConfig, type RowShape, type RuntimeServices, SchemaDef, type SignInEvent, type SignOutEvent, Storage, TableDef, type TypedDB, type TypedTable, type TypedTx, User, type UserCreatedEvent, type WebhookContext, type WebhookEventHandler, type WebhookProvider, type WebhookRequest, type WorkerConfig, type WorkerContext, __getRuntime, __setRuntime, auth, defineJob, defineWebhook, defineWorker, documents, makeTypedDB, storage, typedDatabase };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Cache,
|
|
3
|
+
Database,
|
|
4
|
+
Documents,
|
|
5
|
+
Flags,
|
|
6
|
+
Log,
|
|
7
|
+
Notifications,
|
|
8
|
+
Queue,
|
|
9
|
+
Storage,
|
|
10
|
+
__getRuntime,
|
|
11
|
+
__setRuntime,
|
|
12
|
+
makeTypedDB,
|
|
13
|
+
typedDatabase
|
|
14
|
+
} from "./chunk-7N5ICXCB.js";
|
|
1
15
|
import {
|
|
2
16
|
boolean,
|
|
3
17
|
defineSchema,
|
|
@@ -15,34 +29,6 @@ function defineEndpoint(config) {
|
|
|
15
29
|
return config;
|
|
16
30
|
}
|
|
17
31
|
|
|
18
|
-
// src/db/typed-db.ts
|
|
19
|
-
function makeTypedTable(name, raw) {
|
|
20
|
-
return {
|
|
21
|
-
insert: (data) => raw.insert(name, data),
|
|
22
|
-
update: (id, data) => raw.update(name, id, data),
|
|
23
|
-
delete: (id) => raw.delete(name, id),
|
|
24
|
-
findById: (id) => raw.findById(name, id),
|
|
25
|
-
findMany: (query) => raw.findMany(name, query)
|
|
26
|
-
};
|
|
27
|
-
}
|
|
28
|
-
function makeTypedDB(schema, raw) {
|
|
29
|
-
function buildTables(client) {
|
|
30
|
-
const tables = {};
|
|
31
|
-
for (const key of Object.keys(schema.tables)) {
|
|
32
|
-
const tableDef = schema.tables[key];
|
|
33
|
-
if (tableDef !== void 0) {
|
|
34
|
-
tables[key] = makeTypedTable(tableDef.name, client);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
return tables;
|
|
38
|
-
}
|
|
39
|
-
const result = {
|
|
40
|
-
tables: buildTables(raw),
|
|
41
|
-
transaction: (fn) => raw.transaction((rawTx) => fn({ tables: buildTables(rawTx) }))
|
|
42
|
-
};
|
|
43
|
-
return result;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
32
|
// src/middleware.ts
|
|
47
33
|
function defineMiddleware(fn) {
|
|
48
34
|
return fn;
|
|
@@ -53,17 +39,22 @@ var HttpError = class extends Error {
|
|
|
53
39
|
status;
|
|
54
40
|
error;
|
|
55
41
|
errorDescription;
|
|
56
|
-
|
|
42
|
+
data;
|
|
43
|
+
constructor(status, error, errorDescription, data) {
|
|
57
44
|
super(errorDescription);
|
|
58
45
|
this.name = "HttpError";
|
|
59
46
|
this.status = status;
|
|
60
47
|
this.error = error;
|
|
61
48
|
this.errorDescription = errorDescription;
|
|
49
|
+
if (data !== void 0) {
|
|
50
|
+
this.data = data;
|
|
51
|
+
}
|
|
62
52
|
}
|
|
63
53
|
/**
|
|
64
54
|
* Serialize to the standard Palbase error response format.
|
|
65
55
|
* The `requestId` is injected by the runtime layer from the request context.
|
|
66
56
|
* When called without arguments (e.g. JSON.stringify), request_id is omitted.
|
|
57
|
+
* When `data` is set, it is appended as a strict-superset field.
|
|
67
58
|
*/
|
|
68
59
|
toJSON(requestId) {
|
|
69
60
|
const result = {
|
|
@@ -74,6 +65,9 @@ var HttpError = class extends Error {
|
|
|
74
65
|
if (requestId) {
|
|
75
66
|
result.request_id = requestId;
|
|
76
67
|
}
|
|
68
|
+
if (this.data !== void 0) {
|
|
69
|
+
result.data = this.data;
|
|
70
|
+
}
|
|
77
71
|
return result;
|
|
78
72
|
}
|
|
79
73
|
};
|
|
@@ -332,7 +326,17 @@ var documents = {
|
|
|
332
326
|
// src/index.ts
|
|
333
327
|
import { z } from "zod";
|
|
334
328
|
export {
|
|
329
|
+
Cache,
|
|
330
|
+
Database,
|
|
331
|
+
Documents,
|
|
332
|
+
Flags,
|
|
335
333
|
HttpError,
|
|
334
|
+
Log,
|
|
335
|
+
Notifications,
|
|
336
|
+
Queue,
|
|
337
|
+
Storage,
|
|
338
|
+
__getRuntime,
|
|
339
|
+
__setRuntime,
|
|
336
340
|
auth,
|
|
337
341
|
boolean,
|
|
338
342
|
defineEndpoint,
|
|
@@ -350,6 +354,7 @@ export {
|
|
|
350
354
|
table,
|
|
351
355
|
text,
|
|
352
356
|
timestamp,
|
|
357
|
+
typedDatabase,
|
|
353
358
|
uuid,
|
|
354
359
|
z
|
|
355
360
|
};
|