@brickkit/core 0.3.0-beta.5 → 0.3.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/chunks/client.d.ts +22 -8
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js.map +1 -1
- package/dist/index.d.ts +67 -38
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +335 -221
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/chunks/client.d.ts
CHANGED
|
@@ -93,6 +93,8 @@ declare function getPluginActionRoute(action: Action<any, any, any, any>, prefix
|
|
|
93
93
|
path: string;
|
|
94
94
|
method: PluginRouteMethod;
|
|
95
95
|
clientPath: string[] | undefined;
|
|
96
|
+
plugin: string;
|
|
97
|
+
resource: string | undefined;
|
|
96
98
|
} | undefined;
|
|
97
99
|
declare function getPluginEndpoints(service: Service<any, any>, prefix?: string): {
|
|
98
100
|
path: string;
|
|
@@ -422,6 +424,10 @@ interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema e
|
|
|
422
424
|
}): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
|
|
423
425
|
name: string;
|
|
424
426
|
serviceName?: string;
|
|
427
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
428
|
+
plugin?: string;
|
|
429
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
430
|
+
resource?: string;
|
|
425
431
|
config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;
|
|
426
432
|
/**
|
|
427
433
|
* Optional runtime-only output schema. When present, `validateOutput` and
|
|
@@ -568,26 +574,30 @@ interface ServiceOptions<TServiceContext extends Record<string, any> = Record<st
|
|
|
568
574
|
telemetry?: TelemetryOptions;
|
|
569
575
|
lifecycle?: LifecycleOptions;
|
|
570
576
|
}
|
|
577
|
+
type ActionAccessPolicy = "public" | "authorized" | "scoped";
|
|
571
578
|
interface ActionSchema {
|
|
572
579
|
name: string;
|
|
580
|
+
/** Present only when this action has a registered HTTP route. */
|
|
581
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
582
|
+
path?: string;
|
|
573
583
|
serviceName?: string;
|
|
584
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
585
|
+
plugin?: string;
|
|
586
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
587
|
+
resource?: string;
|
|
574
588
|
description?: string;
|
|
575
589
|
inputSchema?: unknown;
|
|
576
590
|
outputSchema?: unknown;
|
|
577
591
|
hasAuthorize: boolean;
|
|
592
|
+
hasScope?: boolean;
|
|
593
|
+
accessPolicy?: ActionAccessPolicy;
|
|
578
594
|
errors?: Record<string, ActionErrorDefinition>;
|
|
579
595
|
emits?: string[];
|
|
580
596
|
tags?: string[];
|
|
581
597
|
}
|
|
582
598
|
interface ServiceSchema {
|
|
583
599
|
name: string;
|
|
584
|
-
options: Omit<ServiceOptions, "database"
|
|
585
|
-
database?: {
|
|
586
|
-
name?: string;
|
|
587
|
-
engine: "sqlite" | "postgres";
|
|
588
|
-
tables: string[];
|
|
589
|
-
};
|
|
590
|
-
};
|
|
600
|
+
options: Omit<ServiceOptions, "database">;
|
|
591
601
|
hasDatabase: boolean;
|
|
592
602
|
databaseConfig?: {
|
|
593
603
|
name?: string;
|
|
@@ -760,6 +770,10 @@ interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}> {
|
|
|
760
770
|
kind: "action";
|
|
761
771
|
name: string;
|
|
762
772
|
serviceName: string;
|
|
773
|
+
/** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */
|
|
774
|
+
plugin?: string;
|
|
775
|
+
/** Owning resource name for resource-plugin actions (e.g. `page`). */
|
|
776
|
+
resource?: string;
|
|
763
777
|
config: {
|
|
764
778
|
path: string;
|
|
765
779
|
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
@@ -872,5 +886,5 @@ declare function createBrickClient<TApp extends Record<string, any>>(options: Br
|
|
|
872
886
|
}): BrickClient<TApp>;
|
|
873
887
|
declare function createBrickClient<TApp extends Record<string, any>>(options: BrickClientOptions): BrickClient<TApp>;
|
|
874
888
|
//#endregion
|
|
875
|
-
export {
|
|
889
|
+
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 };
|
|
876
890
|
//# sourceMappingURL=client.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","names":["BunSQLiteDatabase","_$__plugin0.ResourcePluginAPI","BunSQLiteDatabase"],"sources":["../../src/plugin.ts","../../src/db/sqlite.ts","../../src/secrets.ts","../../src/db/postgres.ts","../../src/db/define.ts","../../src/types.ts","../../src/client.ts"],"mappings":";;;;;;;;KAcY;KACA;KACA,aAAa,UAAU,mBAAmB,4BAElD,SAAS;EAAyB;EAAe,QAAQ;;KAExD,UAAU,KACb,UAAU,cAAc,SAAS,KAAK,YAAY,KAAK;UAExC,sBACf,UAAU,gBAAgB;EAE1B,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;EACT;IAAO;IAAiB,SAAS;;EACjC,KAAK;;UAGU,qBACf,UAAU,gBAAgB,eAC1B,UAAU,mBAAmB;EAE7B,OACE,UAAU,iCACV,UAAU,iCACV,UAAU,eAAe,yBAAyB,eAEhD,wBAGF,QAAQ,0BAA0B,GAAG,GAAG,GAAG;IACzC;IACA,QAAQ;IACR,QAAQ;MAET,OAAO,GAAG,GAAG,GAAG;EACnB,OACE,UAAU,iCACV,UAAU,iCACV,UAAU,eAAe,yBAAyB,eAEhD,wBAGF,QAAQ,6BAA6B,GAAG,GAAG,GAAG;IAC5C;IACA,QAAQ;IACR,QAAQ;MAET,OAAO,GAAG,GAAG,GAAG;EACnB,SAAS;IACP;IACA;IACA,QAAQ;IACR,QAAQ;IACR,UAAU,SAAS,sBAAsB,iBAAiB;IAC1D;IACA;IACA;;;UAIa,qBACf,UAAU,oBAAoB;EAE9B,SAAS;EACT,QAAQ,qBAAqB,UAAU;;UAExB,sBACf,UAAU,oBAAoB,mBAC9B,UAAU,0BAA0B,cAAc,UAAU;EAE5D,SAAS;EACT,UAAU;EACV,QAAQ,qBAAqB,UAAU;;;UAIxB;WACN;WACA;WACA;WACA;;KAEC,kBAAkB,GAAG,GAAG,GAAG,eAAe;WAC3C,aAAa,UAAU;KAE7B;WACU,OAAO;WACP,SAAS;WACT,UAAU;YAErB,UAAU,+BAA+B,KACvC;
|
|
1
|
+
{"version":3,"file":"client.d.ts","names":["BunSQLiteDatabase","_$__plugin0.ResourcePluginAPI","BunSQLiteDatabase"],"sources":["../../src/plugin.ts","../../src/db/sqlite.ts","../../src/secrets.ts","../../src/db/postgres.ts","../../src/db/define.ts","../../src/types.ts","../../src/client.ts"],"mappings":";;;;;;;;KAcY;KACA;KACA,aAAa,UAAU,mBAAmB,4BAElD,SAAS;EAAyB;EAAe,QAAQ;;KAExD,UAAU,KACb,UAAU,cAAc,SAAS,KAAK,YAAY,KAAK;UAExC,sBACf,UAAU,gBAAgB;EAE1B,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;EACT;IAAO;IAAiB,SAAS;;EACjC,KAAK;;UAGU,qBACf,UAAU,gBAAgB,eAC1B,UAAU,mBAAmB;EAE7B,OACE,UAAU,iCACV,UAAU,iCACV,UAAU,eAAe,yBAAyB,eAEhD,wBAGF,QAAQ,0BAA0B,GAAG,GAAG,GAAG;IACzC;IACA,QAAQ;IACR,QAAQ;MAET,OAAO,GAAG,GAAG,GAAG;EACnB,OACE,UAAU,iCACV,UAAU,iCACV,UAAU,eAAe,yBAAyB,eAEhD,wBAGF,QAAQ,6BAA6B,GAAG,GAAG,GAAG;IAC5C;IACA,QAAQ;IACR,QAAQ;MAET,OAAO,GA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KAchB,kBAAkB,uBACV,iBAAiB,MAE7B,QAAQ,iBAAiB,IACzB,UAAU,qBACP,QAAQ,kBAAkB,OAE7B,OAAO,iBAAiB,IACxB,UAAU,qBACP,QAAQ,kBAAkB;;KAGzB,YAAY,KAAK,UACzB,mCACA,6BACA,kBAAkB,KAClB,eAAc,uBACZ,kBAAkB,KAClB,sBACK,WAAW,IAAI,YAAY,EAAE,SAChC;;;;;;iBAiSQ,kBAAkB,aAAa,qBAC7C,SAAS;EAAuB,UAAU;IACzC,YAAY;iBACC,kBAAkB,aAAa,qBAC7C,SAAS,qBACR,YAAY"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../src/types.ts","../../src/client.ts"],"sourcesContent":["import type { ServicePlugin, ResourcePlugin } from \"./plugin\";\nimport type { TSchema, Static } from \"@sinclair/typebox\";\nimport type { BunSQLiteDatabase } from \"./db/sqlite\";\nimport type { DatabaseHandle } from \"./db/define\";\n\nexport interface Logger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/**\n * Base framework context supplied to all service resolvers and action executions.\n */\nexport interface BaseContext<TDb = any> {\n request: Request;\n db: TDb;\n logger: Logger;\n traceId: string;\n requestId?: string;\n services?: Record<string, any>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Default fallback service context for untyped or simple services.\n */\nexport interface DefaultServiceContext {\n user?: any;\n session?: any;\n [key: string]: any;\n}\n\n/**\n * The combined execution context: BaseContext & TServiceContext.\n */\nexport type ActionContext<\n TDb = any,\n TServiceContext = DefaultServiceContext,\n> = BaseContext<TDb> & TServiceContext;\n\n/**\n * Type utility that automatically narrows ctx.user from User | null to User\n * in execute() when authorize() is declared on the action.\n */\nexport type NarrowAuthorizedContext<TCtx> = TCtx extends { user: infer U }\n ? [U] extends [null | undefined]\n ? TCtx\n : Omit<TCtx, \"user\"> & { user: NonNullable<U> }\n : TCtx;\n\nexport interface ActionErrorDefinition {\n status?: number;\n message: string;\n}\n\nexport interface ValidationErrorItem {\n path: string;\n message: string;\n value?: unknown;\n type?: number;\n}\n\nexport class ValidationError extends Error {\n readonly status: number;\n readonly errors: ValidationErrorItem[];\n\n constructor(\n message: string,\n errors: ValidationErrorItem[] = [],\n status = 400,\n ) {\n super(message);\n this.name = \"ValidationError\";\n this.status = status;\n this.errors = errors;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n errors: this.errors,\n };\n }\n}\n\nexport class ActionExecutionError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(code: string, message: string, status = 400, details?: unknown) {\n super(message);\n this.name = \"ActionExecutionError\";\n this.code = code;\n this.status = status;\n this.details = details;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n details: this.details,\n };\n }\n}\n\nexport interface StandardErrorMap {\n BAD_REQUEST: (overrideMessage?: string, details?: unknown) => never;\n UNAUTHORIZED: (overrideMessage?: string, details?: unknown) => never;\n FORBIDDEN: (overrideMessage?: string, details?: unknown) => never;\n NOT_FOUND: (overrideMessage?: string, details?: unknown) => never;\n CONFLICT: (overrideMessage?: string, details?: unknown) => never;\n INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown) => never;\n [key: string]:\n | ((overrideMessage?: string, details?: unknown) => never)\n | undefined;\n}\n\nexport type ErrorBuilder<\n TErrors extends Record<string, ActionErrorDefinition>,\n> = StandardErrorMap & {\n [K in keyof TErrors]: (overrideMessage?: string, details?: unknown) => never;\n};\n\nexport interface BaseActionConfig<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n> {\n name: string;\n description?: string;\n /** Effective HTTP path, including the prefix; replaces the default action path. */\n path?: string;\n /** Single HTTP method exposed for this action (default POST). */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n input?: TInputSchema;\n output?: TOutputSchema;\n errors?: TErrors;\n emits?: string[];\n tags?: string[];\n}\n\nexport interface ActionConfigWithAuthorize<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {\n authorize: (params: {\n user?: TContext extends { user: infer U } ? U : any;\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n }) => boolean | Promise<boolean>;\n execute: (params: {\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: NarrowAuthorizedContext<TContext>;\n error: ErrorBuilder<TErrors>;\n }) =>\n | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>\n | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);\n}\n\nexport interface ActionConfigWithoutAuthorize<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {\n authorize?: undefined;\n execute: (params: {\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n error: ErrorBuilder<TErrors>;\n }) =>\n | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>\n | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);\n}\n\nexport type ActionConfig<\n TInputSchema extends TSchema | undefined = any,\n TOutputSchema extends TSchema | undefined = any,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> =\n | ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>\n | ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >;\n\nexport interface Action<\n TInputSchema extends TSchema | undefined = any,\n TOutputSchema extends TSchema | undefined = any,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> {\n (params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx?: Partial<TContext>;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n\n name: string;\n serviceName?: string;\n config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;\n /**\n * Optional runtime-only output schema. When present, `validateOutput` and\n * HTTP output checking validate against it instead of `config.output`,\n * while `config.output` remains the published contract (client types,\n * OpenAPI). Lets projected/subset responses validate at runtime without\n * leaking optionality into the generated contract.\n */\n outputValidationSchema?: TSchema;\n run(\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any,\n ctx?: Partial<TContext>,\n ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n execute(params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx?: Partial<TContext>;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n executeResolved?(params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n validateInput(\n input: unknown,\n ):\n | { success: true; data: any }\n | { success: false; errors: ValidationErrorItem[] };\n validateOutput(\n output: unknown,\n ):\n | { success: true; data: any }\n | { success: false; errors: ValidationErrorItem[] };\n errorHelpers?: ErrorBuilder<TErrors>;\n}\n\n/** MCP tool metadata, kept with the executable definition. */\nexport interface ToolAnnotations {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\nexport interface ToolOptions {\n title?: string;\n annotations?: ToolAnnotations;\n /** Also register HTTP routes and OpenAPI. Defaults to false. */\n http?: boolean;\n}\nexport type ToolConfigWithAuthorize<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> = ActionConfigWithAuthorize<I, O, E, C> & ToolOptions;\nexport type ToolConfigWithoutAuthorize<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> = ActionConfigWithoutAuthorize<I, O, E, C> & ToolOptions;\nexport interface Tool<\n I extends TSchema | undefined = any,\n O extends TSchema | undefined = any,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> extends Action<I, O, E, C> {\n readonly kind: \"tool\";\n config:\n | ToolConfigWithAuthorize<I, O, E, C>\n | ToolConfigWithoutAuthorize<I, O, E, C>;\n}\n\n/** A resource declares identity and a table; plugins supply behavior. */\nexport interface ResourceConfig<TTable = any, _TCtx = any> {\n name: string;\n table: TTable;\n id?: import(\"drizzle-orm\").Column;\n}\n\nexport type InferTableRow<TTable> = TTable extends { $inferSelect: infer S }\n ? S\n : any;\nexport type InferTableInsert<TTable> = TTable extends { $inferInsert: infer S }\n ? S\n : any;\nexport type ResourceTypeOptions = Pick<ResourceConfig, \"name\" | \"id\">;\n\ntype PrimaryColumn<T> = T extends { _: { columns: infer C } }\n ? {\n [K in keyof C]: C[K] extends { _: { isPrimaryKey: true } } ? C[K] : never;\n }[keyof C]\n : import(\"drizzle-orm\").Column;\nexport type ResourceIdentity<T, O> = O & {\n id: O extends { id: infer I extends import(\"drizzle-orm\").Column }\n ? I\n : PrimaryColumn<T>;\n};\n\n/** Generic preparation declarations consumed by the application compiler. */\nexport interface PreparationContribution {\n readonly name: string;\n describe(): unknown;\n prepare(): void;\n}\n\nexport interface Resource<\n TTable = any,\n TCtx extends ActionContext = ActionContext,\n TOptions = {},\n> {\n use<\n P extends ResourcePlugin<\n Service<TCtx[\"db\"], Omit<TCtx, keyof BaseContext>>,\n this,\n any\n >,\n >(\n plugin: P,\n ): this & import(\"./plugin\").ResourcePluginAPI<P, TTable, TCtx, this>;\n readonly name: string;\n readonly serviceName: string;\n readonly table: TTable;\n readonly id: TOptions extends {\n id: infer I extends import(\"drizzle-orm\").Column;\n }\n ? I\n : import(\"drizzle-orm\").Column;\n readonly idField: string;\n readonly config: ResourceConfig<TTable, TCtx> & TOptions;\n}\n\nexport interface ServiceAuthOptions {\n requireAuth?: boolean;\n allowedRoles?: string[];\n policy?: (ctx: ActionContext) => boolean | Promise<boolean>;\n}\n\nexport interface RateLimitOptions {\n maxRequests: number;\n window: number | string;\n scope?: \"ip\" | \"user\" | \"tenant\";\n}\n\nexport interface CacheOptions {\n driver?: \"memory\" | \"redis\";\n defaultTtl?: number;\n}\n\nexport interface ResilienceOptions {\n timeoutMs?: number;\n retry?: {\n attempts: number;\n backoff: \"linear\" | \"exponential\";\n delayMs: number;\n };\n circuitBreaker?: {\n errorThresholdPercentage: number;\n resetTimeoutMs: number;\n };\n}\n\nexport interface TelemetryOptions {\n traceQueries?: boolean;\n auditLog?: boolean;\n tags?: Record<string, string>;\n}\n\nexport interface LifecycleOptions {\n onInit?: (ctx: { db?: any; logger?: Logger }) => Promise<void>;\n onDestroy?: () => Promise<void>;\n}\n\nexport interface ServiceOptions<\n TServiceContext extends Record<string, any> = Record<string, any>,\n TDb = any,\n> {\n database?: DatabaseHandle<TDb>;\n context?: (\n baseCtx: BaseContext<TDb>,\n ) => Promise<TServiceContext> | TServiceContext;\n auth?: ServiceAuthOptions;\n rateLimit?: RateLimitOptions;\n cache?: CacheOptions;\n resilience?: ResilienceOptions;\n telemetry?: TelemetryOptions;\n lifecycle?: LifecycleOptions;\n}\n\nexport interface ActionSchema {\n name: string;\n serviceName?: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n hasAuthorize: boolean;\n errors?: Record<string, ActionErrorDefinition>;\n emits?: string[];\n tags?: string[];\n}\n\nexport interface ServiceSchema {\n name: string;\n options: Omit<ServiceOptions, \"database\"> & {\n database?: {\n name?: string;\n engine: \"sqlite\" | \"postgres\";\n tables: string[];\n };\n };\n hasDatabase: boolean;\n databaseConfig?: {\n name?: string;\n engine: \"sqlite\" | \"postgres\";\n tables: string[];\n };\n actions: ActionSchema[];\n resources?: { name: string }[];\n}\n\nexport interface ArchitectureSchema {\n version: string;\n services: ServiceSchema[];\n}\n\nexport interface CompiledRoutePlan {\n service: Service<any, any>;\n action: Action<any, any, any, any>;\n actionName: string;\n serviceName: string;\n routePath: string;\n method?: string;\n isGetLike: boolean;\n hasInput: boolean;\n hasContextHook: boolean;\n contextHook?: (baseCtx: any) => Promise<any> | any;\n hasAuthorize: boolean;\n authorize?: (params: any) => boolean | Promise<boolean>;\n execute: (params: any) => Promise<any> | any;\n inputChecker?: {\n Check: (val: any) => boolean;\n Errors: (val: any) => Iterable<any>;\n };\n outputChecker?: {\n Check: (val: any) => boolean;\n Errors: (val: any) => Iterable<any>;\n };\n coercions?: Array<{ key: string; isNumber: boolean; isBoolean: boolean }>;\n logger: Logger;\n errorBuilder: any;\n cachedDb: any;\n}\n\nexport interface Service<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> {\n readonly name: string;\n readonly options: ServiceOptions<TServiceContext, TDb>;\n readonly actions: Map<string, Action<any, any, any, any>>;\n readonly tools: Map<string, Tool<any, any, any, any>>;\n readonly tables: Map<string, any>;\n readonly resources: Map<\n string,\n Resource<any, BaseContext<TDb> & TServiceContext>\n >;\n readonly db?: TDb;\n readonly isBuilt?: boolean;\n\n use<A>(plugin: ServicePlugin<this, A>): A;\n\n build(): this;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>,\n ): this;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>,\n ): this;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n resource<\n TTable = any,\n const TOptions extends ResourceTypeOptions = ResourceTypeOptions,\n >(\n config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> &\n TOptions &\n Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>,\n ): Resource<\n TTable,\n BaseContext<TDb> & TServiceContext,\n ResourceIdentity<TTable, TOptions>\n >;\n\n readonly preparations: Map<string, PreparationContribution>;\n contributePreparation(contribution: PreparationContribution): void;\n listPreparations(): PreparationContribution[];\n prepareContributions(): void;\n registerTable(table: any): this;\n getAction(name: string): Action<any, any, any, any> | undefined;\n listActions(): Action<any, any, any, any>[];\n getTool(name: string): Tool<any, any, any, any> | undefined;\n listTools(): Tool<any, any, any, any>[];\n getResource(\n name: string,\n ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;\n listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];\n getDb(): TDb | undefined;\n setDb(database: DatabaseHandle<TDb>): void;\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n ): Promise<BaseContext<TDb> & TServiceContext>;\n introspect(): ServiceSchema;\n}\n\nexport interface ProxyOptions {\n isMonolith?: boolean;\n context?: Partial<ActionContext>;\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport type { Action, ActionErrorDefinition } from \"./types\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\n\n/**\n * Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.\n *\n * The frontend imports only the contract *type* — never a backend implementation:\n *\n * ```ts\n * import { createBrickClient } from \"@brickkit/core/client\";\n * import type { AppServer } from \"./server\"; // `import type`: erased at build\n *\n * const api = createBrickClient<AppServer>({ baseUrl: \"http://localhost:4000\" });\n * const pages = await api.page.list({ limit: 10, sort: \"-createdAt\" });\n * const created = await api.page.create({ title: \"Hello\", content: \"World\" });\n * ```\n *\n * Build the contract from individually-typed actions (each `defineAction` call\n * preserves its input/output/error literal types):\n *\n * ```ts\n * // server.ts (backend)\n * export const listPages = pagesService.action({ name: \"page.list\", ... });\n * export const createPage = pagesService.action({ name: \"page.create\", ... });\n * export const contract = { page: { list: listPages, create: createPage } };\n * export type AppServer = typeof contract;\n * ```\n *\n * ## Result / error convention\n *\n * The client uses a throw-based convention that mirrors local `action.execute`\n * semantics, because TypeScript promises cannot encode thrown exception types:\n *\n * - Success → the promise resolves with the action output.\n * - Declared domain failures (your `errors: { SLUG_EXISTS: ... }`) and framework\n * guards (UNAUTHORIZED/FORBIDDEN/NOT_FOUND/...) → rejected with\n * {@link ActionExecutionError} carrying the declared `code`, `status`,\n * `message`, and `details`. Narrow with `instanceof` and read `err.code`.\n * - Input/output validation failures → rejected with {@link ValidationError},\n * exactly as local execution throws.\n * - Network failures, unparsable bodies, and non-OK responses outside the\n * declared contract → {@link BrickTransportError} (4xx) or\n * {@link BrickServerError} (5xx).\n * - Cancellation via `AbortSignal` → the native `AbortError` propagates\n * unwrapped so `err.name === \"AbortError\"` keeps working.\n *\n * ## URL mapping\n *\n * A client path is a namespace walk ending in an action call. The leaf segment\n * decides the route, matching the server compiler (`packages/cli/src/compiler`):\n *\n * | Client call | HTTP request |\n * |---|---|\n * Generated browser contracts carry each action's HTTP method and path,\n * including plugin routes and consumer overrides. Without runtime metadata,\n * callers use `POST /api/<service>/<action>` with dotted action names.\n * GET/DELETE input is serialized as a query string; other methods send JSON.\n\n */\n\nexport interface BrickClientOptions {\n /** Server origin, e.g. `\"http://localhost:4000\"`. No trailing slash required. */\n baseUrl: string;\n /**\n * Route prefix the server was mounted with (default `\"/api\"`).\n * Must match the `prefix` passed to `brick({ prefix })`.\n */\n prefix?: string;\n /**\n * Default headers sent with every call (e.g. an `Authorization` bearer).\n * A thunk is re-evaluated per call, so rotated tokens stay fresh.\n */\n headers?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n /** `fetch` implementation. Defaults to `globalThis.fetch`. */\n fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n /** Default signal applied to every call (per-call `signal` wins). */\n signal?: AbortSignal;\n /** Default per-call timeout in milliseconds (per-call `timeoutMs` wins). */\n timeoutMs?: number;\n /**\n * Browser-safe route metadata generated by the Brick Vite plugin.\n * Required for custom methods/paths and plugin routes. Without a contract,\n * calls use POST and service/action names inferred from namespace keys.\n */\n contract?: Record<string, any>;\n}\n\n/** Browser-safe action metadata generated by the Brick Vite plugin. */\nexport interface BrickClientAction<\n TInput = unknown,\n TOutput = unknown,\n TErrors = {},\n> {\n kind: \"action\";\n name: string;\n serviceName: string;\n config: { path: string; method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" };\n /** Type information only; never emitted at runtime. */\n readonly __types?: { input: TInput; output: TOutput; errors: TErrors };\n}\n\nexport interface BrickCallOptions {\n /** Extra headers merged over the client defaults for this call only. */\n headers?: Record<string, string>;\n /** Abort signal for this call only. Never wrapped: aborts reject with `AbortError`. */\n signal?: AbortSignal;\n /** Per-call timeout in milliseconds. Implemented with `AbortSignal.timeout`. */\n timeoutMs?: number;\n}\n\n/**\n * The request never received a meaningful server answer: DNS / connection\n * failure, a malformed body, or a 4xx response outside the declared contract\n * (no `code` and no `ValidationError` shape).\n */\nexport class BrickTransportError extends Error {\n readonly kind = \"transport\" as const;\n readonly status?: number;\n readonly url: string;\n readonly body?: unknown;\n override readonly cause?: unknown;\n\n constructor(\n message: string,\n opts: { status?: number; url: string; body?: unknown; cause?: unknown },\n ) {\n super(message);\n this.name = \"BrickTransportError\";\n this.status = opts.status;\n this.url = opts.url;\n this.body = opts.body;\n this.cause = opts.cause;\n }\n}\n\n/**\n * The server answered 5xx without a declared `code` / `ValidationError` shape,\n * i.e. an unexpected failure rather than a modelled domain error.\n */\nexport class BrickServerError extends Error {\n readonly kind = \"server\" as const;\n readonly status: number;\n readonly url: string;\n readonly body: unknown;\n\n constructor(\n message: string,\n opts: { status: number; url: string; body: unknown },\n ) {\n super(message);\n this.name = \"BrickServerError\";\n this.status = opts.status;\n this.url = opts.url;\n this.body = opts.body;\n }\n}\n\nexport function isBrickTransportError(\n err: unknown,\n): err is BrickTransportError {\n return err instanceof BrickTransportError;\n}\n\nexport function isBrickServerError(err: unknown): err is BrickServerError {\n return err instanceof BrickServerError;\n}\n\n/** Static input type from the schema, with a fallback for structural actions. */\nexport type InferActionInput<A> =\n A extends BrickClientAction<infer I, any, any>\n ? I\n : A extends {\n config: { input?: infer S extends TSchema };\n }\n ? Static<S>\n : A extends {\n execute(params: { input?: infer I; ctx?: any }): any;\n }\n ? I\n : A extends { run(input?: infer I, ctx?: any): any }\n ? I\n : A extends (params: { input?: infer I; ctx?: any }) => any\n ? I\n : unknown;\n\n/** Resolved output type of an action. */\nexport type InferActionOutput<A> =\n A extends BrickClientAction<any, infer O, any>\n ? O\n : A extends (...args: any[]) => Promise<infer O>\n ? O\n : A extends { execute(params: any): Promise<infer O> }\n ? O\n : unknown;\n\n/** Union of error `code`s declared in an action's `errors` map. */\nexport type InferActionErrorCodes<A> =\n A extends BrickClientAction<any, any, infer E>\n ? Extract<keyof E, string>\n : A extends {\n config: { errors?: infer E };\n }\n ? E extends Record<string, ActionErrorDefinition>\n ? Extract<keyof E, string>\n : never\n : never;\n\n/**\n * The declared failure shape of an action for `catch` narrowing:\n * ```ts\n * try { await api.page.create(input); }\n * catch (err) {\n * if (err instanceof ActionExecutionError) {\n * const code: InferActionErrorCodes<typeof createPage> | \"UNAUTHORIZED\" | ... = err.code;\n * }\n * }\n * ```\n * (Standard framework codes are always possible alongside declared ones.)\n */\nexport type InferActionFailure<A> = ActionExecutionError & {\n code:\n | InferActionErrorCodes<A>\n | \"BAD_REQUEST\"\n | \"UNAUTHORIZED\"\n | \"FORBIDDEN\"\n | \"NOT_FOUND\"\n | \"CONFLICT\"\n | \"INTERNAL_SERVER_ERROR\"\n | \"VALIDATION_ERROR\";\n};\n\n/**\n * Typed caller for one action. Required inputs stay required; actions whose\n * input includes `undefined` (no schema / all-optional) can be called bare.\n */\nexport type BrickActionCaller<A> =\n undefined extends InferActionInput<A>\n ? (\n input?: InferActionInput<A>,\n options?: BrickCallOptions,\n ) => Promise<InferActionOutput<A>>\n : (\n input: InferActionInput<A>,\n options?: BrickCallOptions,\n ) => Promise<InferActionOutput<A>>;\n\n/** Recursively maps action leaves and their namespaces to browser callers. */\nexport type BrickClient<T> = T extends\n | BrickClientAction<any, any, any>\n | Action<any, any, any, any>\n ? BrickActionCaller<T>\n : T extends (...args: any[]) => any\n ? BrickActionCaller<T>\n : T extends object\n ? { [K in keyof T]: BrickClient<T[K]> }\n : T;\n\ninterface ResolvedClientOptions {\n baseUrl: string;\n prefix: string;\n headers?: BrickClientOptions[\"headers\"];\n fetch: NonNullable<BrickClientOptions[\"fetch\"]>;\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/+$/, \"\");\n if (!trimmed)\n throw new Error(\"[Brick-TS client] `baseUrl` must not be empty.\");\n return trimmed;\n}\n\nfunction normalizePrefix(prefix: string | undefined): string {\n if (!prefix) return \"/api\";\n const withLeading = prefix.startsWith(\"/\") ? prefix : `/${prefix}`;\n return withLeading.length > 1 ? withLeading.replace(/\\/+$/, \"\") : withLeading;\n}\n\nfunction toQueryString(input: unknown): string {\n if (input == null || typeof input !== \"object\") return \"\";\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item === undefined || item === null) continue;\n params.append(\n key,\n typeof item === \"object\" ? JSON.stringify(item) : String(item),\n );\n }\n } else if (typeof value === \"object\") {\n params.append(key, JSON.stringify(value));\n } else {\n params.append(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\ninterface PlannedRequest {\n method: string;\n url: string;\n body: unknown;\n hasBody: boolean;\n}\n\nfunction isActionValue(value: unknown): value is {\n serviceName?: unknown;\n name?: unknown;\n config: Action<any, any, any, any>[\"config\"];\n} & Function {\n return (\n typeof value === \"function\" &&\n !!(value as any).config &&\n typeof (value as any).config.execute === \"function\"\n );\n}\n\nfunction isClientAction(value: unknown): value is BrickClientAction {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as BrickClientAction).kind === \"action\"\n );\n}\n\nfunction planRequest(\n path: string[],\n /** Runtime contract value at `path`, when the `contract` option is set. */\n target: unknown,\n input: unknown,\n baseUrl: string,\n prefix: string,\n): PlannedRequest {\n if (path.length === 0) {\n throw new Error(\n \"[Brick-TS client] No action selected: call a leaf such as `api.page.list(input)`.\",\n );\n }\n const actionTarget =\n isActionValue(target) || isClientAction(target) ? target : undefined;\n const actionConfig = actionTarget?.config;\n if (path.length < 2) {\n throw new Error(\n `[Brick-TS client] Cannot address '${path.join(\".\")}': custom actions need a service segment, e.g. \\`api.${path[0]}.<action>(input)\\`.`,\n );\n }\n // Exact mode: the runtime contract reveals the bound service/action names,\n // so contract keys can differ from backend names.\n const service =\n typeof actionTarget?.serviceName === \"string\" && actionTarget.serviceName\n ? actionTarget.serviceName\n : path[0]!;\n const action =\n typeof actionTarget?.name === \"string\" && actionTarget.name\n ? actionTarget.name\n : path.slice(1).join(\".\");\n const method = actionConfig?.method ?? \"POST\";\n const configuredPath = actionConfig?.path;\n let actionPath =\n configuredPath ??\n `${prefix}/${encodeURIComponent(service)}/${action.split(\".\").map(encodeURIComponent).join(\".\")}`;\n let remaining = input;\n if (configuredPath !== undefined) {\n if (!configuredPath.startsWith(\"/\")) {\n throw new Error(\"[Brick-TS client] Action paths must start with '/'.\");\n }\n const source = { ...((input ?? {}) as Record<string, unknown>) };\n const record = { ...source };\n actionPath = actionPath.replace(/:([^/]+)/g, (_match, key: string) => {\n const value = Object.hasOwn(source, key) ? source[key] : undefined;\n if (value === undefined || value === null || value === \"\") {\n throw new Error(`[Brick-TS client] Missing path parameter '${key}'.`);\n }\n delete record[key];\n return encodeURIComponent(String(value));\n });\n remaining = input === undefined ? undefined : record;\n }\n const queryOnly = method === \"GET\" || method === \"DELETE\";\n return {\n method,\n url: `${baseUrl}${actionPath}${queryOnly ? toQueryString(remaining) : \"\"}`,\n body: queryOnly ? undefined : remaining,\n hasBody: !queryOnly && remaining !== undefined,\n };\n}\n\nfunction toActionError(status: number, body: unknown, url: string): Error {\n if (body !== null && typeof body === \"object\") {\n const record = body as Record<string, unknown>;\n if (typeof record.code === \"string\") {\n return new ActionExecutionError(\n record.code,\n typeof record.message === \"string\" ? record.message : record.code,\n typeof record.status === \"number\" ? record.status : status,\n (record.details ?? undefined) as unknown,\n );\n }\n if (record.name === \"ValidationError\") {\n return new ValidationError(\n typeof record.message === \"string\"\n ? record.message\n : \"Validation failed\",\n Array.isArray(record.errors) ? (record.errors as any) : [],\n typeof record.status === \"number\" ? record.status : status,\n );\n }\n }\n if (status >= 500) {\n return new BrickServerError(\n `Unexpected server error (status ${status}) for ${url}.`,\n {\n status,\n url,\n body,\n },\n );\n }\n return new BrickTransportError(\n `Request failed with status ${status} for ${url}.`,\n {\n status,\n url,\n body,\n },\n );\n}\n\nasync function dispatch(\n resolved: ResolvedClientOptions,\n path: string[],\n target: unknown,\n input: unknown,\n callOptions: BrickCallOptions | undefined,\n): Promise<unknown> {\n const { method, url, body, hasBody } = planRequest(\n path,\n target,\n input,\n resolved.baseUrl,\n resolved.prefix,\n );\n\n const staticHeaders =\n typeof resolved.headers === \"function\"\n ? await resolved.headers()\n : (resolved.headers ?? {});\n const headers: Record<string, string> = {\n accept: \"application/json\",\n ...staticHeaders,\n ...callOptions?.headers,\n };\n let payload: string | undefined;\n if (hasBody) {\n headers[\"content-type\"] = \"application/json\";\n payload = JSON.stringify(body ?? null);\n }\n\n const timeoutMs = callOptions?.timeoutMs ?? resolved.timeoutMs;\n let timeoutSignal: AbortSignal | undefined;\n if (timeoutMs !== undefined) timeoutSignal = AbortSignal.timeout(timeoutMs);\n const signal = callOptions?.signal ?? timeoutSignal ?? resolved.signal;\n\n let response: Response;\n try {\n response = await resolved.fetch(url, {\n method,\n headers,\n body: payload,\n signal,\n });\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") throw err;\n throw new BrickTransportError(\n `Network request failed for ${url}: ${err instanceof Error ? err.message : String(err)}`,\n { url, cause: err },\n );\n }\n\n let parsed: unknown;\n const text = await response.text();\n if (response.headers.get(\"content-type\")?.includes(\"text/plain\")) {\n parsed = text;\n } else if (text) {\n try {\n parsed = JSON.parse(text);\n } catch (err) {\n if (!response.headers.has(\"content-type\")) {\n parsed = text;\n } else {\n throw new BrickTransportError(`Unparsable response body for ${url}.`, {\n status: response.status,\n url,\n cause: err,\n });\n }\n }\n }\n\n if (response.ok) return parsed;\n throw toActionError(response.status, parsed, url);\n}\n\nfunction childNode(node: unknown, prop: string): unknown {\n if (\n node != null &&\n (typeof node === \"object\" || typeof node === \"function\")\n ) {\n return (node as Record<string, unknown>)[prop];\n }\n return undefined;\n}\n\nfunction createNamespace(\n resolved: ResolvedClientOptions,\n path: string[],\n node: unknown,\n): any {\n const callable = async (input?: unknown, options?: BrickCallOptions) =>\n dispatch(resolved, path, node, input, options);\n return new Proxy(callable, {\n get(target, prop, receiver) {\n if (typeof prop !== \"string\") return Reflect.get(target, prop, receiver);\n // Never masquerade as a thenable: awaiting a namespace must not dispatch.\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\")\n return undefined;\n return createNamespace(resolved, [...path, prop], childNode(node, prop));\n },\n apply(_target, _thisArg, args: unknown[]) {\n const [input, options] = args as [unknown, BrickCallOptions | undefined];\n return dispatch(resolved, path, node, input, options);\n },\n });\n}\n\n/**\n * Create an Eden/tRPC-style typed client for the application contract `TApp`.\n * `TApp` is a type-only parameter: `import type { AppServer }` keeps backend\n * implementations out of the frontend bundle.\n */\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions & { contract: TApp },\n): BrickClient<TApp>;\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions,\n): BrickClient<TApp>;\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions,\n): BrickClient<TApp> {\n if (!options?.baseUrl)\n throw new Error(\n '[Brick-TS client] `baseUrl` is required, e.g. `{ baseUrl: \"http://localhost:4000\" }`.',\n );\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\n \"[Brick-TS client] No `fetch` implementation available: pass `fetch` explicitly.\",\n );\n }\n const resolved: ResolvedClientOptions = {\n baseUrl: normalizeBaseUrl(options.baseUrl),\n prefix: normalizePrefix(options.prefix),\n headers: options.headers,\n fetch: fetchImpl,\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n };\n return createNamespace(resolved, [], options.contract) as BrickClient<TApp>;\n}\n"],"mappings":";AAgEA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CAEA,YACE,SACA,SAAgC,CAAC,GACjC,SAAS,KACT;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,SAAS;CAChB;CAEA,SAAS;EACP,OAAO;GACL,MAAM,KAAK;GACX,SAAS,KAAK;GACd,QAAQ,KAAK;GACb,QAAQ,KAAK;EACf;CACF;AACF;AAEA,IAAa,uBAAb,cAA0C,MAAM;CAC9C;CACA;CACA;CAEA,YAAY,MAAc,SAAiB,SAAS,KAAK,SAAmB;EAC1E,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,UAAU;CACjB;CAEA,SAAS;EACP,OAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,SAAS,KAAK;GACd,QAAQ,KAAK;GACb,SAAS,KAAK;EAChB;CACF;AACF;;;;;;;;ACOA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,OAAgB;CAChB;CACA;CACA;CACA;CAEA,YACE,SACA,MACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS,KAAK;EACnB,KAAK,MAAM,KAAK;EAChB,KAAK,OAAO,KAAK;EACjB,KAAK,QAAQ,KAAK;CACpB;AACF;;;;;AAMA,IAAa,mBAAb,cAAsC,MAAM;C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AAM,UAAU;GAC1B,IAAI,OAAO,SAAS,UAAU,OAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;GAEvE,IAAI,SAAS,UAAU,SAAS,WAAW,SAAS,WAClD,OAAO,KAAA;GACT,OAAO,gBAAgB,UAAU,CAAC,GAAG,MAAM,IAAI,GAAG,UAAU,MAAM,IAAI,CAAC;EACzE;EACA,MAAM,SAAS,UAAU,MAAiB;GACxC,MAAM,CAAC,OAAO,WAAW;GACzB,OAAO,SAAS,UAAU,MAAM,MAAM,OAAO,OAAO;EACtD;CACF,CAAC;AACH;AAaA,SAAgB,kBACd,SACmB;CACnB,IAAI,CAAC,SAAS,SACZ,MAAM,IAAI,MACR,yFACF;CACF,MAAM,YAAY,QAAQ,SAAS,WAAW;CAC9C,IAAI,OAAO,cAAc,YACvB,MAAM,IAAI,MACR,iFACF;CAUF,OAAO,gBAAgB;EAPrB,SAAS,iBAAiB,QAAQ,OAAO;EACzC,QAAQ,gBAAgB,QAAQ,MAAM;EACtC,SAAS,QAAQ;EACjB,OAAO;EACP,QAAQ,QAAQ;EAChB,WAAW,QAAQ;CAES,GAAG,CAAC,GAAG,QAAQ,QAAQ;AACvD"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/types.ts","../../src/client.ts"],"sourcesContent":["import type { ServicePlugin, ResourcePlugin } from \"./plugin\";\nimport type { TSchema, Static } from \"@sinclair/typebox\";\nimport type { BunSQLiteDatabase } from \"./db/sqlite\";\nimport type { DatabaseHandle } from \"./db/define\";\n\nexport interface Logger {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n}\n\n/**\n * Base framework context supplied to all service resolvers and action executions.\n */\nexport interface BaseContext<TDb = any> {\n request: Request;\n db: TDb;\n logger: Logger;\n traceId: string;\n requestId?: string;\n services?: Record<string, any>;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Default fallback service context for untyped or simple services.\n */\nexport interface DefaultServiceContext {\n user?: any;\n session?: any;\n [key: string]: any;\n}\n\n/**\n * The combined execution context: BaseContext & TServiceContext.\n */\nexport type ActionContext<\n TDb = any,\n TServiceContext = DefaultServiceContext,\n> = BaseContext<TDb> & TServiceContext;\n\n/**\n * Type utility that automatically narrows ctx.user from User | null to User\n * in execute() when authorize() is declared on the action.\n */\nexport type NarrowAuthorizedContext<TCtx> = TCtx extends { user: infer U }\n ? [U] extends [null | undefined]\n ? TCtx\n : Omit<TCtx, \"user\"> & { user: NonNullable<U> }\n : TCtx;\n\nexport interface ActionErrorDefinition {\n status?: number;\n message: string;\n}\n\nexport interface ValidationErrorItem {\n path: string;\n message: string;\n value?: unknown;\n type?: number;\n}\n\nexport class ValidationError extends Error {\n readonly status: number;\n readonly errors: ValidationErrorItem[];\n\n constructor(\n message: string,\n errors: ValidationErrorItem[] = [],\n status = 400,\n ) {\n super(message);\n this.name = \"ValidationError\";\n this.status = status;\n this.errors = errors;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n errors: this.errors,\n };\n }\n}\n\nexport class ActionExecutionError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(code: string, message: string, status = 400, details?: unknown) {\n super(message);\n this.name = \"ActionExecutionError\";\n this.code = code;\n this.status = status;\n this.details = details;\n }\n\n toJSON() {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n details: this.details,\n };\n }\n}\n\nexport interface StandardErrorMap {\n BAD_REQUEST: (overrideMessage?: string, details?: unknown) => never;\n UNAUTHORIZED: (overrideMessage?: string, details?: unknown) => never;\n FORBIDDEN: (overrideMessage?: string, details?: unknown) => never;\n NOT_FOUND: (overrideMessage?: string, details?: unknown) => never;\n CONFLICT: (overrideMessage?: string, details?: unknown) => never;\n INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown) => never;\n [key: string]:\n | ((overrideMessage?: string, details?: unknown) => never)\n | undefined;\n}\n\nexport type ErrorBuilder<\n TErrors extends Record<string, ActionErrorDefinition>,\n> = StandardErrorMap & {\n [K in keyof TErrors]: (overrideMessage?: string, details?: unknown) => never;\n};\n\nexport interface BaseActionConfig<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n> {\n name: string;\n description?: string;\n /** Effective HTTP path, including the prefix; replaces the default action path. */\n path?: string;\n /** Single HTTP method exposed for this action (default POST). */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n input?: TInputSchema;\n output?: TOutputSchema;\n errors?: TErrors;\n emits?: string[];\n tags?: string[];\n}\n\nexport interface ActionConfigWithAuthorize<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {\n authorize: (params: {\n user?: TContext extends { user: infer U } ? U : any;\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n }) => boolean | Promise<boolean>;\n execute: (params: {\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: NarrowAuthorizedContext<TContext>;\n error: ErrorBuilder<TErrors>;\n }) =>\n | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>\n | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);\n}\n\nexport interface ActionConfigWithoutAuthorize<\n TInputSchema extends TSchema | undefined = undefined,\n TOutputSchema extends TSchema | undefined = undefined,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {\n authorize?: undefined;\n execute: (params: {\n input: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n error: ErrorBuilder<TErrors>;\n }) =>\n | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>\n | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);\n}\n\nexport type ActionConfig<\n TInputSchema extends TSchema | undefined = any,\n TOutputSchema extends TSchema | undefined = any,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> =\n | ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>\n | ActionConfigWithoutAuthorize<\n TInputSchema,\n TOutputSchema,\n TErrors,\n TContext\n >;\n\nexport interface Action<\n TInputSchema extends TSchema | undefined = any,\n TOutputSchema extends TSchema | undefined = any,\n TErrors extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n TContext extends ActionContext = ActionContext,\n> {\n (params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx?: Partial<TContext>;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n\n name: string;\n serviceName?: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;\n /**\n * Optional runtime-only output schema. When present, `validateOutput` and\n * HTTP output checking validate against it instead of `config.output`,\n * while `config.output` remains the published contract (client types,\n * OpenAPI). Lets projected/subset responses validate at runtime without\n * leaking optionality into the generated contract.\n */\n outputValidationSchema?: TSchema;\n run(\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any,\n ctx?: Partial<TContext>,\n ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n execute(params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx?: Partial<TContext>;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n executeResolved?(params: {\n input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;\n ctx: TContext;\n }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;\n validateInput(\n input: unknown,\n ):\n | { success: true; data: any }\n | { success: false; errors: ValidationErrorItem[] };\n validateOutput(\n output: unknown,\n ):\n | { success: true; data: any }\n | { success: false; errors: ValidationErrorItem[] };\n errorHelpers?: ErrorBuilder<TErrors>;\n}\n\n/** MCP tool metadata, kept with the executable definition. */\nexport interface ToolAnnotations {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\nexport interface ToolOptions {\n title?: string;\n annotations?: ToolAnnotations;\n /** Also register HTTP routes and OpenAPI. Defaults to false. */\n http?: boolean;\n}\nexport type ToolConfigWithAuthorize<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> = ActionConfigWithAuthorize<I, O, E, C> & ToolOptions;\nexport type ToolConfigWithoutAuthorize<\n I extends TSchema | undefined = undefined,\n O extends TSchema | undefined = undefined,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> = ActionConfigWithoutAuthorize<I, O, E, C> & ToolOptions;\nexport interface Tool<\n I extends TSchema | undefined = any,\n O extends TSchema | undefined = any,\n E extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n C extends ActionContext = ActionContext,\n> extends Action<I, O, E, C> {\n readonly kind: \"tool\";\n config:\n | ToolConfigWithAuthorize<I, O, E, C>\n | ToolConfigWithoutAuthorize<I, O, E, C>;\n}\n\n/** A resource declares identity and a table; plugins supply behavior. */\nexport interface ResourceConfig<TTable = any, _TCtx = any> {\n name: string;\n table: TTable;\n id?: import(\"drizzle-orm\").Column;\n}\n\nexport type InferTableRow<TTable> = TTable extends { $inferSelect: infer S }\n ? S\n : any;\nexport type InferTableInsert<TTable> = TTable extends { $inferInsert: infer S }\n ? S\n : any;\nexport type ResourceTypeOptions = Pick<ResourceConfig, \"name\" | \"id\">;\n\ntype PrimaryColumn<T> = T extends { _: { columns: infer C } }\n ? {\n [K in keyof C]: C[K] extends { _: { isPrimaryKey: true } } ? C[K] : never;\n }[keyof C]\n : import(\"drizzle-orm\").Column;\nexport type ResourceIdentity<T, O> = O & {\n id: O extends { id: infer I extends import(\"drizzle-orm\").Column }\n ? I\n : PrimaryColumn<T>;\n};\n\n/** Generic preparation declarations consumed by the application compiler. */\nexport interface PreparationContribution {\n readonly name: string;\n describe(): unknown;\n prepare(): void;\n}\n\nexport interface Resource<\n TTable = any,\n TCtx extends ActionContext = ActionContext,\n TOptions = {},\n> {\n use<\n P extends ResourcePlugin<\n Service<TCtx[\"db\"], Omit<TCtx, keyof BaseContext>>,\n this,\n any\n >,\n >(\n plugin: P,\n ): this & import(\"./plugin\").ResourcePluginAPI<P, TTable, TCtx, this>;\n readonly name: string;\n readonly serviceName: string;\n readonly table: TTable;\n readonly id: TOptions extends {\n id: infer I extends import(\"drizzle-orm\").Column;\n }\n ? I\n : import(\"drizzle-orm\").Column;\n readonly idField: string;\n readonly config: ResourceConfig<TTable, TCtx> & TOptions;\n}\n\nexport interface ServiceAuthOptions {\n requireAuth?: boolean;\n allowedRoles?: string[];\n policy?: (ctx: ActionContext) => boolean | Promise<boolean>;\n}\n\nexport interface RateLimitOptions {\n maxRequests: number;\n window: number | string;\n scope?: \"ip\" | \"user\" | \"tenant\";\n}\n\nexport interface CacheOptions {\n driver?: \"memory\" | \"redis\";\n defaultTtl?: number;\n}\n\nexport interface ResilienceOptions {\n timeoutMs?: number;\n retry?: {\n attempts: number;\n backoff: \"linear\" | \"exponential\";\n delayMs: number;\n };\n circuitBreaker?: {\n errorThresholdPercentage: number;\n resetTimeoutMs: number;\n };\n}\n\nexport interface TelemetryOptions {\n traceQueries?: boolean;\n auditLog?: boolean;\n tags?: Record<string, string>;\n}\n\nexport interface LifecycleOptions {\n onInit?: (ctx: { db?: any; logger?: Logger }) => Promise<void>;\n onDestroy?: () => Promise<void>;\n}\n\nexport interface ServiceOptions<\n TServiceContext extends Record<string, any> = Record<string, any>,\n TDb = any,\n> {\n database?: DatabaseHandle<TDb>;\n context?: (\n baseCtx: BaseContext<TDb>,\n ) => Promise<TServiceContext> | TServiceContext;\n auth?: ServiceAuthOptions;\n rateLimit?: RateLimitOptions;\n cache?: CacheOptions;\n resilience?: ResilienceOptions;\n telemetry?: TelemetryOptions;\n lifecycle?: LifecycleOptions;\n}\n\nexport type ActionAccessPolicy = \"public\" | \"authorized\" | \"scoped\";\n\nexport interface ActionSchema {\n name: string;\n /** Present only when this action has a registered HTTP route. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path?: string;\n serviceName?: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n hasAuthorize: boolean;\n hasScope?: boolean;\n accessPolicy?: ActionAccessPolicy;\n errors?: Record<string, ActionErrorDefinition>;\n emits?: string[];\n tags?: string[];\n}\n\nexport interface ServiceSchema {\n name: string;\n options: Omit<ServiceOptions, \"database\">;\n hasDatabase: boolean;\n databaseConfig?: {\n name?: string;\n engine: \"sqlite\" | \"postgres\";\n tables: string[];\n };\n actions: ActionSchema[];\n resources?: { name: string }[];\n}\n\nexport interface ArchitectureSchema {\n version: string;\n services: ServiceSchema[];\n}\n\nexport interface CompiledRoutePlan {\n service: Service<any, any>;\n action: Action<any, any, any, any>;\n actionName: string;\n serviceName: string;\n routePath: string;\n method?: string;\n isGetLike: boolean;\n hasInput: boolean;\n hasContextHook: boolean;\n contextHook?: (baseCtx: any) => Promise<any> | any;\n hasAuthorize: boolean;\n authorize?: (params: any) => boolean | Promise<boolean>;\n execute: (params: any) => Promise<any> | any;\n inputChecker?: {\n Check: (val: any) => boolean;\n Errors: (val: any) => Iterable<any>;\n };\n outputChecker?: {\n Check: (val: any) => boolean;\n Errors: (val: any) => Iterable<any>;\n };\n coercions?: Array<{ key: string; isNumber: boolean; isBoolean: boolean }>;\n logger: Logger;\n errorBuilder: any;\n cachedDb: any;\n}\n\nexport interface Service<\n TDb = BunSQLiteDatabase<Record<string, unknown>>,\n TServiceContext extends Record<string, any> = Record<string, any>,\n> {\n readonly name: string;\n readonly options: ServiceOptions<TServiceContext, TDb>;\n readonly actions: Map<string, Action<any, any, any, any>>;\n readonly tools: Map<string, Tool<any, any, any, any>>;\n readonly tables: Map<string, any>;\n readonly resources: Map<\n string,\n Resource<any, BaseContext<TDb> & TServiceContext>\n >;\n readonly db?: TDb;\n readonly isBuilt?: boolean;\n\n use<A>(plugin: ServicePlugin<this, A>): A;\n\n build(): this;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>,\n ): this;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n action<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ActionConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>,\n ): this;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n tool<\n TIn extends TSchema | undefined = undefined,\n TOut extends TSchema | undefined = undefined,\n TErr extends Record<string, ActionErrorDefinition> = Record<\n string,\n ActionErrorDefinition\n >,\n >(\n config: ToolConfigWithoutAuthorize<\n TIn,\n TOut,\n TErr,\n BaseContext<TDb> & TServiceContext\n >,\n ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;\n\n resource<\n TTable = any,\n const TOptions extends ResourceTypeOptions = ResourceTypeOptions,\n >(\n config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> &\n TOptions &\n Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>,\n ): Resource<\n TTable,\n BaseContext<TDb> & TServiceContext,\n ResourceIdentity<TTable, TOptions>\n >;\n\n readonly preparations: Map<string, PreparationContribution>;\n contributePreparation(contribution: PreparationContribution): void;\n listPreparations(): PreparationContribution[];\n prepareContributions(): void;\n registerTable(table: any): this;\n getAction(name: string): Action<any, any, any, any> | undefined;\n listActions(): Action<any, any, any, any>[];\n getTool(name: string): Tool<any, any, any, any> | undefined;\n listTools(): Tool<any, any, any, any>[];\n getResource(\n name: string,\n ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined;\n listResources(): Resource<any, BaseContext<TDb> & TServiceContext>[];\n getDb(): TDb | undefined;\n setDb(database: DatabaseHandle<TDb>): void;\n resolveContext(\n callCtx?: Partial<BaseContext<TDb> & TServiceContext>,\n ): Promise<BaseContext<TDb> & TServiceContext>;\n introspect(): ServiceSchema;\n}\n\nexport interface ProxyOptions {\n isMonolith?: boolean;\n context?: Partial<ActionContext>;\n}\n","import type { Static, TSchema } from \"@sinclair/typebox\";\nimport type { Action, ActionErrorDefinition } from \"./types\";\nimport { ActionExecutionError, ValidationError } from \"./types\";\n\n/**\n * Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.\n *\n * The frontend imports only the contract *type* — never a backend implementation:\n *\n * ```ts\n * import { createBrickClient } from \"@brickkit/core/client\";\n * import type { AppServer } from \"./server\"; // `import type`: erased at build\n *\n * const api = createBrickClient<AppServer>({ baseUrl: \"http://localhost:4000\" });\n * const pages = await api.page.list({ limit: 10, sort: \"-createdAt\" });\n * const created = await api.page.create({ title: \"Hello\", content: \"World\" });\n * ```\n *\n * Build the contract from individually-typed actions (each `defineAction` call\n * preserves its input/output/error literal types):\n *\n * ```ts\n * // server.ts (backend)\n * export const listPages = pagesService.action({ name: \"page.list\", ... });\n * export const createPage = pagesService.action({ name: \"page.create\", ... });\n * export const contract = { page: { list: listPages, create: createPage } };\n * export type AppServer = typeof contract;\n * ```\n *\n * ## Result / error convention\n *\n * The client uses a throw-based convention that mirrors local `action.execute`\n * semantics, because TypeScript promises cannot encode thrown exception types:\n *\n * - Success → the promise resolves with the action output.\n * - Declared domain failures (your `errors: { SLUG_EXISTS: ... }`) and framework\n * guards (UNAUTHORIZED/FORBIDDEN/NOT_FOUND/...) → rejected with\n * {@link ActionExecutionError} carrying the declared `code`, `status`,\n * `message`, and `details`. Narrow with `instanceof` and read `err.code`.\n * - Input/output validation failures → rejected with {@link ValidationError},\n * exactly as local execution throws.\n * - Network failures, unparsable bodies, and non-OK responses outside the\n * declared contract → {@link BrickTransportError} (4xx) or\n * {@link BrickServerError} (5xx).\n * - Cancellation via `AbortSignal` → the native `AbortError` propagates\n * unwrapped so `err.name === \"AbortError\"` keeps working.\n *\n * ## URL mapping\n *\n * A client path is a namespace walk ending in an action call. The leaf segment\n * decides the route, matching the server compiler (`packages/cli/src/compiler`):\n *\n * | Client call | HTTP request |\n * |---|---|\n * Generated browser contracts carry each action's HTTP method and path,\n * including plugin routes and consumer overrides. Without runtime metadata,\n * callers use `POST /api/<service>/<action>` with dotted action names.\n * GET/DELETE input is serialized as a query string; other methods send JSON.\n\n */\n\nexport interface BrickClientOptions {\n /** Server origin, e.g. `\"http://localhost:4000\"`. No trailing slash required. */\n baseUrl: string;\n /**\n * Route prefix the server was mounted with (default `\"/api\"`).\n * Must match the `prefix` passed to `brick({ prefix })`.\n */\n prefix?: string;\n /**\n * Default headers sent with every call (e.g. an `Authorization` bearer).\n * A thunk is re-evaluated per call, so rotated tokens stay fresh.\n */\n headers?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n /** `fetch` implementation. Defaults to `globalThis.fetch`. */\n fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n /** Default signal applied to every call (per-call `signal` wins). */\n signal?: AbortSignal;\n /** Default per-call timeout in milliseconds (per-call `timeoutMs` wins). */\n timeoutMs?: number;\n /**\n * Browser-safe route metadata generated by the Brick Vite plugin.\n * Required for custom methods/paths and plugin routes. Without a contract,\n * calls use POST and service/action names inferred from namespace keys.\n */\n contract?: Record<string, any>;\n}\n\n/** Browser-safe action metadata generated by the Brick Vite plugin. */\nexport interface BrickClientAction<\n TInput = unknown,\n TOutput = unknown,\n TErrors = {},\n> {\n kind: \"action\";\n name: string;\n serviceName: string;\n /** Owning plugin descriptor name for plugin actions (e.g. `@brickkit/crud`). */\n plugin?: string;\n /** Owning resource name for resource-plugin actions (e.g. `page`). */\n resource?: string;\n config: { path: string; method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" };\n /** Type information only; never emitted at runtime. */\n readonly __types?: { input: TInput; output: TOutput; errors: TErrors };\n}\n\nexport interface BrickCallOptions {\n /** Extra headers merged over the client defaults for this call only. */\n headers?: Record<string, string>;\n /** Abort signal for this call only. Never wrapped: aborts reject with `AbortError`. */\n signal?: AbortSignal;\n /** Per-call timeout in milliseconds. Implemented with `AbortSignal.timeout`. */\n timeoutMs?: number;\n}\n\n/**\n * The request never received a meaningful server answer: DNS / connection\n * failure, a malformed body, or a 4xx response outside the declared contract\n * (no `code` and no `ValidationError` shape).\n */\nexport class BrickTransportError extends Error {\n readonly kind = \"transport\" as const;\n readonly status?: number;\n readonly url: string;\n readonly body?: unknown;\n override readonly cause?: unknown;\n\n constructor(\n message: string,\n opts: { status?: number; url: string; body?: unknown; cause?: unknown },\n ) {\n super(message);\n this.name = \"BrickTransportError\";\n this.status = opts.status;\n this.url = opts.url;\n this.body = opts.body;\n this.cause = opts.cause;\n }\n}\n\n/**\n * The server answered 5xx without a declared `code` / `ValidationError` shape,\n * i.e. an unexpected failure rather than a modelled domain error.\n */\nexport class BrickServerError extends Error {\n readonly kind = \"server\" as const;\n readonly status: number;\n readonly url: string;\n readonly body: unknown;\n\n constructor(\n message: string,\n opts: { status: number; url: string; body: unknown },\n ) {\n super(message);\n this.name = \"BrickServerError\";\n this.status = opts.status;\n this.url = opts.url;\n this.body = opts.body;\n }\n}\n\nexport function isBrickTransportError(\n err: unknown,\n): err is BrickTransportError {\n return err instanceof BrickTransportError;\n}\n\nexport function isBrickServerError(err: unknown): err is BrickServerError {\n return err instanceof BrickServerError;\n}\n\n/** Static input type from the schema, with a fallback for structural actions. */\nexport type InferActionInput<A> =\n A extends BrickClientAction<infer I, any, any>\n ? I\n : A extends {\n config: { input?: infer S extends TSchema };\n }\n ? Static<S>\n : A extends {\n execute(params: { input?: infer I; ctx?: any }): any;\n }\n ? I\n : A extends { run(input?: infer I, ctx?: any): any }\n ? I\n : A extends (params: { input?: infer I; ctx?: any }) => any\n ? I\n : unknown;\n\n/** Resolved output type of an action. */\nexport type InferActionOutput<A> =\n A extends BrickClientAction<any, infer O, any>\n ? O\n : A extends (...args: any[]) => Promise<infer O>\n ? O\n : A extends { execute(params: any): Promise<infer O> }\n ? O\n : unknown;\n\n/** Union of error `code`s declared in an action's `errors` map. */\nexport type InferActionErrorCodes<A> =\n A extends BrickClientAction<any, any, infer E>\n ? Extract<keyof E, string>\n : A extends {\n config: { errors?: infer E };\n }\n ? E extends Record<string, ActionErrorDefinition>\n ? Extract<keyof E, string>\n : never\n : never;\n\n/**\n * The declared failure shape of an action for `catch` narrowing:\n * ```ts\n * try { await api.page.create(input); }\n * catch (err) {\n * if (err instanceof ActionExecutionError) {\n * const code: InferActionErrorCodes<typeof createPage> | \"UNAUTHORIZED\" | ... = err.code;\n * }\n * }\n * ```\n * (Standard framework codes are always possible alongside declared ones.)\n */\nexport type InferActionFailure<A> = ActionExecutionError & {\n code:\n | InferActionErrorCodes<A>\n | \"BAD_REQUEST\"\n | \"UNAUTHORIZED\"\n | \"FORBIDDEN\"\n | \"NOT_FOUND\"\n | \"CONFLICT\"\n | \"INTERNAL_SERVER_ERROR\"\n | \"VALIDATION_ERROR\";\n};\n\n/**\n * Typed caller for one action. Required inputs stay required; actions whose\n * input includes `undefined` (no schema / all-optional) can be called bare.\n */\nexport type BrickActionCaller<A> =\n undefined extends InferActionInput<A>\n ? (\n input?: InferActionInput<A>,\n options?: BrickCallOptions,\n ) => Promise<InferActionOutput<A>>\n : (\n input: InferActionInput<A>,\n options?: BrickCallOptions,\n ) => Promise<InferActionOutput<A>>;\n\n/** Recursively maps action leaves and their namespaces to browser callers. */\nexport type BrickClient<T> = T extends\n | BrickClientAction<any, any, any>\n | Action<any, any, any, any>\n ? BrickActionCaller<T>\n : T extends (...args: any[]) => any\n ? BrickActionCaller<T>\n : T extends object\n ? { [K in keyof T]: BrickClient<T[K]> }\n : T;\n\ninterface ResolvedClientOptions {\n baseUrl: string;\n prefix: string;\n headers?: BrickClientOptions[\"headers\"];\n fetch: NonNullable<BrickClientOptions[\"fetch\"]>;\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n const trimmed = baseUrl.replace(/\\/+$/, \"\");\n if (!trimmed)\n throw new Error(\"[Brick-TS client] `baseUrl` must not be empty.\");\n return trimmed;\n}\n\nfunction normalizePrefix(prefix: string | undefined): string {\n if (!prefix) return \"/api\";\n const withLeading = prefix.startsWith(\"/\") ? prefix : `/${prefix}`;\n return withLeading.length > 1 ? withLeading.replace(/\\/+$/, \"\") : withLeading;\n}\n\nfunction toQueryString(input: unknown): string {\n if (input == null || typeof input !== \"object\") return \"\";\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (value === undefined || value === null) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item === undefined || item === null) continue;\n params.append(\n key,\n typeof item === \"object\" ? JSON.stringify(item) : String(item),\n );\n }\n } else if (typeof value === \"object\") {\n params.append(key, JSON.stringify(value));\n } else {\n params.append(key, String(value));\n }\n }\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\ninterface PlannedRequest {\n method: string;\n url: string;\n body: unknown;\n hasBody: boolean;\n}\n\nfunction isActionValue(value: unknown): value is {\n serviceName?: unknown;\n name?: unknown;\n config: Action<any, any, any, any>[\"config\"];\n} & Function {\n return (\n typeof value === \"function\" &&\n !!(value as any).config &&\n typeof (value as any).config.execute === \"function\"\n );\n}\n\nfunction isClientAction(value: unknown): value is BrickClientAction {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as BrickClientAction).kind === \"action\"\n );\n}\n\nfunction planRequest(\n path: string[],\n /** Runtime contract value at `path`, when the `contract` option is set. */\n target: unknown,\n input: unknown,\n baseUrl: string,\n prefix: string,\n): PlannedRequest {\n if (path.length === 0) {\n throw new Error(\n \"[Brick-TS client] No action selected: call a leaf such as `api.page.list(input)`.\",\n );\n }\n const actionTarget =\n isActionValue(target) || isClientAction(target) ? target : undefined;\n const actionConfig = actionTarget?.config;\n if (path.length < 2) {\n throw new Error(\n `[Brick-TS client] Cannot address '${path.join(\".\")}': custom actions need a service segment, e.g. \\`api.${path[0]}.<action>(input)\\`.`,\n );\n }\n // Exact mode: the runtime contract reveals the bound service/action names,\n // so contract keys can differ from backend names.\n const service =\n typeof actionTarget?.serviceName === \"string\" && actionTarget.serviceName\n ? actionTarget.serviceName\n : path[0]!;\n const action =\n typeof actionTarget?.name === \"string\" && actionTarget.name\n ? actionTarget.name\n : path.slice(1).join(\".\");\n const method = actionConfig?.method ?? \"POST\";\n const configuredPath = actionConfig?.path;\n let actionPath =\n configuredPath ??\n `${prefix}/${encodeURIComponent(service)}/${action.split(\".\").map(encodeURIComponent).join(\".\")}`;\n let remaining = input;\n if (configuredPath !== undefined) {\n if (!configuredPath.startsWith(\"/\")) {\n throw new Error(\"[Brick-TS client] Action paths must start with '/'.\");\n }\n const source = { ...((input ?? {}) as Record<string, unknown>) };\n const record = { ...source };\n actionPath = actionPath.replace(/:([^/]+)/g, (_match, key: string) => {\n const value = Object.hasOwn(source, key) ? source[key] : undefined;\n if (value === undefined || value === null || value === \"\") {\n throw new Error(`[Brick-TS client] Missing path parameter '${key}'.`);\n }\n delete record[key];\n return encodeURIComponent(String(value));\n });\n remaining = input === undefined ? undefined : record;\n }\n const queryOnly = method === \"GET\" || method === \"DELETE\";\n return {\n method,\n url: `${baseUrl}${actionPath}${queryOnly ? toQueryString(remaining) : \"\"}`,\n body: queryOnly ? undefined : remaining,\n hasBody: !queryOnly && remaining !== undefined,\n };\n}\n\nfunction toActionError(status: number, body: unknown, url: string): Error {\n if (body !== null && typeof body === \"object\") {\n const record = body as Record<string, unknown>;\n if (typeof record.code === \"string\") {\n return new ActionExecutionError(\n record.code,\n typeof record.message === \"string\" ? record.message : record.code,\n typeof record.status === \"number\" ? record.status : status,\n (record.details ?? undefined) as unknown,\n );\n }\n if (record.name === \"ValidationError\") {\n return new ValidationError(\n typeof record.message === \"string\"\n ? record.message\n : \"Validation failed\",\n Array.isArray(record.errors) ? (record.errors as any) : [],\n typeof record.status === \"number\" ? record.status : status,\n );\n }\n }\n if (status >= 500) {\n return new BrickServerError(\n `Unexpected server error (status ${status}) for ${url}.`,\n {\n status,\n url,\n body,\n },\n );\n }\n return new BrickTransportError(\n `Request failed with status ${status} for ${url}.`,\n {\n status,\n url,\n body,\n },\n );\n}\n\nasync function dispatch(\n resolved: ResolvedClientOptions,\n path: string[],\n target: unknown,\n input: unknown,\n callOptions: BrickCallOptions | undefined,\n): Promise<unknown> {\n const { method, url, body, hasBody } = planRequest(\n path,\n target,\n input,\n resolved.baseUrl,\n resolved.prefix,\n );\n\n const staticHeaders =\n typeof resolved.headers === \"function\"\n ? await resolved.headers()\n : (resolved.headers ?? {});\n const headers: Record<string, string> = {\n accept: \"application/json\",\n ...staticHeaders,\n ...callOptions?.headers,\n };\n let payload: string | undefined;\n if (hasBody) {\n headers[\"content-type\"] = \"application/json\";\n payload = JSON.stringify(body ?? null);\n }\n\n const timeoutMs = callOptions?.timeoutMs ?? resolved.timeoutMs;\n let timeoutSignal: AbortSignal | undefined;\n if (timeoutMs !== undefined) timeoutSignal = AbortSignal.timeout(timeoutMs);\n const signal = callOptions?.signal ?? timeoutSignal ?? resolved.signal;\n\n let response: Response;\n try {\n response = await resolved.fetch(url, {\n method,\n headers,\n body: payload,\n signal,\n });\n } catch (err) {\n if (err instanceof Error && err.name === \"AbortError\") throw err;\n throw new BrickTransportError(\n `Network request failed for ${url}: ${err instanceof Error ? err.message : String(err)}`,\n { url, cause: err },\n );\n }\n\n let parsed: unknown;\n const text = await response.text();\n if (response.headers.get(\"content-type\")?.includes(\"text/plain\")) {\n parsed = text;\n } else if (text) {\n try {\n parsed = JSON.parse(text);\n } catch (err) {\n if (!response.headers.has(\"content-type\")) {\n parsed = text;\n } else {\n throw new BrickTransportError(`Unparsable response body for ${url}.`, {\n status: response.status,\n url,\n cause: err,\n });\n }\n }\n }\n\n if (response.ok) return parsed;\n throw toActionError(response.status, parsed, url);\n}\n\nfunction childNode(node: unknown, prop: string): unknown {\n if (\n node != null &&\n (typeof node === \"object\" || typeof node === \"function\")\n ) {\n return (node as Record<string, unknown>)[prop];\n }\n return undefined;\n}\n\nfunction createNamespace(\n resolved: ResolvedClientOptions,\n path: string[],\n node: unknown,\n): any {\n const callable = async (input?: unknown, options?: BrickCallOptions) =>\n dispatch(resolved, path, node, input, options);\n return new Proxy(callable, {\n get(target, prop, receiver) {\n if (typeof prop !== \"string\") return Reflect.get(target, prop, receiver);\n // Never masquerade as a thenable: awaiting a namespace must not dispatch.\n if (prop === \"then\" || prop === \"catch\" || prop === \"finally\")\n return undefined;\n return createNamespace(resolved, [...path, prop], childNode(node, prop));\n },\n apply(_target, _thisArg, args: unknown[]) {\n const [input, options] = args as [unknown, BrickCallOptions | undefined];\n return dispatch(resolved, path, node, input, options);\n },\n });\n}\n\n/**\n * Create an Eden/tRPC-style typed client for the application contract `TApp`.\n * `TApp` is a type-only parameter: `import type { AppServer }` keeps backend\n * implementations out of the frontend bundle.\n */\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions & { contract: TApp },\n): BrickClient<TApp>;\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions,\n): BrickClient<TApp>;\nexport function createBrickClient<TApp extends Record<string, any>>(\n options: BrickClientOptions,\n): BrickClient<TApp> {\n if (!options?.baseUrl)\n throw new Error(\n '[Brick-TS client] `baseUrl` is required, e.g. `{ baseUrl: \"http://localhost:4000\" }`.',\n );\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\n \"[Brick-TS client] No `fetch` implementation available: pass `fetch` explicitly.\",\n );\n }\n const resolved: ResolvedClientOptions = {\n baseUrl: normalizeBaseUrl(options.baseUrl),\n prefix: normalizePrefix(options.prefix),\n headers: options.headers,\n fetch: fetchImpl,\n signal: options.signal,\n timeoutMs: options.timeoutMs,\n };\n return createNamespace(resolved, [], options.contract) as BrickClient<TApp>;\n}\n"],"mappings":";AAgEA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CAEA,YACE,SACA,SAAgC,CAAC,GACjC,SAAS,KACT;EACA,MAAM,OAAO;EACb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AAI,OAAO,cAAc,YACvB,MAAM,IAAI,MACR,iFACF;CAUF,OAAO,gBAAgB;EAPrB,SAAS,iBAAiB,QAAQ,OAAO;EACzC,QAAQ,gBAAgB,QAAQ,MAAM;EACtC,SAAS,QAAQ;EACjB,OAAO;EACP,QAAQ,QAAQ;EAChB,WAAW,QAAQ;CAES,GAAG,CAAC,GAAG,QAAQ,QAAQ;AACvD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,43 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as ToolConfigWithoutAuthorize, A as ErrorBuilder, At as index, B as Resource, Bt as PluginRouteScope, C as ActionSchema, Ct as secret, D as CacheOptions, Dt as blob, E as BaseContext, Et as SQLiteDatabaseConfig, F as NarrowAuthorizedContext, Ft as text, G as ServiceAuthOptions, Gt as ResourcePluginTypes, H as ResourceIdentity, Ht as ResourcePlugin, I as PreparationContribution, It as uniqueIndex, J as StandardErrorMap, Jt as defineResourcePlugin, K as ServiceOptions, Kt as ServicePlugin, L as ProxyOptions, Lt as PluginEndpointContext, M as InferTableRow, Mt as primaryKey, N as LifecycleOptions, Nt as real, O as CompiledRoutePlan, Ot as createSQLiteDatabase, P as Logger, Pt as sqliteTable, Q as ToolConfigWithAuthorize, R as RateLimitOptions, Rt as PluginRouteMethod, S as ActionExecutionError, St as resolveSecrets, T as BaseActionConfig, Tt as BunSQLiteDatabase, U as ResourceTypeOptions, Ut as ResourcePluginAPI, V as ResourceConfig, Vt as PluginRoutes, W as Service, Wt as ResourcePluginContext, X as Tool, Xt as getPluginActionRoute, Y as TelemetryOptions, Yt as defineServicePlugin, Z as ToolAnnotations, Zt as getPluginEndpoints, _ as ActionConfig, _t as envSource, a as BrickClientOptions, at as EnvInput, b as ActionContext, bt as overrideSecrets, c as InferActionErrorCodes, ct as defineDatabase, d as InferActionOutput, dt as PostgresDatabase, et as ToolOptions, f as createBrickClient, ft as PostgresDatabaseConfig, g as ActionAccessPolicy, gt as SecretSource, h as Action, ht as SecretRef, i as BrickClientAction, it as DatabaseHandle, j as InferTableInsert, jt as integer, k as DefaultServiceContext, kt as foreignKey, l as InferActionFailure, lt as isDatabaseHandle, m as isBrickTransportError, mt as SecretOptions, n as BrickCallOptions, nt as ValidationErrorItem, o as BrickServerError, ot as PostgresDefinition, p as isBrickServerError, pt as createPostgresDatabase, q as ServiceSchema, qt as ServicePluginContext, r as BrickClient, rt as DatabaseDefinition, s as BrickTransportError, st as SQLiteDefinition, t as BrickActionCaller, tt as ValidationError, u as InferActionInput, ut as DatabaseAdapter, v as ActionConfigWithAuthorize, vt as listSecrets, w as ArchitectureSchema, wt as BrickSQLiteDatabase, x as ActionErrorDefinition, xt as resetSecrets, y as ActionConfigWithoutAuthorize, yt as overrideSecret, z as ResilienceOptions, zt as PluginRouteRegistrar } from "./chunks/client.js";
|
|
2
2
|
import { Static, TSchema, TSchema as TSchema$1, Type } from "@sinclair/typebox";
|
|
3
3
|
import { TypeCheck } from "@sinclair/typebox/compiler";
|
|
4
4
|
import { Elysia } from "elysia";
|
|
5
5
|
import { Table, and, asc, desc, eq, getTableColumns, getTableName, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql } from "drizzle-orm";
|
|
6
|
+
//#region src/compiler/ir.d.ts
|
|
7
|
+
type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
8
|
+
interface RouteIR {
|
|
9
|
+
readonly method: RouteMethod;
|
|
10
|
+
readonly path: string;
|
|
11
|
+
readonly service: string;
|
|
12
|
+
readonly action: string;
|
|
13
|
+
readonly kind: "action";
|
|
14
|
+
readonly input: boolean;
|
|
15
|
+
readonly output: boolean;
|
|
16
|
+
readonly context: boolean;
|
|
17
|
+
readonly authorize: boolean;
|
|
18
|
+
readonly inputPrecedence: readonly ("query" | "params" | "body")[];
|
|
19
|
+
readonly coercions: readonly {
|
|
20
|
+
readonly key: string;
|
|
21
|
+
readonly type: "number" | "boolean";
|
|
22
|
+
}[];
|
|
23
|
+
/** JSON projection for inspection and stale-artifact detection, not runtime validation. */
|
|
24
|
+
readonly inputSchema?: unknown;
|
|
25
|
+
readonly outputSchema?: unknown;
|
|
26
|
+
}
|
|
27
|
+
interface BrickIR {
|
|
28
|
+
readonly version: 1;
|
|
29
|
+
readonly target: "bun-elysia";
|
|
30
|
+
readonly prefix: string;
|
|
31
|
+
readonly services: readonly string[];
|
|
32
|
+
readonly routes: readonly RouteIR[];
|
|
33
|
+
readonly preparations: readonly {
|
|
34
|
+
service: string;
|
|
35
|
+
name: string;
|
|
36
|
+
metadata: unknown;
|
|
37
|
+
}[];
|
|
38
|
+
readonly diagnostics: readonly string[];
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
6
41
|
//#region src/endpoints.d.ts
|
|
7
42
|
type EndpointMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
8
43
|
/** Logger subset handed to endpoint handlers (mirrors action context loggers). */
|
|
@@ -55,6 +90,7 @@ export declare function endpointPaths(defs: EndpointDefinition[]): Record<string
|
|
|
55
90
|
type BrickApp = Elysia<any, any, any, any, any, any, any> & {
|
|
56
91
|
/** Service definitions and prefix selected when this app was constructed. */
|
|
57
92
|
readonly definition: {
|
|
93
|
+
readonly routes: readonly RouteIR[];
|
|
58
94
|
readonly services: readonly Service<any, any>[];
|
|
59
95
|
readonly prefix: string;
|
|
60
96
|
};
|
|
@@ -64,46 +100,12 @@ type BrickApp = Elysia<any, any, any, any, any, any, any> & {
|
|
|
64
100
|
listEndpoints(): EndpointDefinition[];
|
|
65
101
|
};
|
|
66
102
|
//#endregion
|
|
67
|
-
//#region src/compiler/ir.d.ts
|
|
68
|
-
type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
69
|
-
interface RouteIR {
|
|
70
|
-
readonly method: RouteMethod;
|
|
71
|
-
readonly path: string;
|
|
72
|
-
readonly service: string;
|
|
73
|
-
readonly action: string;
|
|
74
|
-
readonly kind: "action";
|
|
75
|
-
readonly input: boolean;
|
|
76
|
-
readonly output: boolean;
|
|
77
|
-
readonly context: boolean;
|
|
78
|
-
readonly authorize: boolean;
|
|
79
|
-
readonly inputPrecedence: readonly ("query" | "params" | "body")[];
|
|
80
|
-
readonly coercions: readonly {
|
|
81
|
-
readonly key: string;
|
|
82
|
-
readonly type: "number" | "boolean";
|
|
83
|
-
}[];
|
|
84
|
-
/** JSON projection for inspection and stale-artifact detection, not runtime validation. */
|
|
85
|
-
readonly inputSchema?: unknown;
|
|
86
|
-
readonly outputSchema?: unknown;
|
|
87
|
-
}
|
|
88
|
-
interface BrickIR {
|
|
89
|
-
readonly version: 1;
|
|
90
|
-
readonly target: "bun-elysia";
|
|
91
|
-
readonly prefix: string;
|
|
92
|
-
readonly services: readonly string[];
|
|
93
|
-
readonly routes: readonly RouteIR[];
|
|
94
|
-
readonly preparations: readonly {
|
|
95
|
-
service: string;
|
|
96
|
-
name: string;
|
|
97
|
-
metadata: unknown;
|
|
98
|
-
}[];
|
|
99
|
-
readonly diagnostics: readonly string[];
|
|
100
|
-
}
|
|
101
|
-
//#endregion
|
|
102
103
|
//#region src/compiler/runtime.d.ts
|
|
103
104
|
type CompiledHandler = (context: any) => unknown | Promise<unknown>;
|
|
104
105
|
type HandlerFactory = (binding: CompiledRoutePlan, runtime: typeof compilerRuntime) => CompiledHandler;
|
|
105
106
|
/** Retains Brick's existing source precedence and treatment of empty bodies. */
|
|
106
107
|
declare function mergeInput(first: any, second: any, third: any): any;
|
|
108
|
+
declare function checkDepth(value: unknown, action: string): void;
|
|
107
109
|
declare function validate(check: NonNullable<CompiledRoutePlan["inputChecker"]>, value: unknown, action: string, stage: "input" | "output"): void;
|
|
108
110
|
declare function mapError(err: any, set: any): {
|
|
109
111
|
name: string;
|
|
@@ -126,6 +128,7 @@ export declare const compilerRuntime: Readonly<{
|
|
|
126
128
|
defaultRequest: Request;
|
|
127
129
|
nextSequence: () => string;
|
|
128
130
|
mergeInput: typeof mergeInput;
|
|
131
|
+
checkDepth: typeof checkDepth;
|
|
129
132
|
validate: typeof validate;
|
|
130
133
|
mapError: typeof mapError;
|
|
131
134
|
isThenable: (value: any) => boolean;
|
|
@@ -332,6 +335,7 @@ export declare class ServiceImpl<TDb = BunSQLiteDatabase<Record<string, unknown>
|
|
|
332
335
|
/**
|
|
333
336
|
* Resolves the complete service execution context once per incoming request.
|
|
334
337
|
* Merges framework BaseContext with the service's custom context hook.
|
|
338
|
+
* Always rebuilds context for this service to prevent caller context from overriding.
|
|
335
339
|
*/
|
|
336
340
|
resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>): Promise<BaseContext<TDb> & TServiceContext>;
|
|
337
341
|
private _resolveContextSlow;
|
|
@@ -339,6 +343,24 @@ export declare class ServiceImpl<TDb = BunSQLiteDatabase<Record<string, unknown>
|
|
|
339
343
|
}
|
|
340
344
|
export declare function defineService<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>>(name: string, options?: ServiceOptions<TServiceContext, TDb>): Service<TDb, TServiceContext>;
|
|
341
345
|
//#endregion
|
|
346
|
+
//#region src/access.d.ts
|
|
347
|
+
interface ActionAccessInfo {
|
|
348
|
+
hasAuthorize: boolean;
|
|
349
|
+
hasScope: boolean;
|
|
350
|
+
policy: ActionAccessPolicy;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Cross-copy access metadata protocol. CRUD enforces its access policy
|
|
354
|
+
* inside `execute`, so `config.authorize` is absent and introspection
|
|
355
|
+
* can't see it. The plugin stamps each action under this process-global
|
|
356
|
+
* symbol; introspection and OpenAPI read it back. Uses `Symbol.for` so
|
|
357
|
+
* the binding survives a second copy of core (bundler SSR, Vitest),
|
|
358
|
+
* same as the plugin action-binding key.
|
|
359
|
+
*/
|
|
360
|
+
export declare const ACTION_ACCESS_KEY: unique symbol;
|
|
361
|
+
export declare function setActionAccess(action: object, info: ActionAccessInfo): void;
|
|
362
|
+
export declare function getActionAccess(action: Action | object): ActionAccessInfo;
|
|
363
|
+
//#endregion
|
|
342
364
|
//#region src/action.d.ts
|
|
343
365
|
export declare function buildErrorHelpers<TErrors extends Record<string, ActionErrorDefinition>>(errorsDef?: TErrors): ErrorBuilder<TErrors>;
|
|
344
366
|
export declare function defineAction<TInputSchema extends TSchema$1 | undefined = undefined, TOutputSchema extends TSchema$1 | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>(config: ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>): Action<TInputSchema, TOutputSchema, TErrors, TContext>;
|
|
@@ -352,18 +374,25 @@ export declare function defineResource<TTable = any, TCtx extends ActionContext
|
|
|
352
374
|
export declare function createServiceProxy<T extends Record<string, any>>(serviceName: string, options?: ProxyOptions): T;
|
|
353
375
|
//#endregion
|
|
354
376
|
//#region src/registry.d.ts
|
|
377
|
+
interface ArchitectureApplication {
|
|
378
|
+
services: readonly Service[];
|
|
379
|
+
routes: readonly RouteIR[];
|
|
380
|
+
}
|
|
355
381
|
export declare class ServiceRegistry {
|
|
356
382
|
private _revision;
|
|
357
383
|
/** Definition revision for invalidating serialized architecture snapshots. */
|
|
358
384
|
get revision(): number;
|
|
359
385
|
touch(): void;
|
|
360
386
|
private services;
|
|
387
|
+
private routes;
|
|
388
|
+
/** Remember the actual registered routes for subsequent registry exports. */
|
|
389
|
+
setApplicationRoutes(application: ArchitectureApplication): void;
|
|
361
390
|
register(service: Service): void;
|
|
362
391
|
get(name: string): Service | undefined;
|
|
363
392
|
has(name: string): boolean;
|
|
364
393
|
list(): Service[];
|
|
365
394
|
clear(): void;
|
|
366
|
-
exportArchitecture(): ArchitectureSchema;
|
|
395
|
+
exportArchitecture(application?: ArchitectureApplication): ArchitectureSchema;
|
|
367
396
|
}
|
|
368
397
|
export declare function getGlobalRegistry(): ServiceRegistry;
|
|
369
398
|
export declare function resetGlobalRegistry(): void;
|
|
@@ -428,5 +457,5 @@ interface McpHandlerOptions {
|
|
|
428
457
|
/** Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication. */
|
|
429
458
|
export declare function createMcpHandler(options: McpHandlerOptions): (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>;
|
|
430
459
|
//#endregion
|
|
431
|
-
export { Action, ActionConfig, ActionConfigWithAuthorize, ActionConfigWithoutAuthorize, ActionContext, ActionErrorDefinition, ActionExecutionError, ActionSchema, ArchitectureSchema, BaseActionConfig, BaseContext, type BrickActionCaller, type BrickApp, type BrickCallOptions, type BrickClient, type BrickClientAction, type BrickClientOptions, type BrickIR, BrickSQLiteDatabase, BrickServerError, BrickTransportError, type BunSQLiteDatabase, CacheOptions, type CompiledApplication, type CompiledHandler, type CompiledRoute, CompiledRoutePlan, type CreateServerOptions, DatabaseAdapter, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, EnvInput, ErrorBuilder, type HandlerFactory, type InferActionErrorCodes, type InferActionFailure, type InferActionInput, type InferActionOutput, InferTableInsert, InferTableRow, LifecycleOptions, Logger, type McpHandlerOptions, type McpRegistry, type McpRegistryOptions, type McpToolDefinition, NarrowAuthorizedContext, type OpenApiGeneratorOptions, type PluginEndpointContext, type PluginRouteMethod, type PluginRouteRegistrar, type PluginRouteScope, type PluginRoutes, PostgresDatabase, PostgresDatabaseConfig, PostgresDefinition, PreparationContribution, ProxyOptions, RateLimitOptions, type ReferenceOptions, type RequestLoggingOptions, ResilienceOptions, Resource, ResourceConfig, ResourceIdentity, type ResourcePlugin, type ResourcePluginAPI, type ResourcePluginContext, type ResourcePluginTypes, ResourceTypeOptions, type RouteIR, type RouteMethod, SQLiteDatabaseConfig, SQLiteDefinition, type SecretOptions, SecretRef, type SecretSource, Service, ServiceAuthOptions, ServiceOptions, type ServicePlugin, type ServicePluginContext, ServiceSchema, StandardErrorMap, type Static, type TSchema, Table, TelemetryOptions, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, ValidationError, ValidationErrorItem, and, asc, blob, createBrickClient, createPostgresDatabase, createSQLiteDatabase, defineDatabase, defineResourcePlugin, defineServicePlugin, desc, envSource, eq, foreignKey, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, like, listSecrets, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, relations, resetSecrets, resolveSecrets, secret, sql, sqliteTable, text, uniqueIndex };
|
|
460
|
+
export { Action, type ActionAccessInfo, ActionAccessPolicy, ActionConfig, ActionConfigWithAuthorize, ActionConfigWithoutAuthorize, ActionContext, ActionErrorDefinition, ActionExecutionError, ActionSchema, ArchitectureSchema, BaseActionConfig, BaseContext, type BrickActionCaller, type BrickApp, type BrickCallOptions, type BrickClient, type BrickClientAction, type BrickClientOptions, type BrickIR, BrickSQLiteDatabase, BrickServerError, BrickTransportError, type BunSQLiteDatabase, CacheOptions, type CompiledApplication, type CompiledHandler, type CompiledRoute, CompiledRoutePlan, type CreateServerOptions, DatabaseAdapter, DatabaseDefinition, DatabaseHandle, DefaultServiceContext, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, EnvInput, ErrorBuilder, type HandlerFactory, type InferActionErrorCodes, type InferActionFailure, type InferActionInput, type InferActionOutput, InferTableInsert, InferTableRow, LifecycleOptions, Logger, type McpHandlerOptions, type McpRegistry, type McpRegistryOptions, type McpToolDefinition, NarrowAuthorizedContext, type OpenApiGeneratorOptions, type PluginEndpointContext, type PluginRouteMethod, type PluginRouteRegistrar, type PluginRouteScope, type PluginRoutes, PostgresDatabase, PostgresDatabaseConfig, PostgresDefinition, PreparationContribution, ProxyOptions, RateLimitOptions, type ReferenceOptions, type RequestLoggingOptions, ResilienceOptions, Resource, ResourceConfig, ResourceIdentity, type ResourcePlugin, type ResourcePluginAPI, type ResourcePluginContext, type ResourcePluginTypes, ResourceTypeOptions, type RouteIR, type RouteMethod, SQLiteDatabaseConfig, SQLiteDefinition, type SecretOptions, SecretRef, type SecretSource, Service, ServiceAuthOptions, ServiceOptions, type ServicePlugin, type ServicePluginContext, ServiceSchema, StandardErrorMap, type Static, type TSchema, Table, TelemetryOptions, Tool, ToolAnnotations, ToolConfigWithAuthorize, ToolConfigWithoutAuthorize, ToolOptions, Type, Type as t, ValidationError, ValidationErrorItem, and, asc, blob, createBrickClient, createPostgresDatabase, createSQLiteDatabase, defineDatabase, defineResourcePlugin, defineServicePlugin, desc, envSource, eq, foreignKey, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, like, listSecrets, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, relations, resetSecrets, resolveSecrets, secret, sql, sqliteTable, text, uniqueIndex };
|
|
432
461
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["_$__0.ValidationErrorItem","_$__endpoints0.BrickApp","TSchema","TSchema","TSchema"],"sources":["../src/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["_$__0.ValidationErrorItem","_$__endpoints0.BrickApp","TSchema","TSchema","TSchema"],"sources":["../src/compiler/ir.ts","../src/endpoints.ts","../src/compiler/runtime.ts","../src/compiler.ts","../src/request-logger.ts","../src/docs.ts","../src/action-handler.ts","../src/server.ts","../src/app-entry.ts","../src/compiler/emit.ts","../src/db/index.ts","../src/service.ts","../src/access.ts","../src/action.ts","../src/resource.ts","../src/rpc.ts","../src/registry.ts","../src/typebox.ts","../src/openapi.ts","../src/tool.ts","../src/mcp.ts"],"mappings":";;;;;;KAGY;UACK;WACN,QAAQ;WACR;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;aACE;aACA;;;WAGF;WACA;;UA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