@brickkit/core 0.6.0 → 0.7.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/README.md +179 -72
- package/dist/chunks/client.d.ts +902 -0
- package/dist/chunks/client.d.ts.map +1 -0
- package/dist/chunks/effect.d.ts +574 -0
- package/dist/chunks/effect.d.ts.map +1 -0
- package/dist/chunks/effect.js +2912 -0
- package/dist/chunks/effect.js.map +1 -0
- package/dist/chunks/types.js +46 -0
- package/dist/chunks/types.js.map +1 -0
- package/dist/client.d.ts +2 -0
- package/dist/client.js +205 -0
- package/dist/client.js.map +1 -0
- package/dist/effect.d.ts +3 -0
- package/dist/effect.js +1 -0
- package/dist/index.d.ts +3 -319
- package/dist/index.js +53 -362
- package/dist/index.js.map +1 -1
- package/dist/pg.d.ts +4 -4
- package/dist/pg.d.ts.map +1 -1
- package/dist/pg.js +2 -2
- package/package.json +13 -10
- package/dist/chunks/errors.d.ts +0 -151
- package/dist/chunks/errors.d.ts.map +0 -1
- package/dist/chunks/errors.js +0 -132
- package/dist/chunks/errors.js.map +0 -1
- package/dist/chunks/rolldown-runtime.js +0 -13
- package/dist/contracts.d.ts +0 -2
- package/dist/contracts.js +0 -1
- package/dist/index.d.ts.map +0 -1
|
@@ -0,0 +1,902 @@
|
|
|
1
|
+
import { Static, TSchema } from "@sinclair/typebox";
|
|
2
|
+
import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
3
|
+
import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
|
|
4
|
+
import { Sql } from "postgres";
|
|
5
|
+
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
6
|
+
import { Table } from "drizzle-orm";
|
|
7
|
+
import { Database } from "bun:sqlite";
|
|
8
|
+
//#region src/plugin.d.ts
|
|
9
|
+
type PluginRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
10
|
+
type PluginRouteScope = "app" | "service" | "resource";
|
|
11
|
+
type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> = false | Readonly<Record<string, false | {
|
|
12
|
+
path?: string;
|
|
13
|
+
scope?: S;
|
|
14
|
+
}>>;
|
|
15
|
+
type ContextOf<S> = S extends Service<infer D, infer C> ? BaseContext<D> & C : never;
|
|
16
|
+
interface PluginEndpointContext<C extends ActionContext = ActionContext> {
|
|
17
|
+
params: Record<string, string>;
|
|
18
|
+
query: Record<string, string | undefined>;
|
|
19
|
+
body: unknown;
|
|
20
|
+
headers: Record<string, string>;
|
|
21
|
+
request: Request;
|
|
22
|
+
set: {
|
|
23
|
+
status?: number;
|
|
24
|
+
headers: Record<string, string>;
|
|
25
|
+
};
|
|
26
|
+
ctx: C;
|
|
27
|
+
}
|
|
28
|
+
interface PluginRouteRegistrar<C extends ActionContext = ActionContext, S extends PluginRouteScope = PluginRouteScope> {
|
|
29
|
+
action<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<I, O, E, C> & {
|
|
30
|
+
path: string;
|
|
31
|
+
method: PluginRouteMethod;
|
|
32
|
+
scope?: S;
|
|
33
|
+
}): Action<I, O, E, C>;
|
|
34
|
+
action<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<I, O, E, C> & {
|
|
35
|
+
path: string;
|
|
36
|
+
method: PluginRouteMethod;
|
|
37
|
+
scope?: S;
|
|
38
|
+
}): Action<I, O, E, C>;
|
|
39
|
+
endpoint(config: {
|
|
40
|
+
name: string;
|
|
41
|
+
path: string;
|
|
42
|
+
method: PluginRouteMethod;
|
|
43
|
+
scope?: S;
|
|
44
|
+
handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>;
|
|
45
|
+
summary?: string;
|
|
46
|
+
description?: string;
|
|
47
|
+
tags?: string[];
|
|
48
|
+
}): void;
|
|
49
|
+
}
|
|
50
|
+
interface ServicePluginContext<S extends Service<any, any> = Service<any, any>> {
|
|
51
|
+
service: S;
|
|
52
|
+
routes: PluginRouteRegistrar<ContextOf<S>, "app" | "service">;
|
|
53
|
+
}
|
|
54
|
+
interface ResourcePluginContext<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>> {
|
|
55
|
+
service: S;
|
|
56
|
+
resource: R;
|
|
57
|
+
routes: PluginRouteRegistrar<ContextOf<S>>;
|
|
58
|
+
}
|
|
59
|
+
/** Plugins may specialize their returned API for the installation host. */
|
|
60
|
+
interface ResourcePluginTypes {
|
|
61
|
+
readonly table: unknown;
|
|
62
|
+
readonly context: unknown;
|
|
63
|
+
readonly resource: unknown;
|
|
64
|
+
readonly api: object;
|
|
65
|
+
}
|
|
66
|
+
type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
|
|
67
|
+
readonly types: infer H extends ResourcePluginTypes;
|
|
68
|
+
} ? (H & {
|
|
69
|
+
readonly table: T;
|
|
70
|
+
readonly context: C;
|
|
71
|
+
readonly resource: R;
|
|
72
|
+
})["api"] : P extends ResourcePlugin<any, any, infer A> ? A : never;
|
|
73
|
+
declare const pluginKind: unique symbol;
|
|
74
|
+
interface ServicePlugin<S extends Service<any, any>, A> {
|
|
75
|
+
readonly [pluginKind]: "service";
|
|
76
|
+
readonly name: string;
|
|
77
|
+
readonly routes?: PluginRoutes<"app" | "service">;
|
|
78
|
+
readonly setup: (context: ServicePluginContext<S>) => A;
|
|
79
|
+
}
|
|
80
|
+
interface ResourcePlugin<S extends Service<any, any>, R extends Resource<any, any, any>, A extends object> {
|
|
81
|
+
readonly [pluginKind]: "resource";
|
|
82
|
+
readonly name: string;
|
|
83
|
+
readonly routes?: PluginRoutes;
|
|
84
|
+
readonly setup: (context: ResourcePluginContext<S, R>) => A;
|
|
85
|
+
}
|
|
86
|
+
declare function defineServicePlugin<S extends Service<any, any> = Service<any, any>, A = unknown>(definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & {
|
|
87
|
+
setup: (context: ServicePluginContext<S>) => A & (A extends PromiseLike<unknown> ? never : unknown);
|
|
88
|
+
}): ServicePlugin<S, A>;
|
|
89
|
+
declare function defineResourcePlugin<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>, A extends object = object>(definition: Omit<ResourcePlugin<S, R, A>, typeof pluginKind> & {
|
|
90
|
+
setup: (context: ResourcePluginContext<S, R>) => A & (A extends PromiseLike<unknown> ? never : unknown);
|
|
91
|
+
}): ResourcePlugin<S, R, A>;
|
|
92
|
+
declare function getPluginActionRoute(action: Action<any, any, any, any>, prefix?: string): false | {
|
|
93
|
+
path: string;
|
|
94
|
+
method: PluginRouteMethod;
|
|
95
|
+
clientPath: string[] | undefined;
|
|
96
|
+
plugin: string;
|
|
97
|
+
resource: string | undefined;
|
|
98
|
+
} | undefined;
|
|
99
|
+
declare function getPluginEndpoints(service: Service<any, any>, prefix?: string): {
|
|
100
|
+
path: string;
|
|
101
|
+
method: PluginRouteMethod;
|
|
102
|
+
service: Service<any, any>;
|
|
103
|
+
summary: string | undefined;
|
|
104
|
+
description: string | undefined;
|
|
105
|
+
tags: string[] | undefined;
|
|
106
|
+
handler: (context: Omit<PluginEndpointContext, "ctx">) => Promise<unknown>;
|
|
107
|
+
}[];
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/db/sqlite.d.ts
|
|
110
|
+
interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
|
|
111
|
+
/** Database file path or ':memory:' (default: ':memory:') */
|
|
112
|
+
path?: string;
|
|
113
|
+
/** Alias for path */
|
|
114
|
+
filename?: string;
|
|
115
|
+
/** Whether to enable WAL journal mode for file-based DBs (default: true) */
|
|
116
|
+
wal?: boolean;
|
|
117
|
+
/** Whether to enforce foreign key constraints (default: true) */
|
|
118
|
+
foreignKeys?: boolean;
|
|
119
|
+
/** Optional existing bun:sqlite Database instance */
|
|
120
|
+
client?: Database;
|
|
121
|
+
/** Optional Drizzle schema object for typed relational queries */
|
|
122
|
+
schema?: TSchema;
|
|
123
|
+
}
|
|
124
|
+
type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<TSchema> & {
|
|
125
|
+
$client: Database;
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Creates a zero-config SQLite database using Bun's native `bun:sqlite` engine
|
|
129
|
+
* and Drizzle ORM. Defaults to an ultra-fast in-memory database (`:memory:`).
|
|
130
|
+
*
|
|
131
|
+
* Bun-only: the driver is loaded lazily so importing `@brickkit/core` on
|
|
132
|
+
* other runtimes (e.g. Node) stays safe until this function is actually
|
|
133
|
+
* called.
|
|
134
|
+
*/
|
|
135
|
+
declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase<TSchema>;
|
|
136
|
+
//#endregion
|
|
137
|
+
//#region src/secrets.d.ts
|
|
138
|
+
/**
|
|
139
|
+
* Type-safe secrets & environment variables.
|
|
140
|
+
*
|
|
141
|
+
* Declare each secret once at module scope instead of scattering untyped
|
|
142
|
+
* `process.env.FOO` reads:
|
|
143
|
+
*
|
|
144
|
+
* const port = secret("PORT").default("3333").transform(Number).require();
|
|
145
|
+
* const baseUrl = secret("BASE_URL").url().require();
|
|
146
|
+
* const key = secret("STRIPE_KEY").validate((v) =>
|
|
147
|
+
* v.startsWith("sk_") || "must start with sk_"
|
|
148
|
+
* ).require();
|
|
149
|
+
*
|
|
150
|
+
* Values resolve from the environment (Bun populates `process.env` from
|
|
151
|
+
* `.env` locally; in prod the same env source applies — a future
|
|
152
|
+
* `SecretSource` such as AWS can slot in without touching call sites).
|
|
153
|
+
*
|
|
154
|
+
* Resolution order per secret: test/session override → source (`process.env`
|
|
155
|
+
* by default) → declared `default`. `resolveSecrets()` validates every
|
|
156
|
+
* registered secret at boot and throws listing all missing required ones.
|
|
157
|
+
*/
|
|
158
|
+
interface SecretSource {
|
|
159
|
+
get(name: string): string | undefined;
|
|
160
|
+
}
|
|
161
|
+
/** Default source: `process.env` (Bun loads `.env` into it automatically). */
|
|
162
|
+
declare const envSource: SecretSource;
|
|
163
|
+
interface SecretOptions {
|
|
164
|
+
/** Fallback when the source has no value. Secrets without a default are required. */
|
|
165
|
+
default?: string;
|
|
166
|
+
}
|
|
167
|
+
/** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
|
|
168
|
+
type SecretValidator<T> = (value: T) => void | boolean | string;
|
|
169
|
+
declare class SecretRef<T = string> {
|
|
170
|
+
readonly name: string;
|
|
171
|
+
readonly options: SecretOptions;
|
|
172
|
+
private transformFn?;
|
|
173
|
+
private validators;
|
|
174
|
+
constructor(name: string, options?: SecretOptions);
|
|
175
|
+
/** True when a default was declared (i.e. the secret is optional). */
|
|
176
|
+
get hasDefault(): boolean;
|
|
177
|
+
/** Fallback used when the source has no value. Makes the secret optional. */
|
|
178
|
+
default(value: string): this;
|
|
179
|
+
/**
|
|
180
|
+
* Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
|
|
181
|
+
* Runs before validators; a throwing transform fails resolution.
|
|
182
|
+
*/
|
|
183
|
+
transform<U>(fn: (raw: string) => U): SecretRef<U>;
|
|
184
|
+
/** Run a custom check on the (transformed) value at every resolution. */
|
|
185
|
+
validate(fn: SecretValidator<T>): this;
|
|
186
|
+
/** Shorthand validator: value must parse as a URL. String refs only. */
|
|
187
|
+
url(this: SecretRef<string>): SecretRef<string>;
|
|
188
|
+
private resolveRaw;
|
|
189
|
+
private coerce;
|
|
190
|
+
/** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
|
|
191
|
+
value(source?: SecretSource): T | undefined;
|
|
192
|
+
/** Resolved value, or throws naming the missing/invalid secret. */
|
|
193
|
+
require(source?: SecretSource): T;
|
|
194
|
+
/** True when a value would resolve (override, source, or default). */
|
|
195
|
+
isSet(source?: SecretSource): boolean;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Declare a secret. Idempotent: re-declaring the same name returns the
|
|
199
|
+
* original ref (first declaration wins) so module re-evaluation is safe.
|
|
200
|
+
*/
|
|
201
|
+
declare function secret(name: string, options?: SecretOptions): SecretRef<string>;
|
|
202
|
+
/**
|
|
203
|
+
* Validate every registered secret at boot. Throws a single error listing
|
|
204
|
+
* all missing required secrets. Returns the resolved values.
|
|
205
|
+
*/
|
|
206
|
+
declare function resolveSecrets(opts?: {
|
|
207
|
+
source?: SecretSource;
|
|
208
|
+
}): Record<string, unknown>;
|
|
209
|
+
/** Metadata for introspection (values never exposed — future dashboard use). */
|
|
210
|
+
declare function listSecrets(opts?: {
|
|
211
|
+
source?: SecretSource;
|
|
212
|
+
}): Array<{
|
|
213
|
+
name: string;
|
|
214
|
+
hasDefault: boolean;
|
|
215
|
+
isSet: boolean;
|
|
216
|
+
}>;
|
|
217
|
+
/** Test/session override for one secret (`undefined` clears the override). */
|
|
218
|
+
declare function overrideSecret(name: string, value: string | undefined): void;
|
|
219
|
+
/** Bulk overrides (test/session scoped). */
|
|
220
|
+
declare function overrideSecrets(values: Record<string, string | undefined>): void;
|
|
221
|
+
/** Clear registry and overrides. Test-only. */
|
|
222
|
+
declare function resetSecrets(): void;
|
|
223
|
+
//#endregion
|
|
224
|
+
//#region src/db/postgres.d.ts
|
|
225
|
+
interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
|
|
226
|
+
/** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */
|
|
227
|
+
client?: Sql;
|
|
228
|
+
/** Database connection URL (e.g. postgresql://user:pass@host:5432/dbname) */
|
|
229
|
+
url?: string;
|
|
230
|
+
/** Connection string alias */
|
|
231
|
+
connectionString?: string;
|
|
232
|
+
host?: string;
|
|
233
|
+
port?: number;
|
|
234
|
+
user?: string;
|
|
235
|
+
password?: string;
|
|
236
|
+
database?: string;
|
|
237
|
+
ssl?: boolean | "require" | "allow" | "prefer" | "verify-full";
|
|
238
|
+
max?: number;
|
|
239
|
+
/**
|
|
240
|
+
* Disable prepared statements (required for transaction-mode poolers such
|
|
241
|
+
* as Supabase's Supavisor on :6543, which cannot hold named prepared
|
|
242
|
+
* statements across transactions).
|
|
243
|
+
*/
|
|
244
|
+
prepare?: boolean;
|
|
245
|
+
/** Optional Drizzle schema for relational queries */
|
|
246
|
+
schema?: TSchema;
|
|
247
|
+
/** Custom schema name for Encore-style isolated schemas */
|
|
248
|
+
schemaName?: string;
|
|
249
|
+
}
|
|
250
|
+
type PostgresDatabase<_TSchema extends Record<string, unknown> = Record<string, unknown>> = any;
|
|
251
|
+
interface DatabaseAdapter<TDb = any, TConfig = any> {
|
|
252
|
+
createDatabase(config?: TConfig): TDb;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Creates a PostgreSQL Drizzle instance using postgres-js.
|
|
256
|
+
* Static imports (both are hard dependencies in package.json) so bundlers
|
|
257
|
+
* (Nitro/Rollup) trace and ship the driver. `bun:sqlite` stays lazy in
|
|
258
|
+
* `sqlite.ts` since it only exists under Bun.
|
|
259
|
+
*/
|
|
260
|
+
declare function createPostgresDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: PostgresDatabaseConfig<TSchema>): PostgresDatabase<TSchema>;
|
|
261
|
+
//#endregion
|
|
262
|
+
//#region src/db/define.d.ts
|
|
263
|
+
type EnvInput<T> = T | SecretRef<T>;
|
|
264
|
+
type EnvOptions<T> = { [K in keyof T]: EnvInput<Exclude<T[K], undefined>>; };
|
|
265
|
+
interface DefinitionOptions<TSchema extends Record<string, unknown>> {
|
|
266
|
+
name?: string;
|
|
267
|
+
/** Drizzle tables retained for schema tooling. Never applied at runtime. */
|
|
268
|
+
tables?: (TSchema & Record<string, Table>) | readonly Table[];
|
|
269
|
+
schema?: TSchema;
|
|
270
|
+
}
|
|
271
|
+
type SQLiteDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
|
|
272
|
+
engine?: "sqlite";
|
|
273
|
+
client?: SQLiteDatabaseConfig<TSchema>["client"];
|
|
274
|
+
url?: never;
|
|
275
|
+
connectionString?: never;
|
|
276
|
+
};
|
|
277
|
+
type PostgresDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = DefinitionOptions<TSchema> & EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema" | "client">> & {
|
|
278
|
+
engine: "postgres";
|
|
279
|
+
path?: never;
|
|
280
|
+
filename?: never;
|
|
281
|
+
wal?: never;
|
|
282
|
+
foreignKeys?: never;
|
|
283
|
+
client?: PostgresDatabaseConfig<TSchema>["client"];
|
|
284
|
+
};
|
|
285
|
+
type DatabaseDefinition<TSchema extends Record<string, unknown> = Record<string, unknown>> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;
|
|
286
|
+
interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>> {
|
|
287
|
+
readonly kind: "brick-database";
|
|
288
|
+
readonly name?: string;
|
|
289
|
+
readonly engine: "sqlite" | "postgres";
|
|
290
|
+
readonly tables: Readonly<Record<string, Table>>;
|
|
291
|
+
readonly schema: TSchema;
|
|
292
|
+
getDb(): TDb;
|
|
293
|
+
close?(): void | Promise<void>;
|
|
294
|
+
}
|
|
295
|
+
declare function isDatabaseHandle(value: unknown): value is DatabaseHandle<unknown>;
|
|
296
|
+
declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase$1<TSchema>, TSchema>;
|
|
297
|
+
declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
|
|
298
|
+
$client: Sql;
|
|
299
|
+
}, TSchema>;
|
|
300
|
+
//#endregion
|
|
301
|
+
//#region src/types.d.ts
|
|
302
|
+
interface Logger {
|
|
303
|
+
info: (...args: any[]) => void;
|
|
304
|
+
warn: (...args: any[]) => void;
|
|
305
|
+
error: (...args: any[]) => void;
|
|
306
|
+
debug: (...args: any[]) => void;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Base framework context supplied to all service resolvers and action executions.
|
|
310
|
+
*/
|
|
311
|
+
interface BaseContext<TDb = any> {
|
|
312
|
+
request: Request;
|
|
313
|
+
db: TDb;
|
|
314
|
+
logger: Logger;
|
|
315
|
+
traceId: string;
|
|
316
|
+
requestId?: string;
|
|
317
|
+
caller?: string;
|
|
318
|
+
tenantId?: string;
|
|
319
|
+
services?: Record<string, any>;
|
|
320
|
+
metadata?: Record<string, unknown>;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Default fallback service context for untyped or simple services.
|
|
324
|
+
*/
|
|
325
|
+
interface DefaultServiceContext {
|
|
326
|
+
user?: any;
|
|
327
|
+
session?: any;
|
|
328
|
+
[key: string]: any;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* The combined execution context: BaseContext & TServiceContext.
|
|
332
|
+
*/
|
|
333
|
+
type ActionContext<TDb = any, TServiceContext = DefaultServiceContext> = BaseContext<TDb> & TServiceContext;
|
|
334
|
+
/**
|
|
335
|
+
* Type utility that automatically narrows ctx.user from User | null to User
|
|
336
|
+
* in execute() when authorize() is declared on the action.
|
|
337
|
+
*/
|
|
338
|
+
type NarrowAuthorizedContext<TCtx> = TCtx extends {
|
|
339
|
+
user: infer U;
|
|
340
|
+
} ? [U] extends [null | undefined] ? TCtx : Omit<TCtx, "user"> & {
|
|
341
|
+
user: NonNullable<U>;
|
|
342
|
+
} : TCtx;
|
|
343
|
+
interface ActionErrorDefinition {
|
|
344
|
+
status?: number;
|
|
345
|
+
message: string;
|
|
346
|
+
}
|
|
347
|
+
interface ValidationErrorItem {
|
|
348
|
+
path: string;
|
|
349
|
+
message: string;
|
|
350
|
+
value?: unknown;
|
|
351
|
+
type?: number;
|
|
352
|
+
}
|
|
353
|
+
declare class ValidationError extends Error {
|
|
354
|
+
readonly code = "VALIDATION_FAILED";
|
|
355
|
+
readonly status: number;
|
|
356
|
+
readonly errors: ValidationErrorItem[];
|
|
357
|
+
constructor(message: string, errors?: ValidationErrorItem[], status?: number);
|
|
358
|
+
toJSON(): {
|
|
359
|
+
name: string;
|
|
360
|
+
code: string;
|
|
361
|
+
message: string;
|
|
362
|
+
status: number;
|
|
363
|
+
errors: ValidationErrorItem[];
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
declare class ActionExecutionError extends Error {
|
|
367
|
+
readonly code: string;
|
|
368
|
+
readonly status: number;
|
|
369
|
+
readonly details?: unknown;
|
|
370
|
+
constructor(code: string, message: string, status?: number, details?: unknown, options?: ErrorOptions);
|
|
371
|
+
toJSON(): {
|
|
372
|
+
name: string;
|
|
373
|
+
code: string;
|
|
374
|
+
message: string;
|
|
375
|
+
status: number;
|
|
376
|
+
details: unknown;
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
interface StandardErrorMap {
|
|
380
|
+
BAD_REQUEST: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
381
|
+
UNAUTHORIZED: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
382
|
+
FORBIDDEN: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
383
|
+
NOT_FOUND: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
384
|
+
CONFLICT: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
385
|
+
INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
|
|
386
|
+
[key: string]: ((overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never) | undefined;
|
|
387
|
+
}
|
|
388
|
+
type ErrorBuilder<TErrors extends Record<string, ActionErrorDefinition>> = StandardErrorMap & { [K in keyof TErrors]: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never; };
|
|
389
|
+
interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>> {
|
|
390
|
+
name: string;
|
|
391
|
+
description?: string;
|
|
392
|
+
/** Effective HTTP path, including the prefix; replaces the default action path. */
|
|
393
|
+
path?: string;
|
|
394
|
+
/** Single HTTP method exposed for this action (default POST). */
|
|
395
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
396
|
+
input?: TInputSchema;
|
|
397
|
+
output?: TOutputSchema;
|
|
398
|
+
errors?: TErrors;
|
|
399
|
+
emits?: string[];
|
|
400
|
+
tags?: string[];
|
|
401
|
+
}
|
|
402
|
+
interface ActionConfigWithAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
|
|
403
|
+
authorize: (params: {
|
|
404
|
+
user?: TContext extends {
|
|
405
|
+
user: infer U;
|
|
406
|
+
} ? U : any;
|
|
407
|
+
input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
408
|
+
ctx: TContext;
|
|
409
|
+
}) => boolean | Promise<boolean>;
|
|
410
|
+
execute: (params: {
|
|
411
|
+
input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
412
|
+
ctx: NarrowAuthorizedContext<TContext>;
|
|
413
|
+
error: ErrorBuilder<TErrors>;
|
|
414
|
+
}) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
|
|
415
|
+
}
|
|
416
|
+
interface ActionConfigWithoutAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
|
|
417
|
+
authorize?: undefined;
|
|
418
|
+
execute: (params: {
|
|
419
|
+
input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
420
|
+
ctx: TContext;
|
|
421
|
+
error: ErrorBuilder<TErrors>;
|
|
422
|
+
}) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
|
|
423
|
+
}
|
|
424
|
+
type ActionConfig<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> = ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext> | ActionConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>;
|
|
425
|
+
interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> {
|
|
426
|
+
(params: {
|
|
427
|
+
input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
428
|
+
ctx?: Partial<TContext>;
|
|
429
|
+
}): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
430
|
+
name: string;
|
|
431
|
+
serviceName?: string;
|
|
432
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
433
|
+
plugin?: string;
|
|
434
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
435
|
+
resource?: string;
|
|
436
|
+
config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;
|
|
437
|
+
/**
|
|
438
|
+
* Optional runtime-only output schema. When present, `validateOutput` and
|
|
439
|
+
* HTTP output checking validate against it instead of `config.output`,
|
|
440
|
+
* while `config.output` remains the published contract (client types,
|
|
441
|
+
* OpenAPI). Lets projected/subset responses validate at runtime without
|
|
442
|
+
* leaking optionality into the generated contract.
|
|
443
|
+
*/
|
|
444
|
+
outputValidationSchema?: TSchema;
|
|
445
|
+
run(input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: Partial<TContext>): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
446
|
+
execute(params: {
|
|
447
|
+
input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
448
|
+
ctx?: Partial<TContext>;
|
|
449
|
+
}): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
450
|
+
executeResolved?(params: {
|
|
451
|
+
input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
|
|
452
|
+
ctx: TContext;
|
|
453
|
+
}): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
454
|
+
validateInput(input: unknown): {
|
|
455
|
+
success: true;
|
|
456
|
+
data: any;
|
|
457
|
+
} | {
|
|
458
|
+
success: false;
|
|
459
|
+
errors: ValidationErrorItem[];
|
|
460
|
+
};
|
|
461
|
+
validateOutput(output: unknown): {
|
|
462
|
+
success: true;
|
|
463
|
+
data: any;
|
|
464
|
+
} | {
|
|
465
|
+
success: false;
|
|
466
|
+
errors: ValidationErrorItem[];
|
|
467
|
+
};
|
|
468
|
+
errorHelpers?: ErrorBuilder<TErrors>;
|
|
469
|
+
}
|
|
470
|
+
/** MCP tool metadata, kept with the executable definition. */
|
|
471
|
+
interface ToolAnnotations {
|
|
472
|
+
title?: string;
|
|
473
|
+
readOnlyHint?: boolean;
|
|
474
|
+
destructiveHint?: boolean;
|
|
475
|
+
idempotentHint?: boolean;
|
|
476
|
+
openWorldHint?: boolean;
|
|
477
|
+
}
|
|
478
|
+
interface ToolOptions {
|
|
479
|
+
title?: string;
|
|
480
|
+
annotations?: ToolAnnotations;
|
|
481
|
+
/** Also register HTTP routes and OpenAPI. Defaults to false. */
|
|
482
|
+
http?: boolean;
|
|
483
|
+
}
|
|
484
|
+
type ToolConfigWithAuthorize<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, C extends ActionContext = ActionContext> = ActionConfigWithAuthorize<I, O, E, C> & ToolOptions;
|
|
485
|
+
type ToolConfigWithoutAuthorize<I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, C extends ActionContext = ActionContext> = ActionConfigWithoutAuthorize<I, O, E, C> & ToolOptions;
|
|
486
|
+
interface Tool<I extends TSchema | undefined = any, O extends TSchema | undefined = any, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, C extends ActionContext = ActionContext> extends Action<I, O, E, C> {
|
|
487
|
+
readonly kind: "tool";
|
|
488
|
+
config: ToolConfigWithAuthorize<I, O, E, C> | ToolConfigWithoutAuthorize<I, O, E, C>;
|
|
489
|
+
}
|
|
490
|
+
/** A resource declares identity and a table; plugins supply behavior. */
|
|
491
|
+
interface ResourceConfig<TTable = any, _TCtx = any> {
|
|
492
|
+
name: string;
|
|
493
|
+
table: TTable;
|
|
494
|
+
id?: import("drizzle-orm").Column;
|
|
495
|
+
}
|
|
496
|
+
type InferTableRow<TTable> = TTable extends {
|
|
497
|
+
$inferSelect: infer S;
|
|
498
|
+
} ? S : any;
|
|
499
|
+
type InferTableInsert<TTable> = TTable extends {
|
|
500
|
+
$inferInsert: infer S;
|
|
501
|
+
} ? S : any;
|
|
502
|
+
type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id">;
|
|
503
|
+
type PrimaryColumn<T> = T extends {
|
|
504
|
+
_: {
|
|
505
|
+
columns: infer C;
|
|
506
|
+
};
|
|
507
|
+
} ? { [K in keyof C]: C[K] extends {
|
|
508
|
+
_: {
|
|
509
|
+
isPrimaryKey: true;
|
|
510
|
+
};
|
|
511
|
+
} ? C[K] : never; }[keyof C] : import("drizzle-orm").Column;
|
|
512
|
+
type ResourceIdentity<T, O> = O & {
|
|
513
|
+
id: O extends {
|
|
514
|
+
id: infer I extends import("drizzle-orm").Column;
|
|
515
|
+
} ? I : PrimaryColumn<T>;
|
|
516
|
+
};
|
|
517
|
+
/** Generic preparation declarations consumed by the application compiler. */
|
|
518
|
+
interface PreparationContribution {
|
|
519
|
+
readonly name: string;
|
|
520
|
+
describe(): unknown;
|
|
521
|
+
prepare(): void;
|
|
522
|
+
}
|
|
523
|
+
interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}> {
|
|
524
|
+
use<P extends ResourcePlugin<Service<TCtx["db"], Omit<TCtx, keyof BaseContext>>, this, any>>(plugin: P): this & ResourcePluginAPI<P, TTable, TCtx, this>;
|
|
525
|
+
readonly name: string;
|
|
526
|
+
readonly serviceName: string;
|
|
527
|
+
readonly table: TTable;
|
|
528
|
+
readonly id: TOptions extends {
|
|
529
|
+
id: infer I extends import("drizzle-orm").Column;
|
|
530
|
+
} ? I : import("drizzle-orm").Column;
|
|
531
|
+
readonly idField: string;
|
|
532
|
+
readonly config: ResourceConfig<TTable, TCtx> & TOptions;
|
|
533
|
+
}
|
|
534
|
+
interface ServiceAuthOptions {
|
|
535
|
+
requireAuth?: boolean;
|
|
536
|
+
allowedRoles?: string[];
|
|
537
|
+
policy?: (ctx: ActionContext) => boolean | Promise<boolean>;
|
|
538
|
+
}
|
|
539
|
+
interface RateLimitOptions {
|
|
540
|
+
maxRequests: number;
|
|
541
|
+
window: number | string;
|
|
542
|
+
scope?: "ip" | "user" | "tenant";
|
|
543
|
+
}
|
|
544
|
+
interface CacheOptions {
|
|
545
|
+
driver?: "memory" | "redis";
|
|
546
|
+
defaultTtl?: number;
|
|
547
|
+
}
|
|
548
|
+
interface ResilienceOptions {
|
|
549
|
+
timeoutMs?: number;
|
|
550
|
+
retry?: {
|
|
551
|
+
attempts: number;
|
|
552
|
+
backoff: "linear" | "exponential";
|
|
553
|
+
delayMs: number;
|
|
554
|
+
};
|
|
555
|
+
circuitBreaker?: {
|
|
556
|
+
errorThresholdPercentage: number;
|
|
557
|
+
resetTimeoutMs: number;
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
interface TelemetryOptions {
|
|
561
|
+
traceQueries?: boolean;
|
|
562
|
+
auditLog?: boolean;
|
|
563
|
+
tags?: Record<string, string>;
|
|
564
|
+
}
|
|
565
|
+
interface LifecycleOptions {
|
|
566
|
+
onInit?: (ctx: {
|
|
567
|
+
db?: any;
|
|
568
|
+
logger?: Logger;
|
|
569
|
+
}) => Promise<void>;
|
|
570
|
+
onDestroy?: () => Promise<void>;
|
|
571
|
+
}
|
|
572
|
+
interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
|
|
573
|
+
database?: DatabaseHandle<TDb>;
|
|
574
|
+
context?: (baseCtx: BaseContext<TDb> & {
|
|
575
|
+
user?: unknown;
|
|
576
|
+
}) => Promise<TServiceContext> | TServiceContext;
|
|
577
|
+
auth?: ServiceAuthOptions;
|
|
578
|
+
rateLimit?: RateLimitOptions;
|
|
579
|
+
cache?: CacheOptions;
|
|
580
|
+
resilience?: ResilienceOptions;
|
|
581
|
+
telemetry?: TelemetryOptions;
|
|
582
|
+
lifecycle?: LifecycleOptions;
|
|
583
|
+
}
|
|
584
|
+
type ActionAccessPolicy = "public" | "authorized" | "scoped";
|
|
585
|
+
interface ActionSchema {
|
|
586
|
+
name: string;
|
|
587
|
+
/** Present only when this action has a registered HTTP route. */
|
|
588
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
589
|
+
path?: string;
|
|
590
|
+
serviceName?: string;
|
|
591
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
592
|
+
plugin?: string;
|
|
593
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
594
|
+
resource?: string;
|
|
595
|
+
description?: string;
|
|
596
|
+
inputSchema?: unknown;
|
|
597
|
+
outputSchema?: unknown;
|
|
598
|
+
hasAuthorize: boolean;
|
|
599
|
+
hasScope?: boolean;
|
|
600
|
+
accessPolicy?: ActionAccessPolicy;
|
|
601
|
+
errors?: Record<string, ActionErrorDefinition>;
|
|
602
|
+
emits?: string[];
|
|
603
|
+
tags?: string[];
|
|
604
|
+
}
|
|
605
|
+
interface ServiceSchema {
|
|
606
|
+
name: string;
|
|
607
|
+
options: Omit<ServiceOptions, "database">;
|
|
608
|
+
hasDatabase: boolean;
|
|
609
|
+
databaseConfig?: {
|
|
610
|
+
name?: string;
|
|
611
|
+
engine: "sqlite" | "postgres";
|
|
612
|
+
tables: string[];
|
|
613
|
+
};
|
|
614
|
+
actions: ActionSchema[];
|
|
615
|
+
resources?: {
|
|
616
|
+
name: string;
|
|
617
|
+
}[];
|
|
618
|
+
}
|
|
619
|
+
interface ArchitectureSchema {
|
|
620
|
+
version: string;
|
|
621
|
+
services: ServiceSchema[];
|
|
622
|
+
}
|
|
623
|
+
interface CompiledRoutePlan {
|
|
624
|
+
service: Service<any, any>;
|
|
625
|
+
action: Action<any, any, any, any>;
|
|
626
|
+
actionName: string;
|
|
627
|
+
serviceName: string;
|
|
628
|
+
routePath: string;
|
|
629
|
+
method?: string;
|
|
630
|
+
isGetLike: boolean;
|
|
631
|
+
hasInput: boolean;
|
|
632
|
+
hasContextHook: boolean;
|
|
633
|
+
contextHook?: (baseCtx: any) => Promise<any> | any;
|
|
634
|
+
hasAuthorize: boolean;
|
|
635
|
+
authorize?: (params: any) => boolean | Promise<boolean>;
|
|
636
|
+
execute: (params: any) => Promise<any> | any;
|
|
637
|
+
inputChecker?: {
|
|
638
|
+
Check: (val: any) => boolean;
|
|
639
|
+
Errors: (val: any) => Iterable<any>;
|
|
640
|
+
};
|
|
641
|
+
outputChecker?: {
|
|
642
|
+
Check: (val: any) => boolean;
|
|
643
|
+
Errors: (val: any) => Iterable<any>;
|
|
644
|
+
};
|
|
645
|
+
coercions?: Array<{
|
|
646
|
+
key: string;
|
|
647
|
+
isNumber: boolean;
|
|
648
|
+
isBoolean: boolean;
|
|
649
|
+
}>;
|
|
650
|
+
logger: Logger;
|
|
651
|
+
errorBuilder: any;
|
|
652
|
+
cachedDb: any;
|
|
653
|
+
}
|
|
654
|
+
interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> {
|
|
655
|
+
readonly name: string;
|
|
656
|
+
readonly options: ServiceOptions<TServiceContext, TDb>;
|
|
657
|
+
readonly actions: Map<string, Action<any, any, any, any>>;
|
|
658
|
+
readonly tools: Map<string, Tool<any, any, any, any>>;
|
|
659
|
+
readonly tables: Map<string, any>;
|
|
660
|
+
readonly resources: Map<string, Resource<any, BaseContext<TDb> & TServiceContext>>;
|
|
661
|
+
readonly db?: TDb;
|
|
662
|
+
readonly isBuilt?: boolean;
|
|
663
|
+
use<A>(plugin: ServicePlugin<this, A>): A;
|
|
664
|
+
build(): this;
|
|
665
|
+
action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
|
|
666
|
+
action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
|
|
667
|
+
action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
|
|
668
|
+
tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
|
|
669
|
+
tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
|
|
670
|
+
tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
|
|
671
|
+
resource<TTable = any, const TOptions extends ResourceTypeOptions = ResourceTypeOptions>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> & TOptions & Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>): Resource<TTable, BaseContext<TDb> & TServiceContext, ResourceIdentity<TTable, TOptions>>;
|
|
672
|
+
readonly preparations: Map<string, PreparationContribution>;
|
|
673
|
+
contributePreparation(contribution: PreparationContribution): void;
|
|
674
|
+
listPreparations(): PreparationContribution[];
|
|
675
|
+
prepareContributions(): void;
|
|
676
|
+
registerTable(table: any): this;
|
|
677
|
+
getAction(name: string): Action<any, any, any, any> | undefined;
|
|
678
|
+
listActions(): Action<any, any, any, any>[];
|
|
679
|
+
getTool(name: string): Tool<any, any, any, any> | undefined;
|
|
680
|
+
listTools(): Tool<any, any, any, any>[];
|
|
681
|
+
getResource(name: string): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;
|
|
682
|
+
listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];
|
|
683
|
+
getDb(): TDb | undefined;
|
|
684
|
+
setDb(database: DatabaseHandle<TDb>): void;
|
|
685
|
+
/** The live handle, reflecting setDb swaps (options.database stays declared). */
|
|
686
|
+
getDatabaseHandle(): DatabaseHandle<TDb> | undefined;
|
|
687
|
+
resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
|
|
688
|
+
introspect(): ServiceSchema;
|
|
689
|
+
}
|
|
690
|
+
interface ProxyOptions {
|
|
691
|
+
isMonolith?: boolean;
|
|
692
|
+
/** Name of the service creating this proxy. Populates ctx.caller on the target's envelope. */
|
|
693
|
+
from?: string;
|
|
694
|
+
context?: Partial<ActionContext>;
|
|
695
|
+
}
|
|
696
|
+
//#endregion
|
|
697
|
+
//#region src/client.d.ts
|
|
698
|
+
/**
|
|
699
|
+
* Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.
|
|
700
|
+
*
|
|
701
|
+
* The frontend imports only the contract *type* — never a backend implementation:
|
|
702
|
+
*
|
|
703
|
+
* ```ts
|
|
704
|
+
* import { createBrickClient } from "@brickkit/core/client";
|
|
705
|
+
* import type { AppServer } from "./server"; // `import type`: erased at build
|
|
706
|
+
*
|
|
707
|
+
* const api = createBrickClient<AppServer>({ baseUrl: "http://localhost:4000" });
|
|
708
|
+
* const pages = await api.page.list({ limit: 10, sort: "-createdAt" });
|
|
709
|
+
* const created = await api.page.create({ title: "Hello", content: "World" });
|
|
710
|
+
* ```
|
|
711
|
+
*
|
|
712
|
+
* Build the contract from individually-typed actions (each `defineAction` call
|
|
713
|
+
* preserves its input/output/error literal types):
|
|
714
|
+
*
|
|
715
|
+
* ```ts
|
|
716
|
+
* // server.ts (backend)
|
|
717
|
+
* export const listPages = pagesService.action({ name: "page.list", ... });
|
|
718
|
+
* export const createPage = pagesService.action({ name: "page.create", ... });
|
|
719
|
+
* export const contract = { page: { list: listPages, create: createPage } };
|
|
720
|
+
* export type AppServer = typeof contract;
|
|
721
|
+
* ```
|
|
722
|
+
*
|
|
723
|
+
* ## Result / error convention
|
|
724
|
+
*
|
|
725
|
+
* The client uses a throw-based convention that mirrors local `action.execute`
|
|
726
|
+
* semantics, because TypeScript promises cannot encode thrown exception types:
|
|
727
|
+
*
|
|
728
|
+
* - Success → the promise resolves with the action output.
|
|
729
|
+
* - Declared domain failures (your `errors: { SLUG_EXISTS: ... }`) and framework
|
|
730
|
+
* guards (UNAUTHORIZED/FORBIDDEN/NOT_FOUND/...) → rejected with
|
|
731
|
+
* {@link ActionExecutionError} carrying the declared `code`, `status`,
|
|
732
|
+
* `message`, and `details`. Narrow with `instanceof` and read `err.code`.
|
|
733
|
+
* - Input/output validation failures → rejected with {@link ValidationError},
|
|
734
|
+
* exactly as local execution throws.
|
|
735
|
+
* - Network failures, unparsable bodies, and non-OK responses outside the
|
|
736
|
+
* declared contract → {@link BrickTransportError} (4xx) or
|
|
737
|
+
* {@link BrickServerError} (5xx).
|
|
738
|
+
* - Cancellation via `AbortSignal` → the native `AbortError` propagates
|
|
739
|
+
* unwrapped so `err.name === "AbortError"` keeps working.
|
|
740
|
+
*
|
|
741
|
+
* ## URL mapping
|
|
742
|
+
*
|
|
743
|
+
* A client path is a namespace walk ending in an action call. The leaf segment
|
|
744
|
+
* decides the route, matching the server compiler (`packages/cli/src/compiler`):
|
|
745
|
+
*
|
|
746
|
+
* | Client call | HTTP request |
|
|
747
|
+
* |---|---|
|
|
748
|
+
* Generated browser contracts carry each action's HTTP method and path,
|
|
749
|
+
* including plugin routes and consumer overrides. Without runtime metadata,
|
|
750
|
+
* callers use `POST /api/<service>/<action>` with dotted action names.
|
|
751
|
+
* GET/DELETE input is serialized as a query string; other methods send JSON.
|
|
752
|
+
|
|
753
|
+
*/
|
|
754
|
+
interface BrickClientOptions {
|
|
755
|
+
/** Server origin, e.g. `"http://localhost:4000"`. No trailing slash required. */
|
|
756
|
+
baseUrl: string;
|
|
757
|
+
/**
|
|
758
|
+
* Route prefix the server was mounted with (default `"/api"`).
|
|
759
|
+
* Must match the `prefix` passed to `brick({ prefix })`.
|
|
760
|
+
*/
|
|
761
|
+
prefix?: string;
|
|
762
|
+
/**
|
|
763
|
+
* Default headers sent with every call (e.g. an `Authorization` bearer).
|
|
764
|
+
* A thunk is re-evaluated per call, so rotated tokens stay fresh.
|
|
765
|
+
*/
|
|
766
|
+
headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
|
|
767
|
+
/** `fetch` implementation. Defaults to `globalThis.fetch`. */
|
|
768
|
+
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
769
|
+
/** Default signal applied to every call (per-call `signal` wins). */
|
|
770
|
+
signal?: AbortSignal;
|
|
771
|
+
/** Default per-call timeout in milliseconds (per-call `timeoutMs` wins). */
|
|
772
|
+
timeoutMs?: number;
|
|
773
|
+
/**
|
|
774
|
+
* Browser-safe route metadata generated by the Brick Vite plugin.
|
|
775
|
+
* Required for custom methods/paths and plugin routes. Without a contract,
|
|
776
|
+
* calls use POST and service/action names inferred from namespace keys.
|
|
777
|
+
*/
|
|
778
|
+
contract?: Record<string, any>;
|
|
779
|
+
}
|
|
780
|
+
/** Browser-safe action metadata generated by the Brick Vite plugin. */
|
|
781
|
+
interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}> {
|
|
782
|
+
kind: "action";
|
|
783
|
+
name: string;
|
|
784
|
+
serviceName: string;
|
|
785
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
786
|
+
plugin?: string;
|
|
787
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
788
|
+
resource?: string;
|
|
789
|
+
config: {
|
|
790
|
+
path: string;
|
|
791
|
+
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
792
|
+
};
|
|
793
|
+
/** Type information only; never emitted at runtime. */
|
|
794
|
+
readonly __types?: {
|
|
795
|
+
input: TInput;
|
|
796
|
+
output: TOutput;
|
|
797
|
+
errors: TErrors;
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
interface BrickCallOptions {
|
|
801
|
+
/** Extra headers merged over the client defaults for this call only. */
|
|
802
|
+
headers?: Record<string, string>;
|
|
803
|
+
/** Abort signal for this call only. Never wrapped: aborts reject with `AbortError`. */
|
|
804
|
+
signal?: AbortSignal;
|
|
805
|
+
/** Per-call timeout in milliseconds. Implemented with `AbortSignal.timeout`. */
|
|
806
|
+
timeoutMs?: number;
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* The request never received a meaningful server answer: DNS / connection
|
|
810
|
+
* failure, a malformed body, or a 4xx response outside the declared contract
|
|
811
|
+
* (no `code` and no `ValidationError` shape).
|
|
812
|
+
*/
|
|
813
|
+
declare class BrickTransportError extends Error {
|
|
814
|
+
readonly kind: "transport";
|
|
815
|
+
readonly status?: number;
|
|
816
|
+
readonly url: string;
|
|
817
|
+
readonly body?: unknown;
|
|
818
|
+
readonly cause?: unknown;
|
|
819
|
+
constructor(message: string, opts: {
|
|
820
|
+
status?: number;
|
|
821
|
+
url: string;
|
|
822
|
+
body?: unknown;
|
|
823
|
+
cause?: unknown;
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* The server answered 5xx without a declared `code` / `ValidationError` shape,
|
|
828
|
+
* i.e. an unexpected failure rather than a modelled domain error.
|
|
829
|
+
*/
|
|
830
|
+
declare class BrickServerError extends Error {
|
|
831
|
+
readonly kind: "server";
|
|
832
|
+
readonly status: number;
|
|
833
|
+
readonly url: string;
|
|
834
|
+
readonly body: unknown;
|
|
835
|
+
constructor(message: string, opts: {
|
|
836
|
+
status: number;
|
|
837
|
+
url: string;
|
|
838
|
+
body: unknown;
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
declare function isBrickTransportError(err: unknown): err is BrickTransportError;
|
|
842
|
+
declare function isBrickServerError(err: unknown): err is BrickServerError;
|
|
843
|
+
/** Static input type from the schema, with a fallback for structural actions. */
|
|
844
|
+
type InferActionInput<A> = A extends BrickClientAction<infer I, any, any> ? I : A extends {
|
|
845
|
+
config: {
|
|
846
|
+
input?: infer S extends TSchema;
|
|
847
|
+
};
|
|
848
|
+
} ? Static<S> : A extends {
|
|
849
|
+
execute(params: {
|
|
850
|
+
input?: infer I;
|
|
851
|
+
ctx?: any;
|
|
852
|
+
}): any;
|
|
853
|
+
} ? I : A extends {
|
|
854
|
+
run(input?: infer I, ctx?: any): any;
|
|
855
|
+
} ? I : A extends ((params: {
|
|
856
|
+
input?: infer I;
|
|
857
|
+
ctx?: any;
|
|
858
|
+
}) => any) ? I : unknown;
|
|
859
|
+
/** Resolved output type of an action. */
|
|
860
|
+
type InferActionOutput<A> = A extends BrickClientAction<any, infer O, any> ? O : A extends ((...args: any[]) => Promise<infer O>) ? O : A extends {
|
|
861
|
+
execute(params: any): Promise<infer O>;
|
|
862
|
+
} ? O : unknown;
|
|
863
|
+
/** Union of error `code`s declared in an action's `errors` map. */
|
|
864
|
+
type InferActionErrorCodes<A> = A extends BrickClientAction<any, any, infer E> ? Extract<keyof E, string> : A extends {
|
|
865
|
+
config: {
|
|
866
|
+
errors?: infer E;
|
|
867
|
+
};
|
|
868
|
+
} ? E extends Record<string, ActionErrorDefinition> ? Extract<keyof E, string> : never : never;
|
|
869
|
+
/**
|
|
870
|
+
* The declared failure shape of an action for `catch` narrowing:
|
|
871
|
+
* ```ts
|
|
872
|
+
* try { await api.page.create(input); }
|
|
873
|
+
* catch (err) {
|
|
874
|
+
* if (err instanceof ActionExecutionError) {
|
|
875
|
+
* const code: InferActionErrorCodes<typeof createPage> | "UNAUTHORIZED" | ... = err.code;
|
|
876
|
+
* }
|
|
877
|
+
* }
|
|
878
|
+
* ```
|
|
879
|
+
* (Standard framework codes are always possible alongside declared ones.)
|
|
880
|
+
*/
|
|
881
|
+
type InferActionFailure<A> = ActionExecutionError & {
|
|
882
|
+
code: InferActionErrorCodes<A> | "BAD_REQUEST" | "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "INTERNAL_SERVER_ERROR" | "VALIDATION_FAILED";
|
|
883
|
+
};
|
|
884
|
+
/**
|
|
885
|
+
* Typed caller for one action. Required inputs stay required; actions whose
|
|
886
|
+
* input includes `undefined` (no schema / all-optional) can be called bare.
|
|
887
|
+
*/
|
|
888
|
+
type BrickActionCaller<A> = undefined extends InferActionInput<A> ? (input?: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>> : (input: InferActionInput<A>, options?: BrickCallOptions) => Promise<InferActionOutput<A>>;
|
|
889
|
+
/** Recursively maps action leaves and their namespaces to browser callers. */
|
|
890
|
+
type BrickClient<T> = T extends BrickClientAction<any, any, any> | Action<any, any, any, any> ? BrickActionCaller<T> : T extends ((...args: any[]) => any) ? BrickActionCaller<T> : T extends object ? { [K in keyof T]: BrickClient<T[K]>; } : T;
|
|
891
|
+
/**
|
|
892
|
+
* Create an Eden/tRPC-style typed client for the application contract `TApp`.
|
|
893
|
+
* `TApp` is a type-only parameter: `import type { AppServer }` keeps backend
|
|
894
|
+
* implementations out of the frontend bundle.
|
|
895
|
+
*/
|
|
896
|
+
declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions & {
|
|
897
|
+
contract: TApp;
|
|
898
|
+
}): BrickClient<TApp>;
|
|
899
|
+
declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
|
|
900
|
+
//#endregion
|
|
901
|
+
export { ToolConfigWithoutAuthorize as $, ErrorBuilder as A, index as At, Resource as B, PluginRouteScope as Bt, ActionSchema as C, secret as Ct, CacheOptions as D, blob as Dt, BaseContext as E, SQLiteDatabaseConfig as Et, NarrowAuthorizedContext as F, text as Ft, ServiceAuthOptions as G, ResourcePluginTypes as Gt, ResourceIdentity as H, ResourcePlugin as Ht, PreparationContribution as I, uniqueIndex as It, StandardErrorMap as J, defineResourcePlugin as Jt, ServiceOptions as K, ServicePlugin as Kt, ProxyOptions as L, PluginEndpointContext as Lt, InferTableRow as M, primaryKey as Mt, LifecycleOptions as N, real as Nt, CompiledRoutePlan as O, createSQLiteDatabase as Ot, Logger as P, sqliteTable as Pt, ToolConfigWithAuthorize as Q, RateLimitOptions as R, PluginRouteMethod as Rt, ActionExecutionError as S, resolveSecrets as St, BaseActionConfig as T, BunSQLiteDatabase$1 as Tt, ResourceTypeOptions as U, ResourcePluginAPI as Ut, ResourceConfig as V, PluginRoutes as Vt, Service as W, ResourcePluginContext as Wt, Tool as X, getPluginActionRoute as Xt, TelemetryOptions as Y, defineServicePlugin as Yt, ToolAnnotations as Z, getPluginEndpoints as Zt, ActionConfig as _, envSource as _t, BrickClientOptions as a, EnvInput as at, ActionContext as b, overrideSecrets as bt, InferActionErrorCodes as c, defineDatabase as ct, InferActionOutput as d, PostgresDatabase as dt, ToolOptions as et, createBrickClient as f, PostgresDatabaseConfig as ft, ActionAccessPolicy as g, SecretSource as gt, Action as h, SecretRef as ht, BrickClientAction as i, DatabaseHandle as it, InferTableInsert as j, integer as jt, DefaultServiceContext as k, foreignKey as kt, InferActionFailure as l, isDatabaseHandle as lt, isBrickTransportError as m, SecretOptions as mt, BrickCallOptions as n, ValidationErrorItem as nt, BrickServerError as o, PostgresDefinition as ot, isBrickServerError as p, createPostgresDatabase as pt, ServiceSchema as q, ServicePluginContext as qt, BrickClient as r, DatabaseDefinition as rt, BrickTransportError as s, SQLiteDefinition as st, BrickActionCaller as t, ValidationError as tt, InferActionInput as u, DatabaseAdapter as ut, ActionConfigWithAuthorize as v, listSecrets as vt, ArchitectureSchema as w, BrickSQLiteDatabase as wt, ActionErrorDefinition as x, resetSecrets as xt, ActionConfigWithoutAuthorize as y, overrideSecret as yt, ResilienceOptions as z, PluginRouteRegistrar as zt };
|
|
902
|
+
//# sourceMappingURL=client.d.ts.map
|