@brickkit/core 0.3.0-beta.1 → 0.3.0-beta.3
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 +148 -222
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js +8 -74
- package/dist/chunks/client.js.map +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/index.d.ts +237 -25
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1528 -1307
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -2,48 +2,16 @@ import { a as isBrickTransportError, i as isBrickServerError, n as BrickTranspor
|
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { Type } from "@sinclair/typebox";
|
|
4
4
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
5
|
-
import {
|
|
5
|
+
import { Elysia } from "elysia";
|
|
6
|
+
import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
6
7
|
import postgres from "postgres";
|
|
7
8
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
8
|
-
import {
|
|
9
|
+
import { Table, and, asc, desc, eq, getTableColumns, getTableColumns as getTableColumns$1, getTableName, getTableName as getTableName$1, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql, sql as sql$1 } from "drizzle-orm";
|
|
9
10
|
import { mkdirSync } from "node:fs";
|
|
10
11
|
import { dirname } from "node:path";
|
|
11
12
|
//#region \0rolldown/runtime.js
|
|
12
13
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
13
14
|
//#endregion
|
|
14
|
-
//#region src/typebox.ts
|
|
15
|
-
const compilerCache = /* @__PURE__ */ new WeakMap();
|
|
16
|
-
function getCompiledCheck(schema) {
|
|
17
|
-
let compiled = compilerCache.get(schema);
|
|
18
|
-
if (!compiled) {
|
|
19
|
-
compiled = TypeCompiler.Compile(schema);
|
|
20
|
-
compilerCache.set(schema, compiled);
|
|
21
|
-
}
|
|
22
|
-
return compiled;
|
|
23
|
-
}
|
|
24
|
-
function validateWithSchema(schema, value) {
|
|
25
|
-
if (!schema) return {
|
|
26
|
-
success: true,
|
|
27
|
-
data: value
|
|
28
|
-
};
|
|
29
|
-
const check = getCompiledCheck(schema);
|
|
30
|
-
if (check.Check(value)) return {
|
|
31
|
-
success: true,
|
|
32
|
-
data: value
|
|
33
|
-
};
|
|
34
|
-
const errors = [];
|
|
35
|
-
for (const error of check.Errors(value)) errors.push({
|
|
36
|
-
path: error.path,
|
|
37
|
-
message: error.message,
|
|
38
|
-
value: error.value,
|
|
39
|
-
type: error.type
|
|
40
|
-
});
|
|
41
|
-
return {
|
|
42
|
-
success: false,
|
|
43
|
-
errors
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
//#endregion
|
|
47
15
|
//#region src/registry.ts
|
|
48
16
|
var ServiceRegistry = class {
|
|
49
17
|
_revision = 0;
|
|
@@ -88,6 +56,39 @@ function resetGlobalRegistry() {
|
|
|
88
56
|
globalRegistry = new ServiceRegistry();
|
|
89
57
|
}
|
|
90
58
|
//#endregion
|
|
59
|
+
//#region src/typebox.ts
|
|
60
|
+
const compilerCache = /* @__PURE__ */ new WeakMap();
|
|
61
|
+
function getCompiledCheck(schema) {
|
|
62
|
+
let compiled = compilerCache.get(schema);
|
|
63
|
+
if (!compiled) {
|
|
64
|
+
compiled = TypeCompiler.Compile(schema);
|
|
65
|
+
compilerCache.set(schema, compiled);
|
|
66
|
+
}
|
|
67
|
+
return compiled;
|
|
68
|
+
}
|
|
69
|
+
function validateWithSchema(schema, value) {
|
|
70
|
+
if (!schema) return {
|
|
71
|
+
success: true,
|
|
72
|
+
data: value
|
|
73
|
+
};
|
|
74
|
+
const check = getCompiledCheck(schema);
|
|
75
|
+
if (check.Check(value)) return {
|
|
76
|
+
success: true,
|
|
77
|
+
data: value
|
|
78
|
+
};
|
|
79
|
+
const errors = [];
|
|
80
|
+
for (const error of check.Errors(value)) errors.push({
|
|
81
|
+
path: error.path,
|
|
82
|
+
message: error.message,
|
|
83
|
+
value: error.value,
|
|
84
|
+
type: error.type
|
|
85
|
+
});
|
|
86
|
+
return {
|
|
87
|
+
success: false,
|
|
88
|
+
errors
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
//#endregion
|
|
91
92
|
//#region src/action.ts
|
|
92
93
|
const defaultLogger$1 = {
|
|
93
94
|
info: (...args) => console.log("[INFO]", ...args),
|
|
@@ -95,7 +96,7 @@ const defaultLogger$1 = {
|
|
|
95
96
|
error: (...args) => console.error("[ERROR]", ...args),
|
|
96
97
|
debug: (...args) => console.debug("[DEBUG]", ...args)
|
|
97
98
|
};
|
|
98
|
-
const DEFAULT_REQUEST$
|
|
99
|
+
const DEFAULT_REQUEST$3 = new Request("http://localhost");
|
|
99
100
|
let _defaultCtxSeq = 0;
|
|
100
101
|
const standardErrorDefaults = {
|
|
101
102
|
BAD_REQUEST: {
|
|
@@ -127,7 +128,7 @@ function createDefaultContext(partial) {
|
|
|
127
128
|
if (partial?._resolved) return partial;
|
|
128
129
|
const seq = (++_defaultCtxSeq).toString(36);
|
|
129
130
|
return {
|
|
130
|
-
request: partial?.request ?? DEFAULT_REQUEST$
|
|
131
|
+
request: partial?.request ?? DEFAULT_REQUEST$3,
|
|
131
132
|
traceId: partial?.traceId || `tr_${seq}`,
|
|
132
133
|
requestId: partial?.requestId || `req_${seq}`,
|
|
133
134
|
db: partial?.db,
|
|
@@ -168,7 +169,7 @@ function defineAction(config) {
|
|
|
168
169
|
return validateWithSchema(config.input, input);
|
|
169
170
|
};
|
|
170
171
|
actionFn.validateOutput = (output) => {
|
|
171
|
-
return validateWithSchema(config.output, output);
|
|
172
|
+
return validateWithSchema(actionFn.outputValidationSchema ?? config.output, output);
|
|
172
173
|
};
|
|
173
174
|
actionFn.run = async (input, ctx) => {
|
|
174
175
|
return actionFn.execute({
|
|
@@ -207,13 +208,1416 @@ function defineAction(config) {
|
|
|
207
208
|
ctx: fullCtx,
|
|
208
209
|
error: errorHelpers
|
|
209
210
|
});
|
|
210
|
-
if (config.output) {
|
|
211
|
+
if (actionFn.outputValidationSchema ?? config.output) {
|
|
211
212
|
const outputValidation = actionFn.validateOutput(result);
|
|
212
213
|
if (!outputValidation.success) throw new ValidationError(`Validation failed for action '${config.name}' output`, outputValidation.errors, 500);
|
|
213
214
|
}
|
|
214
215
|
return result;
|
|
215
216
|
};
|
|
216
|
-
return actionFn;
|
|
217
|
+
return actionFn;
|
|
218
|
+
}
|
|
219
|
+
//#endregion
|
|
220
|
+
//#region src/plugin.ts
|
|
221
|
+
const pluginKind = Symbol("Brick plugin");
|
|
222
|
+
function defineServicePlugin(definition) {
|
|
223
|
+
validateName(definition.name);
|
|
224
|
+
return Object.freeze({
|
|
225
|
+
...definition,
|
|
226
|
+
routes: copyControls(definition.routes),
|
|
227
|
+
[pluginKind]: "service"
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
function defineResourcePlugin(definition) {
|
|
231
|
+
validateName(definition.name);
|
|
232
|
+
return Object.freeze({
|
|
233
|
+
...definition,
|
|
234
|
+
routes: copyControls(definition.routes),
|
|
235
|
+
[pluginKind]: "resource"
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
function validateName(name) {
|
|
239
|
+
if (!name || name.trim() !== name) throw new Error("Plugin and route names must be nonempty and have no surrounding whitespace");
|
|
240
|
+
}
|
|
241
|
+
function validatePath(path) {
|
|
242
|
+
if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("//") || path.split("/").some((part) => part === "." || part === "..")) throw new Error(`Invalid plugin route path '${path}'`);
|
|
243
|
+
}
|
|
244
|
+
function copyControls(controls) {
|
|
245
|
+
if (controls === void 0 || controls === false) return controls;
|
|
246
|
+
const result = Object.create(null);
|
|
247
|
+
for (const [name, value] of Object.entries(controls)) {
|
|
248
|
+
validateName(name);
|
|
249
|
+
if (value === false) {
|
|
250
|
+
result[name] = false;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (value.path !== void 0) validatePath(value.path);
|
|
254
|
+
if (value.scope !== void 0 && ![
|
|
255
|
+
"app",
|
|
256
|
+
"service",
|
|
257
|
+
"resource"
|
|
258
|
+
].includes(value.scope)) throw new Error(`Invalid plugin route scope '${value.scope}'`);
|
|
259
|
+
result[name] = Object.freeze({ ...value });
|
|
260
|
+
}
|
|
261
|
+
return Object.freeze(result);
|
|
262
|
+
}
|
|
263
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
264
|
+
const actionBindings = /* @__PURE__ */ new WeakMap();
|
|
265
|
+
/**
|
|
266
|
+
* Cross-copy binding protocol. Bundler SSR runtimes (Vite, Nitro, Vitest)
|
|
267
|
+
* may load a second copy of core that owns a different WeakMap, while the
|
|
268
|
+
* action objects themselves cross the boundary by reference. The binding
|
|
269
|
+
* travels on the action under a process-global symbol so route lookups
|
|
270
|
+
* (including disabled-route suppression) keep working there.
|
|
271
|
+
*/
|
|
272
|
+
const actionBindingKey = Symbol.for("brickkit.plugin.actionBinding");
|
|
273
|
+
function stateOf(service) {
|
|
274
|
+
let state = states.get(service);
|
|
275
|
+
if (!state) {
|
|
276
|
+
state = {
|
|
277
|
+
hosts: /* @__PURE__ */ new Map(),
|
|
278
|
+
actions: /* @__PURE__ */ new Map(),
|
|
279
|
+
endpoints: []
|
|
280
|
+
};
|
|
281
|
+
states.set(service, state);
|
|
282
|
+
}
|
|
283
|
+
return state;
|
|
284
|
+
}
|
|
285
|
+
function isInstallingPlugin(service) {
|
|
286
|
+
return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
|
|
287
|
+
}
|
|
288
|
+
function pathOf(binding, prefix) {
|
|
289
|
+
const scope = binding.scope === "app" ? "" : `/${binding.scope === "resource" ? binding.resource.name : binding.service.name}`;
|
|
290
|
+
return `${prefix.replace(/\/$/, "")}${scope}${binding.path === "/" ? "" : binding.path}` || "/";
|
|
291
|
+
}
|
|
292
|
+
function getPluginActionRoute(action, prefix = "/api") {
|
|
293
|
+
const binding = action[actionBindingKey] ?? actionBindings.get(action);
|
|
294
|
+
if (!binding) return void 0;
|
|
295
|
+
if (!binding.enabled) return false;
|
|
296
|
+
return {
|
|
297
|
+
path: pathOf(binding, prefix),
|
|
298
|
+
method: binding.method,
|
|
299
|
+
clientPath: binding.clientPath
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
function getPluginEndpoints(service, prefix = "/api") {
|
|
303
|
+
return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
|
|
304
|
+
path: pathOf(binding, prefix),
|
|
305
|
+
method: binding.method,
|
|
306
|
+
service,
|
|
307
|
+
summary: binding.summary,
|
|
308
|
+
description: binding.description,
|
|
309
|
+
tags: binding.tags,
|
|
310
|
+
handler: async (context) => binding.handler({
|
|
311
|
+
...context,
|
|
312
|
+
ctx: await service.resolveContext({ request: context.request })
|
|
313
|
+
})
|
|
314
|
+
}));
|
|
315
|
+
}
|
|
316
|
+
/** Descriptor identity is scoped to the service or resource installation host. */
|
|
317
|
+
function installPlugin(service, resource, descriptor) {
|
|
318
|
+
if (service.isBuilt) throw new Error("Plugins must be installed before service build");
|
|
319
|
+
if (descriptor[pluginKind] !== (resource ? "resource" : "service")) throw new Error("Plugin does not support this installation host");
|
|
320
|
+
const state = stateOf(service);
|
|
321
|
+
const host = resource ?? service;
|
|
322
|
+
const existing = state.hosts.get(host)?.get(descriptor.name);
|
|
323
|
+
if (existing) {
|
|
324
|
+
if (existing.status === "installing") throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);
|
|
325
|
+
if (existing.descriptor !== descriptor) throw new Error(`Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`);
|
|
326
|
+
return resource ?? existing.api;
|
|
327
|
+
}
|
|
328
|
+
const snapshots = {
|
|
329
|
+
actions: new Map(service.actions),
|
|
330
|
+
tools: new Map(service.tools),
|
|
331
|
+
tables: new Map(service.tables),
|
|
332
|
+
resources: new Map(service.resources),
|
|
333
|
+
preparations: new Map(service.preparations),
|
|
334
|
+
hosts: new Map([...state.hosts].map(([key, installations]) => [key, new Map(installations)])),
|
|
335
|
+
bindings: new Map(state.actions),
|
|
336
|
+
endpoints: [...state.endpoints],
|
|
337
|
+
properties: new Map([...service.resources.values()].map((item) => [item, Object.getOwnPropertyDescriptors(item)]))
|
|
338
|
+
};
|
|
339
|
+
const installations = state.hosts.get(host) ?? /* @__PURE__ */ new Map();
|
|
340
|
+
state.hosts.set(host, installations);
|
|
341
|
+
installations.set(descriptor.name, {
|
|
342
|
+
descriptor,
|
|
343
|
+
status: "installing"
|
|
344
|
+
});
|
|
345
|
+
const names = /* @__PURE__ */ new Set();
|
|
346
|
+
const ownedActions = /* @__PURE__ */ new Set();
|
|
347
|
+
let active = true;
|
|
348
|
+
const bindingFor = (config) => {
|
|
349
|
+
if (!active || service.isBuilt) throw new Error("Plugin routes can only be registered during setup");
|
|
350
|
+
validateName(config.name);
|
|
351
|
+
validatePath(config.path);
|
|
352
|
+
if (names.has(config.name)) throw new Error(`Duplicate plugin route name '${config.name}'`);
|
|
353
|
+
names.add(config.name);
|
|
354
|
+
const control = descriptor.routes === false ? false : descriptor.routes?.[config.name];
|
|
355
|
+
const scope = control && control.scope || config.scope || (resource ? "resource" : "service");
|
|
356
|
+
if (scope === "resource" && !resource) throw new Error("Service plugin routes cannot use resource scope");
|
|
357
|
+
if (![
|
|
358
|
+
"app",
|
|
359
|
+
"service",
|
|
360
|
+
"resource"
|
|
361
|
+
].includes(scope)) throw new Error(`Invalid plugin route scope '${scope}'`);
|
|
362
|
+
if (![
|
|
363
|
+
"GET",
|
|
364
|
+
"POST",
|
|
365
|
+
"PUT",
|
|
366
|
+
"PATCH",
|
|
367
|
+
"DELETE"
|
|
368
|
+
].includes(config.method)) throw new Error(`Invalid plugin route method '${config.method}'`);
|
|
369
|
+
const path = control && control.path || config.path;
|
|
370
|
+
validatePath(path);
|
|
371
|
+
return {
|
|
372
|
+
service,
|
|
373
|
+
resource,
|
|
374
|
+
path,
|
|
375
|
+
method: config.method,
|
|
376
|
+
scope,
|
|
377
|
+
enabled: control !== false
|
|
378
|
+
};
|
|
379
|
+
};
|
|
380
|
+
const routes = {
|
|
381
|
+
action(config) {
|
|
382
|
+
const binding = bindingFor(config);
|
|
383
|
+
for (const match of binding.path.matchAll(/:([A-Za-z0-9_]+)/g)) if (!config.input?.properties || !Object.hasOwn(config.input.properties, match[1])) throw new Error(`Plugin action path parameter '${match[1]}' must be declared in its input schema`);
|
|
384
|
+
const name = `${resource ? `${resource.name}.` : ""}${descriptor.name}.${config.name}`;
|
|
385
|
+
if (service.actions.has(name)) throw new Error(`Duplicate plugin action '${name}'`);
|
|
386
|
+
const { scope: _scope, ...actionConfig } = config;
|
|
387
|
+
const action = defineAction({
|
|
388
|
+
...actionConfig,
|
|
389
|
+
name
|
|
390
|
+
});
|
|
391
|
+
service.action(action);
|
|
392
|
+
ownedActions.add(action);
|
|
393
|
+
state.actions.set(action, binding);
|
|
394
|
+
actionBindings.set(action, binding);
|
|
395
|
+
action[actionBindingKey] = binding;
|
|
396
|
+
return action;
|
|
397
|
+
},
|
|
398
|
+
endpoint(config) {
|
|
399
|
+
const binding = bindingFor(config);
|
|
400
|
+
state.endpoints.push({
|
|
401
|
+
...binding,
|
|
402
|
+
handler: config.handler,
|
|
403
|
+
summary: config.summary,
|
|
404
|
+
description: config.description,
|
|
405
|
+
tags: config.tags
|
|
406
|
+
});
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
try {
|
|
410
|
+
const api = resource ? descriptor.setup({
|
|
411
|
+
service,
|
|
412
|
+
resource,
|
|
413
|
+
routes
|
|
414
|
+
}) : descriptor.setup({
|
|
415
|
+
service,
|
|
416
|
+
routes
|
|
417
|
+
});
|
|
418
|
+
if (api && typeof api === "object" && "then" in api) throw new Error("Plugin setup must be synchronous");
|
|
419
|
+
if (descriptor.routes && Object.keys(descriptor.routes).some((name) => !names.has(name))) throw new Error(`Plugin '${descriptor.name}' has an override for an unknown route`);
|
|
420
|
+
const walk = (value, path, ancestors) => {
|
|
421
|
+
if (typeof value === "function") {
|
|
422
|
+
const binding = state.actions.get(value);
|
|
423
|
+
if (binding && ownedActions.has(value)) {
|
|
424
|
+
if (binding.clientPath) throw new Error("Plugin actions must have one returned API path");
|
|
425
|
+
binding.clientPath = [resource?.name ?? service.name, ...path];
|
|
426
|
+
}
|
|
427
|
+
} else if (value && typeof value === "object" && !ancestors.has(value)) {
|
|
428
|
+
const next = new Set(ancestors).add(value);
|
|
429
|
+
for (const [key, child] of Object.entries(value)) walk(child, [...path, key], next);
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
walk(api, [], /* @__PURE__ */ new Set());
|
|
433
|
+
if (resource) {
|
|
434
|
+
if (!api || typeof api !== "object" || Array.isArray(api)) throw new Error("Resource plugins must return named API contributions");
|
|
435
|
+
for (const key of Object.keys(api)) if (key in resource || [
|
|
436
|
+
"__proto__",
|
|
437
|
+
"prototype",
|
|
438
|
+
"constructor"
|
|
439
|
+
].includes(key)) throw new Error(`Resource plugin contribution '${key}' collides with an existing property`);
|
|
440
|
+
Object.assign(resource, api);
|
|
441
|
+
}
|
|
442
|
+
state.hosts.get(host).set(descriptor.name, {
|
|
443
|
+
descriptor,
|
|
444
|
+
status: "installed",
|
|
445
|
+
api
|
|
446
|
+
});
|
|
447
|
+
getGlobalRegistry().touch();
|
|
448
|
+
return resource ?? api;
|
|
449
|
+
} catch (error) {
|
|
450
|
+
for (const action of state.actions.keys()) if (!snapshots.bindings.has(action)) {
|
|
451
|
+
actionBindings.delete(action);
|
|
452
|
+
delete action[actionBindingKey];
|
|
453
|
+
}
|
|
454
|
+
restoreMap(service.actions, snapshots.actions);
|
|
455
|
+
restoreMap(service.tools, snapshots.tools);
|
|
456
|
+
restoreMap(service.tables, snapshots.tables);
|
|
457
|
+
restoreMap(service.resources, snapshots.resources);
|
|
458
|
+
restoreMap(service.preparations, snapshots.preparations);
|
|
459
|
+
state.hosts = snapshots.hosts;
|
|
460
|
+
state.actions = snapshots.bindings;
|
|
461
|
+
state.endpoints = snapshots.endpoints;
|
|
462
|
+
for (const [item, properties] of snapshots.properties) {
|
|
463
|
+
for (const key of Reflect.ownKeys(item)) if (!Object.hasOwn(properties, key)) Reflect.deleteProperty(item, key);
|
|
464
|
+
Object.defineProperties(item, properties);
|
|
465
|
+
}
|
|
466
|
+
getGlobalRegistry().touch();
|
|
467
|
+
throw error;
|
|
468
|
+
} finally {
|
|
469
|
+
active = false;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
function restoreMap(target, snapshot) {
|
|
473
|
+
target.clear();
|
|
474
|
+
for (const [key, value] of snapshot) target.set(key, value);
|
|
475
|
+
}
|
|
476
|
+
//#endregion
|
|
477
|
+
//#region src/action-handler.ts
|
|
478
|
+
let _srvSeq = 0;
|
|
479
|
+
const EMPTY_SERVICES$2 = Object.freeze({});
|
|
480
|
+
const DEFAULT_REQUEST$2 = new Request("http://localhost");
|
|
481
|
+
function isNonEmpty$1(obj) {
|
|
482
|
+
if (obj == null) return false;
|
|
483
|
+
for (const _ in obj) return true;
|
|
484
|
+
return false;
|
|
485
|
+
}
|
|
486
|
+
const MAX_INPUT_DEPTH = 128;
|
|
487
|
+
function inputTooDeep(value) {
|
|
488
|
+
if (!value || typeof value !== "object") return false;
|
|
489
|
+
const stack = [{
|
|
490
|
+
node: value,
|
|
491
|
+
depth: 0
|
|
492
|
+
}];
|
|
493
|
+
while (stack.length > 0) {
|
|
494
|
+
const { node, depth } = stack.pop();
|
|
495
|
+
if (depth > MAX_INPUT_DEPTH) return true;
|
|
496
|
+
if (node && typeof node === "object") {
|
|
497
|
+
const children = Array.isArray(node) ? node : Object.values(node);
|
|
498
|
+
for (const child of children) if (child && typeof child === "object") stack.push({
|
|
499
|
+
node: child,
|
|
500
|
+
depth: depth + 1
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
function compileRoutePlan(service, action, routePath, method) {
|
|
507
|
+
const actionName = action.name;
|
|
508
|
+
const serviceName = service.name;
|
|
509
|
+
const isGetLike = method === "GET" || actionName.startsWith("get") || actionName.endsWith(".get") || actionName.startsWith("list") || actionName.endsWith(".list") || actionName.startsWith("find") || actionName.startsWith("read");
|
|
510
|
+
const inputSchema = action.config?.input;
|
|
511
|
+
const outputSchema = action.config?.output;
|
|
512
|
+
const hasInput = Boolean(inputSchema);
|
|
513
|
+
const inputChecker = inputSchema ? getCompiledCheck(inputSchema) : void 0;
|
|
514
|
+
const runtimeOutputSchema = action.outputValidationSchema ?? outputSchema;
|
|
515
|
+
const outputChecker = runtimeOutputSchema ? getCompiledCheck(runtimeOutputSchema) : void 0;
|
|
516
|
+
let coercions;
|
|
517
|
+
if (inputSchema && typeof inputSchema.properties === "object") {
|
|
518
|
+
const list = [];
|
|
519
|
+
for (const [key, prop] of Object.entries(inputSchema.properties)) {
|
|
520
|
+
const type = prop?.type;
|
|
521
|
+
if (type === "number" || type === "integer") list.push({
|
|
522
|
+
key,
|
|
523
|
+
isNumber: true,
|
|
524
|
+
isBoolean: false
|
|
525
|
+
});
|
|
526
|
+
else if (type === "boolean") list.push({
|
|
527
|
+
key,
|
|
528
|
+
isNumber: false,
|
|
529
|
+
isBoolean: true
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
if (list.length > 0) coercions = list;
|
|
533
|
+
}
|
|
534
|
+
const contextHook = service.options?.context;
|
|
535
|
+
const hasContextHook = typeof contextHook === "function";
|
|
536
|
+
const authorize = action.config?.authorize;
|
|
537
|
+
const hasAuthorize = typeof authorize === "function";
|
|
538
|
+
const execute = action.config?.execute;
|
|
539
|
+
const tag = `[${serviceName}:${actionName}]`;
|
|
540
|
+
const logger = {
|
|
541
|
+
info: (...args) => console.log(tag, ...args),
|
|
542
|
+
warn: (...args) => console.warn(tag, ...args),
|
|
543
|
+
error: (...args) => console.error(tag, ...args),
|
|
544
|
+
debug: (...args) => console.debug(tag, ...args)
|
|
545
|
+
};
|
|
546
|
+
const errorBuilder = action.errorHelpers ?? buildErrorHelpers(action.config?.errors);
|
|
547
|
+
const cachedDb = service.getDb();
|
|
548
|
+
return {
|
|
549
|
+
service,
|
|
550
|
+
action,
|
|
551
|
+
actionName,
|
|
552
|
+
serviceName,
|
|
553
|
+
routePath,
|
|
554
|
+
method,
|
|
555
|
+
isGetLike,
|
|
556
|
+
hasInput,
|
|
557
|
+
hasContextHook,
|
|
558
|
+
contextHook,
|
|
559
|
+
hasAuthorize,
|
|
560
|
+
authorize,
|
|
561
|
+
execute,
|
|
562
|
+
inputChecker,
|
|
563
|
+
outputChecker,
|
|
564
|
+
coercions,
|
|
565
|
+
logger,
|
|
566
|
+
errorBuilder,
|
|
567
|
+
cachedDb
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
async function executeCompiledRoute(plan, elysiaCtx) {
|
|
571
|
+
const { params, body, query, headers, request, set } = elysiaCtx;
|
|
572
|
+
const seq = (++_srvSeq).toString(36);
|
|
573
|
+
const traceId = headers && headers["x-trace-id"] || `tr_${seq}`;
|
|
574
|
+
const requestId = headers && headers["x-request-id"] || `req_${seq}`;
|
|
575
|
+
if (set?.headers) {
|
|
576
|
+
set.headers["x-trace-id"] = traceId;
|
|
577
|
+
set.headers["x-request-id"] = requestId;
|
|
578
|
+
}
|
|
579
|
+
let input;
|
|
580
|
+
if (plan.hasInput) {
|
|
581
|
+
let coercedQuery = query;
|
|
582
|
+
if (query && plan.coercions && plan.coercions.length > 0) {
|
|
583
|
+
coercedQuery = { ...query };
|
|
584
|
+
for (let i = 0; i < plan.coercions.length; i++) {
|
|
585
|
+
const c = plan.coercions[i];
|
|
586
|
+
const val = query[c.key];
|
|
587
|
+
if (val !== void 0) {
|
|
588
|
+
if (c.isNumber) {
|
|
589
|
+
const num = Number(val);
|
|
590
|
+
if (!isNaN(num)) coercedQuery[c.key] = num;
|
|
591
|
+
} else if (c.isBoolean) {
|
|
592
|
+
if (val === "true" || val === "1") coercedQuery[c.key] = true;
|
|
593
|
+
else if (val === "false" || val === "0") coercedQuery[c.key] = false;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const hasP = isNonEmpty$1(params);
|
|
599
|
+
const hasB = isNonEmpty$1(body);
|
|
600
|
+
const hasQ = isNonEmpty$1(coercedQuery);
|
|
601
|
+
if (plan.isGetLike) {
|
|
602
|
+
if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
603
|
+
else if (hasP && !hasQ && !hasB) input = params;
|
|
604
|
+
else if (hasB && !hasP && !hasQ) input = body;
|
|
605
|
+
else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, params, body);
|
|
606
|
+
} else if (hasB && !hasP && !hasQ) input = body;
|
|
607
|
+
else if (hasP && !hasB && !hasQ) input = params;
|
|
608
|
+
else if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
609
|
+
else if (hasP || hasB || hasQ) input = Object.assign({}, params, body, coercedQuery);
|
|
610
|
+
}
|
|
611
|
+
const ctx = {
|
|
612
|
+
request: request instanceof Request ? request : DEFAULT_REQUEST$2,
|
|
613
|
+
traceId,
|
|
614
|
+
requestId,
|
|
615
|
+
db: plan.cachedDb ?? plan.service.getDb(),
|
|
616
|
+
logger: plan.logger,
|
|
617
|
+
services: EMPTY_SERVICES$2,
|
|
618
|
+
metadata: { headers },
|
|
619
|
+
_resolved: true
|
|
620
|
+
};
|
|
621
|
+
try {
|
|
622
|
+
if (plan.hasContextHook) {
|
|
623
|
+
const extra = plan.contextHook(ctx);
|
|
624
|
+
const resolved = extra instanceof Promise ? await extra : extra;
|
|
625
|
+
if (resolved) Object.assign(ctx, resolved);
|
|
626
|
+
}
|
|
627
|
+
if (input === void 0 && plan.action.config?.input?.type === "object") input = {};
|
|
628
|
+
if (plan.hasInput && plan.inputChecker) {
|
|
629
|
+
if (inputTooDeep(input)) throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, [{
|
|
630
|
+
path: "",
|
|
631
|
+
message: "Input exceeds maximum nesting depth"
|
|
632
|
+
}]);
|
|
633
|
+
if (!plan.inputChecker.Check(input)) {
|
|
634
|
+
const errors = Array.from(plan.inputChecker.Errors(input)).map((err) => ({
|
|
635
|
+
path: err.path,
|
|
636
|
+
message: err.message,
|
|
637
|
+
value: err.value
|
|
638
|
+
}));
|
|
639
|
+
throw new ValidationError(`Validation failed for action '${plan.actionName}' input`, errors);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
if (plan.hasAuthorize) {
|
|
643
|
+
const authRes = plan.authorize({
|
|
644
|
+
ctx,
|
|
645
|
+
input,
|
|
646
|
+
user: ctx.user
|
|
647
|
+
});
|
|
648
|
+
if (!(authRes instanceof Promise ? await authRes : authRes)) throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${plan.actionName}'`, 403);
|
|
649
|
+
}
|
|
650
|
+
const execRes = plan.execute({
|
|
651
|
+
input,
|
|
652
|
+
ctx,
|
|
653
|
+
error: plan.errorBuilder
|
|
654
|
+
});
|
|
655
|
+
const result = execRes instanceof Promise ? await execRes : execRes;
|
|
656
|
+
if (plan.outputChecker) {
|
|
657
|
+
if (!plan.outputChecker.Check(result)) {
|
|
658
|
+
const errors = Array.from(plan.outputChecker.Errors(result)).map((err) => ({
|
|
659
|
+
path: err.path,
|
|
660
|
+
message: err.message,
|
|
661
|
+
value: err.value
|
|
662
|
+
}));
|
|
663
|
+
throw new ValidationError(`Validation failed for action '${plan.actionName}' output`, errors, 500);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return result;
|
|
667
|
+
} catch (err) {
|
|
668
|
+
if (err instanceof ValidationError || err instanceof ActionExecutionError) {
|
|
669
|
+
set.status = err.status || 400;
|
|
670
|
+
return err.toJSON();
|
|
671
|
+
}
|
|
672
|
+
set.status = 500;
|
|
673
|
+
return {
|
|
674
|
+
name: "InternalServerError",
|
|
675
|
+
message: err.message || "An unexpected error occurred",
|
|
676
|
+
status: 500
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
function createActionHandler(service, action, routePath, method) {
|
|
681
|
+
const plan = compileRoutePlan(service, action, routePath, method);
|
|
682
|
+
return (elysiaCtx) => executeCompiledRoute(plan, elysiaCtx);
|
|
683
|
+
}
|
|
684
|
+
//#endregion
|
|
685
|
+
//#region src/compiler/ir.ts
|
|
686
|
+
function freezeIR(value) {
|
|
687
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
688
|
+
for (const child of Object.values(value)) freezeIR(child);
|
|
689
|
+
Object.freeze(value);
|
|
690
|
+
}
|
|
691
|
+
return value;
|
|
692
|
+
}
|
|
693
|
+
function schemaSnapshot(schema) {
|
|
694
|
+
return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
|
|
695
|
+
}
|
|
696
|
+
function analyzeApplication(services, prefix = "/api") {
|
|
697
|
+
if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
|
|
698
|
+
const names = /* @__PURE__ */ new Set();
|
|
699
|
+
for (const service of services) {
|
|
700
|
+
if (names.has(service.name)) throw new Error(`Brick compiler: duplicate service '${service.name}'`);
|
|
701
|
+
names.add(service.name);
|
|
702
|
+
service.build();
|
|
703
|
+
}
|
|
704
|
+
const routes = [];
|
|
705
|
+
const bindings = [];
|
|
706
|
+
const registered = /* @__PURE__ */ new Map();
|
|
707
|
+
const diagnostics = [];
|
|
708
|
+
const add = (service, action, method, path, kind) => {
|
|
709
|
+
if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
|
|
710
|
+
const plugin = getPluginActionRoute(action, prefix) !== void 0;
|
|
711
|
+
const key = `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
712
|
+
const previous = registered.get(key);
|
|
713
|
+
if (previous) {
|
|
714
|
+
if (plugin || previous.plugin) throw new Error(`Brick compiler: duplicate plugin route '${method} ${path}'`);
|
|
715
|
+
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
719
|
+
registered.set(key, {
|
|
720
|
+
name: `${service.name}.${action.name}`,
|
|
721
|
+
plugin
|
|
722
|
+
});
|
|
723
|
+
const readLike = method === "GET" || action.name.startsWith("get") || action.name.endsWith(".get") || action.name.startsWith("list") || action.name.endsWith(".list") || action.name.startsWith("find") || action.name.startsWith("read");
|
|
724
|
+
const coercions = [];
|
|
725
|
+
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
|
|
726
|
+
key,
|
|
727
|
+
type: "number"
|
|
728
|
+
});
|
|
729
|
+
else if (prop.type === "boolean") coercions.push({
|
|
730
|
+
key,
|
|
731
|
+
type: "boolean"
|
|
732
|
+
});
|
|
733
|
+
routes.push({
|
|
734
|
+
method,
|
|
735
|
+
path,
|
|
736
|
+
service: service.name,
|
|
737
|
+
action: action.name,
|
|
738
|
+
kind,
|
|
739
|
+
input: Boolean(action.config.input),
|
|
740
|
+
output: Boolean(action.config.output),
|
|
741
|
+
context: typeof service.options.context === "function",
|
|
742
|
+
authorize: typeof action.config.authorize === "function",
|
|
743
|
+
inputPrecedence: readLike ? [
|
|
744
|
+
"query",
|
|
745
|
+
"params",
|
|
746
|
+
"body"
|
|
747
|
+
] : [
|
|
748
|
+
"params",
|
|
749
|
+
"body",
|
|
750
|
+
"query"
|
|
751
|
+
],
|
|
752
|
+
coercions,
|
|
753
|
+
inputSchema: schemaSnapshot(action.config.input),
|
|
754
|
+
outputSchema: schemaSnapshot(action.config.output)
|
|
755
|
+
});
|
|
756
|
+
bindings.push({
|
|
757
|
+
service,
|
|
758
|
+
action
|
|
759
|
+
});
|
|
760
|
+
};
|
|
761
|
+
for (const service of services) for (const action of service.listActions()) {
|
|
762
|
+
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
763
|
+
if (pluginRoute === false) continue;
|
|
764
|
+
const path = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
765
|
+
add(service, action, pluginRoute?.method ?? action.config.method ?? "POST", path, "action");
|
|
766
|
+
}
|
|
767
|
+
const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
|
|
768
|
+
service: service.name,
|
|
769
|
+
name: contribution.name,
|
|
770
|
+
metadata: schemaSnapshot(contribution.describe?.())
|
|
771
|
+
})));
|
|
772
|
+
return {
|
|
773
|
+
ir: freezeIR({
|
|
774
|
+
version: 1,
|
|
775
|
+
target: "bun-elysia",
|
|
776
|
+
prefix,
|
|
777
|
+
services: [...names],
|
|
778
|
+
routes,
|
|
779
|
+
preparations,
|
|
780
|
+
diagnostics
|
|
781
|
+
}),
|
|
782
|
+
bindings
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
//#endregion
|
|
786
|
+
//#region src/compiler/emit.ts
|
|
787
|
+
/** Emits framework code only. User callbacks remain closures bound separately. */
|
|
788
|
+
function emitHandlerFactory(route) {
|
|
789
|
+
const name = JSON.stringify(route.action);
|
|
790
|
+
const fields = route.input ? "params, body, query, headers, request, set" : "headers, request, set";
|
|
791
|
+
const input = ["let input;"];
|
|
792
|
+
if (route.input) {
|
|
793
|
+
input.push("let coercedQuery = query;");
|
|
794
|
+
if (route.coercions.length) {
|
|
795
|
+
input.push("if (query) {", "coercedQuery = { ...query };");
|
|
796
|
+
for (const [index, coercion] of route.coercions.entries()) {
|
|
797
|
+
const key = JSON.stringify(coercion.key);
|
|
798
|
+
input.push(`const v${index} = query[${key}];`);
|
|
799
|
+
if (coercion.type === "number") input.push(`if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`);
|
|
800
|
+
else input.push(`if (v${index} === "true" || v${index} === "1") coercedQuery[${key}] = true; else if (v${index} === "false" || v${index} === "0") coercedQuery[${key}] = false;`);
|
|
801
|
+
}
|
|
802
|
+
input.push("}");
|
|
803
|
+
}
|
|
804
|
+
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source).join(", ")});`);
|
|
805
|
+
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
806
|
+
}
|
|
807
|
+
const asyncStages = route.context || route.authorize;
|
|
808
|
+
const context = route.context ? "const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);" : "";
|
|
809
|
+
const validation = route.input ? `validate(inputChecker, input, ${name}, "input");` : "";
|
|
810
|
+
const authorization = route.authorize ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});` : "";
|
|
811
|
+
const output = route.output ? `validate(outputChecker, result, ${name}, "output");` : "";
|
|
812
|
+
const execute = asyncStages ? `const result = await execute({ input, ctx, error: errorBuilder });\n${output}\nreturn result;` : `const result = execute({ input, ctx, error: errorBuilder });
|
|
813
|
+
if (isThenable(result)) return Promise.resolve(result).then(value => {
|
|
814
|
+
${route.output ? `validate(outputChecker, value, ${name}, "output");` : ""}
|
|
815
|
+
return value;
|
|
816
|
+
}).catch(err => mapError(err, set));
|
|
817
|
+
${output}
|
|
818
|
+
return result;`;
|
|
819
|
+
return `function bindAction(binding, runtime) {
|
|
820
|
+
const { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;
|
|
821
|
+
const { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;
|
|
822
|
+
return ${asyncStages ? "async " : ""}function brickAction({ ${fields} }) {
|
|
823
|
+
const seq = nextSequence();
|
|
824
|
+
const traceId = (headers && headers["x-trace-id"]) || "tr_" + seq;
|
|
825
|
+
const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
|
|
826
|
+
if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
|
|
827
|
+
${input.join("\n")}
|
|
828
|
+
const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
|
|
829
|
+
db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
|
|
830
|
+
try {
|
|
831
|
+
${context}
|
|
832
|
+
${validation}
|
|
833
|
+
${authorization}
|
|
834
|
+
${execute}
|
|
835
|
+
} catch (err) { return mapError(err, set); }
|
|
836
|
+
};
|
|
837
|
+
}`;
|
|
838
|
+
}
|
|
839
|
+
//#endregion
|
|
840
|
+
//#region src/compiler/runtime.ts
|
|
841
|
+
const EMPTY_SERVICES$1 = Object.freeze({});
|
|
842
|
+
const DEFAULT_REQUEST$1 = new Request("http://localhost");
|
|
843
|
+
let sequence = 0;
|
|
844
|
+
function isNonEmpty(value) {
|
|
845
|
+
if (value == null) return false;
|
|
846
|
+
for (const _ in value) return true;
|
|
847
|
+
return false;
|
|
848
|
+
}
|
|
849
|
+
/** Retains Brick's existing source precedence and treatment of empty bodies. */
|
|
850
|
+
function mergeInput(first, second, third) {
|
|
851
|
+
const a = isNonEmpty(first), b = isNonEmpty(second), c = isNonEmpty(third);
|
|
852
|
+
if (a && !b && !c) return first;
|
|
853
|
+
if (b && !a && !c) return second;
|
|
854
|
+
if (c && !a && !b) return third;
|
|
855
|
+
if (a || b || c) return Object.assign({}, first, second, third);
|
|
856
|
+
}
|
|
857
|
+
function validate(check, value, action, stage) {
|
|
858
|
+
if (check.Check(value)) return;
|
|
859
|
+
const errors = Array.from(check.Errors(value)).map((err) => ({
|
|
860
|
+
path: err.path,
|
|
861
|
+
message: err.message,
|
|
862
|
+
value: err.value
|
|
863
|
+
}));
|
|
864
|
+
throw new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
|
|
865
|
+
}
|
|
866
|
+
function mapError(err, set) {
|
|
867
|
+
if (err instanceof ValidationError || err instanceof ActionExecutionError) {
|
|
868
|
+
set.status = err.status || 400;
|
|
869
|
+
return err.toJSON();
|
|
870
|
+
}
|
|
871
|
+
set.status = 500;
|
|
872
|
+
return {
|
|
873
|
+
name: "InternalServerError",
|
|
874
|
+
message: err?.message || "An unexpected error occurred",
|
|
875
|
+
status: 500
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
const compilerRuntime = Object.freeze({
|
|
879
|
+
emptyServices: EMPTY_SERVICES$1,
|
|
880
|
+
defaultRequest: DEFAULT_REQUEST$1,
|
|
881
|
+
nextSequence: () => (++sequence).toString(36),
|
|
882
|
+
mergeInput,
|
|
883
|
+
validate,
|
|
884
|
+
mapError,
|
|
885
|
+
isThenable: (value) => value != null && typeof value.then === "function",
|
|
886
|
+
deny: (action) => {
|
|
887
|
+
throw new ActionExecutionError("UNAUTHORIZED", `Access denied for action '${action}'`, 403);
|
|
888
|
+
}
|
|
889
|
+
});
|
|
890
|
+
//#endregion
|
|
891
|
+
//#region src/app-entry.ts
|
|
892
|
+
function isBrickApp(app) {
|
|
893
|
+
if (!app || typeof app !== "object") return false;
|
|
894
|
+
return "endpoint" in app && typeof app.endpoint === "function" && "fetch" in app && typeof app.fetch === "function" && "listen" in app && typeof app.listen === "function" && "definition" in app && !!app.definition && typeof app.definition === "object" && "services" in app.definition && Array.isArray(app.definition.services) && "prefix" in app.definition && typeof app.definition.prefix === "string";
|
|
895
|
+
}
|
|
896
|
+
function requireBrickApp(app) {
|
|
897
|
+
if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
|
|
898
|
+
if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
|
|
899
|
+
return app;
|
|
900
|
+
}
|
|
901
|
+
//#endregion
|
|
902
|
+
//#region src/compiler.ts
|
|
903
|
+
const buildBindings = /* @__PURE__ */ new Map();
|
|
904
|
+
function applicationKey(services, prefix = "/api") {
|
|
905
|
+
return JSON.stringify([prefix, services.map((service) => service.name)]);
|
|
906
|
+
}
|
|
907
|
+
/** Build artifact bootstrap: bind generated handlers while evaluating the original app. */
|
|
908
|
+
async function loadCompiledBrickApp(load, ir, bind) {
|
|
909
|
+
const key = JSON.stringify([ir.prefix, ir.services]);
|
|
910
|
+
if (buildBindings.has(key)) throw new Error("Brick compiler: overlapping compiled app imports");
|
|
911
|
+
buildBindings.set(key, bind);
|
|
912
|
+
try {
|
|
913
|
+
const app = requireBrickApp((await load()).default);
|
|
914
|
+
if (applicationKey(app.definition.services, app.definition.prefix) !== key) throw new Error("Brick compiler: app services/prefix changed; rebuild the application");
|
|
915
|
+
return app;
|
|
916
|
+
} finally {
|
|
917
|
+
buildBindings.delete(key);
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
function bindAnalyzed(ir, bindings, factories) {
|
|
921
|
+
if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
|
|
922
|
+
const routes = ir.routes.map((route, index) => {
|
|
923
|
+
const { service, action } = bindings[index];
|
|
924
|
+
const plan = Object.freeze(compileRoutePlan(service, action, route.path, route.method));
|
|
925
|
+
const handler = factories[index](plan, compilerRuntime);
|
|
926
|
+
return Object.freeze({
|
|
927
|
+
ir: route,
|
|
928
|
+
handler
|
|
929
|
+
});
|
|
930
|
+
});
|
|
931
|
+
return Object.freeze({
|
|
932
|
+
ir: freezeIR(ir),
|
|
933
|
+
routes: Object.freeze(routes)
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */
|
|
937
|
+
function compileBrickApplication(options) {
|
|
938
|
+
const bind = buildBindings.get(applicationKey(options.services, options.prefix));
|
|
939
|
+
if (bind && options.mode !== "generic") return bind(options.services);
|
|
940
|
+
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
941
|
+
const factories = options.mode === "generic" ? ir.routes.map(() => (plan) => (context) => executeCompiledRoute(plan, context)) : ir.routes.map((route) => new Function(`return (${emitHandlerFactory(route)});`)());
|
|
942
|
+
if (options.mode !== "generic") for (const service of options.services) service.prepareContributions();
|
|
943
|
+
return bindAnalyzed(ir, bindings, factories);
|
|
944
|
+
}
|
|
945
|
+
/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */
|
|
946
|
+
function bindCompiledApplication(ir, services, factories) {
|
|
947
|
+
if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
|
|
948
|
+
const analyzed = analyzeApplication(services, ir.prefix);
|
|
949
|
+
if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
|
|
950
|
+
for (const service of services) service.prepareContributions();
|
|
951
|
+
return bindAnalyzed(ir, analyzed.bindings, factories);
|
|
952
|
+
}
|
|
953
|
+
//#endregion
|
|
954
|
+
//#region src/openapi.ts
|
|
955
|
+
function generateOpenApiSpec(options = {}) {
|
|
956
|
+
const title = options.title ?? "Brick-TS API Mesh";
|
|
957
|
+
const version = options.version ?? "1.0.0";
|
|
958
|
+
const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
|
|
959
|
+
const prefix = options.prefix ?? "/api";
|
|
960
|
+
const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
|
|
961
|
+
const paths = {};
|
|
962
|
+
const tagsSet = /* @__PURE__ */ new Set();
|
|
963
|
+
let hasAnyAuthorizedAction = false;
|
|
964
|
+
for (const service of services) {
|
|
965
|
+
tagsSet.add(service.name);
|
|
966
|
+
for (const action of service.listActions()) {
|
|
967
|
+
const pluginRoute = getPluginActionRoute(action, prefix);
|
|
968
|
+
if (pluginRoute === false) continue;
|
|
969
|
+
const routePath = pluginRoute?.path ?? action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
970
|
+
const method = (pluginRoute?.method ?? action.config.method ?? "POST").toLowerCase();
|
|
971
|
+
const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
|
|
972
|
+
const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
|
|
973
|
+
if (!paths[actionPath]) paths[actionPath] = {};
|
|
974
|
+
if (paths[actionPath][method]) continue;
|
|
975
|
+
const hasAuth = Boolean(action.config.authorize);
|
|
976
|
+
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
977
|
+
const responses = {};
|
|
978
|
+
if (action.config.output) responses["200"] = {
|
|
979
|
+
description: "Successful response",
|
|
980
|
+
content: { "application/json": { schema: action.config.output } }
|
|
981
|
+
};
|
|
982
|
+
else responses["200"] = { description: "Successful response" };
|
|
983
|
+
if (action.config.input) responses["400"] = {
|
|
984
|
+
description: "Validation error",
|
|
985
|
+
content: { "application/json": { schema: {
|
|
986
|
+
type: "object",
|
|
987
|
+
properties: {
|
|
988
|
+
name: { type: "string" },
|
|
989
|
+
message: { type: "string" },
|
|
990
|
+
status: { type: "integer" },
|
|
991
|
+
errors: {
|
|
992
|
+
type: "array",
|
|
993
|
+
items: {
|
|
994
|
+
type: "object",
|
|
995
|
+
properties: {
|
|
996
|
+
path: { type: "string" },
|
|
997
|
+
message: { type: "string" }
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
} } }
|
|
1003
|
+
};
|
|
1004
|
+
if (hasAuth) responses["403"] = { description: "Access denied / Unauthorized" };
|
|
1005
|
+
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
1006
|
+
const def = errorDef;
|
|
1007
|
+
const status = String(def.status || 400);
|
|
1008
|
+
responses[status] = {
|
|
1009
|
+
description: def.message || code,
|
|
1010
|
+
content: { "application/json": { schema: {
|
|
1011
|
+
type: "object",
|
|
1012
|
+
properties: {
|
|
1013
|
+
name: {
|
|
1014
|
+
type: "string",
|
|
1015
|
+
example: "ActionExecutionError"
|
|
1016
|
+
},
|
|
1017
|
+
code: {
|
|
1018
|
+
type: "string",
|
|
1019
|
+
example: code
|
|
1020
|
+
},
|
|
1021
|
+
message: {
|
|
1022
|
+
type: "string",
|
|
1023
|
+
example: def.message
|
|
1024
|
+
},
|
|
1025
|
+
status: {
|
|
1026
|
+
type: "integer",
|
|
1027
|
+
example: def.status || 400
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
} } }
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
responses["500"] = { description: "Internal server error" };
|
|
1034
|
+
const operation = {
|
|
1035
|
+
operationId: `${service.name}_${action.name}_${method}`,
|
|
1036
|
+
summary: `${service.name}.${action.name}`,
|
|
1037
|
+
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
1038
|
+
tags: action.config.tags && action.config.tags.length > 0 ? action.config.tags : [service.name],
|
|
1039
|
+
responses
|
|
1040
|
+
};
|
|
1041
|
+
const inputSchema = action.config.input;
|
|
1042
|
+
const properties = inputSchema?.properties ?? {};
|
|
1043
|
+
const parameters = [...new Set(pathParams)].map((key) => ({
|
|
1044
|
+
name: key,
|
|
1045
|
+
in: "path",
|
|
1046
|
+
required: true,
|
|
1047
|
+
schema: properties[key] ?? { type: "string" }
|
|
1048
|
+
}));
|
|
1049
|
+
if (method === "get" || method === "delete") for (const [key, schema] of Object.entries(properties)) {
|
|
1050
|
+
if (pathParams.includes(key)) continue;
|
|
1051
|
+
parameters.push({
|
|
1052
|
+
name: key,
|
|
1053
|
+
in: "query",
|
|
1054
|
+
required: inputSchema?.required?.includes(key) ?? false,
|
|
1055
|
+
schema
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
else if (inputSchema) operation.requestBody = {
|
|
1059
|
+
required: true,
|
|
1060
|
+
content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
|
|
1061
|
+
...inputSchema,
|
|
1062
|
+
properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
|
|
1063
|
+
required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
|
|
1064
|
+
} : inputSchema } }
|
|
1065
|
+
};
|
|
1066
|
+
if (parameters.length) operation.parameters = parameters;
|
|
1067
|
+
if (hasAuth) operation.security = [{ bearerAuth: [] }];
|
|
1068
|
+
paths[actionPath][method] = operation;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
const spec = {
|
|
1072
|
+
openapi: "3.1.0",
|
|
1073
|
+
info: {
|
|
1074
|
+
title,
|
|
1075
|
+
version,
|
|
1076
|
+
description
|
|
1077
|
+
},
|
|
1078
|
+
paths,
|
|
1079
|
+
tags: Array.from(tagsSet).map((name) => ({
|
|
1080
|
+
name,
|
|
1081
|
+
description: `Actions exposed by '${name}' service`
|
|
1082
|
+
}))
|
|
1083
|
+
};
|
|
1084
|
+
if (hasAnyAuthorizedAction) spec.components = { securitySchemes: { bearerAuth: {
|
|
1085
|
+
type: "http",
|
|
1086
|
+
scheme: "bearer",
|
|
1087
|
+
bearerFormat: "JWT",
|
|
1088
|
+
description: "Enter your Bearer authentication token"
|
|
1089
|
+
} } };
|
|
1090
|
+
return spec;
|
|
1091
|
+
}
|
|
1092
|
+
//#endregion
|
|
1093
|
+
//#region src/secrets.ts
|
|
1094
|
+
/** Default source: `process.env` (Bun loads `.env` into it automatically). */
|
|
1095
|
+
const envSource = { get: (name) => process.env[name] };
|
|
1096
|
+
const registry = /* @__PURE__ */ new Map();
|
|
1097
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
1098
|
+
var SecretRef = class {
|
|
1099
|
+
name;
|
|
1100
|
+
options;
|
|
1101
|
+
transformFn;
|
|
1102
|
+
validators = [];
|
|
1103
|
+
constructor(name, options = {}) {
|
|
1104
|
+
this.name = name;
|
|
1105
|
+
this.options = options;
|
|
1106
|
+
}
|
|
1107
|
+
/** True when a default was declared (i.e. the secret is optional). */
|
|
1108
|
+
get hasDefault() {
|
|
1109
|
+
return this.options.default !== void 0;
|
|
1110
|
+
}
|
|
1111
|
+
/** Fallback used when the source has no value. Makes the secret optional. */
|
|
1112
|
+
default(value) {
|
|
1113
|
+
this.options.default = value;
|
|
1114
|
+
return this;
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
|
|
1118
|
+
* Runs before validators; a throwing transform fails resolution.
|
|
1119
|
+
*/
|
|
1120
|
+
transform(fn) {
|
|
1121
|
+
this.transformFn = fn;
|
|
1122
|
+
return this;
|
|
1123
|
+
}
|
|
1124
|
+
/** Run a custom check on the (transformed) value at every resolution. */
|
|
1125
|
+
validate(fn) {
|
|
1126
|
+
this.validators.push(fn);
|
|
1127
|
+
return this;
|
|
1128
|
+
}
|
|
1129
|
+
/** Shorthand validator: value must parse as a URL. String refs only. */
|
|
1130
|
+
url() {
|
|
1131
|
+
this.validators.push((v) => {
|
|
1132
|
+
try {
|
|
1133
|
+
new URL(v);
|
|
1134
|
+
} catch {
|
|
1135
|
+
return "must be a valid URL";
|
|
1136
|
+
}
|
|
1137
|
+
});
|
|
1138
|
+
return this;
|
|
1139
|
+
}
|
|
1140
|
+
resolveRaw(source) {
|
|
1141
|
+
if (overrides.has(this.name)) {
|
|
1142
|
+
const v = overrides.get(this.name);
|
|
1143
|
+
if (v !== void 0) return v;
|
|
1144
|
+
}
|
|
1145
|
+
return source.get(this.name) ?? this.options.default;
|
|
1146
|
+
}
|
|
1147
|
+
coerce(raw) {
|
|
1148
|
+
let value;
|
|
1149
|
+
if (this.transformFn) try {
|
|
1150
|
+
value = this.transformFn(raw);
|
|
1151
|
+
} catch (err) {
|
|
1152
|
+
throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
|
|
1153
|
+
}
|
|
1154
|
+
else value = raw;
|
|
1155
|
+
for (const fn of this.validators) {
|
|
1156
|
+
let result;
|
|
1157
|
+
try {
|
|
1158
|
+
result = fn(value);
|
|
1159
|
+
} catch (err) {
|
|
1160
|
+
throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
|
|
1161
|
+
}
|
|
1162
|
+
if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
|
|
1163
|
+
if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
|
|
1164
|
+
}
|
|
1165
|
+
return value;
|
|
1166
|
+
}
|
|
1167
|
+
/** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
|
|
1168
|
+
value(source = envSource) {
|
|
1169
|
+
const raw = this.resolveRaw(source);
|
|
1170
|
+
if (raw === void 0) return void 0;
|
|
1171
|
+
return this.coerce(raw);
|
|
1172
|
+
}
|
|
1173
|
+
/** Resolved value, or throws naming the missing/invalid secret. */
|
|
1174
|
+
require(source = envSource) {
|
|
1175
|
+
const raw = this.resolveRaw(source);
|
|
1176
|
+
if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
|
|
1177
|
+
return this.coerce(raw);
|
|
1178
|
+
}
|
|
1179
|
+
/** True when a value would resolve (override, source, or default). */
|
|
1180
|
+
isSet(source = envSource) {
|
|
1181
|
+
return this.resolveRaw(source) !== void 0;
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
/**
|
|
1185
|
+
* Declare a secret. Idempotent: re-declaring the same name returns the
|
|
1186
|
+
* original ref (first declaration wins) so module re-evaluation is safe.
|
|
1187
|
+
*/
|
|
1188
|
+
function secret(name, options = {}) {
|
|
1189
|
+
const existing = registry.get(name);
|
|
1190
|
+
if (existing) return existing;
|
|
1191
|
+
const ref = new SecretRef(name, options);
|
|
1192
|
+
registry.set(name, ref);
|
|
1193
|
+
return ref;
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Validate every registered secret at boot. Throws a single error listing
|
|
1197
|
+
* all missing required secrets. Returns the resolved values.
|
|
1198
|
+
*/
|
|
1199
|
+
function resolveSecrets(opts = {}) {
|
|
1200
|
+
const source = opts.source ?? envSource;
|
|
1201
|
+
const missing = [];
|
|
1202
|
+
const resolved = {};
|
|
1203
|
+
for (const ref of registry.values()) {
|
|
1204
|
+
const v = ref.value(source);
|
|
1205
|
+
if (v === void 0) missing.push(ref.name);
|
|
1206
|
+
else resolved[ref.name] = v;
|
|
1207
|
+
}
|
|
1208
|
+
if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
|
|
1209
|
+
return resolved;
|
|
1210
|
+
}
|
|
1211
|
+
/** Metadata for introspection (values never exposed — future dashboard use). */
|
|
1212
|
+
function listSecrets(opts = {}) {
|
|
1213
|
+
const source = opts.source ?? envSource;
|
|
1214
|
+
return [...registry.values()].map((ref) => ({
|
|
1215
|
+
hasDefault: ref.hasDefault,
|
|
1216
|
+
isSet: ref.isSet(source),
|
|
1217
|
+
name: ref.name
|
|
1218
|
+
}));
|
|
1219
|
+
}
|
|
1220
|
+
/** Test/session override for one secret (`undefined` clears the override). */
|
|
1221
|
+
function overrideSecret(name, value) {
|
|
1222
|
+
overrides.set(name, value);
|
|
1223
|
+
}
|
|
1224
|
+
/** Bulk overrides (test/session scoped). */
|
|
1225
|
+
function overrideSecrets(values) {
|
|
1226
|
+
for (const [name, value] of Object.entries(values)) overrides.set(name, value);
|
|
1227
|
+
}
|
|
1228
|
+
/** Clear registry and overrides. Test-only. */
|
|
1229
|
+
function resetSecrets() {
|
|
1230
|
+
registry.clear();
|
|
1231
|
+
overrides.clear();
|
|
1232
|
+
}
|
|
1233
|
+
//#endregion
|
|
1234
|
+
//#region src/request-logger.ts
|
|
1235
|
+
function formatLog(method, path, status, elapsedMs) {
|
|
1236
|
+
return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError
|
|
1240
|
+
* while `set.status` may still hold the 200 default when onError runs).
|
|
1241
|
+
*/
|
|
1242
|
+
function thrownStatus(error) {
|
|
1243
|
+
if (typeof error === "object" && error !== null && "status" in error) {
|
|
1244
|
+
const status = error.status;
|
|
1245
|
+
if (typeof status === "number") return status;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
|
|
1250
|
+
* Timing is tracked per-Request via a WeakMap. The onError hook only logs and
|
|
1251
|
+
* returns undefined so existing error mapping is preserved. Logging only —
|
|
1252
|
+
* no CORS headers are set here.
|
|
1253
|
+
*
|
|
1254
|
+
* Hooks are registered with the "global" scope so they propagate to the
|
|
1255
|
+
* parent app when mounted via `app.use(...)` — Elysia scopes plain instance
|
|
1256
|
+
* hooks to the plugin's own routes. Timing is captured in beforeHandle
|
|
1257
|
+
* because request hooks are not propagated from a
|
|
1258
|
+
* used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
|
|
1259
|
+
*/
|
|
1260
|
+
function requestLoggingPlugin(opts = {}) {
|
|
1261
|
+
const plugin = new Elysia();
|
|
1262
|
+
if (!(opts.enabled ?? true)) return plugin;
|
|
1263
|
+
const logger = opts.logger ?? console.log;
|
|
1264
|
+
const startedAt = /* @__PURE__ */ new WeakMap();
|
|
1265
|
+
const markStarted = ({ request }) => {
|
|
1266
|
+
startedAt.set(request, Date.now());
|
|
1267
|
+
};
|
|
1268
|
+
const logSuccess = ({ request, set }) => {
|
|
1269
|
+
const start = startedAt.get(request) ?? Date.now();
|
|
1270
|
+
const path = new URL(request.url).pathname;
|
|
1271
|
+
logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
|
|
1272
|
+
};
|
|
1273
|
+
const logError = ({ request, set, error }) => {
|
|
1274
|
+
if (request) {
|
|
1275
|
+
const start = startedAt.get(request) ?? Date.now();
|
|
1276
|
+
const path = new URL(request.url).pathname;
|
|
1277
|
+
const status = thrownStatus(error) ?? set.status ?? 500;
|
|
1278
|
+
logger(formatLog(request.method, path, status, Date.now() - start));
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
plugin.beforeHandle("global", markStarted);
|
|
1282
|
+
plugin.afterHandle("global", logSuccess);
|
|
1283
|
+
plugin.error("global", logError);
|
|
1284
|
+
return plugin;
|
|
1285
|
+
}
|
|
1286
|
+
//#endregion
|
|
1287
|
+
//#region src/docs.ts
|
|
1288
|
+
/** Renders the Scalar API reference page for the given OpenAPI URL. */
|
|
1289
|
+
function scalarDocsHTML(specUrl, title) {
|
|
1290
|
+
return `<!doctype html>
|
|
1291
|
+
<html>
|
|
1292
|
+
<head>
|
|
1293
|
+
<title>${title} — API Reference</title>
|
|
1294
|
+
<meta charset="utf-8" />
|
|
1295
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
1296
|
+
<link rel="icon" type="image/svg+xml" href="https://scalar.com/favicon.svg" />
|
|
1297
|
+
<style>
|
|
1298
|
+
body { margin: 0; padding: 0; height: 100vh; }
|
|
1299
|
+
</style>
|
|
1300
|
+
</head>
|
|
1301
|
+
<body>
|
|
1302
|
+
<script
|
|
1303
|
+
id="api-reference"
|
|
1304
|
+
data-url="${specUrl}"
|
|
1305
|
+
data-configuration='{"theme": "purple", "layout": "modern"}'
|
|
1306
|
+
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference">
|
|
1307
|
+
<\/script>
|
|
1308
|
+
</body>
|
|
1309
|
+
</html>`;
|
|
1310
|
+
}
|
|
1311
|
+
/** Standalone Elysia plugin serving GET <path> with the Scalar HTML page. */
|
|
1312
|
+
function referencePlugin(opts = {}) {
|
|
1313
|
+
const path = opts.path ?? "/reference";
|
|
1314
|
+
const title = opts.title ?? "Brick-TS API Mesh";
|
|
1315
|
+
const specUrl = opts.specUrl ?? "/openapi.json";
|
|
1316
|
+
const plugin = new Elysia();
|
|
1317
|
+
plugin.get(path, ({ set }) => {
|
|
1318
|
+
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
1319
|
+
return scalarDocsHTML(specUrl, title);
|
|
1320
|
+
});
|
|
1321
|
+
return plugin;
|
|
1322
|
+
}
|
|
1323
|
+
/** Mounts the Scalar reference route onto an existing app. */
|
|
1324
|
+
function registerReferenceRoute(app, opts = {}) {
|
|
1325
|
+
return app.use(referencePlugin(opts));
|
|
1326
|
+
}
|
|
1327
|
+
/** Renders the Swagger UI page. */
|
|
1328
|
+
function swaggerDocsHTML(specUrl, title) {
|
|
1329
|
+
return `<!DOCTYPE html>
|
|
1330
|
+
<html lang="en">
|
|
1331
|
+
<head>
|
|
1332
|
+
<meta charset="UTF-8">
|
|
1333
|
+
<title>${title} — Swagger UI</title>
|
|
1334
|
+
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
|
|
1335
|
+
<style>
|
|
1336
|
+
html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }
|
|
1337
|
+
*, *:before, *:after { box-sizing: inherit; }
|
|
1338
|
+
body { margin:0; background: #fafafa; }
|
|
1339
|
+
</style>
|
|
1340
|
+
</head>
|
|
1341
|
+
<body>
|
|
1342
|
+
<div id="swagger-ui"></div>
|
|
1343
|
+
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" charset="UTF-8"><\/script>
|
|
1344
|
+
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js" charset="UTF-8"><\/script>
|
|
1345
|
+
<script>
|
|
1346
|
+
window.onload = function() {
|
|
1347
|
+
SwaggerUIBundle({
|
|
1348
|
+
url: "${specUrl}",
|
|
1349
|
+
dom_id: '#swagger-ui',
|
|
1350
|
+
deepLinking: true,
|
|
1351
|
+
presets: [
|
|
1352
|
+
SwaggerUIBundle.presets.apis,
|
|
1353
|
+
SwaggerUIStandalonePreset
|
|
1354
|
+
],
|
|
1355
|
+
plugins: [
|
|
1356
|
+
SwaggerUIBundle.plugins.DownloadUrl
|
|
1357
|
+
],
|
|
1358
|
+
layout: "StandaloneLayout"
|
|
1359
|
+
});
|
|
1360
|
+
};
|
|
1361
|
+
<\/script>
|
|
1362
|
+
</body>
|
|
1363
|
+
</html>`;
|
|
1364
|
+
}
|
|
1365
|
+
//#endregion
|
|
1366
|
+
//#region src/endpoints.ts
|
|
1367
|
+
/** Resolve the db for an endpoint: explicit service first, else first service holding one. */
|
|
1368
|
+
function resolveEndpointDb(service, services) {
|
|
1369
|
+
if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb() ?? void 0;
|
|
1370
|
+
for (const svc of services) {
|
|
1371
|
+
const db = svc.getDb();
|
|
1372
|
+
if (db) return db;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
|
|
1376
|
+
function createEndpointHandler(def, services) {
|
|
1377
|
+
return async ({ params, body, query, headers, request, set }) => {
|
|
1378
|
+
const traceId = headers?.["x-trace-id"] || `tr_${Math.random().toString(36).substring(2, 10)}`;
|
|
1379
|
+
const requestId = headers?.["x-request-id"] || `req_${Math.random().toString(36).substring(2, 10)}`;
|
|
1380
|
+
if (set?.headers) {
|
|
1381
|
+
set.headers["x-trace-id"] = traceId;
|
|
1382
|
+
set.headers["x-request-id"] = requestId;
|
|
1383
|
+
}
|
|
1384
|
+
const tag = `endpoint:${def.method} ${def.path}`;
|
|
1385
|
+
const ctx = {
|
|
1386
|
+
body,
|
|
1387
|
+
db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
|
|
1388
|
+
headers: headers ?? {},
|
|
1389
|
+
logger: {
|
|
1390
|
+
info: (...args) => console.log(`[${tag}]`, ...args),
|
|
1391
|
+
warn: (...args) => console.warn(`[${tag}]`, ...args),
|
|
1392
|
+
error: (...args) => console.error(`[${tag}]`, ...args),
|
|
1393
|
+
debug: (...args) => console.debug(`[${tag}]`, ...args)
|
|
1394
|
+
},
|
|
1395
|
+
params: params ?? {},
|
|
1396
|
+
query: query ?? {},
|
|
1397
|
+
request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
|
|
1398
|
+
headers: new Headers(headers ?? {}),
|
|
1399
|
+
method: def.method
|
|
1400
|
+
}),
|
|
1401
|
+
requestId,
|
|
1402
|
+
set,
|
|
1403
|
+
traceId
|
|
1404
|
+
};
|
|
1405
|
+
try {
|
|
1406
|
+
return await def.handler(ctx);
|
|
1407
|
+
} catch (err) {
|
|
1408
|
+
if (err instanceof ValidationError) {
|
|
1409
|
+
set.status = err.status || 400;
|
|
1410
|
+
return err.toJSON();
|
|
1411
|
+
}
|
|
1412
|
+
if (err instanceof ActionExecutionError) {
|
|
1413
|
+
set.status = err.status || 400;
|
|
1414
|
+
return err.toJSON();
|
|
1415
|
+
}
|
|
1416
|
+
if (typeof err?.status === "number") {
|
|
1417
|
+
set.status = err.status;
|
|
1418
|
+
return {
|
|
1419
|
+
message: err.message || "Endpoint error",
|
|
1420
|
+
status: err.status
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
1423
|
+
set.status = 500;
|
|
1424
|
+
return {
|
|
1425
|
+
message: err?.message || "An unexpected error occurred",
|
|
1426
|
+
status: 500
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
/** `/p/:slug` → `/p/{slug}` for OpenAPI. */
|
|
1432
|
+
function toOpenApiPath(elysiaPath) {
|
|
1433
|
+
return elysiaPath.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
1434
|
+
}
|
|
1435
|
+
/** Parameter names (`:slug`) extracted for the OpenAPI path item. */
|
|
1436
|
+
function pathParamNames(elysiaPath) {
|
|
1437
|
+
return [...elysiaPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);
|
|
1438
|
+
}
|
|
1439
|
+
/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
|
|
1440
|
+
function endpointPaths(defs) {
|
|
1441
|
+
const paths = {};
|
|
1442
|
+
for (const def of defs) {
|
|
1443
|
+
const openApiPath = toOpenApiPath(def.path);
|
|
1444
|
+
if (!paths[openApiPath]) paths[openApiPath] = {};
|
|
1445
|
+
const params = pathParamNames(def.path).map((name) => ({
|
|
1446
|
+
in: "path",
|
|
1447
|
+
name,
|
|
1448
|
+
required: true,
|
|
1449
|
+
schema: { type: "string" }
|
|
1450
|
+
}));
|
|
1451
|
+
paths[openApiPath][def.method.toLowerCase()] = {
|
|
1452
|
+
...def.summary ? { summary: def.summary } : {},
|
|
1453
|
+
...def.description ? { description: def.description } : {},
|
|
1454
|
+
...def.tags ? { tags: def.tags } : {},
|
|
1455
|
+
...params.length > 0 ? { parameters: params } : {},
|
|
1456
|
+
responses: { 200: { description: "Successful response" } }
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
1459
|
+
return paths;
|
|
1460
|
+
}
|
|
1461
|
+
//#endregion
|
|
1462
|
+
//#region src/server.ts
|
|
1463
|
+
function brick(options = {}) {
|
|
1464
|
+
const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
|
|
1465
|
+
const title = options.title ?? "Brick-TS API Mesh";
|
|
1466
|
+
const version = options.version ?? "1.0.0";
|
|
1467
|
+
const compiled = options.compiler !== false;
|
|
1468
|
+
const enableDocs = options.docs ?? true;
|
|
1469
|
+
const openApiPath = options.openApiPath ?? "/openapi.json";
|
|
1470
|
+
const docsPath = options.docsPath ?? "/docs";
|
|
1471
|
+
const swaggerPath = options.swaggerPath ?? "/swagger";
|
|
1472
|
+
const app = new Elysia();
|
|
1473
|
+
if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
|
|
1474
|
+
app.get("/_health", () => ({
|
|
1475
|
+
status: "ok",
|
|
1476
|
+
uptime: process.uptime(),
|
|
1477
|
+
timestamp: Date.now()
|
|
1478
|
+
}));
|
|
1479
|
+
app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(), () => {
|
|
1480
|
+
const registry = getGlobalRegistry();
|
|
1481
|
+
return [registry, registry.revision];
|
|
1482
|
+
}) : () => getGlobalRegistry().exportArchitecture());
|
|
1483
|
+
const requestLogging = options.requestLogging ?? true;
|
|
1484
|
+
if (requestLogging !== false) {
|
|
1485
|
+
const pluginOpts = requestLogging === true ? {} : requestLogging;
|
|
1486
|
+
if (pluginOpts.enabled !== false) app.use(requestLoggingPlugin(pluginOpts));
|
|
1487
|
+
}
|
|
1488
|
+
const reference = options.reference ?? false;
|
|
1489
|
+
if (reference !== false) {
|
|
1490
|
+
const refOpts = reference === true ? {} : reference;
|
|
1491
|
+
const settings = {
|
|
1492
|
+
path: refOpts.path ?? "/reference",
|
|
1493
|
+
title: refOpts.title ?? title,
|
|
1494
|
+
specUrl: refOpts.specUrl ?? openApiPath
|
|
1495
|
+
};
|
|
1496
|
+
if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
|
|
1497
|
+
else registerReferenceRoute(app, settings);
|
|
1498
|
+
}
|
|
1499
|
+
const services = options.services ?? getGlobalRegistry().list();
|
|
1500
|
+
for (const service of services) if (typeof service.build === "function") service.build();
|
|
1501
|
+
const endpointDefs = [];
|
|
1502
|
+
let endpointRevision = 0;
|
|
1503
|
+
if (enableDocs) {
|
|
1504
|
+
const buildSpec = () => {
|
|
1505
|
+
const spec = generateOpenApiSpec({
|
|
1506
|
+
title,
|
|
1507
|
+
version,
|
|
1508
|
+
description: options.description,
|
|
1509
|
+
prefix,
|
|
1510
|
+
services
|
|
1511
|
+
});
|
|
1512
|
+
const paths = { ...spec.paths };
|
|
1513
|
+
for (const [path, operations] of Object.entries(endpointPaths(endpointDefs))) paths[path] = {
|
|
1514
|
+
...paths[path],
|
|
1515
|
+
...operations
|
|
1516
|
+
};
|
|
1517
|
+
return {
|
|
1518
|
+
...spec,
|
|
1519
|
+
paths
|
|
1520
|
+
};
|
|
1521
|
+
};
|
|
1522
|
+
app.get(openApiPath, compiled ? cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]) : buildSpec);
|
|
1523
|
+
if (compiled) {
|
|
1524
|
+
app.get(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));
|
|
1525
|
+
app.get(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
|
|
1526
|
+
} else {
|
|
1527
|
+
app.get(docsPath, ({ set }) => {
|
|
1528
|
+
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
1529
|
+
return scalarDocsHTML(openApiPath, title);
|
|
1530
|
+
});
|
|
1531
|
+
app.get(swaggerPath, ({ set }) => {
|
|
1532
|
+
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
1533
|
+
return swaggerDocsHTML(openApiPath, title);
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
const registeredRoutes = /* @__PURE__ */ new Map();
|
|
1538
|
+
const routeKey = (method, path) => `${method} ${path.replace(/:[^/]+/g, ":param")}`;
|
|
1539
|
+
registeredRoutes.set(routeKey("GET", "/_health"), false);
|
|
1540
|
+
registeredRoutes.set(routeKey("GET", "/_brick/services"), false);
|
|
1541
|
+
if (enableDocs) for (const path of [
|
|
1542
|
+
openApiPath,
|
|
1543
|
+
docsPath,
|
|
1544
|
+
swaggerPath
|
|
1545
|
+
]) registeredRoutes.set(routeKey("GET", path), false);
|
|
1546
|
+
if (reference !== false) registeredRoutes.set(routeKey("GET", reference === true ? "/reference" : reference.path ?? "/reference"), false);
|
|
1547
|
+
const mountRoute = (method, path, handler, plugin = false) => {
|
|
1548
|
+
const key = routeKey(method, path);
|
|
1549
|
+
if (registeredRoutes.has(key)) {
|
|
1550
|
+
if (plugin || registeredRoutes.get(key)) throw new Error(`Brick: duplicate plugin route '${method} ${path}'`);
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
switch (method) {
|
|
1554
|
+
case "GET":
|
|
1555
|
+
app.get(path, handler);
|
|
1556
|
+
break;
|
|
1557
|
+
case "POST":
|
|
1558
|
+
app.post(path, handler);
|
|
1559
|
+
break;
|
|
1560
|
+
case "PUT":
|
|
1561
|
+
app.put(path, handler);
|
|
1562
|
+
break;
|
|
1563
|
+
case "PATCH":
|
|
1564
|
+
app.patch(path, handler);
|
|
1565
|
+
break;
|
|
1566
|
+
case "DELETE": app.delete(path, handler);
|
|
1567
|
+
}
|
|
1568
|
+
registeredRoutes.set(key, plugin);
|
|
1569
|
+
};
|
|
1570
|
+
const mountEndpoint = (def, plugin = false) => {
|
|
1571
|
+
mountRoute(def.method, def.path, createEndpointHandler(def, services), plugin);
|
|
1572
|
+
endpointDefs.push(def);
|
|
1573
|
+
endpointRevision++;
|
|
1574
|
+
};
|
|
1575
|
+
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
|
|
1576
|
+
for (const def of options.endpoints ?? []) mountEndpoint(def);
|
|
1577
|
+
const brickApp = app;
|
|
1578
|
+
Object.defineProperty(brickApp, "definition", { value: Object.freeze({
|
|
1579
|
+
services: Object.freeze([...services]),
|
|
1580
|
+
prefix
|
|
1581
|
+
}) });
|
|
1582
|
+
brickApp.endpoint = (def) => {
|
|
1583
|
+
mountEndpoint(def);
|
|
1584
|
+
};
|
|
1585
|
+
brickApp.listEndpoints = () => [...endpointDefs];
|
|
1586
|
+
const compilation = options.compilation ?? compileBrickApplication({
|
|
1587
|
+
services,
|
|
1588
|
+
prefix,
|
|
1589
|
+
mode: options.compiler === false ? "generic" : "specialized"
|
|
1590
|
+
});
|
|
1591
|
+
if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
|
|
1592
|
+
for (const route of compilation.routes) {
|
|
1593
|
+
const action = services.find((candidate) => candidate.name === route.ir.service).listActions().find((candidate) => candidate.name === route.ir.action);
|
|
1594
|
+
mountRoute(route.ir.method, route.ir.path, (context) => {
|
|
1595
|
+
const result = route.handler(context);
|
|
1596
|
+
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
1597
|
+
}, getPluginActionRoute(action, prefix) !== void 0);
|
|
1598
|
+
}
|
|
1599
|
+
return brickApp;
|
|
1600
|
+
}
|
|
1601
|
+
function jsonActionResult(value) {
|
|
1602
|
+
return value === null ? new Response("null", { headers: { "content-type": "application/json" } }) : value;
|
|
1603
|
+
}
|
|
1604
|
+
function htmlResponse(html) {
|
|
1605
|
+
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
1606
|
+
}
|
|
1607
|
+
/** Reuse serialized JSON, without sharing a mutable response body between requests. */
|
|
1608
|
+
function cachedJsonRoute(build, revision) {
|
|
1609
|
+
let [owner, version] = revision();
|
|
1610
|
+
let json = JSON.stringify(build());
|
|
1611
|
+
return ({ set }) => {
|
|
1612
|
+
const [currentOwner, currentVersion] = revision();
|
|
1613
|
+
if (currentOwner !== owner || currentVersion !== version) {
|
|
1614
|
+
json = JSON.stringify(build());
|
|
1615
|
+
owner = currentOwner;
|
|
1616
|
+
version = currentVersion;
|
|
1617
|
+
}
|
|
1618
|
+
set.headers["content-type"] = "application/json;charset=utf-8";
|
|
1619
|
+
return json;
|
|
1620
|
+
};
|
|
217
1621
|
}
|
|
218
1622
|
//#endregion
|
|
219
1623
|
//#region src/tool.ts
|
|
@@ -288,147 +1692,6 @@ function createPostgresDatabase(config = {}) {
|
|
|
288
1692
|
});
|
|
289
1693
|
}
|
|
290
1694
|
//#endregion
|
|
291
|
-
//#region src/secrets.ts
|
|
292
|
-
/** Default source: `process.env` (Bun loads `.env` into it automatically). */
|
|
293
|
-
const envSource = { get: (name) => process.env[name] };
|
|
294
|
-
const registry = /* @__PURE__ */ new Map();
|
|
295
|
-
const overrides = /* @__PURE__ */ new Map();
|
|
296
|
-
var SecretRef = class {
|
|
297
|
-
name;
|
|
298
|
-
options;
|
|
299
|
-
transformFn;
|
|
300
|
-
validators = [];
|
|
301
|
-
constructor(name, options = {}) {
|
|
302
|
-
this.name = name;
|
|
303
|
-
this.options = options;
|
|
304
|
-
}
|
|
305
|
-
/** True when a default was declared (i.e. the secret is optional). */
|
|
306
|
-
get hasDefault() {
|
|
307
|
-
return this.options.default !== void 0;
|
|
308
|
-
}
|
|
309
|
-
/** Fallback used when the source has no value. Makes the secret optional. */
|
|
310
|
-
default(value) {
|
|
311
|
-
this.options.default = value;
|
|
312
|
-
return this;
|
|
313
|
-
}
|
|
314
|
-
/**
|
|
315
|
-
* Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
|
|
316
|
-
* Runs before validators; a throwing transform fails resolution.
|
|
317
|
-
*/
|
|
318
|
-
transform(fn) {
|
|
319
|
-
this.transformFn = fn;
|
|
320
|
-
return this;
|
|
321
|
-
}
|
|
322
|
-
/** Run a custom check on the (transformed) value at every resolution. */
|
|
323
|
-
validate(fn) {
|
|
324
|
-
this.validators.push(fn);
|
|
325
|
-
return this;
|
|
326
|
-
}
|
|
327
|
-
/** Shorthand validator: value must parse as a URL. String refs only. */
|
|
328
|
-
url() {
|
|
329
|
-
this.validators.push((v) => {
|
|
330
|
-
try {
|
|
331
|
-
new URL(v);
|
|
332
|
-
} catch {
|
|
333
|
-
return "must be a valid URL";
|
|
334
|
-
}
|
|
335
|
-
});
|
|
336
|
-
return this;
|
|
337
|
-
}
|
|
338
|
-
resolveRaw(source) {
|
|
339
|
-
if (overrides.has(this.name)) {
|
|
340
|
-
const v = overrides.get(this.name);
|
|
341
|
-
if (v !== void 0) return v;
|
|
342
|
-
}
|
|
343
|
-
return source.get(this.name) ?? this.options.default;
|
|
344
|
-
}
|
|
345
|
-
coerce(raw) {
|
|
346
|
-
let value;
|
|
347
|
-
if (this.transformFn) try {
|
|
348
|
-
value = this.transformFn(raw);
|
|
349
|
-
} catch (err) {
|
|
350
|
-
throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
|
|
351
|
-
}
|
|
352
|
-
else value = raw;
|
|
353
|
-
for (const fn of this.validators) {
|
|
354
|
-
let result;
|
|
355
|
-
try {
|
|
356
|
-
result = fn(value);
|
|
357
|
-
} catch (err) {
|
|
358
|
-
throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
|
|
359
|
-
}
|
|
360
|
-
if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
|
|
361
|
-
if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
|
|
362
|
-
}
|
|
363
|
-
return value;
|
|
364
|
-
}
|
|
365
|
-
/** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
|
|
366
|
-
value(source = envSource) {
|
|
367
|
-
const raw = this.resolveRaw(source);
|
|
368
|
-
if (raw === void 0) return void 0;
|
|
369
|
-
return this.coerce(raw);
|
|
370
|
-
}
|
|
371
|
-
/** Resolved value, or throws naming the missing/invalid secret. */
|
|
372
|
-
require(source = envSource) {
|
|
373
|
-
const raw = this.resolveRaw(source);
|
|
374
|
-
if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
|
|
375
|
-
return this.coerce(raw);
|
|
376
|
-
}
|
|
377
|
-
/** True when a value would resolve (override, source, or default). */
|
|
378
|
-
isSet(source = envSource) {
|
|
379
|
-
return this.resolveRaw(source) !== void 0;
|
|
380
|
-
}
|
|
381
|
-
};
|
|
382
|
-
/**
|
|
383
|
-
* Declare a secret. Idempotent: re-declaring the same name returns the
|
|
384
|
-
* original ref (first declaration wins) so module re-evaluation is safe.
|
|
385
|
-
*/
|
|
386
|
-
function secret(name, options = {}) {
|
|
387
|
-
const existing = registry.get(name);
|
|
388
|
-
if (existing) return existing;
|
|
389
|
-
const ref = new SecretRef(name, options);
|
|
390
|
-
registry.set(name, ref);
|
|
391
|
-
return ref;
|
|
392
|
-
}
|
|
393
|
-
/**
|
|
394
|
-
* Validate every registered secret at boot. Throws a single error listing
|
|
395
|
-
* all missing required secrets. Returns the resolved values.
|
|
396
|
-
*/
|
|
397
|
-
function resolveSecrets(opts = {}) {
|
|
398
|
-
const source = opts.source ?? envSource;
|
|
399
|
-
const missing = [];
|
|
400
|
-
const resolved = {};
|
|
401
|
-
for (const ref of registry.values()) {
|
|
402
|
-
const v = ref.value(source);
|
|
403
|
-
if (v === void 0) missing.push(ref.name);
|
|
404
|
-
else resolved[ref.name] = v;
|
|
405
|
-
}
|
|
406
|
-
if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
|
|
407
|
-
return resolved;
|
|
408
|
-
}
|
|
409
|
-
/** Metadata for introspection (values never exposed — future dashboard use). */
|
|
410
|
-
function listSecrets(opts = {}) {
|
|
411
|
-
const source = opts.source ?? envSource;
|
|
412
|
-
return [...registry.values()].map((ref) => ({
|
|
413
|
-
hasDefault: ref.hasDefault,
|
|
414
|
-
isSet: ref.isSet(source),
|
|
415
|
-
name: ref.name
|
|
416
|
-
}));
|
|
417
|
-
}
|
|
418
|
-
/** Test/session override for one secret (`undefined` clears the override). */
|
|
419
|
-
function overrideSecret(name, value) {
|
|
420
|
-
overrides.set(name, value);
|
|
421
|
-
}
|
|
422
|
-
/** Bulk overrides (test/session scoped). */
|
|
423
|
-
function overrideSecrets(values) {
|
|
424
|
-
for (const [name, value] of Object.entries(values)) overrides.set(name, value);
|
|
425
|
-
}
|
|
426
|
-
/** Clear registry and overrides. Test-only. */
|
|
427
|
-
function resetSecrets() {
|
|
428
|
-
registry.clear();
|
|
429
|
-
overrides.clear();
|
|
430
|
-
}
|
|
431
|
-
//#endregion
|
|
432
1695
|
//#region src/db/define.ts
|
|
433
1696
|
function isDatabaseHandle(value) {
|
|
434
1697
|
return typeof value === "object" && value !== null && "kind" in value && value.kind === "brick-database";
|
|
@@ -667,992 +1930,76 @@ function buildFtsMatchQuery(search) {
|
|
|
667
1930
|
if (terms.length === 0) return null;
|
|
668
1931
|
const escaped = terms.map((term) => {
|
|
669
1932
|
const clean = term.replace(/"/g, "").trim();
|
|
670
|
-
if (!clean) return null;
|
|
671
|
-
return `"${clean.replace(/"/g, "\"\"")}"*`;
|
|
672
|
-
}).filter((x) => !!x);
|
|
673
|
-
if (escaped.length === 0) return null;
|
|
674
|
-
return escaped.join(" AND ");
|
|
675
|
-
}
|
|
676
|
-
/**
|
|
677
|
-
* Explicit SQLite development/test schema preparation helper.
|
|
678
|
-
* Never called by services, resources, auth, or server startup.
|
|
679
|
-
* Not a migration runner; PostgreSQL schema management is caller-owned.
|
|
680
|
-
*/
|
|
681
|
-
function syncSchema(tablesOrService, dbInstance) {
|
|
682
|
-
let db = dbInstance;
|
|
683
|
-
let tables = [];
|
|
684
|
-
if (tablesOrService && typeof tablesOrService.listActions === "function" && tablesOrService.tables) {
|
|
685
|
-
const service = tablesOrService;
|
|
686
|
-
tables = Array.from(service.tables.values());
|
|
687
|
-
if (!db) db = service.getDb();
|
|
688
|
-
} else if (tablesOrService instanceof Map) tables = Array.from(tablesOrService.values());
|
|
689
|
-
else if (Array.isArray(tablesOrService)) tables = tablesOrService;
|
|
690
|
-
else if (tablesOrService && typeof tablesOrService === "object") tables = Object.values(tablesOrService);
|
|
691
|
-
if (!db || tables.length === 0) return;
|
|
692
|
-
if (db.$client?.run || db.run) {
|
|
693
|
-
for (const table of tables) try {
|
|
694
|
-
const ddl = generateSQLiteTableDdl(table);
|
|
695
|
-
if (db.$client?.run) db.$client.run(ddl);
|
|
696
|
-
else if (db.run) db.run(sql$1.raw(ddl));
|
|
697
|
-
} catch (err) {
|
|
698
|
-
console.warn(`[Brick-TS DB] Failed to create table:`, err.message);
|
|
699
|
-
}
|
|
700
|
-
return;
|
|
701
|
-
}
|
|
702
|
-
return (async () => {
|
|
703
|
-
for (const table of tables) try {
|
|
704
|
-
getTableName$1(table);
|
|
705
|
-
} catch (err) {
|
|
706
|
-
console.warn(`[Brick-TS DB] Postgres syncSchema error:`, err.message);
|
|
707
|
-
}
|
|
708
|
-
})();
|
|
709
|
-
}
|
|
710
|
-
//#endregion
|
|
711
|
-
//#region src/resource.ts
|
|
712
|
-
function getColumn(table, fieldName) {
|
|
713
|
-
if (table[fieldName]) return table[fieldName];
|
|
714
|
-
const cols = getTableColumns$1(table);
|
|
715
|
-
if (cols[fieldName]) return cols[fieldName];
|
|
716
|
-
for (const col of Object.values(cols)) if (col.name === fieldName) return col;
|
|
717
|
-
}
|
|
718
|
-
const RESERVED_LIST_KEYS = /* @__PURE__ */ new Set([
|
|
719
|
-
"limit",
|
|
720
|
-
"offset",
|
|
721
|
-
"page",
|
|
722
|
-
"sort",
|
|
723
|
-
"search",
|
|
724
|
-
"select",
|
|
725
|
-
"order",
|
|
726
|
-
"orderBy",
|
|
727
|
-
"cursor"
|
|
728
|
-
]);
|
|
729
|
-
function isStringColumn(col) {
|
|
730
|
-
const dt = col.dataType;
|
|
731
|
-
const ct = col.columnType;
|
|
732
|
-
return dt === "string" || ct === "SQLiteText" || ct === "PgText" || ct === "PgVarchar" || ct === "PgChar" || typeof ct === "string" && ct.toLowerCase().includes("text");
|
|
733
|
-
}
|
|
734
|
-
function resolveSearchColumns(table, columns, explicit) {
|
|
735
|
-
if (explicit && explicit.length > 0) {
|
|
736
|
-
const out = [];
|
|
737
|
-
for (const f of explicit) {
|
|
738
|
-
const col = getColumn(table, f);
|
|
739
|
-
if (col) out.push(col);
|
|
740
|
-
}
|
|
741
|
-
if (out.length > 0) return out;
|
|
742
|
-
}
|
|
743
|
-
const preferred = [
|
|
744
|
-
"title",
|
|
745
|
-
"slug",
|
|
746
|
-
"name",
|
|
747
|
-
"email"
|
|
748
|
-
];
|
|
749
|
-
const found = [];
|
|
750
|
-
for (const key of preferred) {
|
|
751
|
-
const col = getColumn(table, key);
|
|
752
|
-
if (col && isStringColumn(col)) found.push(col);
|
|
753
|
-
}
|
|
754
|
-
if (found.length > 0) return found;
|
|
755
|
-
const out = [];
|
|
756
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
757
|
-
const name = col.name ?? key;
|
|
758
|
-
if (key === "id" || name === "id") continue;
|
|
759
|
-
if (key === "userId" || name === "user_id") continue;
|
|
760
|
-
if (key === "content" || name === "content") continue;
|
|
761
|
-
if (isStringColumn(col)) out.push(col);
|
|
762
|
-
}
|
|
763
|
-
return out;
|
|
764
|
-
}
|
|
765
|
-
function parseSelectParam(table, columns, select) {
|
|
766
|
-
if (!select) return void 0;
|
|
767
|
-
const names = Array.isArray(select) ? select.flatMap((s) => String(s).split(",")) : String(select).split(",").map((s) => s.trim()).filter(Boolean);
|
|
768
|
-
if (names.length === 0) return void 0;
|
|
769
|
-
const proj = {};
|
|
770
|
-
for (const n of names) {
|
|
771
|
-
const col = getColumn(table, n);
|
|
772
|
-
if (col) {
|
|
773
|
-
const key = Object.keys(columns).find((k) => columns[k] === col) ?? col.name ?? n;
|
|
774
|
-
proj[key] = col;
|
|
775
|
-
}
|
|
776
|
-
}
|
|
777
|
-
return Object.keys(proj).length > 0 ? proj : void 0;
|
|
778
|
-
}
|
|
779
|
-
/** Default list exclusion: large body columns (Go pageMeta parity). */
|
|
780
|
-
function defaultListProjection(table, columns, exclude) {
|
|
781
|
-
const names = new Set((exclude ?? ["content"]).map((s) => s.trim()).filter(Boolean));
|
|
782
|
-
if (names.size === 0) return void 0;
|
|
783
|
-
if (!Object.keys(columns).some((k) => names.has(k) || names.has(columns[k].name))) return void 0;
|
|
784
|
-
const proj = {};
|
|
785
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
786
|
-
if (names.has(key) || names.has(col.name)) continue;
|
|
787
|
-
proj[key] = col;
|
|
788
|
-
}
|
|
789
|
-
return Object.keys(proj).length > 0 ? proj : void 0;
|
|
790
|
-
}
|
|
791
|
-
function parseSortEntries(sort) {
|
|
792
|
-
const parts = Array.isArray(sort) ? sort.flatMap((s) => String(s).split(",")) : String(sort ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
793
|
-
const out = [];
|
|
794
|
-
for (const part of parts) {
|
|
795
|
-
let field = part;
|
|
796
|
-
let dir;
|
|
797
|
-
if (field.startsWith("-")) {
|
|
798
|
-
field = field.slice(1);
|
|
799
|
-
dir = "desc";
|
|
800
|
-
} else if (field.startsWith("+")) {
|
|
801
|
-
field = field.slice(1);
|
|
802
|
-
dir = "asc";
|
|
803
|
-
} else if (field.includes(":")) {
|
|
804
|
-
const [f, d] = field.split(":");
|
|
805
|
-
field = f.trim();
|
|
806
|
-
dir = d.trim().toLowerCase() === "desc" ? "desc" : "asc";
|
|
807
|
-
}
|
|
808
|
-
if (!field) continue;
|
|
809
|
-
out.push({
|
|
810
|
-
field,
|
|
811
|
-
dir: dir ?? "asc"
|
|
812
|
-
});
|
|
813
|
-
}
|
|
814
|
-
return out;
|
|
815
|
-
}
|
|
816
|
-
function encodeCursor(payload) {
|
|
817
|
-
return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
|
|
818
|
-
}
|
|
819
|
-
function decodeCursor(cursor) {
|
|
820
|
-
try {
|
|
821
|
-
const json = Buffer.from(cursor, "base64url").toString("utf8");
|
|
822
|
-
return JSON.parse(json);
|
|
823
|
-
} catch {
|
|
824
|
-
return null;
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
function rowValue(row, field, col) {
|
|
828
|
-
if (row == null) return void 0;
|
|
829
|
-
if (field in row) return row[field];
|
|
830
|
-
const name = col?.name;
|
|
831
|
-
if (name && name in row) return row[name];
|
|
832
|
-
}
|
|
833
|
-
function columnToTypeBox(col, customSchema) {
|
|
834
|
-
if (customSchema) return customSchema;
|
|
835
|
-
const dataType = col.dataType;
|
|
836
|
-
const columnType = col.columnType;
|
|
837
|
-
if (dataType === "boolean" || columnType === "SQLiteBoolean") return Type.Boolean();
|
|
838
|
-
if (dataType === "number" || columnType === "SQLiteInteger" || columnType === "SQLiteReal") return Type.Number();
|
|
839
|
-
if (dataType === "string" || columnType === "SQLiteText") {
|
|
840
|
-
if (col.enumValues && col.enumValues.length > 0) return Type.Union(col.enumValues.map((val) => Type.Literal(val)));
|
|
841
|
-
if (col.name === "slug") return Type.String({
|
|
842
|
-
minLength: 2,
|
|
843
|
-
maxLength: 100,
|
|
844
|
-
pattern: "^[a-z0-9-]+$",
|
|
845
|
-
description: "URL-friendly unique slug (lowercase letters, numbers, dashes)"
|
|
846
|
-
});
|
|
847
|
-
return Type.String();
|
|
848
|
-
}
|
|
849
|
-
return Type.Any();
|
|
850
|
-
}
|
|
851
|
-
/**
|
|
852
|
-
* Precomputes and freezes an immutable execution plan for a resource at registration or service.build().
|
|
853
|
-
* Per-request execution paths do O(1) ID lookups against this plan.
|
|
854
|
-
*/
|
|
855
|
-
function buildResourcePlan(service, config) {
|
|
856
|
-
const resourceName = config.name;
|
|
857
|
-
const pluralName = config.pluralName ?? `${resourceName}s`;
|
|
858
|
-
const idField = config.idField ?? "id";
|
|
859
|
-
const ownerField = config.ownerField;
|
|
860
|
-
const table = config.table;
|
|
861
|
-
const columns = getTableColumns$1(table);
|
|
862
|
-
const columnMap = /* @__PURE__ */ new Map();
|
|
863
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
864
|
-
columnMap.set(key, col);
|
|
865
|
-
if (col.name && col.name !== key) columnMap.set(col.name, col);
|
|
866
|
-
if (table[key]) columnMap.set(key, table[key]);
|
|
867
|
-
}
|
|
868
|
-
const idCol = columnMap.get(idField) ?? table[idField] ?? table.id;
|
|
869
|
-
const ownerCol = ownerField ? columnMap.get(ownerField) : void 0;
|
|
870
|
-
const ownerColName = ownerCol?.name ?? ownerField;
|
|
871
|
-
const defaultColumns = [];
|
|
872
|
-
let createdAtKey = null;
|
|
873
|
-
let updatedAtKey = null;
|
|
874
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
875
|
-
if (col.hasDefault && col.default !== void 0) defaultColumns.push({
|
|
876
|
-
key,
|
|
877
|
-
default: col.default
|
|
878
|
-
});
|
|
879
|
-
const colName = col.name;
|
|
880
|
-
if (colName === "created_at" || key === "createdAt") createdAtKey = key;
|
|
881
|
-
if (colName === "updated_at" || key === "updatedAt") updatedAtKey = key;
|
|
882
|
-
}
|
|
883
|
-
const operations = config.operations ?? {};
|
|
884
|
-
const listOpts = typeof operations.list === "object" ? operations.list : {};
|
|
885
|
-
const searchFieldNames = config.searchable ?? listOpts.searchable ?? ["title", "slug"];
|
|
886
|
-
const searchCols = resolveSearchColumns(table, columns, searchFieldNames);
|
|
887
|
-
const sortableArr = config.sortable ?? listOpts.sortable ?? [];
|
|
888
|
-
const sortableFields = new Set(sortableArr);
|
|
889
|
-
const defaultSort = config.defaultSort ?? listOpts.defaultSort ?? "-updatedAt";
|
|
890
|
-
const defaultSortEntries = parseSortEntries(defaultSort).filter((e) => {
|
|
891
|
-
if (sortableFields.size > 0 && !sortableFields.has(e.field)) return false;
|
|
892
|
-
return columnMap.has(e.field);
|
|
893
|
-
});
|
|
894
|
-
const fallbackField = columnMap.has("updatedAt") && "updatedAt" || columnMap.has("updated_at") && "updated_at" || columnMap.has("createdAt") && "createdAt" || columnMap.has("created_at") && "created_at" || null;
|
|
895
|
-
const fallbackEntries = fallbackField != null ? [{
|
|
896
|
-
field: fallbackField,
|
|
897
|
-
dir: "desc"
|
|
898
|
-
}] : [];
|
|
899
|
-
const defaultProjection = defaultListProjection(table, columns, config.excludeFromList);
|
|
900
|
-
const plan = {
|
|
901
|
-
resourceName,
|
|
902
|
-
pluralName,
|
|
903
|
-
table,
|
|
904
|
-
idField,
|
|
905
|
-
idCol,
|
|
906
|
-
ownerField,
|
|
907
|
-
ownerCol,
|
|
908
|
-
ownerColName,
|
|
909
|
-
columnMap,
|
|
910
|
-
columns,
|
|
911
|
-
defaultColumns: Object.freeze(defaultColumns),
|
|
912
|
-
timestampColumns: Object.freeze({
|
|
913
|
-
createdAtKey,
|
|
914
|
-
updatedAtKey
|
|
915
|
-
}),
|
|
916
|
-
searchable: Object.freeze({
|
|
917
|
-
fields: searchFieldNames,
|
|
918
|
-
columns: searchCols
|
|
919
|
-
}),
|
|
920
|
-
sortable: Object.freeze({
|
|
921
|
-
fields: sortableFields,
|
|
922
|
-
defaultSort,
|
|
923
|
-
defaultSortEntries: Object.freeze(defaultSortEntries),
|
|
924
|
-
fallbackEntries: Object.freeze(fallbackEntries),
|
|
925
|
-
tiebreakCol: idCol
|
|
926
|
-
}),
|
|
927
|
-
projections: Object.freeze({ defaultProjection }),
|
|
928
|
-
routeTargets: Object.freeze({
|
|
929
|
-
listPath: `/${resourceName}`,
|
|
930
|
-
itemPath: `/${resourceName}/:id`
|
|
931
|
-
})
|
|
932
|
-
};
|
|
933
|
-
return Object.freeze(plan);
|
|
934
|
-
}
|
|
935
|
-
const dbCaches = /* @__PURE__ */ new WeakMap();
|
|
936
|
-
function getResourceDbCache(db, plan) {
|
|
937
|
-
let resMap = dbCaches.get(db);
|
|
938
|
-
if (!resMap) {
|
|
939
|
-
resMap = /* @__PURE__ */ new WeakMap();
|
|
940
|
-
dbCaches.set(db, resMap);
|
|
941
|
-
}
|
|
942
|
-
let cache = resMap.get(plan);
|
|
943
|
-
if (!cache) {
|
|
944
|
-
cache = {
|
|
945
|
-
listCache: /* @__PURE__ */ new Map(),
|
|
946
|
-
defaultLists: /* @__PURE__ */ new Map()
|
|
947
|
-
};
|
|
948
|
-
resMap.set(plan, cache);
|
|
949
|
-
}
|
|
950
|
-
return cache;
|
|
951
|
-
}
|
|
952
|
-
function defaultListOrder(plan) {
|
|
953
|
-
const entries = plan.sortable.defaultSortEntries.length ? plan.sortable.defaultSortEntries : plan.sortable.fallbackEntries;
|
|
954
|
-
const order = entries.map((entry) => entry.dir === "desc" ? desc$1(plan.columnMap.get(entry.field)) : asc$1(plan.columnMap.get(entry.field)));
|
|
955
|
-
const dir = entries[0]?.dir ?? "desc";
|
|
956
|
-
if (plan.sortable.tiebreakCol && plan.columnMap.get(entries[0]?.field ?? "") !== plan.sortable.tiebreakCol) order.push(dir === "desc" ? desc$1(plan.sortable.tiebreakCol) : asc$1(plan.sortable.tiebreakCol));
|
|
957
|
-
return {
|
|
958
|
-
entries,
|
|
959
|
-
order
|
|
960
|
-
};
|
|
961
|
-
}
|
|
962
|
-
function buildDefaultListQueries(db, plan, scoped) {
|
|
963
|
-
const where = scoped ? eq$1(plan.ownerCol, sql$1.placeholder("__ownerId")) : void 0;
|
|
964
|
-
const { order } = defaultListOrder(plan);
|
|
965
|
-
let select = plan.projections.defaultProjection ? db.select(plan.projections.defaultProjection).from(plan.table) : db.select().from(plan.table);
|
|
966
|
-
let count = db.select({ n: sql$1`count(*)`.mapWith(Number) }).from(plan.table);
|
|
967
|
-
if (where) {
|
|
968
|
-
select = select.where(where);
|
|
969
|
-
count = count.where(where);
|
|
970
|
-
}
|
|
971
|
-
if (order.length) select = select.orderBy(...order);
|
|
972
|
-
select = select.limit(sql$1.placeholder("__limit")).offset(sql$1.placeholder("__offset"));
|
|
973
|
-
return {
|
|
974
|
-
select,
|
|
975
|
-
count
|
|
976
|
-
};
|
|
977
|
-
}
|
|
978
|
-
/** SQL for inspection: query builders are constructed, not executed. */
|
|
979
|
-
function describeResourceReads(service, resource) {
|
|
980
|
-
const db = service.getDb();
|
|
981
|
-
const plan = resource.plan;
|
|
982
|
-
if (!plan || typeof db?.select !== "function") return void 0;
|
|
983
|
-
try {
|
|
984
|
-
const global = buildDefaultListQueries(db, plan, false);
|
|
985
|
-
const owner = plan.ownerCol ? buildDefaultListQueries(db, plan, true) : void 0;
|
|
986
|
-
const get = plan.idCol ? db.select().from(plan.table).where(eq$1(plan.idCol, sql$1.placeholder("id"))).limit(1) : void 0;
|
|
987
|
-
return {
|
|
988
|
-
service: service.name,
|
|
989
|
-
resource: resource.name,
|
|
990
|
-
get: get?.toSQL().sql,
|
|
991
|
-
list: global.select.toSQL().sql,
|
|
992
|
-
count: global.count.toSQL().sql,
|
|
993
|
-
ownerList: owner?.select.toSQL().sql,
|
|
994
|
-
ownerCount: owner?.count.toSQL().sql
|
|
995
|
-
};
|
|
996
|
-
} catch {
|
|
997
|
-
return;
|
|
998
|
-
}
|
|
999
|
-
}
|
|
1000
|
-
/** Prepare reusable queries once. Values and rows are never cached. */
|
|
1001
|
-
function prepareResourceReads(service) {
|
|
1002
|
-
const db = service.getDb();
|
|
1003
|
-
if (typeof db?.select !== "function") return;
|
|
1004
|
-
for (const resource of service.listResources()) {
|
|
1005
|
-
const plan = resource.plan;
|
|
1006
|
-
if (!plan) continue;
|
|
1007
|
-
const cache = getResourceDbCache(db, plan);
|
|
1008
|
-
if (plan.idCol && cache.getById === void 0) try {
|
|
1009
|
-
cache.getById = db.select().from(plan.table).where(eq$1(plan.idCol, sql$1.placeholder("id"))).limit(1).prepare();
|
|
1010
|
-
} catch {}
|
|
1011
|
-
for (const scoped of plan.ownerCol ? [false, true] : [false]) {
|
|
1012
|
-
if (cache.defaultLists.has(scoped)) continue;
|
|
1013
|
-
try {
|
|
1014
|
-
const queries = buildDefaultListQueries(db, plan, scoped);
|
|
1015
|
-
const pair = {
|
|
1016
|
-
select: queries.select.prepare(),
|
|
1017
|
-
count: queries.count.prepare()
|
|
1018
|
-
};
|
|
1019
|
-
cache.defaultLists.set(scoped, pair);
|
|
1020
|
-
cache.listCache.set(`|${scoped ? "1" : "0"}|${plan.sortable.defaultSort}|default`, pair);
|
|
1021
|
-
} catch {}
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
1025
|
-
/** Refresh on DDL, including TEMP triggers added after compilation. */
|
|
1026
|
-
function refreshWriteSchema(writes) {
|
|
1027
|
-
const version = `${writes.mainVersion.get().schema_version}:${writes.tempVersion.get().schema_version}`;
|
|
1028
|
-
if (writes.version === version) return;
|
|
1029
|
-
writes.hasTriggers = Boolean(writes.triggers.get());
|
|
1030
|
-
writes.inserts.clear();
|
|
1031
|
-
writes.updates.clear();
|
|
1032
|
-
writes.version = version;
|
|
1033
|
-
}
|
|
1034
|
-
/** A statement shape contains column keys, never values or evaluated JS defaults. */
|
|
1035
|
-
function writeShape(writes, plan, operation, data) {
|
|
1036
|
-
const fields = [];
|
|
1037
|
-
const params = {};
|
|
1038
|
-
for (let index = 0; index < writes.columns.length; index++) {
|
|
1039
|
-
const [key, column] = writes.columns[index];
|
|
1040
|
-
if (operation === "insert" && column.shouldDisableInsert()) continue;
|
|
1041
|
-
if (operation === "update" && column.onUpdateFn !== void 0) return;
|
|
1042
|
-
const value = data[key];
|
|
1043
|
-
if (value === void 0) {
|
|
1044
|
-
if (operation === "insert" && column.default == null && (column.defaultFn !== void 0 || column.onUpdateFn !== void 0)) return;
|
|
1045
|
-
continue;
|
|
1046
|
-
}
|
|
1047
|
-
if (is$1(value, SQL) || is$1(value, Column) || column === plan.idCol && (operation === "update" || value === null)) return;
|
|
1048
|
-
fields.push(index);
|
|
1049
|
-
params[`__write_${index}`] = value;
|
|
1050
|
-
}
|
|
1051
|
-
if (!fields.length) return;
|
|
1052
|
-
return {
|
|
1053
|
-
fields,
|
|
1054
|
-
params
|
|
1055
|
-
};
|
|
1056
|
-
}
|
|
1057
|
-
function preparedWrite(db, plan, writes, operation, fields) {
|
|
1058
|
-
const cache = operation === "insert" ? writes.inserts : writes.updates;
|
|
1059
|
-
const shape = fields.join(",");
|
|
1060
|
-
if (cache.has(shape)) return cache.get(shape);
|
|
1061
|
-
if (cache.size >= 64) return;
|
|
1062
|
-
let statement;
|
|
1063
|
-
try {
|
|
1064
|
-
const values = Object.fromEntries(fields.map((index) => [writes.columns[index][0], sql$1.placeholder(`__write_${index}`)]));
|
|
1065
|
-
let query = operation === "insert" ? db.insert(plan.table).values(values) : db.update(plan.table).set(values).where(eq$1(plan.idCol, sql$1.placeholder("__write_id")));
|
|
1066
|
-
if (!writes.hasTriggers && (plan.idCol.primary || plan.idCol.isUnique)) query = query.returning();
|
|
1067
|
-
statement = query.prepare();
|
|
1068
|
-
} catch {
|
|
1069
|
-
statement = null;
|
|
1070
|
-
}
|
|
1071
|
-
cache.set(shape, statement);
|
|
1072
|
-
return statement;
|
|
1073
|
-
}
|
|
1074
|
-
/** Bun SQLite writes: prime common shapes; discover other shapes once and reuse them. */
|
|
1075
|
-
function prepareResourceWrites(service) {
|
|
1076
|
-
const db = service.getDb();
|
|
1077
|
-
if (db?.constructor?.[entityKind] !== "BunSQLiteDatabase" || !db.$client?.prepare) return;
|
|
1078
|
-
for (const resource of service.listResources()) {
|
|
1079
|
-
const plan = resource.plan;
|
|
1080
|
-
if (!plan?.idCol || !is$1(plan.table, SQLiteTable)) continue;
|
|
1081
|
-
const cache = getResourceDbCache(db, plan);
|
|
1082
|
-
if (cache.writes) continue;
|
|
1083
|
-
const columns = Object.entries(getTableColumns$1(plan.table));
|
|
1084
|
-
if (!columns.some(([key, column]) => key === plan.idField && column === plan.idCol)) continue;
|
|
1085
|
-
try {
|
|
1086
|
-
const writes = {
|
|
1087
|
-
columns,
|
|
1088
|
-
inserts: /* @__PURE__ */ new Map(),
|
|
1089
|
-
updates: /* @__PURE__ */ new Map(),
|
|
1090
|
-
hasTriggers: true,
|
|
1091
|
-
mainVersion: db.$client.prepare("PRAGMA main.schema_version"),
|
|
1092
|
-
tempVersion: db.$client.prepare("PRAGMA temp.schema_version"),
|
|
1093
|
-
triggers: db.$client.prepare("SELECT 1 FROM main.sqlite_schema WHERE type = 'trigger' UNION ALL SELECT 1 FROM temp.sqlite_schema WHERE type = 'trigger' LIMIT 1")
|
|
1094
|
-
};
|
|
1095
|
-
refreshWriteSchema(writes);
|
|
1096
|
-
cache.writes = writes;
|
|
1097
|
-
const prime = (operation, keys) => {
|
|
1098
|
-
const data = Object.fromEntries(keys.map((key) => [key, true]));
|
|
1099
|
-
const shape = writeShape(writes, plan, operation, data);
|
|
1100
|
-
if (shape) preparedWrite(db, plan, writes, operation, shape.fields);
|
|
1101
|
-
};
|
|
1102
|
-
if (resource.config.operations?.create !== false) {
|
|
1103
|
-
prime("insert", columns.filter(([, col]) => !col.shouldDisableInsert()).map(([key]) => key));
|
|
1104
|
-
prime("insert", columns.filter(([key, col]) => key === plan.idField || key === plan.ownerField || key === plan.timestampColumns.createdAtKey || key === plan.timestampColumns.updatedAtKey || col.notNull && !col.hasDefault || plan.defaultColumns.some((item) => item.key === key)).map(([key]) => key));
|
|
1105
|
-
}
|
|
1106
|
-
if (resource.config.operations?.update !== false) {
|
|
1107
|
-
const keys = columns.filter(([, col]) => col !== plan.idCol).map(([key]) => key);
|
|
1108
|
-
prime("update", keys);
|
|
1109
|
-
const timestamp = plan.timestampColumns.updatedAtKey;
|
|
1110
|
-
if (timestamp) prime("update", [timestamp]);
|
|
1111
|
-
for (const key of keys) prime("update", timestamp && timestamp !== key ? [key, timestamp] : [key]);
|
|
1112
|
-
}
|
|
1113
|
-
} catch {}
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
function executePreparedWrite(db, plan, operation, data, id, hookData = false) {
|
|
1117
|
-
const writes = getResourceDbCache(db, plan).writes;
|
|
1118
|
-
if (!writes) return;
|
|
1119
|
-
if (hookData && (Object.getPrototypeOf(data) !== Object.prototype && Object.getPrototypeOf(data) !== null || Object.values(Object.getOwnPropertyDescriptors(data)).some((property) => property.get || property.set || !property.enumerable))) return;
|
|
1120
|
-
refreshWriteSchema(writes);
|
|
1121
|
-
const shape = writeShape(writes, plan, operation, data);
|
|
1122
|
-
if (!shape) return;
|
|
1123
|
-
const statement = preparedWrite(db, plan, writes, operation, shape.fields);
|
|
1124
|
-
if (!statement) return;
|
|
1125
|
-
const params = shape.params;
|
|
1126
|
-
params.__write_id = id;
|
|
1127
|
-
if (writes.hasTriggers || !(plan.idCol.primary || plan.idCol.isUnique)) {
|
|
1128
|
-
statement.run(params);
|
|
1129
|
-
return {
|
|
1130
|
-
row: void 0,
|
|
1131
|
-
readBack: true
|
|
1132
|
-
};
|
|
1133
|
-
}
|
|
1134
|
-
return {
|
|
1135
|
-
row: statement.get(params),
|
|
1136
|
-
readBack: false
|
|
1137
|
-
};
|
|
1138
|
-
}
|
|
1139
|
-
function formatListResult(plan, rows, total, limit, offset, page, cursorActive, primarySort, primaryCol, requestedSort) {
|
|
1140
|
-
const hasMore = cursorActive ? rows.length === limit : offset + rows.length < total;
|
|
1141
|
-
let nextCursor = null;
|
|
1142
|
-
if (hasMore && rows.length && primarySort && primaryCol && plan.sortable.tiebreakCol) {
|
|
1143
|
-
const last = rows[rows.length - 1];
|
|
1144
|
-
const sortVal = rowValue(last, primarySort.field, primaryCol);
|
|
1145
|
-
const idVal = rowValue(last, plan.idField, plan.sortable.tiebreakCol);
|
|
1146
|
-
if (sortVal !== void 0 && sortVal !== null) nextCursor = encodeCursor({
|
|
1147
|
-
v: [sortVal, idVal ?? null],
|
|
1148
|
-
s: requestedSort
|
|
1149
|
-
});
|
|
1150
|
-
}
|
|
1151
|
-
const result = {
|
|
1152
|
-
items: rows,
|
|
1153
|
-
total,
|
|
1154
|
-
limit,
|
|
1155
|
-
offset: cursorActive ? 0 : offset,
|
|
1156
|
-
pageCount: Math.max(Math.ceil(total / limit), total > 0 ? 1 : 0),
|
|
1157
|
-
hasMore,
|
|
1158
|
-
nextCursor
|
|
1159
|
-
};
|
|
1160
|
-
return cursorActive ? result : {
|
|
1161
|
-
...result,
|
|
1162
|
-
page
|
|
1163
|
-
};
|
|
1933
|
+
if (!clean) return null;
|
|
1934
|
+
return `"${clean.replace(/"/g, "\"\"")}"*`;
|
|
1935
|
+
}).filter((x) => !!x);
|
|
1936
|
+
if (escaped.length === 0) return null;
|
|
1937
|
+
return escaped.join(" AND ");
|
|
1164
1938
|
}
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1939
|
+
/**
|
|
1940
|
+
* Explicit SQLite development/test schema preparation helper.
|
|
1941
|
+
* Never called by services, resources, auth, or server startup.
|
|
1942
|
+
* Not a migration runner; PostgreSQL schema management is caller-owned.
|
|
1943
|
+
*/
|
|
1944
|
+
function syncSchema(tablesOrService, dbInstance) {
|
|
1945
|
+
let db = dbInstance;
|
|
1946
|
+
let tables = [];
|
|
1947
|
+
if (tablesOrService && typeof tablesOrService.listActions === "function" && tablesOrService.tables) {
|
|
1948
|
+
const service = tablesOrService;
|
|
1949
|
+
tables = Array.from(service.tables.values());
|
|
1950
|
+
if (!db) db = service.getDb();
|
|
1951
|
+
} else if (tablesOrService instanceof Map) tables = Array.from(tablesOrService.values());
|
|
1952
|
+
else if (Array.isArray(tablesOrService)) tables = tablesOrService;
|
|
1953
|
+
else if (tablesOrService && typeof tablesOrService === "object") tables = Object.values(tablesOrService);
|
|
1954
|
+
if (!db || tables.length === 0) return;
|
|
1955
|
+
if (db.$client?.run || db.run) {
|
|
1956
|
+
for (const table of tables) try {
|
|
1957
|
+
const ddl = generateSQLiteTableDdl(table);
|
|
1958
|
+
if (db.$client?.run) db.$client.run(ddl);
|
|
1959
|
+
else if (db.run) db.run(sql$1.raw(ddl));
|
|
1960
|
+
} catch (err) {
|
|
1961
|
+
console.warn(`[Brick-TS DB] Failed to create table:`, err.message);
|
|
1172
1962
|
}
|
|
1173
|
-
|
|
1174
|
-
if (typeof cache.getById.get === "function") return await cache.getById.get({ id: idVal });
|
|
1175
|
-
return (await cache.getById.execute({ id: idVal }))[0];
|
|
1176
|
-
} catch {}
|
|
1963
|
+
return;
|
|
1177
1964
|
}
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
const cache = getResourceDbCache(db, plan);
|
|
1184
|
-
if (cache.deleteById === void 0) try {
|
|
1185
|
-
cache.deleteById = db.delete(plan.table).where(eq$1(plan.idCol, sql$1.placeholder("id"))).prepare();
|
|
1186
|
-
} catch {
|
|
1187
|
-
cache.deleteById = null;
|
|
1965
|
+
return (async () => {
|
|
1966
|
+
for (const table of tables) try {
|
|
1967
|
+
getTableName$1(table);
|
|
1968
|
+
} catch (err) {
|
|
1969
|
+
console.warn(`[Brick-TS DB] Postgres syncSchema error:`, err.message);
|
|
1188
1970
|
}
|
|
1189
|
-
|
|
1190
|
-
return await cache.deleteById.execute({ id: idVal });
|
|
1191
|
-
} catch {}
|
|
1192
|
-
}
|
|
1193
|
-
return await db.delete(plan.table).where(eq$1(plan.idCol, idVal));
|
|
1971
|
+
})();
|
|
1194
1972
|
}
|
|
1973
|
+
//#endregion
|
|
1974
|
+
//#region src/resource.ts
|
|
1975
|
+
/** Declares a plugin host without registering actions or changing the schema. */
|
|
1195
1976
|
function defineResource(service, config) {
|
|
1196
|
-
const
|
|
1197
|
-
const
|
|
1198
|
-
const
|
|
1199
|
-
const
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
if (col.primary || key === idField || colName === idField || ownerField && (key === ownerField || colName === ownerField) || key === "createdAt" || key === "updatedAt" || colName === "created_at" || colName === "updated_at") continue;
|
|
1217
|
-
const baseType = columnToTypeBox(col, fieldsOverride[key] ?? fieldsOverride[colName]);
|
|
1218
|
-
if (col.hasDefault || !col.notNull) createProperties[key] = Type.Optional(baseType);
|
|
1219
|
-
else createProperties[key] = baseType;
|
|
1220
|
-
}
|
|
1221
|
-
const createSchema = Type.Object(createProperties);
|
|
1222
|
-
const updateProperties = { [idField]: Type.String() };
|
|
1223
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
1224
|
-
const colName = col.name;
|
|
1225
|
-
if (col.primary || key === idField || colName === idField || ownerField && (key === ownerField || colName === ownerField) || key === "createdAt" || key === "updatedAt" || colName === "created_at" || colName === "updated_at") continue;
|
|
1226
|
-
const baseType = columnToTypeBox(col, fieldsOverride[key] ?? fieldsOverride[colName]);
|
|
1227
|
-
updateProperties[key] = Type.Optional(baseType);
|
|
1228
|
-
}
|
|
1229
|
-
const updateSchema = Type.Object(updateProperties);
|
|
1230
|
-
const getSchema = Type.Object({ [idField]: Type.String() });
|
|
1231
|
-
const deleteSchema = Type.Object({ [idField]: Type.String() });
|
|
1232
|
-
const operations = config.operations ?? {};
|
|
1233
|
-
const listOpts = typeof operations.list === "object" ? operations.list : {};
|
|
1234
|
-
const maxLimit = listOpts.maxLimit ?? 100;
|
|
1235
|
-
const listProperties = {
|
|
1236
|
-
limit: Type.Optional(Type.Number({
|
|
1237
|
-
minimum: 1,
|
|
1238
|
-
maximum: maxLimit
|
|
1239
|
-
})),
|
|
1240
|
-
offset: Type.Optional(Type.Number({ minimum: 0 })),
|
|
1241
|
-
page: Type.Optional(Type.Number({ minimum: 1 })),
|
|
1242
|
-
sort: Type.Optional(Type.String()),
|
|
1243
|
-
search: Type.Optional(Type.String()),
|
|
1244
|
-
select: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())])),
|
|
1245
|
-
cursor: Type.Optional(Type.String())
|
|
1246
|
-
};
|
|
1247
|
-
for (const [key, col] of Object.entries(columns)) {
|
|
1248
|
-
const colName = col.name;
|
|
1249
|
-
if (key === "createdAt" || key === "updatedAt" || colName === "created_at" || colName === "updated_at") continue;
|
|
1250
|
-
const baseType = columnToTypeBox(col, fieldsOverride[key] ?? fieldsOverride[colName]);
|
|
1251
|
-
listProperties[key] = Type.Optional(baseType);
|
|
1252
|
-
}
|
|
1253
|
-
const listSchema = Type.Object(listProperties);
|
|
1254
|
-
const createAction = defineAction({
|
|
1255
|
-
name: `${resourceName}.create`,
|
|
1256
|
-
description: `Create a new ${resourceName}`,
|
|
1257
|
-
input: createSchema,
|
|
1258
|
-
output: rowSchema,
|
|
1259
|
-
errors: {
|
|
1260
|
-
CONFLICT: {
|
|
1261
|
-
status: 409,
|
|
1262
|
-
message: "Resource already exists"
|
|
1263
|
-
},
|
|
1264
|
-
...config.errors
|
|
1265
|
-
},
|
|
1266
|
-
execute: async ({ input, ctx, error }) => {
|
|
1267
|
-
const db = ctx.db ?? service.getDb();
|
|
1268
|
-
const data = { ...input };
|
|
1269
|
-
if (!data[idField]) {
|
|
1270
|
-
if (config.idGenerator) data[idField] = config.idGenerator();
|
|
1271
|
-
else {
|
|
1272
|
-
const prefix = config.idPrefix ?? (resourceName.toLowerCase() === "page" ? "pg" : resourceName.slice(0, 3));
|
|
1273
|
-
const rand = Math.random().toString(36).substring(2, 10);
|
|
1274
|
-
data[idField] = `${prefix}_${rand}`;
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
for (let i = 0; i < plan.defaultColumns.length; i++) {
|
|
1278
|
-
const item = plan.defaultColumns[i];
|
|
1279
|
-
if (data[item.key] === void 0) data[item.key] = item.default;
|
|
1280
|
-
}
|
|
1281
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1282
|
-
if (plan.timestampColumns.createdAtKey && data[plan.timestampColumns.createdAtKey] === void 0) data[plan.timestampColumns.createdAtKey] = now;
|
|
1283
|
-
if (plan.timestampColumns.updatedAtKey && data[plan.timestampColumns.updatedAtKey] === void 0) data[plan.timestampColumns.updatedAtKey] = now;
|
|
1284
|
-
if (ownerField) {
|
|
1285
|
-
if (ctx.user?.id) data[ownerField] = ctx.user.id;
|
|
1286
|
-
else if (data[ownerField] === void 0) data[ownerField] = null;
|
|
1287
|
-
}
|
|
1288
|
-
if (config.hooks?.beforeCreate) await config.hooks.beforeCreate({
|
|
1289
|
-
data,
|
|
1290
|
-
ctx,
|
|
1291
|
-
error
|
|
1292
|
-
});
|
|
1293
|
-
const written = executePreparedWrite(db, plan, "insert", data, void 0, Boolean(config.hooks?.beforeCreate));
|
|
1294
|
-
if (!written) await db.insert(table).values(data);
|
|
1295
|
-
const idVal = data[idField];
|
|
1296
|
-
let createdRow = written?.row ?? data;
|
|
1297
|
-
if (plan.idCol && (!written || written.readBack)) {
|
|
1298
|
-
const row = await executeGet(db, plan, idVal);
|
|
1299
|
-
if (row) createdRow = row;
|
|
1300
|
-
}
|
|
1301
|
-
if (ctx.logger?.info) {
|
|
1302
|
-
const titleOrName = createdRow.title ?? createdRow.name ?? createdRow.slug ?? idVal;
|
|
1303
|
-
ctx.logger.info(`${capitalizedName} created: '${titleOrName}' (slug: /${createdRow.slug ?? idVal})`);
|
|
1304
|
-
}
|
|
1305
|
-
if (config.hooks?.afterCreate) await config.hooks.afterCreate({
|
|
1306
|
-
data,
|
|
1307
|
-
result: createdRow,
|
|
1308
|
-
ctx
|
|
1309
|
-
});
|
|
1310
|
-
return createdRow;
|
|
1311
|
-
}
|
|
1312
|
-
});
|
|
1313
|
-
const getAction = defineAction({
|
|
1314
|
-
name: `${resourceName}.get`,
|
|
1315
|
-
description: `Retrieve a ${resourceName} by ID`,
|
|
1316
|
-
input: getSchema,
|
|
1317
|
-
output: rowSchema,
|
|
1318
|
-
errors: {
|
|
1319
|
-
NOT_FOUND: {
|
|
1320
|
-
status: 404,
|
|
1321
|
-
message: `${capitalizedName} not found`
|
|
1322
|
-
},
|
|
1323
|
-
FORBIDDEN: {
|
|
1324
|
-
status: 403,
|
|
1325
|
-
message: `Access denied to ${resourceName}`
|
|
1326
|
-
},
|
|
1327
|
-
...config.errors
|
|
1328
|
-
},
|
|
1329
|
-
execute: async ({ input, ctx, error }) => {
|
|
1330
|
-
const db = ctx.db ?? service.getDb();
|
|
1331
|
-
const idVal = input[idField] ?? input.id;
|
|
1332
|
-
if (!plan.idCol) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' does not exist`);
|
|
1333
|
-
const row = await executeGet(db, plan, idVal);
|
|
1334
|
-
if (!row) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' does not exist`);
|
|
1335
|
-
if (ownerField && ctx.user?.id) {
|
|
1336
|
-
const rowOwner = row[ownerField] ?? row[plan.ownerColName];
|
|
1337
|
-
if (rowOwner && rowOwner !== ctx.user.id) error.FORBIDDEN(`Access denied to ${resourceName}`);
|
|
1338
|
-
}
|
|
1339
|
-
return row;
|
|
1340
|
-
}
|
|
1341
|
-
});
|
|
1342
|
-
const listItemProperties = {};
|
|
1343
|
-
for (const [key, prop] of Object.entries(rowProperties)) listItemProperties[key] = Type.Optional(prop);
|
|
1344
|
-
const listItemSchema = Type.Object(listItemProperties);
|
|
1345
|
-
const listAction = defineAction({
|
|
1346
|
-
name: `${resourceName}.list`,
|
|
1347
|
-
description: `List ${pluralName}`,
|
|
1348
|
-
input: listSchema,
|
|
1349
|
-
output: Type.Object({
|
|
1350
|
-
items: Type.Array(listItemSchema),
|
|
1351
|
-
total: Type.Number(),
|
|
1352
|
-
limit: Type.Number(),
|
|
1353
|
-
offset: Type.Number(),
|
|
1354
|
-
page: Type.Optional(Type.Number()),
|
|
1355
|
-
pageCount: Type.Number(),
|
|
1356
|
-
hasMore: Type.Boolean(),
|
|
1357
|
-
nextCursor: Type.Union([Type.String(), Type.Null()])
|
|
1358
|
-
}),
|
|
1359
|
-
errors: config.errors,
|
|
1360
|
-
execute: async ({ input = {}, ctx }) => {
|
|
1361
|
-
const db = ctx.db ?? service.getDb();
|
|
1362
|
-
const defaultLimit = listOpts.defaultLimit ?? 50;
|
|
1363
|
-
const maxLimitVal = listOpts.maxLimit ?? 100;
|
|
1364
|
-
const isPostgres = typeof db?.execute === "function" && !db?.$client?.run;
|
|
1365
|
-
const isSQLite = !isPostgres;
|
|
1366
|
-
const raw = input;
|
|
1367
|
-
const limit = raw.limit !== void 0 && raw.limit !== null ? Math.min(Math.max(Number(raw.limit) || defaultLimit, 1), maxLimitVal) : defaultLimit;
|
|
1368
|
-
let offset = raw.offset !== void 0 && raw.offset !== null ? Math.max(Number(raw.offset) || 0, 0) : 0;
|
|
1369
|
-
let page = raw.page !== void 0 && raw.page !== null ? Math.max(Number(raw.page) || 1, 1) : Math.floor(offset / limit) + 1;
|
|
1370
|
-
if (raw.page !== void 0 && raw.page !== null) offset = (page - 1) * limit;
|
|
1371
|
-
else page = Math.floor(offset / limit) + 1;
|
|
1372
|
-
const defaultLists = typeof db?.select === "function" ? getResourceDbCache(db, plan).defaultLists : void 0;
|
|
1373
|
-
if (defaultLists?.size && Object.entries(raw).every(([key, value]) => value === void 0 || value === null || key === "limit" || key === "offset" || key === "page")) {
|
|
1374
|
-
const scoped = Boolean(ownerField && ctx.user?.id && plan.ownerCol);
|
|
1375
|
-
const pair = defaultLists.get(scoped);
|
|
1376
|
-
if (pair) try {
|
|
1377
|
-
const params = {
|
|
1378
|
-
__limit: limit,
|
|
1379
|
-
__offset: offset,
|
|
1380
|
-
...scoped ? { __ownerId: ctx.user.id } : {}
|
|
1381
|
-
};
|
|
1382
|
-
const count = await pair.count.execute(params);
|
|
1383
|
-
const rows = await pair.select.execute(params);
|
|
1384
|
-
const primary = (plan.sortable.defaultSortEntries.length ? plan.sortable.defaultSortEntries : plan.sortable.fallbackEntries)[0] ?? null;
|
|
1385
|
-
return formatListResult(plan, rows, count[0]?.n ?? 0, limit, offset, page, false, primary, primary ? plan.columnMap.get(primary.field) : null, plan.sortable.defaultSort);
|
|
1386
|
-
} catch {}
|
|
1387
|
-
}
|
|
1388
|
-
const requestedSort = typeof raw.sort === "string" && raw.sort.trim() ? raw.sort : plan.sortable.defaultSort;
|
|
1389
|
-
let sortEntries;
|
|
1390
|
-
if (requestedSort === plan.sortable.defaultSort) sortEntries = plan.sortable.defaultSortEntries;
|
|
1391
|
-
else sortEntries = parseSortEntries(requestedSort).filter((e) => {
|
|
1392
|
-
if (plan.sortable.fields.size > 0 && !plan.sortable.fields.has(e.field)) return false;
|
|
1393
|
-
return plan.columnMap.has(e.field);
|
|
1394
|
-
});
|
|
1395
|
-
if (sortEntries.length === 0) sortEntries = plan.sortable.fallbackEntries;
|
|
1396
|
-
const orderBys = sortEntries.map((e) => {
|
|
1397
|
-
const col = plan.columnMap.get(e.field);
|
|
1398
|
-
return e.dir === "desc" ? desc$1(col) : asc$1(col);
|
|
1399
|
-
});
|
|
1400
|
-
const idColForSort = plan.sortable.tiebreakCol;
|
|
1401
|
-
const primaryDir = sortEntries.length > 0 ? sortEntries[0].dir : "desc";
|
|
1402
|
-
if (idColForSort) {
|
|
1403
|
-
if (!(sortEntries.length > 0 && plan.columnMap.get(sortEntries[0].field) === idColForSort)) orderBys.push(primaryDir === "desc" ? desc$1(idColForSort) : asc$1(idColForSort));
|
|
1404
|
-
}
|
|
1405
|
-
const primarySort = sortEntries.length > 0 ? sortEntries[0] : null;
|
|
1406
|
-
const primaryCol = primarySort ? plan.columnMap.get(primarySort.field) : null;
|
|
1407
|
-
const conditions = [];
|
|
1408
|
-
const exactFilters = [];
|
|
1409
|
-
const isOwnerScoped = Boolean(ownerField && ctx.user?.id && plan.ownerCol);
|
|
1410
|
-
if (isOwnerScoped) conditions.push(eq$1(plan.ownerCol, ctx.user.id));
|
|
1411
|
-
for (const [key, val] of Object.entries(raw)) {
|
|
1412
|
-
if (RESERVED_LIST_KEYS.has(key)) continue;
|
|
1413
|
-
if (val === void 0 || val === null) continue;
|
|
1414
|
-
const col = plan.columnMap.get(key);
|
|
1415
|
-
if (col) {
|
|
1416
|
-
conditions.push(eq$1(col, val));
|
|
1417
|
-
exactFilters.push({
|
|
1418
|
-
key,
|
|
1419
|
-
col,
|
|
1420
|
-
val
|
|
1421
|
-
});
|
|
1422
|
-
}
|
|
1423
|
-
}
|
|
1424
|
-
const searchTerm = typeof raw.search === "string" ? raw.search.trim() : "";
|
|
1425
|
-
if (searchTerm) {
|
|
1426
|
-
let pushed = false;
|
|
1427
|
-
if (isSQLite) try {
|
|
1428
|
-
const ftsQuery = buildFtsMatchQuery(searchTerm);
|
|
1429
|
-
if (ftsQuery && plan.idCol) {
|
|
1430
|
-
const fts = `${getTableName$1(table)}_fts`;
|
|
1431
|
-
conditions.push(sql$1`${plan.idCol} IN (SELECT "id" FROM ${sql$1.raw(`"${fts.replace(/"/g, "\"\"")}"`)} WHERE ${sql$1.raw(`"${fts.replace(/"/g, "\"\"")}"`)} MATCH ${ftsQuery})`);
|
|
1432
|
-
pushed = true;
|
|
1433
|
-
}
|
|
1434
|
-
} catch {
|
|
1435
|
-
pushed = false;
|
|
1436
|
-
}
|
|
1437
|
-
if (!pushed) {
|
|
1438
|
-
const searchCols = plan.searchable.columns;
|
|
1439
|
-
if (searchCols.length > 0) {
|
|
1440
|
-
const ors = searchCols.map((col) => isPostgres ? ilike$1(col, `%${searchTerm}%`) : like$1(sql$1`lower(${col})`, `%${searchTerm.toLowerCase()}%`));
|
|
1441
|
-
conditions.push(ors.length === 1 ? ors[0] : or$1(...ors));
|
|
1442
|
-
}
|
|
1443
|
-
}
|
|
1444
|
-
}
|
|
1445
|
-
let cursorActive = false;
|
|
1446
|
-
const cursorRaw = typeof raw.cursor === "string" ? raw.cursor : "";
|
|
1447
|
-
if (cursorRaw && primarySort && primaryCol && idColForSort) {
|
|
1448
|
-
const decoded = decodeCursor(cursorRaw);
|
|
1449
|
-
if (decoded && Array.isArray(decoded.v) && decoded.v.length >= 1 && (decoded.s === void 0 || decoded.s === requestedSort)) {
|
|
1450
|
-
const [sortVal, idVal] = decoded.v;
|
|
1451
|
-
if (sortVal !== void 0 && sortVal !== null) {
|
|
1452
|
-
const cmp = primarySort.dir === "desc" ? lt$1 : gt$1;
|
|
1453
|
-
const cmpOrEq = primarySort.dir === "desc" ? lte$1 : gte$1;
|
|
1454
|
-
const tie = idVal !== void 0 && idVal !== null ? or$1(cmp(primaryCol, sortVal), and$1(cmpOrEq(primaryCol, sortVal), cmp(idColForSort, idVal))) : cmp(primaryCol, sortVal);
|
|
1455
|
-
conditions.push(tie);
|
|
1456
|
-
cursorActive = true;
|
|
1457
|
-
offset = 0;
|
|
1458
|
-
}
|
|
1459
|
-
}
|
|
1460
|
-
}
|
|
1461
|
-
const projection = (raw.select ? parseSelectParam(table, columns, raw.select) : void 0) ?? plan.projections.defaultProjection;
|
|
1462
|
-
let total;
|
|
1463
|
-
let rows;
|
|
1464
|
-
const canPrepare = !cursorActive && !searchTerm && typeof db?.select === "function";
|
|
1465
|
-
let usedPrepared = false;
|
|
1466
|
-
if (canPrepare) {
|
|
1467
|
-
const cache = getResourceDbCache(db, plan);
|
|
1468
|
-
const filterKey = exactFilters.map((f) => f.key).sort().join(",");
|
|
1469
|
-
const sortKey = requestedSort;
|
|
1470
|
-
const projKey = raw.select ? String(raw.select) : "default";
|
|
1471
|
-
const shapeKey = `${filterKey}|${isOwnerScoped ? "1" : "0"}|${sortKey}|${projKey}`;
|
|
1472
|
-
let preparedPair = cache.listCache.get(shapeKey);
|
|
1473
|
-
if (!preparedPair) try {
|
|
1474
|
-
const prepWhereParts = [];
|
|
1475
|
-
if (isOwnerScoped) prepWhereParts.push(eq$1(plan.ownerCol, sql$1.placeholder("__ownerId")));
|
|
1476
|
-
for (let i = 0; i < exactFilters.length; i++) prepWhereParts.push(eq$1(exactFilters[i].col, sql$1.placeholder(`__f_${exactFilters[i].key}`)));
|
|
1477
|
-
const prepWhere = prepWhereParts.length === 1 ? prepWhereParts[0] : prepWhereParts.length > 1 ? and$1(...prepWhereParts) : void 0;
|
|
1478
|
-
let sQuery = projection ? db.select(projection).from(table) : db.select().from(table);
|
|
1479
|
-
if (prepWhere) sQuery = sQuery.where(prepWhere);
|
|
1480
|
-
if (orderBys.length > 0) sQuery = sQuery.orderBy(...orderBys);
|
|
1481
|
-
sQuery = sQuery.limit(sql$1.placeholder("__limit")).offset(sql$1.placeholder("__offset"));
|
|
1482
|
-
const preparedSelect = sQuery.prepare();
|
|
1483
|
-
let cQuery = db.select({ n: sql$1`count(*)`.mapWith(Number) }).from(table);
|
|
1484
|
-
if (prepWhere) cQuery = cQuery.where(prepWhere);
|
|
1485
|
-
preparedPair = {
|
|
1486
|
-
select: preparedSelect,
|
|
1487
|
-
count: cQuery.prepare()
|
|
1488
|
-
};
|
|
1489
|
-
if (cache.listCache.size < 64) cache.listCache.set(shapeKey, preparedPair);
|
|
1490
|
-
} catch {
|
|
1491
|
-
preparedPair = void 0;
|
|
1492
|
-
}
|
|
1493
|
-
if (preparedPair) try {
|
|
1494
|
-
const execParams = {
|
|
1495
|
-
__limit: limit,
|
|
1496
|
-
__offset: offset
|
|
1497
|
-
};
|
|
1498
|
-
if (isOwnerScoped) execParams.__ownerId = ctx.user.id;
|
|
1499
|
-
for (let i = 0; i < exactFilters.length; i++) execParams[`__f_${exactFilters[i].key}`] = exactFilters[i].val;
|
|
1500
|
-
total = (await preparedPair.count.execute(execParams))[0]?.n ?? 0;
|
|
1501
|
-
rows = await preparedPair.select.execute(execParams);
|
|
1502
|
-
usedPrepared = true;
|
|
1503
|
-
} catch {
|
|
1504
|
-
usedPrepared = false;
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
if (!usedPrepared) {
|
|
1508
|
-
const where = conditions.length > 0 ? and$1(...conditions) : void 0;
|
|
1509
|
-
const countQuery = db.select({ n: sql$1`count(*)`.mapWith(Number) }).from(table);
|
|
1510
|
-
const [{ n: totalCount } = { n: 0 }] = await (where ? countQuery.where(where) : countQuery);
|
|
1511
|
-
total = totalCount;
|
|
1512
|
-
const baseSelect = projection ? db.select(projection).from(table) : db.select().from(table);
|
|
1513
|
-
const filtered = where !== void 0 ? baseSelect.where(where) : baseSelect;
|
|
1514
|
-
rows = await (orderBys.length > 0 ? filtered.orderBy(...orderBys) : filtered).limit(limit).offset(cursorActive ? 0 : offset);
|
|
1515
|
-
}
|
|
1516
|
-
return formatListResult(plan, rows, total, limit, offset, page, cursorActive, primarySort, primaryCol, requestedSort);
|
|
1517
|
-
}
|
|
1518
|
-
});
|
|
1519
|
-
const updateAction = defineAction({
|
|
1520
|
-
name: `${resourceName}.update`,
|
|
1521
|
-
description: `Update a ${resourceName} by ID`,
|
|
1522
|
-
input: updateSchema,
|
|
1523
|
-
output: rowSchema,
|
|
1524
|
-
errors: {
|
|
1525
|
-
NOT_FOUND: {
|
|
1526
|
-
status: 404,
|
|
1527
|
-
message: `${capitalizedName} not found`
|
|
1528
|
-
},
|
|
1529
|
-
FORBIDDEN: {
|
|
1530
|
-
status: 403,
|
|
1531
|
-
message: `Access denied to update ${resourceName}`
|
|
1532
|
-
},
|
|
1533
|
-
...config.errors
|
|
1534
|
-
},
|
|
1535
|
-
execute: async ({ input, ctx, error }) => {
|
|
1536
|
-
const db = ctx.db ?? service.getDb();
|
|
1537
|
-
const idVal = input[idField] ?? input.id;
|
|
1538
|
-
if (!plan.idCol) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' not found`);
|
|
1539
|
-
const existing = await executeGet(db, plan, idVal);
|
|
1540
|
-
if (!existing) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' not found`);
|
|
1541
|
-
if (ownerField && ctx.user?.id) {
|
|
1542
|
-
const rowOwner = existing[ownerField] ?? existing[plan.ownerColName];
|
|
1543
|
-
if (rowOwner && rowOwner !== ctx.user.id) error.FORBIDDEN(`Access denied to update ${resourceName}`);
|
|
1544
|
-
}
|
|
1545
|
-
const { id: _ignoreId, [idField]: _ignoreIdField, ...updateData } = input;
|
|
1546
|
-
if (plan.timestampColumns.updatedAtKey) updateData[plan.timestampColumns.updatedAtKey] = (/* @__PURE__ */ new Date()).toISOString();
|
|
1547
|
-
if (config.hooks?.beforeUpdate) await config.hooks.beforeUpdate({
|
|
1548
|
-
id: idVal,
|
|
1549
|
-
data: updateData,
|
|
1550
|
-
existing,
|
|
1551
|
-
ctx,
|
|
1552
|
-
error
|
|
1553
|
-
});
|
|
1554
|
-
let written;
|
|
1555
|
-
if (Object.keys(updateData).length > 0) {
|
|
1556
|
-
written = executePreparedWrite(db, plan, "update", updateData, idVal, Boolean(config.hooks?.beforeUpdate));
|
|
1557
|
-
if (!written) await db.update(table).set(updateData).where(eq$1(plan.idCol, idVal));
|
|
1558
|
-
}
|
|
1559
|
-
const updated = written && !written.readBack ? written.row : await executeGet(db, plan, idVal);
|
|
1560
|
-
if (config.hooks?.afterUpdate) await config.hooks.afterUpdate({
|
|
1561
|
-
id: idVal,
|
|
1562
|
-
data: updateData,
|
|
1563
|
-
result: updated ?? existing,
|
|
1564
|
-
ctx
|
|
1565
|
-
});
|
|
1566
|
-
return updated ?? existing;
|
|
1567
|
-
}
|
|
1568
|
-
});
|
|
1569
|
-
const deleteAction = defineAction({
|
|
1570
|
-
name: `${resourceName}.delete`,
|
|
1571
|
-
description: `Delete a ${resourceName} by ID`,
|
|
1572
|
-
input: deleteSchema,
|
|
1573
|
-
output: Type.Object({
|
|
1574
|
-
success: Type.Boolean(),
|
|
1575
|
-
id: Type.Union([Type.String(), Type.Number()])
|
|
1977
|
+
const columns = getTableColumns$1(config.table);
|
|
1978
|
+
const primary = Object.entries(columns).filter(([, column]) => column.primary);
|
|
1979
|
+
const id = config.id ?? (primary.length === 1 ? primary[0]?.[1] : void 0);
|
|
1980
|
+
const entry = Object.entries(columns).find(([, column]) => column === id);
|
|
1981
|
+
if (!entry || !id) throw new Error(`Resource '${config.name}' requires an id column belonging to its table`);
|
|
1982
|
+
if (!config.name || config.name.includes("/") || [
|
|
1983
|
+
"__proto__",
|
|
1984
|
+
"constructor",
|
|
1985
|
+
"prototype"
|
|
1986
|
+
].includes(config.name)) throw new Error(`Invalid resource name '${config.name}'`);
|
|
1987
|
+
service.registerTable(config.table);
|
|
1988
|
+
const resource = {
|
|
1989
|
+
name: config.name,
|
|
1990
|
+
serviceName: service.name,
|
|
1991
|
+
table: config.table,
|
|
1992
|
+
id,
|
|
1993
|
+
idField: entry[0],
|
|
1994
|
+
config: Object.freeze({
|
|
1995
|
+
...config,
|
|
1996
|
+
id
|
|
1576
1997
|
}),
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
status: 404,
|
|
1580
|
-
message: `${capitalizedName} not found`
|
|
1581
|
-
},
|
|
1582
|
-
FORBIDDEN: {
|
|
1583
|
-
status: 403,
|
|
1584
|
-
message: `Access denied to delete ${resourceName}`
|
|
1585
|
-
},
|
|
1586
|
-
...config.errors
|
|
1587
|
-
},
|
|
1588
|
-
execute: async ({ input, ctx, error }) => {
|
|
1589
|
-
const db = ctx.db ?? service.getDb();
|
|
1590
|
-
const idVal = input[idField] ?? input.id;
|
|
1591
|
-
if (!plan.idCol) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' not found`);
|
|
1592
|
-
const existing = await executeGet(db, plan, idVal);
|
|
1593
|
-
if (!existing) error.NOT_FOUND(`${capitalizedName} with ID '${idVal}' not found`);
|
|
1594
|
-
if (ownerField && ctx.user?.id) {
|
|
1595
|
-
const rowOwner = existing[ownerField] ?? existing[plan.ownerColName];
|
|
1596
|
-
if (rowOwner && rowOwner !== ctx.user.id) error.FORBIDDEN(`Access denied to delete ${resourceName}`);
|
|
1597
|
-
}
|
|
1598
|
-
if (config.hooks?.beforeDelete) await config.hooks.beforeDelete({
|
|
1599
|
-
id: idVal,
|
|
1600
|
-
existing,
|
|
1601
|
-
ctx,
|
|
1602
|
-
error
|
|
1603
|
-
});
|
|
1604
|
-
await executeDelete(db, plan, idVal);
|
|
1605
|
-
if (config.hooks?.afterDelete) await config.hooks.afterDelete({
|
|
1606
|
-
id: idVal,
|
|
1607
|
-
existing,
|
|
1608
|
-
ctx,
|
|
1609
|
-
error
|
|
1610
|
-
});
|
|
1611
|
-
return {
|
|
1612
|
-
success: true,
|
|
1613
|
-
id: idVal
|
|
1614
|
-
};
|
|
1998
|
+
use(plugin) {
|
|
1999
|
+
return installPlugin(service, resource, plugin);
|
|
1615
2000
|
}
|
|
1616
|
-
});
|
|
1617
|
-
if (operations.create !== false) {
|
|
1618
|
-
service.action(createAction);
|
|
1619
|
-
service.actions.set(`create${capitalizedName}`, createAction);
|
|
1620
|
-
}
|
|
1621
|
-
if (operations.get !== false) {
|
|
1622
|
-
service.action(getAction);
|
|
1623
|
-
service.actions.set(`get${capitalizedName}`, getAction);
|
|
1624
|
-
}
|
|
1625
|
-
if (operations.list !== false) {
|
|
1626
|
-
service.action(listAction);
|
|
1627
|
-
service.actions.set(`list${pluralName.charAt(0).toUpperCase() + pluralName.slice(1)}`, listAction);
|
|
1628
|
-
}
|
|
1629
|
-
if (operations.update !== false) {
|
|
1630
|
-
service.action(updateAction);
|
|
1631
|
-
service.actions.set(`update${capitalizedName}`, updateAction);
|
|
1632
|
-
}
|
|
1633
|
-
if (operations.delete !== false) {
|
|
1634
|
-
service.action(deleteAction);
|
|
1635
|
-
service.actions.set(`delete${capitalizedName}`, deleteAction);
|
|
1636
|
-
}
|
|
1637
|
-
const actions = {
|
|
1638
|
-
list: listAction,
|
|
1639
|
-
get: getAction,
|
|
1640
|
-
create: createAction,
|
|
1641
|
-
update: updateAction,
|
|
1642
|
-
delete: deleteAction
|
|
1643
|
-
};
|
|
1644
|
-
return {
|
|
1645
|
-
name: resourceName,
|
|
1646
|
-
serviceName: service.name,
|
|
1647
|
-
table,
|
|
1648
|
-
ownerField,
|
|
1649
|
-
idField,
|
|
1650
|
-
pluralName,
|
|
1651
|
-
config,
|
|
1652
|
-
plan,
|
|
1653
|
-
actions,
|
|
1654
|
-
...actions
|
|
1655
2001
|
};
|
|
2002
|
+
return resource;
|
|
1656
2003
|
}
|
|
1657
2004
|
//#endregion
|
|
1658
2005
|
//#region src/service.ts
|
|
@@ -1673,6 +2020,7 @@ var ServiceImpl = class {
|
|
|
1673
2020
|
tools = /* @__PURE__ */ new Map();
|
|
1674
2021
|
tables = /* @__PURE__ */ new Map();
|
|
1675
2022
|
resources = /* @__PURE__ */ new Map();
|
|
2023
|
+
preparations = /* @__PURE__ */ new Map();
|
|
1676
2024
|
database;
|
|
1677
2025
|
_isBuilt = false;
|
|
1678
2026
|
constructor(name, options = {}) {
|
|
@@ -1681,6 +2029,9 @@ var ServiceImpl = class {
|
|
|
1681
2029
|
if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
|
|
1682
2030
|
this.database = options.database;
|
|
1683
2031
|
}
|
|
2032
|
+
use(plugin) {
|
|
2033
|
+
return installPlugin(this, void 0, plugin);
|
|
2034
|
+
}
|
|
1684
2035
|
get db() {
|
|
1685
2036
|
return this.getDb();
|
|
1686
2037
|
}
|
|
@@ -1688,18 +2039,26 @@ var ServiceImpl = class {
|
|
|
1688
2039
|
return this._isBuilt;
|
|
1689
2040
|
}
|
|
1690
2041
|
/**
|
|
1691
|
-
*
|
|
1692
|
-
* Per-request paths perform O(1) lookups against these immutable plans.
|
|
2042
|
+
* Closes declarations after plugins have registered their actions and preparations.
|
|
1693
2043
|
*/
|
|
1694
2044
|
build() {
|
|
2045
|
+
if (isInstallingPlugin(this)) throw new Error("Cannot build a service during plugin setup");
|
|
1695
2046
|
if (this._isBuilt) return this;
|
|
1696
|
-
for (const resource of this.resources.values()) {
|
|
1697
|
-
if (!resource.plan) resource.plan = buildResourcePlan(this, resource.config);
|
|
1698
|
-
Object.freeze(resource.plan);
|
|
1699
|
-
}
|
|
1700
2047
|
this._isBuilt = true;
|
|
1701
2048
|
return this;
|
|
1702
2049
|
}
|
|
2050
|
+
contributePreparation(contribution) {
|
|
2051
|
+
if (this._isBuilt) throw new Error("Preparations must be registered before service build");
|
|
2052
|
+
if (this.preparations.has(contribution.name)) throw new Error(`Duplicate preparation '${contribution.name}'`);
|
|
2053
|
+
this.preparations.set(contribution.name, contribution);
|
|
2054
|
+
getGlobalRegistry().touch();
|
|
2055
|
+
}
|
|
2056
|
+
listPreparations() {
|
|
2057
|
+
return [...this.preparations.values()];
|
|
2058
|
+
}
|
|
2059
|
+
prepareContributions() {
|
|
2060
|
+
for (const contribution of this.preparations.values()) contribution.prepare();
|
|
2061
|
+
}
|
|
1703
2062
|
registerTable(table) {
|
|
1704
2063
|
try {
|
|
1705
2064
|
const tableName = getTableName(table);
|
|
@@ -1711,6 +2070,8 @@ var ServiceImpl = class {
|
|
|
1711
2070
|
return this;
|
|
1712
2071
|
}
|
|
1713
2072
|
resource = ((config) => {
|
|
2073
|
+
if (this._isBuilt) throw new Error("Resources must be registered before service build");
|
|
2074
|
+
if (this.resources.has(config.name)) throw new Error(`Duplicate plugin resource: ${config.name}`);
|
|
1714
2075
|
const resourceInstance = defineResource(this, config);
|
|
1715
2076
|
this.resources.set(resourceInstance.name, resourceInstance);
|
|
1716
2077
|
getGlobalRegistry().touch();
|
|
@@ -1727,6 +2088,7 @@ var ServiceImpl = class {
|
|
|
1727
2088
|
const isActionFunction = typeof actionOrConfig === "function" && "config" in actionOrConfig;
|
|
1728
2089
|
if (isActionFunction) actionInstance = actionOrConfig;
|
|
1729
2090
|
else actionInstance = defineAction(actionOrConfig);
|
|
2091
|
+
if (isInstallingPlugin(this) && this.actions.has(actionInstance.name) && this.actions.get(actionInstance.name) !== actionInstance) throw new Error(`Duplicate plugin action: ${actionInstance.name}`);
|
|
1730
2092
|
if (isTool(actionInstance)) actionInstance.config.http = true;
|
|
1731
2093
|
actionInstance.serviceName = this.name;
|
|
1732
2094
|
actionInstance.service = this;
|
|
@@ -1840,11 +2202,7 @@ var ServiceImpl = class {
|
|
|
1840
2202
|
emits: act.config.emits,
|
|
1841
2203
|
tags: act.config.tags
|
|
1842
2204
|
})),
|
|
1843
|
-
resources: this.listResources().map((res) => ({
|
|
1844
|
-
name: res.name,
|
|
1845
|
-
ownerField: res.ownerField,
|
|
1846
|
-
operations: Object.keys(res.actions)
|
|
1847
|
-
}))
|
|
2205
|
+
resources: this.listResources().map((res) => ({ name: res.name }))
|
|
1848
2206
|
};
|
|
1849
2207
|
}
|
|
1850
2208
|
};
|
|
@@ -1878,143 +2236,6 @@ function createServiceProxy(serviceName, options = {}) {
|
|
|
1878
2236
|
} });
|
|
1879
2237
|
}
|
|
1880
2238
|
//#endregion
|
|
1881
|
-
//#region src/openapi.ts
|
|
1882
|
-
function generateOpenApiSpec(options = {}) {
|
|
1883
|
-
const title = options.title ?? "Brick-TS API Mesh";
|
|
1884
|
-
const version = options.version ?? "1.0.0";
|
|
1885
|
-
const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
|
|
1886
|
-
const prefix = options.prefix ?? "/api";
|
|
1887
|
-
const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
|
|
1888
|
-
const paths = {};
|
|
1889
|
-
const tagsSet = /* @__PURE__ */ new Set();
|
|
1890
|
-
let hasAnyAuthorizedAction = false;
|
|
1891
|
-
for (const service of services) {
|
|
1892
|
-
tagsSet.add(service.name);
|
|
1893
|
-
for (const action of service.listActions()) {
|
|
1894
|
-
const routePath = action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
1895
|
-
const method = (action.config.method ?? "POST").toLowerCase();
|
|
1896
|
-
const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
|
|
1897
|
-
const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
|
|
1898
|
-
if (!paths[actionPath]) paths[actionPath] = {};
|
|
1899
|
-
if (paths[actionPath][method]) continue;
|
|
1900
|
-
const hasAuth = Boolean(action.config.authorize);
|
|
1901
|
-
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
1902
|
-
const responses = {};
|
|
1903
|
-
if (action.config.output) responses["200"] = {
|
|
1904
|
-
description: "Successful response",
|
|
1905
|
-
content: { "application/json": { schema: action.config.output } }
|
|
1906
|
-
};
|
|
1907
|
-
else responses["200"] = { description: "Successful response" };
|
|
1908
|
-
if (action.config.input) responses["400"] = {
|
|
1909
|
-
description: "Validation error",
|
|
1910
|
-
content: { "application/json": { schema: {
|
|
1911
|
-
type: "object",
|
|
1912
|
-
properties: {
|
|
1913
|
-
name: { type: "string" },
|
|
1914
|
-
message: { type: "string" },
|
|
1915
|
-
status: { type: "integer" },
|
|
1916
|
-
errors: {
|
|
1917
|
-
type: "array",
|
|
1918
|
-
items: {
|
|
1919
|
-
type: "object",
|
|
1920
|
-
properties: {
|
|
1921
|
-
path: { type: "string" },
|
|
1922
|
-
message: { type: "string" }
|
|
1923
|
-
}
|
|
1924
|
-
}
|
|
1925
|
-
}
|
|
1926
|
-
}
|
|
1927
|
-
} } }
|
|
1928
|
-
};
|
|
1929
|
-
if (hasAuth) responses["403"] = { description: "Access denied / Unauthorized" };
|
|
1930
|
-
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
1931
|
-
const def = errorDef;
|
|
1932
|
-
const status = String(def.status || 400);
|
|
1933
|
-
responses[status] = {
|
|
1934
|
-
description: def.message || code,
|
|
1935
|
-
content: { "application/json": { schema: {
|
|
1936
|
-
type: "object",
|
|
1937
|
-
properties: {
|
|
1938
|
-
name: {
|
|
1939
|
-
type: "string",
|
|
1940
|
-
example: "ActionExecutionError"
|
|
1941
|
-
},
|
|
1942
|
-
code: {
|
|
1943
|
-
type: "string",
|
|
1944
|
-
example: code
|
|
1945
|
-
},
|
|
1946
|
-
message: {
|
|
1947
|
-
type: "string",
|
|
1948
|
-
example: def.message
|
|
1949
|
-
},
|
|
1950
|
-
status: {
|
|
1951
|
-
type: "integer",
|
|
1952
|
-
example: def.status || 400
|
|
1953
|
-
}
|
|
1954
|
-
}
|
|
1955
|
-
} } }
|
|
1956
|
-
};
|
|
1957
|
-
}
|
|
1958
|
-
responses["500"] = { description: "Internal server error" };
|
|
1959
|
-
const operation = {
|
|
1960
|
-
operationId: `${service.name}_${action.name}_${method}`,
|
|
1961
|
-
summary: `${service.name}.${action.name}`,
|
|
1962
|
-
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
1963
|
-
tags: action.config.tags && action.config.tags.length > 0 ? action.config.tags : [service.name],
|
|
1964
|
-
responses
|
|
1965
|
-
};
|
|
1966
|
-
const inputSchema = action.config.input;
|
|
1967
|
-
const properties = inputSchema?.properties ?? {};
|
|
1968
|
-
const parameters = [...new Set(pathParams)].map((key) => ({
|
|
1969
|
-
name: key,
|
|
1970
|
-
in: "path",
|
|
1971
|
-
required: true,
|
|
1972
|
-
schema: properties[key] ?? { type: "string" }
|
|
1973
|
-
}));
|
|
1974
|
-
if (method === "get" || method === "delete") for (const [key, schema] of Object.entries(properties)) {
|
|
1975
|
-
if (pathParams.includes(key)) continue;
|
|
1976
|
-
parameters.push({
|
|
1977
|
-
name: key,
|
|
1978
|
-
in: "query",
|
|
1979
|
-
required: inputSchema?.required?.includes(key) ?? false,
|
|
1980
|
-
schema
|
|
1981
|
-
});
|
|
1982
|
-
}
|
|
1983
|
-
else if (inputSchema) operation.requestBody = {
|
|
1984
|
-
required: true,
|
|
1985
|
-
content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
|
|
1986
|
-
...inputSchema,
|
|
1987
|
-
properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
|
|
1988
|
-
required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
|
|
1989
|
-
} : inputSchema } }
|
|
1990
|
-
};
|
|
1991
|
-
if (parameters.length) operation.parameters = parameters;
|
|
1992
|
-
if (hasAuth) operation.security = [{ bearerAuth: [] }];
|
|
1993
|
-
paths[actionPath][method] = operation;
|
|
1994
|
-
}
|
|
1995
|
-
}
|
|
1996
|
-
const spec = {
|
|
1997
|
-
openapi: "3.1.0",
|
|
1998
|
-
info: {
|
|
1999
|
-
title,
|
|
2000
|
-
version,
|
|
2001
|
-
description
|
|
2002
|
-
},
|
|
2003
|
-
paths,
|
|
2004
|
-
tags: Array.from(tagsSet).map((name) => ({
|
|
2005
|
-
name,
|
|
2006
|
-
description: `Actions exposed by '${name}' service`
|
|
2007
|
-
}))
|
|
2008
|
-
};
|
|
2009
|
-
if (hasAnyAuthorizedAction) spec.components = { securitySchemes: { bearerAuth: {
|
|
2010
|
-
type: "http",
|
|
2011
|
-
scheme: "bearer",
|
|
2012
|
-
bearerFormat: "JWT",
|
|
2013
|
-
description: "Enter your Bearer authentication token"
|
|
2014
|
-
} } };
|
|
2015
|
-
return spec;
|
|
2016
|
-
}
|
|
2017
|
-
//#endregion
|
|
2018
2239
|
//#region src/mcp.ts
|
|
2019
2240
|
var UnknownToolError = class extends Error {
|
|
2020
2241
|
constructor(name) {
|
|
@@ -2136,6 +2357,6 @@ function createMcpHandler(options) {
|
|
|
2136
2357
|
};
|
|
2137
2358
|
}
|
|
2138
2359
|
//#endregion
|
|
2139
|
-
export { ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, Type as t, UnknownToolError, ValidationError, and, asc, attachDatabase, blob, buildErrorHelpers, buildFtsMatchQuery,
|
|
2360
|
+
export { ActionExecutionError, BrickServerError, BrickTransportError, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, Type as t, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, createServiceProxy, defineAction, defineDatabase, defineResource, defineResourcePlugin, defineService, defineServicePlugin, defineTool, desc, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isNotNull, isNull, isTool, like, listSecrets, loadCompiledBrickApp, lt, lte, ne, not, notInArray, or, overrideSecret, overrideSecrets, primaryKey, real, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, scalarDocsHTML, secret, sql, sqliteTable, swaggerDocsHTML, syncSchema, text, toOpenApiPath, uniqueIndex, validateWithSchema };
|
|
2140
2361
|
|
|
2141
2362
|
//# sourceMappingURL=index.js.map
|