@brickkit/core 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunks/client.d.ts +1558 -649
- package/dist/chunks/client.d.ts.map +1 -1
- package/dist/chunks/client.js +313 -73
- package/dist/chunks/client.js.map +1 -1
- package/dist/client.d.ts +2 -2
- package/dist/index.d.ts +252 -177
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1855 -248
- package/dist/index.js.map +1 -1
- package/dist/tanstack-query.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,23 +1,85 @@
|
|
|
1
|
-
import { a as isBrickTransportError, c as SOCKET_MAX_BYTES, d as
|
|
1
|
+
import { a as isBrickTransportError, c as SOCKET_MAX_BYTES, d as isSocketRoom, f as isSocketSeq, g as kebabCase, h as ValidationError, i as isBrickServerError, l as compareSocketSeq, m as ActionExecutionError, n as BrickTransportError, p as serializeSocketSchema, r as createBrickClient, s as SOCKET_BUFFER_BYTES, t as BrickServerError, u as isSocketEnvelope } from "./chunks/client.js";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
3
4
|
import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
4
5
|
import { Type, Type as t } from "@sinclair/typebox";
|
|
5
6
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
6
7
|
import { formatWithOptions } from "node:util";
|
|
7
|
-
import {
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
9
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
10
|
+
import { Value } from "@sinclair/typebox/value";
|
|
8
11
|
import { Table, and, and as and$1, asc, asc as asc$1, desc, eq, eq as eq$1, getTableColumns, getTableColumns as getTableColumns$1, getTableName, getTableName as getTableName$1, gt, gte, ilike, inArray, inArray as inArray$1, is, isNotNull, isNull, like, lt, lt as lt$1, lte, lte as lte$1, ne, not, notInArray, or, or as or$1, relations, sql, sql as sql$1 } from "drizzle-orm";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
12
|
+
import { blob, foreignKey, index, index as index$1, integer, integer as integer$1, primaryKey, real, real as real$1, sqliteTable, sqliteTable as sqliteTable$1, text, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
13
|
+
import { bigserial, boolean, doublePrecision, index as index$2, integer as integer$2, jsonb, pgTable, text as text$2, timestamp } from "drizzle-orm/pg-core";
|
|
11
14
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import { pathToFileURL } from "node:url";
|
|
15
|
+
import { Elysia } from "elysia";
|
|
16
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
15
17
|
import { websocket } from "elysia/websocket";
|
|
16
18
|
import postgres from "postgres";
|
|
17
19
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
18
20
|
//#region \0rolldown/runtime.js
|
|
19
21
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
20
22
|
//#endregion
|
|
23
|
+
//#region src/routes.ts
|
|
24
|
+
/**
|
|
25
|
+
* The route every name of an owner mounts under: `${prefix}`,
|
|
26
|
+
* `${prefix}/${service}`, or `${prefix}/${service}/${resource}`, in kebab-case.
|
|
27
|
+
*/
|
|
28
|
+
function ownerPath(prefix, service, resource) {
|
|
29
|
+
let path = prefix.replace(/\/$/, "");
|
|
30
|
+
if (service !== void 0) path += `/${kebabCase(service)}`;
|
|
31
|
+
if (resource !== void 0) path += `/${kebabCase(resource)}`;
|
|
32
|
+
return path;
|
|
33
|
+
}
|
|
34
|
+
/** Joins a path relative to its owner. `/` is the owner's own route. */
|
|
35
|
+
function joinRoute(base, path) {
|
|
36
|
+
return `${base}${path === "/" ? "" : path}` || "/";
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Where an action is served over HTTP: its method and its path under the owner
|
|
40
|
+
* tree (`${prefix}/${service}/${action}`, a plugin's route, or a resource
|
|
41
|
+
* action's `${prefix}/${service}/${resource}[/:id]/${action}`).
|
|
42
|
+
*
|
|
43
|
+
* @param action - An action registered on a service.
|
|
44
|
+
* @param prefix - The application's route prefix (default `/api`).
|
|
45
|
+
* @returns `false` when a plugin switched the route off, otherwise the route.
|
|
46
|
+
*/
|
|
47
|
+
function getActionRoute(action, prefix = "/api") {
|
|
48
|
+
const plugin = getPluginActionRoute(action, prefix);
|
|
49
|
+
if (plugin === false) return false;
|
|
50
|
+
if (plugin) return {
|
|
51
|
+
method: plugin.method,
|
|
52
|
+
path: plugin.path,
|
|
53
|
+
legacyPath: plugin.legacyPath
|
|
54
|
+
};
|
|
55
|
+
const service = action.serviceName ?? "";
|
|
56
|
+
const method = action.config.method ?? "POST";
|
|
57
|
+
const { resourceAction } = action;
|
|
58
|
+
if (resourceAction) {
|
|
59
|
+
const base = ownerPath(prefix, service, resourceAction.resource);
|
|
60
|
+
return {
|
|
61
|
+
method,
|
|
62
|
+
path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}${resourceAction.record ? "/:id" : ""}/${kebabCase(resourceAction.name)}`
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const base = ownerPath(prefix, service);
|
|
66
|
+
return {
|
|
67
|
+
method,
|
|
68
|
+
path: action.config.path !== void 0 ? joinRoute(base, action.config.path) : `${base}/${kebabCase(action.name)}`,
|
|
69
|
+
legacyPath: legacyPath(prefix, service, action.name, action.config.path)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The v0.10 route of a service action or socket: the names as declared, or an
|
|
74
|
+
* explicit path that still reads as absolute (it starts with the prefix). A
|
|
75
|
+
* path already rewritten as relative has no v0.10 form.
|
|
76
|
+
*/
|
|
77
|
+
function legacyPath(prefix, service, name, path) {
|
|
78
|
+
const root = prefix.replace(/\/$/, "");
|
|
79
|
+
if (path === void 0) return `${root}/${service}/${name}`;
|
|
80
|
+
return path.startsWith(`${root}/`) ? path : void 0;
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
21
83
|
//#region src/compiler/ir.ts
|
|
22
84
|
function freezeIR(value) {
|
|
23
85
|
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
@@ -102,11 +164,13 @@ function analyzeDeclaredApplication(services, prefix = "/api") {
|
|
|
102
164
|
action
|
|
103
165
|
});
|
|
104
166
|
};
|
|
105
|
-
for (const service of services)
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
167
|
+
for (const service of services) {
|
|
168
|
+
checkSegments(service);
|
|
169
|
+
for (const action of service.listActions()) {
|
|
170
|
+
const route = getActionRoute(action, prefix);
|
|
171
|
+
if (route === false) continue;
|
|
172
|
+
add(service, action, route.method, route.path, "action");
|
|
173
|
+
}
|
|
110
174
|
}
|
|
111
175
|
const preparations = services.flatMap((service) => service.listPreparations().map((contribution) => ({
|
|
112
176
|
service: service.name,
|
|
@@ -126,8 +190,49 @@ function analyzeDeclaredApplication(services, prefix = "/api") {
|
|
|
126
190
|
bindings
|
|
127
191
|
};
|
|
128
192
|
}
|
|
193
|
+
/** A service action, resource, and socket own the URL segment after the service. */
|
|
194
|
+
function checkSegments(service) {
|
|
195
|
+
const owners = /* @__PURE__ */ new Map();
|
|
196
|
+
const claim = (segment, owner) => {
|
|
197
|
+
const previous = owners.get(segment);
|
|
198
|
+
if (previous) throw new Error(`Brick: duplicate name "${segment}" in service "${service.name}": ${previous} and ${owner} share the URL segment`);
|
|
199
|
+
owners.set(segment, owner);
|
|
200
|
+
};
|
|
201
|
+
for (const resource of service.listResources()) claim(kebabCase(resource.name), `resource "${resource.name}"`);
|
|
202
|
+
for (const socket of service.listSockets()) if (socket.schema.path === void 0) claim(kebabCase(socket.schema.name), `socket "${socket.schema.name}"`);
|
|
203
|
+
for (const action of service.listActions()) if (action.config.path === void 0 && !action.resourceAction && getPluginActionRoute(action) === void 0) claim(kebabCase(action.name), `action "${action.name}"`);
|
|
204
|
+
}
|
|
129
205
|
//#endregion
|
|
130
206
|
//#region src/registry.ts
|
|
207
|
+
const brickRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
208
|
+
/**
|
|
209
|
+
* The first `file:line` outside Brick on the current stack: where a name is
|
|
210
|
+
* being defined. Best-effort: `undefined` when there is no stack.
|
|
211
|
+
*/
|
|
212
|
+
function definitionSite() {
|
|
213
|
+
const limit = Error.stackTraceLimit;
|
|
214
|
+
Error.stackTraceLimit = 50;
|
|
215
|
+
const stack = (/* @__PURE__ */ new Error()).stack;
|
|
216
|
+
Error.stackTraceLimit = limit;
|
|
217
|
+
for (const line of stack?.split("\n").slice(1) ?? []) {
|
|
218
|
+
const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
|
|
219
|
+
if (!match) continue;
|
|
220
|
+
const [, file, row] = match;
|
|
221
|
+
if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
|
|
222
|
+
return `${file}:${row}`;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Records where `name` is defined. The same file defining it again (a dev
|
|
227
|
+
* reload) replaces the old definition.
|
|
228
|
+
*
|
|
229
|
+
* @throws When a different file already defined `name`.
|
|
230
|
+
*/
|
|
231
|
+
function claimName(sites, label, name, site) {
|
|
232
|
+
const file = (at) => at?.replace(/:\d+$/, "");
|
|
233
|
+
if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new Error(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
|
|
234
|
+
sites.set(name, site);
|
|
235
|
+
}
|
|
131
236
|
var ServiceRegistry = class {
|
|
132
237
|
_revision = 0;
|
|
133
238
|
/** Definition revision for invalidating serialized architecture snapshots. */
|
|
@@ -138,14 +243,16 @@ var ServiceRegistry = class {
|
|
|
138
243
|
this._revision++;
|
|
139
244
|
}
|
|
140
245
|
services = /* @__PURE__ */ new Map();
|
|
246
|
+
sites = /* @__PURE__ */ new Map();
|
|
141
247
|
routes = /* @__PURE__ */ new Map();
|
|
142
248
|
/** Remember the actual registered routes for subsequent registry exports. */
|
|
143
249
|
setApplicationRoutes(application) {
|
|
144
250
|
for (const service of application.services) this.routes.set(service, application.routes.filter((route) => route.service === service.name));
|
|
145
251
|
this.touch();
|
|
146
252
|
}
|
|
147
|
-
|
|
148
|
-
|
|
253
|
+
/** @throws When a different file already registered a service with this name. */
|
|
254
|
+
register(service, site = definitionSite()) {
|
|
255
|
+
claimName(this.sites, `service "${service.name}"`, service.name, site);
|
|
149
256
|
const previous = this.services.get(service.name);
|
|
150
257
|
if (previous) this.routes.delete(previous);
|
|
151
258
|
this.services.set(service.name, service);
|
|
@@ -162,6 +269,7 @@ var ServiceRegistry = class {
|
|
|
162
269
|
}
|
|
163
270
|
clear() {
|
|
164
271
|
this.services.clear();
|
|
272
|
+
this.sites.clear();
|
|
165
273
|
this.routes.clear();
|
|
166
274
|
this.touch();
|
|
167
275
|
}
|
|
@@ -169,6 +277,7 @@ var ServiceRegistry = class {
|
|
|
169
277
|
return {
|
|
170
278
|
version: "1.0.0",
|
|
171
279
|
...application?.events ? { events: application.events } : {},
|
|
280
|
+
...application?.plugins?.length ? { plugins: [...application.plugins] } : {},
|
|
172
281
|
services: (application?.services ?? this.list()).map((service) => {
|
|
173
282
|
const routes = application ? application.routes.filter((route) => route.service === service.name) : this.routes.get(service) ?? analyzeDeclaredApplication([service]).ir.routes;
|
|
174
283
|
const byAction = new Map(routes.map((route) => [route.action, route]));
|
|
@@ -192,7 +301,7 @@ var ServiceRegistry = class {
|
|
|
192
301
|
let globalRegistry = new ServiceRegistry();
|
|
193
302
|
/**
|
|
194
303
|
* The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
|
|
195
|
-
* generator, `
|
|
304
|
+
* generator, `useService`, and the dashboard find services by name.
|
|
196
305
|
*
|
|
197
306
|
* @returns The current global registry.
|
|
198
307
|
*/
|
|
@@ -262,12 +371,14 @@ function traceRoute(route, handler) {
|
|
|
262
371
|
* Wrap one HTTP request in a server span. The span continues the caller's
|
|
263
372
|
* trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the
|
|
264
373
|
* request id Brick returns is the span's trace id, so clients can find the
|
|
265
|
-
* request in the dashboard.
|
|
374
|
+
* request in the dashboard. `extra` adds attributes, such as
|
|
375
|
+
* `brick.legacy_route` on a v0.10 path.
|
|
266
376
|
*/
|
|
267
|
-
function traceHttpRequest(request, method, route, fn) {
|
|
377
|
+
function traceHttpRequest(request, method, route, fn, extra) {
|
|
268
378
|
const attributes = {
|
|
269
379
|
"http.request.method": method,
|
|
270
|
-
"http.route": route
|
|
380
|
+
"http.route": route,
|
|
381
|
+
...extra
|
|
271
382
|
};
|
|
272
383
|
if (request.request) attributes["url.path"] = new URL(request.request.url).pathname;
|
|
273
384
|
const headers = request.headers ?? {};
|
|
@@ -705,6 +816,26 @@ function buildErrorHelpers(errorsDef) {
|
|
|
705
816
|
};
|
|
706
817
|
return helpers;
|
|
707
818
|
}
|
|
819
|
+
/**
|
|
820
|
+
* Define a reusable error. Spread it into the `errors` of any action, listener or
|
|
821
|
+
* command; give it a `details` schema and `error.CODE(message, details)` checks
|
|
822
|
+
* the details against it in types. The details are not validated at runtime.
|
|
823
|
+
*
|
|
824
|
+
* @example
|
|
825
|
+
* const SlugExists = defineError("SLUG_EXISTS", {
|
|
826
|
+
* status: 409,
|
|
827
|
+
* message: "Slug is already taken",
|
|
828
|
+
* details: t.Object({ slug: t.String() }),
|
|
829
|
+
* });
|
|
830
|
+
* // errors: { ...SlugExists } then error.SLUG_EXISTS(undefined, { slug })
|
|
831
|
+
*/
|
|
832
|
+
function defineError(code, definition) {
|
|
833
|
+
return { [code]: definition };
|
|
834
|
+
}
|
|
835
|
+
/** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */
|
|
836
|
+
function errorsOf(action) {
|
|
837
|
+
return action.config.errors ?? {};
|
|
838
|
+
}
|
|
708
839
|
function defineAction(config) {
|
|
709
840
|
const errorHelpers = buildErrorHelpers(config.errors);
|
|
710
841
|
const actionFn = (async (params) => {
|
|
@@ -766,6 +897,8 @@ function defineAction(config) {
|
|
|
766
897
|
//#endregion
|
|
767
898
|
//#region src/plugin.ts
|
|
768
899
|
const pluginKind = Symbol.for("brickkit.plugin.kind");
|
|
900
|
+
/** `definePlugin` instances install on either host; see `define-plugin.ts`. */
|
|
901
|
+
const pluginFinish = Symbol.for("brickkit.plugin.finish");
|
|
769
902
|
/**
|
|
770
903
|
* Define a plugin that installs onto a service with `service.use(plugin)`. Its
|
|
771
904
|
* `setup` receives the service and a `routes` registrar for adding actions and
|
|
@@ -807,7 +940,7 @@ function defineServicePlugin(definition) {
|
|
|
807
940
|
/**
|
|
808
941
|
* Define a plugin that installs onto a resource (a table and its entity) with
|
|
809
942
|
* `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
|
|
810
|
-
* `routes` registrar, whose routes
|
|
943
|
+
* `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and
|
|
811
944
|
* returns the typed API that `resource.use` hands back. `crud` is built this way.
|
|
812
945
|
*
|
|
813
946
|
* @param definition - A unique `name`, optional `routes` controls, and `setup`,
|
|
@@ -874,8 +1007,12 @@ function isInstallingPlugin(service) {
|
|
|
874
1007
|
return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
|
|
875
1008
|
}
|
|
876
1009
|
function pathOf(binding, prefix) {
|
|
1010
|
+
return joinRoute(binding.scope === "app" ? ownerPath(prefix) : ownerPath(prefix, binding.service.name, binding.scope === "resource" ? binding.resource.name : void 0), binding.path);
|
|
1011
|
+
}
|
|
1012
|
+
/** v0.10 mounted resource scope at `${prefix}/${resource}`, with names as declared. */
|
|
1013
|
+
function legacyPathOf(binding, prefix) {
|
|
877
1014
|
const scope = binding.scope === "app" ? "" : `/${binding.scope === "resource" ? binding.resource.name : binding.service.name}`;
|
|
878
|
-
return `${prefix.replace(/\/$/, "")}${scope}
|
|
1015
|
+
return joinRoute(`${prefix.replace(/\/$/, "")}${scope}`, binding.path);
|
|
879
1016
|
}
|
|
880
1017
|
/**
|
|
881
1018
|
* Where a plugin mounted an action over HTTP, for the OpenAPI generator, the
|
|
@@ -885,7 +1022,7 @@ function pathOf(binding, prefix) {
|
|
|
885
1022
|
* @param prefix - The application's route prefix (default `/api`).
|
|
886
1023
|
* @returns `undefined` when no plugin bound the action (it uses its own route),
|
|
887
1024
|
* `false` when the plugin's route was switched off, otherwise the route's
|
|
888
|
-
* `path
|
|
1025
|
+
* `path`, the v0.10 `legacyPath`, `method`, the `clientPath` the typed client uses, and the owning
|
|
889
1026
|
* `plugin` and `resource`.
|
|
890
1027
|
*/
|
|
891
1028
|
function getPluginActionRoute(action, prefix = "/api") {
|
|
@@ -894,6 +1031,7 @@ function getPluginActionRoute(action, prefix = "/api") {
|
|
|
894
1031
|
if (!binding.enabled) return false;
|
|
895
1032
|
return {
|
|
896
1033
|
path: pathOf(binding, prefix),
|
|
1034
|
+
legacyPath: legacyPathOf(binding, prefix),
|
|
897
1035
|
method: binding.method,
|
|
898
1036
|
clientPath: binding.clientPath,
|
|
899
1037
|
plugin: binding.plugin,
|
|
@@ -912,8 +1050,10 @@ function getPluginActionRoute(action, prefix = "/api") {
|
|
|
912
1050
|
function getPluginEndpoints(service, prefix = "/api") {
|
|
913
1051
|
return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
|
|
914
1052
|
path: pathOf(binding, prefix),
|
|
1053
|
+
legacyPath: legacyPathOf(binding, prefix),
|
|
915
1054
|
method: binding.method,
|
|
916
1055
|
service,
|
|
1056
|
+
plugin: binding.plugin,
|
|
917
1057
|
summary: binding.summary,
|
|
918
1058
|
description: binding.description,
|
|
919
1059
|
tags: binding.tags,
|
|
@@ -926,7 +1066,7 @@ function getPluginEndpoints(service, prefix = "/api") {
|
|
|
926
1066
|
/** Descriptor identity is scoped to the service or resource installation host. */
|
|
927
1067
|
function installPlugin(service, resource, descriptor) {
|
|
928
1068
|
if (service.isBuilt) throw new Error("Plugins must be installed before service build");
|
|
929
|
-
if (descriptor[pluginKind] !== (resource ? "resource" : "service")) throw new Error("Plugin does not support this installation host");
|
|
1069
|
+
if (descriptor[pluginKind] !== (resource ? "resource" : "service") && descriptor[pluginKind] !== "plugin") throw new Error("Plugin does not support this installation host");
|
|
930
1070
|
const state = stateOf(service);
|
|
931
1071
|
const host = resource ?? service;
|
|
932
1072
|
const existing = state.hosts.get(host)?.get(descriptor.name);
|
|
@@ -1035,7 +1175,11 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1035
1175
|
const binding = state.actions.get(value);
|
|
1036
1176
|
if (binding && ownedActions.has(value)) {
|
|
1037
1177
|
if (binding.clientPath) throw new Error("Plugin actions must have one returned API path");
|
|
1038
|
-
binding.clientPath =
|
|
1178
|
+
binding.clientPath = resource ? [
|
|
1179
|
+
service.name,
|
|
1180
|
+
resource.name,
|
|
1181
|
+
...path
|
|
1182
|
+
] : [service.name, ...path];
|
|
1039
1183
|
}
|
|
1040
1184
|
} else if (value && typeof value === "object" && !ancestors.has(value)) {
|
|
1041
1185
|
const next = new Set(ancestors).add(value);
|
|
@@ -1057,9 +1201,11 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1057
1201
|
status: "installed",
|
|
1058
1202
|
api
|
|
1059
1203
|
});
|
|
1204
|
+
finish(descriptor, true);
|
|
1060
1205
|
getGlobalRegistry().touch();
|
|
1061
1206
|
return resource ?? api;
|
|
1062
1207
|
} catch (error) {
|
|
1208
|
+
finish(descriptor, false);
|
|
1063
1209
|
for (const action of state.actions.keys()) if (!snapshots.bindings.has(action)) {
|
|
1064
1210
|
actionBindings.delete(action);
|
|
1065
1211
|
delete action[actionBindingKey];
|
|
@@ -1082,11 +1228,571 @@ function installPlugin(service, resource, descriptor) {
|
|
|
1082
1228
|
active = false;
|
|
1083
1229
|
}
|
|
1084
1230
|
}
|
|
1231
|
+
function finish(descriptor, installed) {
|
|
1232
|
+
descriptor[pluginFinish]?.(installed);
|
|
1233
|
+
}
|
|
1234
|
+
/** Whether a plugin named `name` is installed on `host` (the service or a resource). */
|
|
1235
|
+
function hasPlugin(service, host, name) {
|
|
1236
|
+
return states.get(service)?.hosts.get(host)?.get(name)?.status === "installed";
|
|
1237
|
+
}
|
|
1238
|
+
/** Every descriptor installed on the service or its resources, in install order per host. */
|
|
1239
|
+
function installedPlugins(service) {
|
|
1240
|
+
return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
|
|
1241
|
+
}
|
|
1085
1242
|
function restoreMap(target, snapshot) {
|
|
1086
1243
|
target.clear();
|
|
1087
1244
|
for (const [key, value] of snapshot) target.set(key, value);
|
|
1088
1245
|
}
|
|
1089
1246
|
//#endregion
|
|
1247
|
+
//#region src/deps.ts
|
|
1248
|
+
/**
|
|
1249
|
+
* Declare a dependency a service needs, without creating it. The app provides
|
|
1250
|
+
* the value with `brick({ deps })`, and the service's code reads it as
|
|
1251
|
+
* `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).
|
|
1252
|
+
*
|
|
1253
|
+
* @returns A slot typed as `T`. It holds nothing at runtime.
|
|
1254
|
+
* @example
|
|
1255
|
+
* import { defineService, port } from "@brickkit/core";
|
|
1256
|
+
*
|
|
1257
|
+
* export const orders = defineService("orders", {
|
|
1258
|
+
* database,
|
|
1259
|
+
* deps: { carrier: port<Carrier>() },
|
|
1260
|
+
* });
|
|
1261
|
+
*
|
|
1262
|
+
* // app.ts
|
|
1263
|
+
* export default brick({ services: [orders], deps: { carrier: createCarrier() } });
|
|
1264
|
+
*/
|
|
1265
|
+
function port() {
|
|
1266
|
+
return Object.freeze({});
|
|
1267
|
+
}
|
|
1268
|
+
/** Where a socket a plugin declared keeps the plugin's deps; global so a second core copy finds it. */
|
|
1269
|
+
const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
|
|
1270
|
+
const running = new AsyncLocalStorage();
|
|
1271
|
+
/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
|
|
1272
|
+
function runWithDeps(deps, fn) {
|
|
1273
|
+
return running.run(deps, fn);
|
|
1274
|
+
}
|
|
1275
|
+
function useDeps() {
|
|
1276
|
+
const deps = running.getStore();
|
|
1277
|
+
if (!deps) throw new Error("useDeps() was called outside a Brick app: call it from a listener or a workflow step (actions read ctx.deps).");
|
|
1278
|
+
return deps;
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* Check `brick({ deps })` against what the services declare, and give each
|
|
1282
|
+
* service the values of its own ports.
|
|
1283
|
+
*
|
|
1284
|
+
* @throws When a service declares a dep the app does not provide, or the app
|
|
1285
|
+
* provides one that no service declares.
|
|
1286
|
+
*/
|
|
1287
|
+
function bindDeps(services, provided = {}) {
|
|
1288
|
+
const declared = /* @__PURE__ */ new Set();
|
|
1289
|
+
for (const service of services) {
|
|
1290
|
+
const own = {};
|
|
1291
|
+
for (const name of Object.keys(service.options.deps ?? {})) {
|
|
1292
|
+
if (!Object.hasOwn(provided, name) || provided[name] === void 0) throw new Error(`Brick: service "${service.name}" declares dep "${name}", but brick({ deps }) does not provide it`);
|
|
1293
|
+
declared.add(name);
|
|
1294
|
+
own[name] = provided[name];
|
|
1295
|
+
}
|
|
1296
|
+
service.setDeps?.(Object.freeze(own));
|
|
1297
|
+
}
|
|
1298
|
+
for (const name of Object.keys(provided)) if (!declared.has(name)) throw new Error(`Brick: brick({ deps }) provides "${name}", but no service declares it (services: ${services.map((service) => service.name).join(", ") || "none"})`);
|
|
1299
|
+
}
|
|
1300
|
+
//#endregion
|
|
1301
|
+
//#region src/define-plugin.ts
|
|
1302
|
+
let runningVersion;
|
|
1303
|
+
/** The version of this @brickkit/core, read from its package.json; `""` when unknown. */
|
|
1304
|
+
function brickVersion() {
|
|
1305
|
+
if (runningVersion !== void 0) return runningVersion;
|
|
1306
|
+
for (const relative of ["../package.json", "../../package.json"]) try {
|
|
1307
|
+
const json = JSON.parse(readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8"));
|
|
1308
|
+
if (json.name === "@brickkit/core") return runningVersion = json.version;
|
|
1309
|
+
} catch {}
|
|
1310
|
+
return runningVersion = "";
|
|
1311
|
+
}
|
|
1312
|
+
function parseVersion(version) {
|
|
1313
|
+
const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[-+]/)[0].split(".").map(Number);
|
|
1314
|
+
return [
|
|
1315
|
+
major,
|
|
1316
|
+
minor,
|
|
1317
|
+
patch
|
|
1318
|
+
];
|
|
1319
|
+
}
|
|
1320
|
+
function compare(a, b) {
|
|
1321
|
+
return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,
|
|
1325
|
+
* `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.
|
|
1326
|
+
*/
|
|
1327
|
+
function satisfiesRange(version, range) {
|
|
1328
|
+
const current = parseVersion(version);
|
|
1329
|
+
return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
|
|
1330
|
+
const match = /^(\^|~|>=|<=|>|<|=)?v?([\dx*]+(?:\.[\dx*]+){0,2})?/i.exec(comparator);
|
|
1331
|
+
const operator = match?.[1] ?? "";
|
|
1332
|
+
const parts = (match?.[2] ?? "*").split(".");
|
|
1333
|
+
const wild = parts.findIndex((part) => /^[x*]$/i.test(part));
|
|
1334
|
+
const given = wild === -1 ? parts.length : wild;
|
|
1335
|
+
const low = parseVersion(parts.slice(0, given).join(".") || "0");
|
|
1336
|
+
if (given === 0) return true;
|
|
1337
|
+
const cmp = compare(current, low);
|
|
1338
|
+
if (operator === ">=") return cmp >= 0;
|
|
1339
|
+
if (operator === ">") return cmp > 0;
|
|
1340
|
+
if (operator === "<") return cmp < 0;
|
|
1341
|
+
if (operator === "<=") return cmp <= 0;
|
|
1342
|
+
let high;
|
|
1343
|
+
if (operator === "^") high = low[0] > 0 || given === 1 ? [
|
|
1344
|
+
low[0] + 1,
|
|
1345
|
+
0,
|
|
1346
|
+
0
|
|
1347
|
+
] : low[1] > 0 || given === 2 ? [
|
|
1348
|
+
0,
|
|
1349
|
+
low[1] + 1,
|
|
1350
|
+
0
|
|
1351
|
+
] : [
|
|
1352
|
+
0,
|
|
1353
|
+
0,
|
|
1354
|
+
low[2] + 1
|
|
1355
|
+
];
|
|
1356
|
+
else if (operator === "~" || given < 3) high = given === 1 ? [
|
|
1357
|
+
low[0] + 1,
|
|
1358
|
+
0,
|
|
1359
|
+
0
|
|
1360
|
+
] : [
|
|
1361
|
+
low[0],
|
|
1362
|
+
low[1] + 1,
|
|
1363
|
+
0
|
|
1364
|
+
];
|
|
1365
|
+
else return cmp === 0;
|
|
1366
|
+
return cmp >= 0 && compare(current, high) < 0;
|
|
1367
|
+
}));
|
|
1368
|
+
}
|
|
1369
|
+
const OWNER = Symbol.for("brickkit.plugin.owner");
|
|
1370
|
+
/** The plugin that owns a table, for tables a `definePlugin` contributed. */
|
|
1371
|
+
function pluginOwner(table) {
|
|
1372
|
+
return table && typeof table === "object" ? table[OWNER] : void 0;
|
|
1373
|
+
}
|
|
1374
|
+
const sqliteBuilders = {
|
|
1375
|
+
/** A table. Its name gets the plugin's prefix (`page_comments`). */
|
|
1376
|
+
table: (name, columns) => sqliteTable$1(name, columns),
|
|
1377
|
+
text: (name) => text$1(name),
|
|
1378
|
+
integer: (name) => integer$1(name, { mode: "number" }),
|
|
1379
|
+
real: (name) => real$1(name),
|
|
1380
|
+
boolean: (name) => integer$1(name, { mode: "boolean" }),
|
|
1381
|
+
/** A `Date`, stored as epoch milliseconds or `timestamptz`. */
|
|
1382
|
+
timestamp: (name) => integer$1(name, { mode: "timestamp_ms" }),
|
|
1383
|
+
json: (name) => text$1(name, { mode: "json" })
|
|
1384
|
+
};
|
|
1385
|
+
function builders(engine, tableName) {
|
|
1386
|
+
if (engine === "postgres") return {
|
|
1387
|
+
engine,
|
|
1388
|
+
table: (name, columns) => pgTable(tableName(name), columns),
|
|
1389
|
+
text: (name) => text$2(name),
|
|
1390
|
+
integer: (name) => integer$2(name),
|
|
1391
|
+
real: (name) => doublePrecision(name),
|
|
1392
|
+
boolean: (name) => boolean(name),
|
|
1393
|
+
timestamp: (name) => timestamp(name, {
|
|
1394
|
+
mode: "date",
|
|
1395
|
+
withTimezone: true
|
|
1396
|
+
}),
|
|
1397
|
+
json: (name) => jsonb(name)
|
|
1398
|
+
};
|
|
1399
|
+
return {
|
|
1400
|
+
...sqliteBuilders,
|
|
1401
|
+
engine,
|
|
1402
|
+
table: (name, columns) => sqliteTable$1(tableName(name), columns)
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
/** Where `hooks.*` stores a plugin's hooks; `@brickkit/crud` runs them. */
|
|
1406
|
+
const HOST_HOOKS = Symbol.for("brickkit.plugin.hooks");
|
|
1407
|
+
const HOOK_NAMES = [
|
|
1408
|
+
"beforeCreate",
|
|
1409
|
+
"afterCreate",
|
|
1410
|
+
"beforeUpdate",
|
|
1411
|
+
"afterUpdate",
|
|
1412
|
+
"beforeDelete",
|
|
1413
|
+
"afterDelete",
|
|
1414
|
+
"afterCommit"
|
|
1415
|
+
];
|
|
1416
|
+
const INTERNALS = Symbol.for("brickkit.plugin.internals");
|
|
1417
|
+
let installCount = 0;
|
|
1418
|
+
const toWords = (name) => (name.split("/").pop() ?? name).replace(/^brick-/, "").replace(/-plugin$/, "").split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
1419
|
+
const snake = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
1420
|
+
/**
|
|
1421
|
+
* Define a plugin: a manifest Brick checks, plus the capabilities the plugin
|
|
1422
|
+
* brings. Install its instances with `resource.use()`, `service.use()` or
|
|
1423
|
+
* `brick({ plugins })`; scope comes from where it is installed.
|
|
1424
|
+
*
|
|
1425
|
+
* @param manifest - `name`, `brick` (semver range), `requires`, `options`
|
|
1426
|
+
* (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`
|
|
1427
|
+
* parts, and a `dashboard` extension.
|
|
1428
|
+
* @returns A factory: `comments({ maxLength: 500 })` validates the options and
|
|
1429
|
+
* the Brick version and returns an instance to install.
|
|
1430
|
+
* @throws From the factory, when the running Brick is outside `brick` or an
|
|
1431
|
+
* option is invalid; when installed, when a required plugin is missing or the
|
|
1432
|
+
* host does not suit the plugin.
|
|
1433
|
+
* @example
|
|
1434
|
+
* export const audit = definePlugin({
|
|
1435
|
+
* name: "@acme/brick-audit",
|
|
1436
|
+
* brick: "^0.11.0",
|
|
1437
|
+
* requires: ["@brickkit/crud"],
|
|
1438
|
+
* options: t.Object({ table: t.String({ default: "audit" }) }),
|
|
1439
|
+
* tables: ({ table, text, timestamp }) => ({
|
|
1440
|
+
* log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
|
|
1441
|
+
* }),
|
|
1442
|
+
* resource: ({ tables, hooks }) => {
|
|
1443
|
+
* hooks.afterCreate(({ row, tx }) =>
|
|
1444
|
+
* tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
|
|
1445
|
+
* return {};
|
|
1446
|
+
* },
|
|
1447
|
+
* });
|
|
1448
|
+
*
|
|
1449
|
+
* page.use(audit());
|
|
1450
|
+
*/
|
|
1451
|
+
function definePlugin(manifest) {
|
|
1452
|
+
const { name } = manifest;
|
|
1453
|
+
if (!name || name.trim() !== name) throw new Error("Plugin names must be nonempty and have no surrounding whitespace");
|
|
1454
|
+
if (!manifest.resource && !manifest.service && !manifest.app) throw new Error(`Plugin "${name}" needs a resource, service or app part to install`);
|
|
1455
|
+
for (const key of Object.keys(manifest.events ?? {})) if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key)) throw new Error(`Event "${key}" of plugin "${name}" must be a plain name such as added`);
|
|
1456
|
+
const site = definitionSite()?.replace(/:\d+$/, "");
|
|
1457
|
+
const dashboard = manifest.dashboard === void 0 ? void 0 : manifest.dashboard.startsWith("file:") ? fileURLToPath(manifest.dashboard) : isAbsolute(manifest.dashboard) || !site ? resolve(manifest.dashboard) : resolve(dirname(site), manifest.dashboard);
|
|
1458
|
+
const info = Object.freeze({
|
|
1459
|
+
name,
|
|
1460
|
+
description: manifest.description,
|
|
1461
|
+
brick: manifest.brick,
|
|
1462
|
+
requires: Object.freeze([...manifest.requires ?? []]),
|
|
1463
|
+
options: manifest.options,
|
|
1464
|
+
secrets: Object.freeze(Object.values(manifest.secrets ?? {}).map((secret) => secret.name)),
|
|
1465
|
+
deps: Object.freeze(Object.keys(manifest.deps ?? {})),
|
|
1466
|
+
capabilities: Object.freeze([
|
|
1467
|
+
"tables",
|
|
1468
|
+
"events",
|
|
1469
|
+
"resource",
|
|
1470
|
+
"service",
|
|
1471
|
+
"app",
|
|
1472
|
+
"dashboard"
|
|
1473
|
+
].filter((key) => manifest[key] !== void 0))
|
|
1474
|
+
});
|
|
1475
|
+
const words = toWords(name);
|
|
1476
|
+
const eventSpace = words.map((word, index) => index ? word[0].toUpperCase() + word.slice(1) : word).join("");
|
|
1477
|
+
const tableSpace = snake(words.join("_"));
|
|
1478
|
+
if (!eventSpace) throw new Error(`Plugin "${name}" needs letters or digits in its name`);
|
|
1479
|
+
const factory = (input = {}, install = {}) => {
|
|
1480
|
+
const version = brickVersion();
|
|
1481
|
+
if (manifest.brick && version && !satisfiesRange(version, manifest.brick)) throw new Error(`${name} supports Brick ${manifest.brick}; this app runs ${version}`);
|
|
1482
|
+
const options = checkOptions(name, manifest.options, input);
|
|
1483
|
+
const deps = checkDeps(name, eventSpace, manifest.deps, install.deps);
|
|
1484
|
+
const secrets = manifest.secrets ?? {};
|
|
1485
|
+
const internals = {
|
|
1486
|
+
manifest,
|
|
1487
|
+
options,
|
|
1488
|
+
deps,
|
|
1489
|
+
install,
|
|
1490
|
+
dashboard,
|
|
1491
|
+
installs: []
|
|
1492
|
+
};
|
|
1493
|
+
const pending = [];
|
|
1494
|
+
const setup = (context) => {
|
|
1495
|
+
const { service, resource } = context;
|
|
1496
|
+
const host = resource ?? service;
|
|
1497
|
+
const where = resource ? `resource "${resource.name}"` : `service "${service.name}"`;
|
|
1498
|
+
const part = resource ? manifest.resource : manifest.service;
|
|
1499
|
+
if (!part) throw new Error(`${name} cannot be installed on a ${resource ? "resource" : "service"}; ${manifest.resource ? "use resource.use()" : manifest.service ? "use service.use()" : "add it to brick({ plugins })"}`);
|
|
1500
|
+
for (const required of manifest.requires ?? []) if (!hasPlugin(service, host, required)) throw new Error(`${name} requires ${required}, installed on ${where} before it`);
|
|
1501
|
+
let tables = {};
|
|
1502
|
+
if (manifest.tables) {
|
|
1503
|
+
const database = service.getDatabaseHandle?.();
|
|
1504
|
+
if (!database) throw new Error(`${name} owns tables, so service "${service.name}" needs a database`);
|
|
1505
|
+
const prefix = install.prefix ?? `${snake(resource?.name ?? service.name)}_`;
|
|
1506
|
+
tables = manifest.tables(builders(database.engine, (table) => install.prefix !== void 0 || table === tableSpace ? `${prefix}${table}` : `${prefix}${tableSpace}_${table}`));
|
|
1507
|
+
const taken = new Set([...service.tables.values(), ...Object.values(database.tables)].map((table) => getTableName$1(table)));
|
|
1508
|
+
for (const table of Object.values(tables)) {
|
|
1509
|
+
const tableName = getTableName$1(table);
|
|
1510
|
+
if (taken.has(tableName)) throw new Error(`${name} table "${tableName}" clashes with a table service "${service.name}" already has; install it with another prefix`);
|
|
1511
|
+
taken.add(tableName);
|
|
1512
|
+
Object.defineProperty(table, OWNER, { value: name });
|
|
1513
|
+
service.registerTable(table);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
const catalog = service.events;
|
|
1517
|
+
const events = {};
|
|
1518
|
+
for (const [key, schema] of Object.entries(manifest.events ?? {})) {
|
|
1519
|
+
const existing = catalog[`${eventSpace}.${key}`];
|
|
1520
|
+
if (existing && existing.plugin !== name) throw new Error(`${name} event "${eventSpace}.${key}" is already in the catalog of service "${service.name}"`);
|
|
1521
|
+
events[key] = existing ?? Object.freeze({
|
|
1522
|
+
name: `${service.name}.${eventSpace}.${key}`,
|
|
1523
|
+
service: service.name,
|
|
1524
|
+
schema,
|
|
1525
|
+
plugin: name
|
|
1526
|
+
});
|
|
1527
|
+
}
|
|
1528
|
+
const added = {};
|
|
1529
|
+
const hooks = Object.fromEntries(HOOK_NAMES.map((hook) => [hook, (fn) => {
|
|
1530
|
+
if (typeof fn !== "function") throw new Error(`${name}: hooks.${hook} needs a function`);
|
|
1531
|
+
(added[hook] ??= []).push((args) => fn({
|
|
1532
|
+
...args,
|
|
1533
|
+
ctx: {
|
|
1534
|
+
...args.ctx,
|
|
1535
|
+
deps
|
|
1536
|
+
}
|
|
1537
|
+
}));
|
|
1538
|
+
}]));
|
|
1539
|
+
const routes = {
|
|
1540
|
+
action: (config) => context.routes.action(config),
|
|
1541
|
+
endpoint: (config) => context.routes.endpoint({
|
|
1542
|
+
...config,
|
|
1543
|
+
handler: (args) => config.handler({
|
|
1544
|
+
...args,
|
|
1545
|
+
ctx: {
|
|
1546
|
+
...args.ctx,
|
|
1547
|
+
deps
|
|
1548
|
+
}
|
|
1549
|
+
})
|
|
1550
|
+
})
|
|
1551
|
+
};
|
|
1552
|
+
const before = /* @__PURE__ */ new Set([
|
|
1553
|
+
...service.actions.values(),
|
|
1554
|
+
...service.tools.values(),
|
|
1555
|
+
...service.listSockets()
|
|
1556
|
+
]);
|
|
1557
|
+
const started = bindings;
|
|
1558
|
+
const api = part({
|
|
1559
|
+
options,
|
|
1560
|
+
secrets,
|
|
1561
|
+
tables,
|
|
1562
|
+
events,
|
|
1563
|
+
deps,
|
|
1564
|
+
service,
|
|
1565
|
+
resource,
|
|
1566
|
+
routes,
|
|
1567
|
+
hooks
|
|
1568
|
+
});
|
|
1569
|
+
if (api && typeof api.then === "function") throw new Error("Plugin setup must be synchronous");
|
|
1570
|
+
for (const action of [...service.actions.values(), ...service.tools.values()]) if (!before.has(action)) bindPluginDeps(name, action, deps, started);
|
|
1571
|
+
for (const socket of service.listSockets()) if (!before.has(socket)) socket[PLUGIN_DEPS] ??= deps;
|
|
1572
|
+
pending.push(() => {
|
|
1573
|
+
const database = service.getDatabaseHandle?.();
|
|
1574
|
+
for (const table of Object.values(tables)) database?.addTable?.(getTableName$1(table), table);
|
|
1575
|
+
if (Object.keys(events).length) service.events = Object.freeze({
|
|
1576
|
+
...catalog,
|
|
1577
|
+
...Object.fromEntries(Object.entries(events).map(([key, ref]) => [`${eventSpace}.${key}`, ref]))
|
|
1578
|
+
});
|
|
1579
|
+
const store = host[HOST_HOOKS] ??= {};
|
|
1580
|
+
for (const [hook, fns] of Object.entries(added)) (store[hook] ??= []).push(...fns);
|
|
1581
|
+
internals.installs.push({
|
|
1582
|
+
scope: resource ? "resource" : "service",
|
|
1583
|
+
service: service.name,
|
|
1584
|
+
resource: resource?.name
|
|
1585
|
+
});
|
|
1586
|
+
internals.order ??= ++installCount;
|
|
1587
|
+
});
|
|
1588
|
+
return resource ? api ?? {} : api;
|
|
1589
|
+
};
|
|
1590
|
+
return Object.freeze({
|
|
1591
|
+
[Symbol.for("brickkit.plugin.kind")]: "plugin",
|
|
1592
|
+
name,
|
|
1593
|
+
info,
|
|
1594
|
+
setup,
|
|
1595
|
+
[INTERNALS]: internals,
|
|
1596
|
+
[pluginFinish]: (installed) => {
|
|
1597
|
+
const commit = pending.pop();
|
|
1598
|
+
if (installed) commit?.();
|
|
1599
|
+
}
|
|
1600
|
+
});
|
|
1601
|
+
};
|
|
1602
|
+
return Object.assign(factory, { info });
|
|
1603
|
+
}
|
|
1604
|
+
/** Counts bindings, so a setup can tell a nested install's from an earlier one's. */
|
|
1605
|
+
let bindings = 0;
|
|
1606
|
+
/**
|
|
1607
|
+
* Give an action's `execute` and `authorize` the plugin's deps as `ctx.deps`.
|
|
1608
|
+
* The config is changed in place: every way an action runs (HTTP, compiled
|
|
1609
|
+
* routes, `action.run`, RPC) reads `config.execute` from it. A nested
|
|
1610
|
+
* definePlugin binds its own actions first, so they keep its deps.
|
|
1611
|
+
*
|
|
1612
|
+
* @throws When the action is already bound to another install's deps: one
|
|
1613
|
+
* action object shared by two installs could only run with one of them.
|
|
1614
|
+
*/
|
|
1615
|
+
function bindPluginDeps(plugin, action, deps, started) {
|
|
1616
|
+
const config = action.config;
|
|
1617
|
+
if (!config) return;
|
|
1618
|
+
const bound = config[PLUGIN_DEPS];
|
|
1619
|
+
if (bound) {
|
|
1620
|
+
if (bound.deps === deps || bound.at > started) return;
|
|
1621
|
+
throw new Error(`${plugin}: action "${action.name}" is already bound to the deps of another install; create the action inside the setup so each install gets its own`);
|
|
1622
|
+
}
|
|
1623
|
+
config[PLUGIN_DEPS] = {
|
|
1624
|
+
deps,
|
|
1625
|
+
at: ++bindings
|
|
1626
|
+
};
|
|
1627
|
+
const { execute, authorize } = config;
|
|
1628
|
+
if (typeof execute === "function") config.execute = (args) => execute({
|
|
1629
|
+
...args,
|
|
1630
|
+
ctx: {
|
|
1631
|
+
...args.ctx,
|
|
1632
|
+
deps
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
if (typeof authorize === "function") config.authorize = (args) => authorize({
|
|
1636
|
+
...args,
|
|
1637
|
+
ctx: {
|
|
1638
|
+
...args.ctx,
|
|
1639
|
+
deps
|
|
1640
|
+
}
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
/** Check the deps passed at install against the ports the plugin declares. */
|
|
1644
|
+
function checkDeps(plugin, factory, ports, given = {}) {
|
|
1645
|
+
if (given === null || typeof given !== "object" || Array.isArray(given)) throw new Error(`${plugin}: deps must be an object`);
|
|
1646
|
+
const declared = Object.keys(ports ?? {});
|
|
1647
|
+
const provided = given;
|
|
1648
|
+
const extra = Object.keys(provided).filter((key) => !declared.includes(key));
|
|
1649
|
+
if (extra.length) throw new Error(`${plugin} does not declare ${extra.map((key) => `deps.${key}`).join(", ")}; ${declared.length ? `it takes ${declared.join(", ")}` : "it takes no deps"}`);
|
|
1650
|
+
const missing = declared.filter((key) => provided[key] === void 0);
|
|
1651
|
+
if (missing.length) throw new Error(`${plugin} needs ${missing.map((key) => `deps.${key}`).join(", ")}; pass it when installing: ${factory}(options, { deps: { ${missing.join(", ")} } })`);
|
|
1652
|
+
return Object.freeze(Object.fromEntries(declared.map((key) => [key, provided[key]])));
|
|
1653
|
+
}
|
|
1654
|
+
function checkOptions(plugin, schema, input) {
|
|
1655
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error(`${plugin}: options must be an object`);
|
|
1656
|
+
if (!schema) {
|
|
1657
|
+
if (Object.keys(input).length) throw new Error(`${plugin} takes no options`);
|
|
1658
|
+
return {};
|
|
1659
|
+
}
|
|
1660
|
+
const value = Value.Default(schema, structuredClone(input));
|
|
1661
|
+
const result = validateWithSchema(schema, value);
|
|
1662
|
+
if (!result.success) {
|
|
1663
|
+
const [first] = result.errors;
|
|
1664
|
+
const option = first.path.replace(/^\//, "").replaceAll("/", ".");
|
|
1665
|
+
throw new Error(`${plugin}: option ${option ? `"${option}"` : ""} ${first.message}`.replace(/\s+/g, " "));
|
|
1666
|
+
}
|
|
1667
|
+
return value;
|
|
1668
|
+
}
|
|
1669
|
+
function isPluginInstance(value) {
|
|
1670
|
+
return typeof value === "object" && value !== null && INTERNALS in value;
|
|
1671
|
+
}
|
|
1672
|
+
function internalsOf(value) {
|
|
1673
|
+
return isPluginInstance(value) ? value[INTERNALS] ?? void 0 : void 0;
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* What `brick()` does with plugins: install those given in `plugins` on the
|
|
1677
|
+
* app, run every plugin's `app` part in install order, and return the
|
|
1678
|
+
* lifecycle, middleware and listeners they contributed.
|
|
1679
|
+
*/
|
|
1680
|
+
function setupAppPlugins(installedOnServices, appPlugins) {
|
|
1681
|
+
const instances = /* @__PURE__ */ new Set();
|
|
1682
|
+
for (const descriptor of installedOnServices) if (isPluginInstance(descriptor)) instances.add(descriptor);
|
|
1683
|
+
const ordered = [...instances].sort((a, b) => (internalsOf(a).order ?? 0) - (internalsOf(b).order ?? 0));
|
|
1684
|
+
const onApp = /* @__PURE__ */ new Set();
|
|
1685
|
+
for (const plugin of appPlugins) {
|
|
1686
|
+
const internals = internalsOf(plugin);
|
|
1687
|
+
if (!internals) throw new Error("brick({ plugins }) takes instances from definePlugin(), such as audit()");
|
|
1688
|
+
const { manifest } = internals;
|
|
1689
|
+
if (!manifest.app || manifest.tables || manifest.events) throw new Error(`${manifest.name} cannot be installed on the app; ${manifest.resource ? "use resource.use()" : "use service.use()"}`);
|
|
1690
|
+
for (const required of manifest.requires ?? []) if (!onApp.has(required)) throw new Error(`${manifest.name} requires ${required}, installed in brick({ plugins }) before it`);
|
|
1691
|
+
if (onApp.has(manifest.name)) throw new Error(`Plugin ${manifest.name} is installed on the app twice`);
|
|
1692
|
+
const installed = ordered.find((other) => internalsOf(other).manifest.name === manifest.name);
|
|
1693
|
+
if (installed) throw new Error(`Plugin ${manifest.name} is already installed with ${internalsOf(installed).installs.map((install) => install.scope === "resource" ? `${install.service}.${install.resource}.use()` : `${install.service}.use()`).join(", ")}, which runs its app part too; remove it from brick({ plugins })`);
|
|
1694
|
+
onApp.add(manifest.name);
|
|
1695
|
+
if (!internals.installs.some((item) => item.scope === "app")) internals.installs.push({ scope: "app" });
|
|
1696
|
+
ordered.push(plugin);
|
|
1697
|
+
}
|
|
1698
|
+
const lifecycles = [];
|
|
1699
|
+
const middleware = [];
|
|
1700
|
+
const listeners = [];
|
|
1701
|
+
const listed = [];
|
|
1702
|
+
for (const plugin of ordered) {
|
|
1703
|
+
const { manifest, options, deps, installs, dashboard } = internalsOf(plugin);
|
|
1704
|
+
for (const install of installs) listed.push(Object.freeze({
|
|
1705
|
+
name: manifest.name,
|
|
1706
|
+
...manifest.brick ? { brick: manifest.brick } : {},
|
|
1707
|
+
...install,
|
|
1708
|
+
...dashboard ? { dashboard } : {}
|
|
1709
|
+
}));
|
|
1710
|
+
if (!manifest.app) continue;
|
|
1711
|
+
const lifecycle = {
|
|
1712
|
+
options,
|
|
1713
|
+
secrets: manifest.secrets ?? {},
|
|
1714
|
+
deps
|
|
1715
|
+
};
|
|
1716
|
+
const own = {
|
|
1717
|
+
start: [],
|
|
1718
|
+
stop: []
|
|
1719
|
+
};
|
|
1720
|
+
manifest.app({
|
|
1721
|
+
...lifecycle,
|
|
1722
|
+
on(event, handler) {
|
|
1723
|
+
if (event !== "start" && event !== "stop") throw new Error(`${manifest.name}: on() takes "start" or "stop"`);
|
|
1724
|
+
own[event].push(handler);
|
|
1725
|
+
},
|
|
1726
|
+
middleware(handler) {
|
|
1727
|
+
middleware.push(handler);
|
|
1728
|
+
},
|
|
1729
|
+
listeners(...items) {
|
|
1730
|
+
listeners.push(...items.map((listener) => {
|
|
1731
|
+
if (listener.workflow) throw new Error(`${manifest.name}: plugins can't add workflow listeners yet, because workflow steps would see the app's deps instead of the plugin's; use a run listener ('${listener.name}')`);
|
|
1732
|
+
const run = listener.run;
|
|
1733
|
+
return run ? {
|
|
1734
|
+
...listener,
|
|
1735
|
+
run: (delivery) => runWithDeps(deps, () => run(delivery))
|
|
1736
|
+
} : listener;
|
|
1737
|
+
}));
|
|
1738
|
+
}
|
|
1739
|
+
});
|
|
1740
|
+
lifecycles.push({
|
|
1741
|
+
start: async () => {
|
|
1742
|
+
for (const handler of own.start) await handler(lifecycle);
|
|
1743
|
+
},
|
|
1744
|
+
stop: async () => {
|
|
1745
|
+
for (const handler of own.stop) await handler(lifecycle);
|
|
1746
|
+
}
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
return {
|
|
1750
|
+
lifecycles,
|
|
1751
|
+
middleware,
|
|
1752
|
+
listeners,
|
|
1753
|
+
plugins: listed
|
|
1754
|
+
};
|
|
1755
|
+
}
|
|
1756
|
+
/**
|
|
1757
|
+
* Start in install order. Stop what started, in reverse order; a start that
|
|
1758
|
+
* fails stops those before it and rethrows.
|
|
1759
|
+
*/
|
|
1760
|
+
function pluginLifecycle(lifecycles) {
|
|
1761
|
+
let started;
|
|
1762
|
+
const running = [];
|
|
1763
|
+
const stopAll = async () => {
|
|
1764
|
+
const errors = [];
|
|
1765
|
+
for (const item of running.splice(0).reverse()) try {
|
|
1766
|
+
await item.stop();
|
|
1767
|
+
} catch (error) {
|
|
1768
|
+
errors.push(error);
|
|
1769
|
+
}
|
|
1770
|
+
if (errors.length === 1) throw errors[0];
|
|
1771
|
+
if (errors.length) throw new AggregateError(errors, "Plugins failed to stop");
|
|
1772
|
+
};
|
|
1773
|
+
return {
|
|
1774
|
+
start() {
|
|
1775
|
+
return started ??= (async () => {
|
|
1776
|
+
for (const item of lifecycles) {
|
|
1777
|
+
try {
|
|
1778
|
+
await item.start();
|
|
1779
|
+
} catch (error) {
|
|
1780
|
+
await stopAll().catch(() => void 0);
|
|
1781
|
+
started = void 0;
|
|
1782
|
+
throw error;
|
|
1783
|
+
}
|
|
1784
|
+
running.push(item);
|
|
1785
|
+
}
|
|
1786
|
+
})();
|
|
1787
|
+
},
|
|
1788
|
+
async stop() {
|
|
1789
|
+
await started?.catch(() => void 0);
|
|
1790
|
+
started = void 0;
|
|
1791
|
+
await stopAll();
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
//#endregion
|
|
1090
1796
|
//#region src/compiler/runtime.ts
|
|
1091
1797
|
const EMPTY_SERVICES$2 = Object.freeze({});
|
|
1092
1798
|
const DEFAULT_REQUEST$2 = new Request("http://localhost");
|
|
@@ -1285,18 +1991,26 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
1285
1991
|
}
|
|
1286
1992
|
}
|
|
1287
1993
|
}
|
|
1288
|
-
|
|
1994
|
+
let coercedParams = params;
|
|
1995
|
+
if (params && plan.coercions) for (const c of plan.coercions) {
|
|
1996
|
+
if (!c.isNumber || typeof params[c.key] !== "string") continue;
|
|
1997
|
+
const num = Number(params[c.key]);
|
|
1998
|
+
if (isNaN(num)) continue;
|
|
1999
|
+
if (coercedParams === params) coercedParams = { ...params };
|
|
2000
|
+
coercedParams[c.key] = num;
|
|
2001
|
+
}
|
|
2002
|
+
const hasP = isNonEmpty(coercedParams);
|
|
1289
2003
|
const hasB = isNonEmpty(body);
|
|
1290
2004
|
const hasQ = isNonEmpty(coercedQuery);
|
|
1291
2005
|
if (plan.isGetLike) {
|
|
1292
2006
|
if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
1293
|
-
else if (hasP && !hasQ && !hasB) input =
|
|
2007
|
+
else if (hasP && !hasQ && !hasB) input = coercedParams;
|
|
1294
2008
|
else if (hasB && !hasP && !hasQ) input = body;
|
|
1295
|
-
else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery,
|
|
2009
|
+
else if (hasQ || hasP || hasB) input = Object.assign({}, coercedQuery, coercedParams, body);
|
|
1296
2010
|
} else if (hasB && !hasP && !hasQ) input = body;
|
|
1297
|
-
else if (hasP && !hasB && !hasQ) input =
|
|
2011
|
+
else if (hasP && !hasB && !hasQ) input = coercedParams;
|
|
1298
2012
|
else if (hasQ && !hasP && !hasB) input = coercedQuery;
|
|
1299
|
-
else if (hasP || hasB || hasQ) input = Object.assign({},
|
|
2013
|
+
else if (hasP || hasB || hasQ) input = Object.assign({}, coercedParams, body, coercedQuery);
|
|
1300
2014
|
}
|
|
1301
2015
|
const ctx = {
|
|
1302
2016
|
request: request instanceof Request ? request : DEFAULT_REQUEST$1,
|
|
@@ -1305,6 +2019,7 @@ async function executeCompiledRoute(plan, elysiaCtx) {
|
|
|
1305
2019
|
db: plan.cachedDb ?? plan.service.getDb(),
|
|
1306
2020
|
logger: plan.logger,
|
|
1307
2021
|
services: EMPTY_SERVICES$1,
|
|
2022
|
+
deps: plan.service.deps ?? EMPTY_SERVICES$1,
|
|
1308
2023
|
metadata: { headers },
|
|
1309
2024
|
_resolved: true
|
|
1310
2025
|
};
|
|
@@ -1407,7 +2122,15 @@ function createHandlerFactory(route) {
|
|
|
1407
2122
|
coercedQuery = { ...query };
|
|
1408
2123
|
for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type, request, key);
|
|
1409
2124
|
}
|
|
1410
|
-
let
|
|
2125
|
+
let coercedParams = params;
|
|
2126
|
+
if (params && route.coercions.length) for (const { key, type } of route.coercions) {
|
|
2127
|
+
if (type !== "number" || typeof params[key] !== "string") continue;
|
|
2128
|
+
const value = Number(params[key]);
|
|
2129
|
+
if (Number.isNaN(value)) continue;
|
|
2130
|
+
if (coercedParams === params) coercedParams = { ...params };
|
|
2131
|
+
coercedParams[key] = value;
|
|
2132
|
+
}
|
|
2133
|
+
let input = readLike ? runtime.mergeInput(coercedQuery, coercedParams, body) : runtime.mergeInput(coercedParams, body, coercedQuery);
|
|
1411
2134
|
if (objectInput) input ??= {};
|
|
1412
2135
|
return input;
|
|
1413
2136
|
} : () => void 0;
|
|
@@ -1436,6 +2159,7 @@ function createHandlerFactory(route) {
|
|
|
1436
2159
|
db: cachedDb ?? service.getDb(),
|
|
1437
2160
|
logger,
|
|
1438
2161
|
services: runtime.emptyServices,
|
|
2162
|
+
deps: service.deps ?? runtime.emptyServices,
|
|
1439
2163
|
metadata: { headers },
|
|
1440
2164
|
_resolved: true
|
|
1441
2165
|
};
|
|
@@ -1676,7 +2400,8 @@ function hoistAnchoredSchemas(spec) {
|
|
|
1676
2400
|
* Build the OpenAPI 3.1 document for the services: one path per action route,
|
|
1677
2401
|
* with request and response schemas from the actions' TypeBox schemas, their
|
|
1678
2402
|
* declared errors, tags by service, and a bearer security scheme where any
|
|
1679
|
-
* action needs authorization.
|
|
2403
|
+
* action needs authorization. Declared events are listed under `x-brick-events`,
|
|
2404
|
+
* by wire name, with their service and payload schema.
|
|
1680
2405
|
*
|
|
1681
2406
|
* `brick()` calls this for `/openapi.json`; call it yourself to write the
|
|
1682
2407
|
* document to a file or feed another tool.
|
|
@@ -1693,19 +2418,22 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1693
2418
|
const prefix = options.prefix ?? "/api";
|
|
1694
2419
|
const services = options.services ?? (options.registry ? options.registry.list() : getGlobalRegistry().list());
|
|
1695
2420
|
const paths = {};
|
|
1696
|
-
const
|
|
2421
|
+
const tags = /* @__PURE__ */ new Map();
|
|
1697
2422
|
let hasAnyAuthorizedAction = false;
|
|
1698
2423
|
for (const service of services) {
|
|
1699
|
-
|
|
2424
|
+
tags.set(service.name, `Actions exposed by '${service.name}' service`);
|
|
1700
2425
|
for (const action of service.listActions()) {
|
|
1701
|
-
const
|
|
1702
|
-
if (
|
|
1703
|
-
const routePath =
|
|
1704
|
-
const method =
|
|
2426
|
+
const route = getActionRoute(action, prefix);
|
|
2427
|
+
if (route === false) continue;
|
|
2428
|
+
const routePath = route.path;
|
|
2429
|
+
const method = route.method.toLowerCase();
|
|
1705
2430
|
const pathParams = [...routePath.matchAll(/:([^/]+)/g)].map((match) => match[1]);
|
|
1706
2431
|
const actionPath = routePath.replace(/:([^/]+)/g, "{$1}");
|
|
1707
2432
|
if (!paths[actionPath]) paths[actionPath] = {};
|
|
1708
2433
|
if (paths[actionPath][method]) continue;
|
|
2434
|
+
const resource = action.resource;
|
|
2435
|
+
const group = resource ? `${service.name} · ${resource}` : service.name;
|
|
2436
|
+
if (resource) tags.set(group, `Routes of resource '${resource}' in service '${service.name}'`);
|
|
1709
2437
|
const hasAuth = getActionAccess(action).hasAuthorize;
|
|
1710
2438
|
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
1711
2439
|
const responses = {};
|
|
@@ -1715,7 +2443,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1715
2443
|
};
|
|
1716
2444
|
else responses["200"] = { description: "Successful response" };
|
|
1717
2445
|
const errorAlternatives = /* @__PURE__ */ new Set();
|
|
1718
|
-
const addError = (code, status, message) => {
|
|
2446
|
+
const addError = (code, status, message, details) => {
|
|
1719
2447
|
const key = `${status}:${code}`;
|
|
1720
2448
|
if (errorAlternatives.has(key)) return;
|
|
1721
2449
|
errorAlternatives.add(key);
|
|
@@ -1723,7 +2451,8 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1723
2451
|
type: "object",
|
|
1724
2452
|
properties: {
|
|
1725
2453
|
code: { const: code },
|
|
1726
|
-
status: { const: status }
|
|
2454
|
+
status: { const: status },
|
|
2455
|
+
...details ? { details } : {}
|
|
1727
2456
|
}
|
|
1728
2457
|
}] };
|
|
1729
2458
|
const existing = responses[String(status)];
|
|
@@ -1742,7 +2471,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1742
2471
|
}
|
|
1743
2472
|
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
1744
2473
|
const def = errorDef;
|
|
1745
|
-
addError(code, def.status || 400, def.message || code);
|
|
2474
|
+
addError(code, def.status || 400, def.message || code, def.details);
|
|
1746
2475
|
}
|
|
1747
2476
|
addError("INTERNAL_SERVER_ERROR", 500, "Internal server error");
|
|
1748
2477
|
if (action.config.output) addError("VALIDATION_FAILED", 500, "Output validation error");
|
|
@@ -1750,7 +2479,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1750
2479
|
operationId: `${service.name}_${action.name}_${method}`,
|
|
1751
2480
|
summary: `${service.name}.${action.name}`,
|
|
1752
2481
|
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
1753
|
-
tags:
|
|
2482
|
+
tags: [.../* @__PURE__ */ new Set([group, ...action.config.tags ?? []])],
|
|
1754
2483
|
...action.plugin ? { "x-brick-plugin": action.plugin } : {},
|
|
1755
2484
|
...action.resource ? { "x-brick-resource": action.resource } : {},
|
|
1756
2485
|
responses
|
|
@@ -1793,9 +2522,9 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1793
2522
|
description
|
|
1794
2523
|
},
|
|
1795
2524
|
paths,
|
|
1796
|
-
tags: Array.from(
|
|
2525
|
+
tags: Array.from(tags, ([name, description]) => ({
|
|
1797
2526
|
name,
|
|
1798
|
-
description
|
|
2527
|
+
description
|
|
1799
2528
|
}))
|
|
1800
2529
|
};
|
|
1801
2530
|
spec.components = { schemas: { ErrorEnvelope: {
|
|
@@ -1834,6 +2563,12 @@ function generateOpenApiSpec(options = {}) {
|
|
|
1834
2563
|
bearerFormat: "JWT",
|
|
1835
2564
|
description: "Enter your Bearer authentication token"
|
|
1836
2565
|
} } });
|
|
2566
|
+
const events = Object.fromEntries(services.flatMap((service) => Object.values(service.events ?? {}).map((ref) => [ref.name, {
|
|
2567
|
+
service: service.name,
|
|
2568
|
+
payload: ref.schema,
|
|
2569
|
+
...ref.plugin ? { "x-brick-plugin": ref.plugin } : {}
|
|
2570
|
+
}])));
|
|
2571
|
+
if (Object.keys(events).length) spec["x-brick-events"] = events;
|
|
1837
2572
|
const document = JSON.parse(JSON.stringify(spec));
|
|
1838
2573
|
hoistAnchoredSchemas(document);
|
|
1839
2574
|
return document;
|
|
@@ -1934,7 +2669,7 @@ var SecretRef = class {
|
|
|
1934
2669
|
* Declare a secret. Idempotent: re-declaring the same name returns the
|
|
1935
2670
|
* original ref (first declaration wins) so module re-evaluation is safe.
|
|
1936
2671
|
*/
|
|
1937
|
-
function
|
|
2672
|
+
function defineSecret(name, options = {}) {
|
|
1938
2673
|
const existing = registry.get(name);
|
|
1939
2674
|
if (existing) return existing;
|
|
1940
2675
|
const ref = new SecretRef(name, options);
|
|
@@ -2217,6 +2952,7 @@ function endpointPaths(defs) {
|
|
|
2217
2952
|
...def.summary ? { summary: def.summary } : {},
|
|
2218
2953
|
...def.description ? { description: def.description } : {},
|
|
2219
2954
|
...def.tags ? { tags: def.tags } : {},
|
|
2955
|
+
...def.plugin ? { "x-brick-plugin": def.plugin } : {},
|
|
2220
2956
|
...params.length > 0 ? { parameters: params } : {},
|
|
2221
2957
|
responses: { 200: { description: "Successful response" } }
|
|
2222
2958
|
};
|
|
@@ -2227,44 +2963,44 @@ function endpointPaths(defs) {
|
|
|
2227
2963
|
//#region src/events/outbox.ts
|
|
2228
2964
|
const OUTBOX = Symbol.for("brick.outbox");
|
|
2229
2965
|
function sqliteOutbox(name) {
|
|
2230
|
-
const timestampMs = (column) => integer$
|
|
2966
|
+
const timestampMs = (column) => integer$1(column, { mode: "timestamp_ms" });
|
|
2231
2967
|
return sqliteTable$1(name, {
|
|
2232
|
-
seq: integer$
|
|
2233
|
-
id: text$
|
|
2234
|
-
eventId: text$
|
|
2235
|
-
listener: text$
|
|
2236
|
-
name: text$
|
|
2237
|
-
payload: text$
|
|
2238
|
-
traceId: text$
|
|
2239
|
-
source: text$
|
|
2968
|
+
seq: integer$1("seq").primaryKey({ autoIncrement: true }),
|
|
2969
|
+
id: text$1("id").notNull().unique(),
|
|
2970
|
+
eventId: text$1("event_id").notNull(),
|
|
2971
|
+
listener: text$1("listener").notNull(),
|
|
2972
|
+
name: text$1("name").notNull(),
|
|
2973
|
+
payload: text$1("payload", { mode: "json" }).notNull(),
|
|
2974
|
+
traceId: text$1("trace_id"),
|
|
2975
|
+
source: text$1("source"),
|
|
2240
2976
|
occurredAt: timestampMs("occurred_at").notNull(),
|
|
2241
|
-
status: text$
|
|
2242
|
-
attempts: integer$
|
|
2243
|
-
lastError: text$
|
|
2977
|
+
status: text$1("status").$type().notNull(),
|
|
2978
|
+
attempts: integer$1("attempts").notNull().default(0),
|
|
2979
|
+
lastError: text$1("last_error"),
|
|
2244
2980
|
availableAt: timestampMs("available_at").notNull(),
|
|
2245
2981
|
claimedAt: timestampMs("claimed_at"),
|
|
2246
2982
|
deliveredAt: timestampMs("delivered_at")
|
|
2247
|
-
}, (table) => [index$
|
|
2983
|
+
}, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
|
|
2248
2984
|
}
|
|
2249
2985
|
function postgresOutbox(name) {
|
|
2250
2986
|
const at = (column) => timestamp(column, { withTimezone: true });
|
|
2251
2987
|
return pgTable(name, {
|
|
2252
2988
|
seq: bigserial("seq", { mode: "number" }).primaryKey(),
|
|
2253
|
-
id: text$
|
|
2254
|
-
eventId: text$
|
|
2255
|
-
listener: text$
|
|
2256
|
-
name: text$
|
|
2989
|
+
id: text$2("id").notNull().unique(),
|
|
2990
|
+
eventId: text$2("event_id").notNull(),
|
|
2991
|
+
listener: text$2("listener").notNull(),
|
|
2992
|
+
name: text$2("name").notNull(),
|
|
2257
2993
|
payload: jsonb("payload").notNull(),
|
|
2258
|
-
traceId: text$
|
|
2259
|
-
source: text$
|
|
2994
|
+
traceId: text$2("trace_id"),
|
|
2995
|
+
source: text$2("source"),
|
|
2260
2996
|
occurredAt: at("occurred_at").notNull(),
|
|
2261
|
-
status: text$
|
|
2262
|
-
attempts: integer$
|
|
2263
|
-
lastError: text$
|
|
2997
|
+
status: text$2("status").$type().notNull(),
|
|
2998
|
+
attempts: integer$2("attempts").notNull().default(0),
|
|
2999
|
+
lastError: text$2("last_error"),
|
|
2264
3000
|
availableAt: at("available_at").notNull(),
|
|
2265
3001
|
claimedAt: at("claimed_at"),
|
|
2266
3002
|
deliveredAt: at("delivered_at")
|
|
2267
|
-
}, (table) => [index$
|
|
3003
|
+
}, (table) => [index$2(`${name}_due`).on(table.status, table.availableAt), index$2(`${name}_event`).on(table.eventId)]);
|
|
2268
3004
|
}
|
|
2269
3005
|
function outboxTable(engine, options = {}) {
|
|
2270
3006
|
const name = options.name ?? "brick_outbox";
|
|
@@ -2391,6 +3127,10 @@ async function begin(db, open, fn) {
|
|
|
2391
3127
|
release();
|
|
2392
3128
|
}
|
|
2393
3129
|
}
|
|
3130
|
+
/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
|
|
3131
|
+
function inTransaction(db) {
|
|
3132
|
+
return joined(db) !== void 0;
|
|
3133
|
+
}
|
|
2394
3134
|
/**
|
|
2395
3135
|
* Run `fn` once the transaction that `db` belongs to has committed, or now when
|
|
2396
3136
|
* `db` is not in one opened by `runInTransaction`. It never runs when that
|
|
@@ -2419,6 +3159,23 @@ function resolveDispatchOptions(options = {}) {
|
|
|
2419
3159
|
};
|
|
2420
3160
|
}
|
|
2421
3161
|
const PURGE_INTERVAL_MS = 6e4;
|
|
3162
|
+
/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry". */
|
|
3163
|
+
function decideRetry(listener, error) {
|
|
3164
|
+
if (!listener.retry) return "retry";
|
|
3165
|
+
try {
|
|
3166
|
+
return listener.retry(error instanceof ActionExecutionError && listener.errors?.[error.code] ? {
|
|
3167
|
+
code: error.code,
|
|
3168
|
+
message: error.message,
|
|
3169
|
+
details: error.details
|
|
3170
|
+
} : {
|
|
3171
|
+
code: "UNKNOWN",
|
|
3172
|
+
message: error instanceof Error ? error.message : String(error),
|
|
3173
|
+
cause: error
|
|
3174
|
+
});
|
|
3175
|
+
} catch {
|
|
3176
|
+
return "retry";
|
|
3177
|
+
}
|
|
3178
|
+
}
|
|
2422
3179
|
function backoffMs(attempt, maxBackoffMs) {
|
|
2423
3180
|
return Math.min(1e3 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);
|
|
2424
3181
|
}
|
|
@@ -2596,7 +3353,7 @@ var Dispatcher = class {
|
|
|
2596
3353
|
try {
|
|
2597
3354
|
await listener.run(delivery);
|
|
2598
3355
|
} catch (error) {
|
|
2599
|
-
await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts);
|
|
3356
|
+
await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts, decideRetry(listener, error));
|
|
2600
3357
|
return;
|
|
2601
3358
|
}
|
|
2602
3359
|
await this.markDelivered(row);
|
|
@@ -2614,9 +3371,9 @@ var Dispatcher = class {
|
|
|
2614
3371
|
this.onError(error);
|
|
2615
3372
|
}
|
|
2616
3373
|
}
|
|
2617
|
-
async fail(row, error, maxAttempts) {
|
|
3374
|
+
async fail(row, error, maxAttempts, decision = "retry") {
|
|
2618
3375
|
const message = error instanceof Error ? error.message : String(error);
|
|
2619
|
-
if (row.attempts >= maxAttempts) {
|
|
3376
|
+
if (decision === "dead" || row.attempts >= maxAttempts) {
|
|
2620
3377
|
await this.park(row, message);
|
|
2621
3378
|
return;
|
|
2622
3379
|
}
|
|
@@ -2702,14 +3459,16 @@ function resolveWorkflowPaths(options = {}) {
|
|
|
2702
3459
|
var WorkflowRuntime = class {
|
|
2703
3460
|
world;
|
|
2704
3461
|
listeners;
|
|
3462
|
+
deps;
|
|
2705
3463
|
root;
|
|
2706
3464
|
dir;
|
|
2707
3465
|
ready;
|
|
2708
3466
|
connected;
|
|
2709
3467
|
closed = false;
|
|
2710
|
-
constructor(world, options, listeners) {
|
|
3468
|
+
constructor(world, options, listeners, deps = {}) {
|
|
2711
3469
|
this.world = world;
|
|
2712
3470
|
this.listeners = listeners;
|
|
3471
|
+
this.deps = deps;
|
|
2713
3472
|
({root: this.root, dir: this.dir} = resolveWorkflowPaths(options));
|
|
2714
3473
|
}
|
|
2715
3474
|
/** Begin loading the runtime now rather than at the first delivery. */
|
|
@@ -2788,7 +3547,8 @@ var WorkflowRuntime = class {
|
|
|
2788
3547
|
this.checkListeners(manifest);
|
|
2789
3548
|
const bundle = await this.loadBundle(flow);
|
|
2790
3549
|
if (typeof bundle.POST !== "function") throw new Error(`${flow} does not export a POST handler`);
|
|
2791
|
-
|
|
3550
|
+
const post = bundle.POST;
|
|
3551
|
+
this.world.registerHandler?.(WORKFLOW_QUEUE_PREFIX, (request) => runWithDeps(this.deps, () => post(request)));
|
|
2792
3552
|
await this.world.start?.();
|
|
2793
3553
|
return sdk;
|
|
2794
3554
|
}
|
|
@@ -2870,6 +3630,7 @@ async function stopAllEvents() {
|
|
|
2870
3630
|
* `app.events`.
|
|
2871
3631
|
*/
|
|
2872
3632
|
var EventsHub = class {
|
|
3633
|
+
deps;
|
|
2873
3634
|
byName = /* @__PURE__ */ new Map();
|
|
2874
3635
|
dispatchers = /* @__PURE__ */ new Map();
|
|
2875
3636
|
deliverables = /* @__PURE__ */ new Map();
|
|
@@ -2878,7 +3639,13 @@ var EventsHub = class {
|
|
|
2878
3639
|
recorderNames = [];
|
|
2879
3640
|
started = false;
|
|
2880
3641
|
stopping;
|
|
2881
|
-
|
|
3642
|
+
/**
|
|
3643
|
+
* @param options - The `events` option.
|
|
3644
|
+
* @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
|
|
3645
|
+
* listeners and workflow steps.
|
|
3646
|
+
*/
|
|
3647
|
+
constructor(options, deps = {}) {
|
|
3648
|
+
this.deps = deps;
|
|
2882
3649
|
for (const listener of options.listeners ?? []) {
|
|
2883
3650
|
if (typeof listener.name !== "string" || !listener.name) throw new Error("An event listener needs a name");
|
|
2884
3651
|
if (listener.name.includes(":")) throw new Error(`Event listener name '${listener.name}' must not contain ':'`);
|
|
@@ -2890,7 +3657,7 @@ var EventsHub = class {
|
|
|
2890
3657
|
const workflowListeners = [...this.byName.values()].filter((listener) => listener.workflow);
|
|
2891
3658
|
if (workflowListeners.length) {
|
|
2892
3659
|
if (!options.world) throw new Error(`Event listener '${workflowListeners[0].name}' runs a workflow, so events needs a world: brick({ events: { world: createWorld(...) } }) with createWorld from @brickkit/redis-world.`);
|
|
2893
|
-
this.runtime = new WorkflowRuntime(options.world, options.workflows, workflowListeners);
|
|
3660
|
+
this.runtime = new WorkflowRuntime(options.world, options.workflows, workflowListeners, deps);
|
|
2894
3661
|
}
|
|
2895
3662
|
this.dispatchOptions = options.dispatch === false ? false : options.dispatch === true || options.dispatch === void 0 ? {} : options.dispatch;
|
|
2896
3663
|
}
|
|
@@ -2909,8 +3676,8 @@ var EventsHub = class {
|
|
|
2909
3676
|
if (!table) continue;
|
|
2910
3677
|
attached++;
|
|
2911
3678
|
this.recorderNames.push(service.name);
|
|
2912
|
-
const bound = this.bind(table);
|
|
2913
|
-
service.
|
|
3679
|
+
const bound = this.bind(table, (name, payload) => service.checkEvent?.(name, payload));
|
|
3680
|
+
service.setRecorder?.(bound);
|
|
2914
3681
|
const db = service.getDb();
|
|
2915
3682
|
if (db && typeof db === "object") recorders.set(db, bound);
|
|
2916
3683
|
}
|
|
@@ -3030,22 +3797,30 @@ var EventsHub = class {
|
|
|
3030
3797
|
let found = this.deliverables.get(name);
|
|
3031
3798
|
if (!found) {
|
|
3032
3799
|
const runtime = this.runtime;
|
|
3033
|
-
found =
|
|
3034
|
-
...listener.
|
|
3035
|
-
|
|
3036
|
-
|
|
3800
|
+
found = {
|
|
3801
|
+
...listener.errors ? { errors: listener.errors } : {},
|
|
3802
|
+
...listener.retry ? { retry: listener.retry } : {},
|
|
3803
|
+
...listener.workflow ? {
|
|
3804
|
+
...listener.maxAttempts !== void 0 ? { maxAttempts: listener.maxAttempts } : {},
|
|
3805
|
+
run: async (delivery) => {
|
|
3806
|
+
await runtime.startRun(listener, delivery);
|
|
3807
|
+
}
|
|
3808
|
+
} : {
|
|
3809
|
+
...listener.maxAttempts !== void 0 ? { maxAttempts: listener.maxAttempts } : {},
|
|
3810
|
+
run: (delivery) => runWithDeps(this.deps, () => listener.run(delivery))
|
|
3037
3811
|
}
|
|
3038
|
-
}
|
|
3812
|
+
};
|
|
3039
3813
|
this.deliverables.set(name, found);
|
|
3040
3814
|
}
|
|
3041
3815
|
return found;
|
|
3042
3816
|
}
|
|
3043
|
-
bind(table) {
|
|
3817
|
+
bind(table, check) {
|
|
3044
3818
|
const startAndNotify = () => {
|
|
3045
3819
|
this.start();
|
|
3046
3820
|
this.dispatchers.get(table)?.notify();
|
|
3047
3821
|
};
|
|
3048
3822
|
const insert = async (tx, context, name, payload) => {
|
|
3823
|
+
check(name, payload);
|
|
3049
3824
|
const listeners = this.matching(name);
|
|
3050
3825
|
if (!listeners.length) return false;
|
|
3051
3826
|
const eventId = newEventId();
|
|
@@ -3087,13 +3862,96 @@ var EventsHub = class {
|
|
|
3087
3862
|
//#endregion
|
|
3088
3863
|
//#region src/socket.ts
|
|
3089
3864
|
var SocketDenied = class extends Error {};
|
|
3090
|
-
|
|
3865
|
+
const bytes = (value) => new TextEncoder().encode(value).byteLength;
|
|
3866
|
+
/** Validates and serializes one output message, rechecking what survives JSON. */
|
|
3867
|
+
function outputFrame(output, event, data) {
|
|
3868
|
+
const schema = Object.hasOwn(output, event) ? output[event] : void 0;
|
|
3869
|
+
if (!schema || !getCompiledCheck(schema).Check(data)) throw new Error("Invalid socket output");
|
|
3870
|
+
const frame = JSON.stringify({
|
|
3871
|
+
event,
|
|
3872
|
+
data
|
|
3873
|
+
});
|
|
3874
|
+
if (bytes(frame) > 65536) throw new Error("Socket output too large");
|
|
3875
|
+
if (!getCompiledCheck(schema).Check(JSON.parse(frame).data)) throw new Error("Socket output is not JSON-compatible");
|
|
3876
|
+
return frame;
|
|
3877
|
+
}
|
|
3878
|
+
/** Delivers within this process. The default broker of every app. */
|
|
3879
|
+
function localBroker() {
|
|
3880
|
+
const topics = /* @__PURE__ */ new Map();
|
|
3881
|
+
const epoch = Date.now();
|
|
3882
|
+
let counter = 0;
|
|
3883
|
+
/** Rooms dropped from `kept` once idle, at counter values up to this. */
|
|
3884
|
+
let swept = 0;
|
|
3885
|
+
const kept = /* @__PURE__ */ new Map();
|
|
3886
|
+
const prune = (names) => {
|
|
3887
|
+
for (const topic of names) {
|
|
3888
|
+
const room = kept.get(topic);
|
|
3889
|
+
if (!room) continue;
|
|
3890
|
+
const oldest = Date.now() - room.maxAgeMs;
|
|
3891
|
+
while (room.entries[0] && room.entries[0].at < oldest) room.trimmed = room.entries.shift().n;
|
|
3892
|
+
if (!room.entries.length) {
|
|
3893
|
+
kept.delete(topic);
|
|
3894
|
+
swept = counter;
|
|
3895
|
+
}
|
|
3896
|
+
}
|
|
3897
|
+
};
|
|
3898
|
+
return {
|
|
3899
|
+
publish(message, replay) {
|
|
3900
|
+
if (message.type === "emit" && replay) {
|
|
3901
|
+
const n = ++counter;
|
|
3902
|
+
message = {
|
|
3903
|
+
...message,
|
|
3904
|
+
seq: `${epoch}-${n}`
|
|
3905
|
+
};
|
|
3906
|
+
const room = kept.get(message.topic) ?? {
|
|
3907
|
+
entries: [],
|
|
3908
|
+
trimmed: 0,
|
|
3909
|
+
maxAgeMs: replay.maxAgeMs
|
|
3910
|
+
};
|
|
3911
|
+
kept.set(message.topic, room);
|
|
3912
|
+
room.entries.push({
|
|
3913
|
+
n,
|
|
3914
|
+
at: Date.now(),
|
|
3915
|
+
message
|
|
3916
|
+
});
|
|
3917
|
+
if (room.entries.length > replay.keep) room.trimmed = room.entries.shift().n;
|
|
3918
|
+
if (n % 1e3 === 0) prune([...kept.keys()]);
|
|
3919
|
+
}
|
|
3920
|
+
for (const deliver of topics.get(message.topic) ?? []) deliver(message);
|
|
3921
|
+
},
|
|
3922
|
+
head: () => `${epoch}-${counter}`,
|
|
3923
|
+
history(topic, since) {
|
|
3924
|
+
const [from, n] = since.split("-").map(Number);
|
|
3925
|
+
if (from !== epoch || n > counter) return void 0;
|
|
3926
|
+
prune([topic]);
|
|
3927
|
+
const room = kept.get(topic);
|
|
3928
|
+
if (!room) return n >= swept ? [] : void 0;
|
|
3929
|
+
if (n < room.trimmed) return void 0;
|
|
3930
|
+
return room.entries.filter((entry) => entry.n > n).map((entry) => entry.message);
|
|
3931
|
+
},
|
|
3932
|
+
subscribe(topic, deliver) {
|
|
3933
|
+
const listeners = topics.get(topic) ?? /* @__PURE__ */ new Set();
|
|
3934
|
+
listeners.add(deliver);
|
|
3935
|
+
topics.set(topic, listeners);
|
|
3936
|
+
return () => {
|
|
3937
|
+
listeners.delete(deliver);
|
|
3938
|
+
if (!listeners.size) topics.delete(topic);
|
|
3939
|
+
};
|
|
3940
|
+
}
|
|
3941
|
+
};
|
|
3942
|
+
}
|
|
3943
|
+
function defineServiceSocket(service, config, resolve) {
|
|
3091
3944
|
if (!config.name || config.name.split(".").some((part) => !/^[a-zA-Z_][\w-]*$/.test(part))) throw new Error("Invalid socket name");
|
|
3092
|
-
if (config.path !== void 0 && (!config.path.startsWith("/") || /[?#*]/.test(config.path) || config.path.split("/").some((segment) => segment.startsWith(":")))) throw new Error("Socket path must be a static
|
|
3945
|
+
if (config.path !== void 0 && (!config.path.startsWith("/") || /[?#*]/.test(config.path) || config.path.split("/").some((segment) => segment.startsWith(":")))) throw new Error("Socket path must be a static route (relative to its service) without a query or fragment");
|
|
3093
3946
|
const input = Object.freeze({ ...config.input });
|
|
3094
3947
|
const output = Object.freeze({ ...config.output });
|
|
3095
3948
|
const handlers = { ...config.handlers };
|
|
3096
3949
|
if (Object.keys(input).length !== Object.keys(handlers).length || Object.keys(input).some((key) => !Object.hasOwn(handlers, key) || typeof handlers[key] !== "function")) throw new Error("Every socket input event needs exactly one handler");
|
|
3950
|
+
if ([...Object.keys(input), ...Object.keys(output)].some((key) => key.startsWith("$"))) throw new Error("Socket event names starting with $ are reserved");
|
|
3951
|
+
const maxRooms = config.maxRooms ?? 100;
|
|
3952
|
+
if (!Number.isInteger(maxRooms) || maxRooms < 1) throw new Error("Socket maxRooms must be a positive integer");
|
|
3953
|
+
const replay = config.replay && { ...config.replay };
|
|
3954
|
+
if (replay && !(Number.isInteger(replay.keep) && replay.keep > 0 && replay.maxAgeMs > 0 && Number.isFinite(replay.maxAgeMs))) throw new Error("Socket replay needs a positive integer keep and a positive finite maxAgeMs");
|
|
3097
3955
|
for (const schema of [...Object.values(input), ...Object.values(output)]) {
|
|
3098
3956
|
serializeSocketSchema(schema);
|
|
3099
3957
|
getCompiledCheck(schema);
|
|
@@ -3104,6 +3962,20 @@ function defineServiceSocket(config, resolve) {
|
|
|
3104
3962
|
if (config.authorize && !await config.authorize({ ctx })) throw new SocketDenied();
|
|
3105
3963
|
return ctx;
|
|
3106
3964
|
};
|
|
3965
|
+
const topicPrefix = `${service}.${config.name}:`;
|
|
3966
|
+
const topic = (room) => {
|
|
3967
|
+
if (!isSocketRoom(room)) throw new Error(`Invalid socket room: ${room}`);
|
|
3968
|
+
return topicPrefix + room;
|
|
3969
|
+
};
|
|
3970
|
+
const brokers = /* @__PURE__ */ new Set();
|
|
3971
|
+
const publish = (messages, after) => {
|
|
3972
|
+
const send = () => {
|
|
3973
|
+
for (const broker of brokers) for (const message of messages) broker.publish(message, replay);
|
|
3974
|
+
};
|
|
3975
|
+
if (after === void 0) return send();
|
|
3976
|
+
if (!inTransaction(after)) throw new Error("Socket emit { after: tx } needs a tx from runInTransaction(db, (tx) => ...); a plain db.transaction() is not tracked, so the emit could be sent for a write that rolls back");
|
|
3977
|
+
onTransactionCommit(after, send);
|
|
3978
|
+
};
|
|
3107
3979
|
return {
|
|
3108
3980
|
schema: {
|
|
3109
3981
|
name: config.name,
|
|
@@ -3117,9 +3989,39 @@ function defineServiceSocket(config, resolve) {
|
|
|
3117
3989
|
output,
|
|
3118
3990
|
allowedOrigins: config.allowedOrigins ? [...config.allowedOrigins] : void 0,
|
|
3119
3991
|
allowMissingOrigin: config.allowMissingOrigin,
|
|
3992
|
+
maxRooms,
|
|
3993
|
+
replay,
|
|
3994
|
+
brokers,
|
|
3995
|
+
topicPrefix,
|
|
3996
|
+
topic,
|
|
3997
|
+
handle: {
|
|
3998
|
+
name: config.name,
|
|
3999
|
+
emit(rooms, ...[event, payload, options]) {
|
|
4000
|
+
const topics = [...new Set(typeof rooms === "string" ? [rooms] : rooms)].map(topic);
|
|
4001
|
+
const frame = outputFrame(output, event, payload);
|
|
4002
|
+
if (replay && bytes(frame) > 65236) throw new Error("Socket output too large");
|
|
4003
|
+
publish(topics.map((topic) => ({
|
|
4004
|
+
type: "emit",
|
|
4005
|
+
topic,
|
|
4006
|
+
frame
|
|
4007
|
+
})), options?.after);
|
|
4008
|
+
},
|
|
4009
|
+
kick(room, options = {}) {
|
|
4010
|
+
publish([{
|
|
4011
|
+
type: "kick",
|
|
4012
|
+
topic: topic(room),
|
|
4013
|
+
...options.also !== void 0 ? { also: topic(options.also) } : {},
|
|
4014
|
+
...options.reason !== void 0 ? { reason: String(options.reason) } : {}
|
|
4015
|
+
}], void 0);
|
|
4016
|
+
}
|
|
4017
|
+
},
|
|
3120
4018
|
async connect(request) {
|
|
3121
4019
|
const initial = await context(request);
|
|
4020
|
+
const rooms = [...new Set(config.rooms ? await config.rooms({ ctx: initial }) : [])];
|
|
4021
|
+
rooms.forEach(topic);
|
|
4022
|
+
if (rooms.length > maxRooms) throw new Error("Too many socket rooms");
|
|
3122
4023
|
return {
|
|
4024
|
+
rooms,
|
|
3123
4025
|
async open(socket) {
|
|
3124
4026
|
await config.open?.({
|
|
3125
4027
|
ctx: initial,
|
|
@@ -3138,6 +4040,13 @@ function defineServiceSocket(config, resolve) {
|
|
|
3138
4040
|
socket: typed(socket)
|
|
3139
4041
|
});
|
|
3140
4042
|
},
|
|
4043
|
+
async join(room) {
|
|
4044
|
+
const ctx = await context(request);
|
|
4045
|
+
return !!config.join && await config.join({
|
|
4046
|
+
ctx,
|
|
4047
|
+
room
|
|
4048
|
+
});
|
|
4049
|
+
},
|
|
3141
4050
|
async close(socket, code, reason) {
|
|
3142
4051
|
await config.close?.({
|
|
3143
4052
|
ctx: initial,
|
|
@@ -3150,8 +4059,13 @@ function defineServiceSocket(config, resolve) {
|
|
|
3150
4059
|
}
|
|
3151
4060
|
};
|
|
3152
4061
|
}
|
|
4062
|
+
/** `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */
|
|
3153
4063
|
function socketPath(prefix, service, socket) {
|
|
3154
|
-
return socket.schema.path ??
|
|
4064
|
+
return joinRoute(ownerPath(prefix, service), socket.schema.path ?? `/${kebabCase(socket.schema.name)}`);
|
|
4065
|
+
}
|
|
4066
|
+
/** The v0.10 route, served too by `brick({ legacyRoutes: true })`. */
|
|
4067
|
+
function legacySocketPath(prefix, service, socket) {
|
|
4068
|
+
return legacyPath(prefix, service, socket.schema.name, socket.schema.path);
|
|
3155
4069
|
}
|
|
3156
4070
|
/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */
|
|
3157
4071
|
function publicOrigin(request) {
|
|
@@ -3160,18 +4074,151 @@ function publicOrigin(request) {
|
|
|
3160
4074
|
const proto = forwarded("x-forwarded-proto");
|
|
3161
4075
|
return `${proto ? `${proto}:` : url.protocol}//${forwarded("x-forwarded-host") ?? url.host}`;
|
|
3162
4076
|
}
|
|
4077
|
+
const TOKEN_PROTOCOL = "brick.token.";
|
|
4078
|
+
const protocols = (request) => (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((protocol) => protocol.trim()).filter(Boolean);
|
|
4079
|
+
/** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */
|
|
4080
|
+
function tokenRequest(request) {
|
|
4081
|
+
const offered = protocols(request);
|
|
4082
|
+
const token = offered.find((protocol) => protocol.startsWith(TOKEN_PROTOCOL))?.slice(12);
|
|
4083
|
+
if (!token) return {
|
|
4084
|
+
token: false,
|
|
4085
|
+
request
|
|
4086
|
+
};
|
|
4087
|
+
const headers = new Headers(request.headers);
|
|
4088
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
4089
|
+
const rest = offered.filter((protocol) => !protocol.startsWith(TOKEN_PROTOCOL));
|
|
4090
|
+
if (rest.length) headers.set("sec-websocket-protocol", rest.join(", "));
|
|
4091
|
+
else headers.delete("sec-websocket-protocol");
|
|
4092
|
+
return {
|
|
4093
|
+
token: true,
|
|
4094
|
+
request: new Request(request.url, {
|
|
4095
|
+
method: request.method,
|
|
4096
|
+
headers
|
|
4097
|
+
})
|
|
4098
|
+
};
|
|
4099
|
+
}
|
|
3163
4100
|
/** Mounts native adapters. Each connection owns its queue and service session. */
|
|
3164
|
-
function mountSockets(app, sockets) {
|
|
4101
|
+
function mountSockets(app, sockets, broker, secret) {
|
|
4102
|
+
if (secret === "") throw new Error("Brick: sockets.secret can't be empty");
|
|
4103
|
+
const key = secret ?? randomBytes(32);
|
|
4104
|
+
const signature = (topic, seq) => createHmac("sha256", key).update(`${topic}\n${seq}`).digest("base64url").slice(0, 22);
|
|
4105
|
+
const sign = (topic, seq) => `${seq}.${signature(topic, seq)}`;
|
|
4106
|
+
const verify = (topic, signed) => {
|
|
4107
|
+
const [seq, sig] = signed.split(".");
|
|
4108
|
+
return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq))) ? seq : void 0;
|
|
4109
|
+
};
|
|
4110
|
+
if (sockets.some(({ definition }) => definition.replay) && !(broker.head && broker.history)) throw new Error("Brick: the socket broker does not support replay");
|
|
4111
|
+
for (const { definition } of sockets) definition.brokers.add(broker);
|
|
4112
|
+
app.cleanup(async () => {
|
|
4113
|
+
for (const { definition } of sockets) definition.brokers.delete(broker);
|
|
4114
|
+
await broker.close?.();
|
|
4115
|
+
});
|
|
3165
4116
|
if (!sockets.length) return;
|
|
3166
4117
|
app.use(websocket({
|
|
3167
4118
|
maxPayloadLength: SOCKET_MAX_BYTES,
|
|
3168
4119
|
backpressureLimit: SOCKET_BUFFER_BYTES,
|
|
3169
4120
|
closeOnBackpressureLimit: true
|
|
3170
4121
|
}));
|
|
3171
|
-
|
|
4122
|
+
const paths = /* @__PURE__ */ new Map();
|
|
4123
|
+
for (const { path, definition } of sockets) paths.set(definition, [...paths.get(definition) ?? [], path]);
|
|
4124
|
+
for (const { service, definition } of sockets) {
|
|
4125
|
+
const routes = paths.get(definition);
|
|
4126
|
+
if (!routes) continue;
|
|
4127
|
+
paths.delete(definition);
|
|
3172
4128
|
const logger = createLogger(`[Brick socket ${service}.${definition.schema.name}]`);
|
|
3173
4129
|
const sessions = /* @__PURE__ */ new WeakMap();
|
|
3174
4130
|
const connections = /* @__PURE__ */ new WeakMap();
|
|
4131
|
+
const roomOf = (topic) => topic.slice(definition.topicPrefix.length);
|
|
4132
|
+
const holders = /* @__PURE__ */ new Map();
|
|
4133
|
+
const control = (ws, event, data) => {
|
|
4134
|
+
if (ws.readyState === 1) ws.send(JSON.stringify({
|
|
4135
|
+
event,
|
|
4136
|
+
data
|
|
4137
|
+
}));
|
|
4138
|
+
};
|
|
4139
|
+
/** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */
|
|
4140
|
+
const enter = async (connection, topic, live = true) => {
|
|
4141
|
+
if (connection.rooms.has(topic)) return;
|
|
4142
|
+
connection.rooms.add(topic);
|
|
4143
|
+
if (live) connection.ws.subscribe(topic);
|
|
4144
|
+
let holder = holders.get(topic);
|
|
4145
|
+
if (!holder) {
|
|
4146
|
+
holder = {
|
|
4147
|
+
connections: /* @__PURE__ */ new Set(),
|
|
4148
|
+
unsubscribe: () => {}
|
|
4149
|
+
};
|
|
4150
|
+
holders.set(topic, holder);
|
|
4151
|
+
holder.unsubscribe = broker.subscribe(topic, deliver);
|
|
4152
|
+
}
|
|
4153
|
+
holder.connections.add(connection);
|
|
4154
|
+
await broker.ready?.(topic).catch(() => {});
|
|
4155
|
+
};
|
|
4156
|
+
const exit = (connection, topic) => {
|
|
4157
|
+
if (!connection.rooms.delete(topic)) return;
|
|
4158
|
+
connection.requested.delete(topic);
|
|
4159
|
+
if (connection.ws.readyState === 1) connection.ws.unsubscribe(topic);
|
|
4160
|
+
const holder = holders.get(topic);
|
|
4161
|
+
if (!holder?.connections.delete(connection) || holder.connections.size) return;
|
|
4162
|
+
holders.delete(topic);
|
|
4163
|
+
holder.unsubscribe();
|
|
4164
|
+
};
|
|
4165
|
+
/** A replayable emit carries its room and sequence. */
|
|
4166
|
+
const frameOf = (message) => message.seq === void 0 ? message.frame : `${message.frame.slice(0, -1)},"room":${JSON.stringify(roomOf(message.topic))},"seq":${JSON.stringify(sign(message.topic, message.seq))}}`;
|
|
4167
|
+
const deliver = (message) => {
|
|
4168
|
+
if (message.type === "emit") {
|
|
4169
|
+
app.server?.publish(message.topic, frameOf(message));
|
|
4170
|
+
return;
|
|
4171
|
+
}
|
|
4172
|
+
for (const connection of holders.get(message.topic)?.connections ?? []) {
|
|
4173
|
+
if (message.also && !connection.ws.isSubscribed(message.also)) continue;
|
|
4174
|
+
exit(connection, message.topic);
|
|
4175
|
+
control(connection.ws, "$left", {
|
|
4176
|
+
room: roomOf(message.topic),
|
|
4177
|
+
...message.reason !== void 0 ? { reason: message.reason } : {}
|
|
4178
|
+
});
|
|
4179
|
+
}
|
|
4180
|
+
};
|
|
4181
|
+
/** `$join` and `$leave`, acknowledged with the same event. */
|
|
4182
|
+
const room = async (connection, event, data) => {
|
|
4183
|
+
const { room: name, since } = data && typeof data === "object" ? data : {};
|
|
4184
|
+
if (!isSocketRoom(name) || since !== void 0 && !isSocketSeq(since)) throw new SocketDenied();
|
|
4185
|
+
const topic = definition.topic(name);
|
|
4186
|
+
if (event === "$leave") {
|
|
4187
|
+
if (connection.requested.has(topic)) exit(connection, topic);
|
|
4188
|
+
control(connection.ws, "$leave", { room: name });
|
|
4189
|
+
return;
|
|
4190
|
+
}
|
|
4191
|
+
const isOpen = () => !connection.closed && connection.ws.readyState === 1;
|
|
4192
|
+
const ok = connection.rooms.has(topic) || connection.rooms.size < definition.maxRooms && await connection.session.join(name);
|
|
4193
|
+
if (!isOpen()) return;
|
|
4194
|
+
const replay = definition.replay;
|
|
4195
|
+
let seq;
|
|
4196
|
+
if (ok && !connection.rooms.has(topic)) {
|
|
4197
|
+
const entered = enter(connection, topic, !replay);
|
|
4198
|
+
connection.requested.add(topic);
|
|
4199
|
+
await entered;
|
|
4200
|
+
if (replay && connection.rooms.has(topic)) {
|
|
4201
|
+
const start = since === void 0 ? await broker.head(topic) : verify(topic, since);
|
|
4202
|
+
const missed = start === void 0 ? void 0 : await broker.history(topic, start, replay);
|
|
4203
|
+
const restart = missed ? void 0 : await broker.head(topic);
|
|
4204
|
+
if (!isOpen()) return;
|
|
4205
|
+
if (connection.rooms.has(topic)) {
|
|
4206
|
+
connection.ws.subscribe(topic);
|
|
4207
|
+
if (since === void 0) seq = sign(topic, start);
|
|
4208
|
+
for (const message of missed ?? []) if (message.type === "emit") connection.ws.send(frameOf(message));
|
|
4209
|
+
if (restart !== void 0) control(connection.ws, "$gap", {
|
|
4210
|
+
room: name,
|
|
4211
|
+
seq: sign(topic, restart)
|
|
4212
|
+
});
|
|
4213
|
+
}
|
|
4214
|
+
}
|
|
4215
|
+
}
|
|
4216
|
+
control(connection.ws, "$join", {
|
|
4217
|
+
room: name,
|
|
4218
|
+
ok: ok && connection.rooms.has(topic),
|
|
4219
|
+
...seq !== void 0 ? { seq } : {}
|
|
4220
|
+
});
|
|
4221
|
+
};
|
|
3175
4222
|
const fail = (ws, error) => {
|
|
3176
4223
|
if (!(error instanceof SocketDenied)) logger.error({
|
|
3177
4224
|
error,
|
|
@@ -3181,13 +4228,14 @@ function mountSockets(app, sockets) {
|
|
|
3181
4228
|
if (ws.readyState !== 1) return;
|
|
3182
4229
|
ws.close(error instanceof SocketDenied ? 1008 : 1011, error instanceof SocketDenied ? "Message refused" : "Socket handler failed");
|
|
3183
4230
|
};
|
|
3184
|
-
app.ws(path, {
|
|
4231
|
+
for (const path of routes) app.ws(path, {
|
|
3185
4232
|
async beforeHandle({ request }) {
|
|
3186
4233
|
if (sessions.has(request)) return;
|
|
4234
|
+
const { token, request: resolved } = tokenRequest(request);
|
|
3187
4235
|
const origin = request.headers.get("origin");
|
|
3188
|
-
if (origin ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(origin) : !definition.allowMissingOrigin) return new Response("Socket origin refused", { status: 403 });
|
|
4236
|
+
if (origin ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(origin) : !(definition.allowMissingOrigin ?? token)) return new Response("Socket origin refused", { status: 403 });
|
|
3189
4237
|
try {
|
|
3190
|
-
sessions.set(request, await definition.connect(
|
|
4238
|
+
sessions.set(request, await definition.connect(resolved));
|
|
3191
4239
|
} catch (error) {
|
|
3192
4240
|
if (!(error instanceof SocketDenied)) logger.error({
|
|
3193
4241
|
error,
|
|
@@ -3197,6 +4245,7 @@ function mountSockets(app, sockets) {
|
|
|
3197
4245
|
return new Response("Socket connection refused", { status: error instanceof SocketDenied ? 403 : 500 });
|
|
3198
4246
|
}
|
|
3199
4247
|
},
|
|
4248
|
+
upgrade: ({ request }) => protocols(request).includes("brick.v1") ? { "Sec-WebSocket-Protocol": "brick.v1" } : void 0,
|
|
3200
4249
|
async open(ws) {
|
|
3201
4250
|
const session = sessions.get(ws.request);
|
|
3202
4251
|
if (!session) {
|
|
@@ -3212,30 +4261,26 @@ function mountSockets(app, sockets) {
|
|
|
3212
4261
|
},
|
|
3213
4262
|
send(event, data) {
|
|
3214
4263
|
if (!sender.isOpen) throw new Error("Socket is closed");
|
|
3215
|
-
|
|
3216
|
-
if (!schema || !getCompiledCheck(schema).Check(data)) throw new Error("Invalid socket output");
|
|
3217
|
-
const frame = JSON.stringify({
|
|
3218
|
-
event,
|
|
3219
|
-
data
|
|
3220
|
-
});
|
|
3221
|
-
if (new TextEncoder().encode(frame).byteLength > 65536) throw new Error("Socket output too large");
|
|
3222
|
-
if (!getCompiledCheck(schema).Check(JSON.parse(frame).data)) throw new Error("Socket output is not JSON-compatible");
|
|
3223
|
-
if (ws.send(frame) === 0) {
|
|
4264
|
+
if (ws.send(outputFrame(definition.output, event, data)) === 0) {
|
|
3224
4265
|
ws.close(1013, "Socket buffer full");
|
|
3225
4266
|
throw new Error("Socket buffer full");
|
|
3226
4267
|
}
|
|
3227
4268
|
}
|
|
3228
4269
|
};
|
|
3229
4270
|
const state = {
|
|
4271
|
+
ws,
|
|
3230
4272
|
session,
|
|
3231
4273
|
sender,
|
|
3232
4274
|
tail: Promise.resolve(),
|
|
3233
4275
|
pending: 0,
|
|
3234
4276
|
bytes: 0,
|
|
3235
|
-
closed: false
|
|
4277
|
+
closed: false,
|
|
4278
|
+
rooms: /* @__PURE__ */ new Set(),
|
|
4279
|
+
requested: /* @__PURE__ */ new Set()
|
|
3236
4280
|
};
|
|
3237
4281
|
connections.set(ws.request, state);
|
|
3238
4282
|
try {
|
|
4283
|
+
await Promise.all(session.rooms.map((room) => enter(state, definition.topic(room))));
|
|
3239
4284
|
await session.open(sender);
|
|
3240
4285
|
} catch (error) {
|
|
3241
4286
|
fail(ws, error);
|
|
@@ -3256,7 +4301,7 @@ function mountSockets(app, sockets) {
|
|
|
3256
4301
|
ws.close(1008, "Invalid socket envelope");
|
|
3257
4302
|
return;
|
|
3258
4303
|
}
|
|
3259
|
-
const size =
|
|
4304
|
+
const size = bytes(JSON.stringify(value));
|
|
3260
4305
|
if (size > 65536) {
|
|
3261
4306
|
ws.close(1009, "Message too large");
|
|
3262
4307
|
return;
|
|
@@ -3269,7 +4314,8 @@ function mountSockets(app, sockets) {
|
|
|
3269
4314
|
state.bytes += size;
|
|
3270
4315
|
state.tail = state.tail.then(async () => {
|
|
3271
4316
|
if (state.closed || ws.readyState !== 1) return;
|
|
3272
|
-
|
|
4317
|
+
if (value.event === "$join" || value.event === "$leave") await room(state, value.event, value.data);
|
|
4318
|
+
else await state.session.message(value.event, value.data, state.sender);
|
|
3273
4319
|
}).catch((error) => fail(ws, error)).finally(() => {
|
|
3274
4320
|
state.pending--;
|
|
3275
4321
|
state.bytes -= size;
|
|
@@ -3280,6 +4326,7 @@ function mountSockets(app, sockets) {
|
|
|
3280
4326
|
sessions.delete(ws.request);
|
|
3281
4327
|
if (!state || state.closed) return;
|
|
3282
4328
|
state.closed = true;
|
|
4329
|
+
for (const topic of state.rooms) exit(state, topic);
|
|
3283
4330
|
try {
|
|
3284
4331
|
await state.session.close(state.sender, code, reason);
|
|
3285
4332
|
} catch (error) {
|
|
@@ -3311,11 +4358,11 @@ function mountSockets(app, sockets) {
|
|
|
3311
4358
|
* @param options - `prefix` for action routes (default `/api`), `services`,
|
|
3312
4359
|
* `title`, `version`, and `description` for the OpenAPI document, `docs` and the
|
|
3313
4360
|
* paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
|
|
3314
|
-
* `telemetry`, `documentation`, and `
|
|
4361
|
+
* `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.
|
|
3315
4362
|
* @returns The app, with `definition` (its services, prefix, and routes),
|
|
3316
4363
|
* `endpoint()` to add raw routes, and `listEndpoints()` to list them.
|
|
3317
|
-
* @throws When a required secret is missing,
|
|
3318
|
-
* is invalid.
|
|
4364
|
+
* @throws When a required secret is missing, `documentation` or `dashboard`
|
|
4365
|
+
* is invalid, or `deps` misses a dep a service declares or has one none declares.
|
|
3319
4366
|
* @example
|
|
3320
4367
|
* import { brick } from "@brickkit/core";
|
|
3321
4368
|
* import { pagesService } from "./services/pages";
|
|
@@ -3339,6 +4386,9 @@ function brick(options = {}) {
|
|
|
3339
4386
|
const telemetry = options.telemetry === true || dashboard !== void 0;
|
|
3340
4387
|
const app = new Elysia();
|
|
3341
4388
|
if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
|
|
4389
|
+
const services = options.services ?? getGlobalRegistry().list();
|
|
4390
|
+
const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
|
|
4391
|
+
for (const handler of plugins.middleware) app.request(handler);
|
|
3342
4392
|
app.get("/_health", () => ({
|
|
3343
4393
|
status: "ok",
|
|
3344
4394
|
uptime: process.uptime(),
|
|
@@ -3361,8 +4411,17 @@ function brick(options = {}) {
|
|
|
3361
4411
|
if (compiled) app.get(settings.path, htmlResponse(scalarDocsHTML(settings.specUrl, settings.title)));
|
|
3362
4412
|
else registerReferenceRoute(app, settings);
|
|
3363
4413
|
}
|
|
3364
|
-
const
|
|
3365
|
-
const
|
|
4414
|
+
const byName = /* @__PURE__ */ new Map();
|
|
4415
|
+
for (const service of services) {
|
|
4416
|
+
if ((byName.get(service.name) ?? service) !== service) throw new Error(`Brick: duplicate service "${service.name}" in brick()`);
|
|
4417
|
+
byName.set(service.name, service);
|
|
4418
|
+
}
|
|
4419
|
+
bindDeps(services, options.deps);
|
|
4420
|
+
const eventsOptions = plugins.listeners.length ? {
|
|
4421
|
+
...options.events,
|
|
4422
|
+
listeners: [...options.events?.listeners ?? [], ...plugins.listeners]
|
|
4423
|
+
} : options.events;
|
|
4424
|
+
const events = eventsOptions ? new EventsHub(eventsOptions, options.deps).attach(services) : void 0;
|
|
3366
4425
|
if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
|
|
3367
4426
|
if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
|
|
3368
4427
|
for (const service of services) if (typeof service.build === "function") service.build();
|
|
@@ -3423,6 +4482,27 @@ function brick(options = {}) {
|
|
|
3423
4482
|
if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new Error(`Brick: duplicate socket route '${socket.path}'`);
|
|
3424
4483
|
socketRoutes.add(key);
|
|
3425
4484
|
}
|
|
4485
|
+
const legacySockets = options.legacyRoutes ? services.flatMap((service) => service.listSockets().flatMap((definition) => {
|
|
4486
|
+
const path = legacySocketPath(prefix, service.name, definition);
|
|
4487
|
+
if (path === void 0) return [];
|
|
4488
|
+
const key = routeKey("GET", path);
|
|
4489
|
+
if (registeredRoutes.has(key) || socketRoutes.has(key)) return [];
|
|
4490
|
+
socketRoutes.add(key);
|
|
4491
|
+
return [{
|
|
4492
|
+
service: service.name,
|
|
4493
|
+
path,
|
|
4494
|
+
definition
|
|
4495
|
+
}];
|
|
4496
|
+
})) : [];
|
|
4497
|
+
const legacyRoutes = [];
|
|
4498
|
+
const addLegacy = (method, path, successor, handler) => {
|
|
4499
|
+
if (options.legacyRoutes && path !== void 0 && path !== successor) legacyRoutes.push({
|
|
4500
|
+
method,
|
|
4501
|
+
path,
|
|
4502
|
+
successor,
|
|
4503
|
+
handler
|
|
4504
|
+
});
|
|
4505
|
+
};
|
|
3426
4506
|
const mountRoute = (method, path, handler, plugin = false) => {
|
|
3427
4507
|
const key = routeKey(method, path);
|
|
3428
4508
|
if (socketRoutes.has(key)) throw new Error(`Brick: route '${method} ${path}' conflicts with a socket`);
|
|
@@ -3448,13 +4528,14 @@ function brick(options = {}) {
|
|
|
3448
4528
|
registeredRoutes.set(key, plugin);
|
|
3449
4529
|
return true;
|
|
3450
4530
|
};
|
|
3451
|
-
const mountEndpoint = (def, plugin = false) => {
|
|
4531
|
+
const mountEndpoint = (def, plugin = false, legacyPath) => {
|
|
3452
4532
|
const handler = createEndpointHandler(def, services);
|
|
4533
|
+
addLegacy(def.method, legacyPath, def.path, handler);
|
|
3453
4534
|
mountRoute(def.method, def.path, telemetry ? (context) => traceHttpRequest(context, def.method, def.path, () => handler(context)) : handler, plugin);
|
|
3454
4535
|
endpointDefs.push(def);
|
|
3455
4536
|
endpointRevision++;
|
|
3456
4537
|
};
|
|
3457
|
-
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
|
|
4538
|
+
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true, def.legacyPath);
|
|
3458
4539
|
for (const def of options.endpoints ?? []) mountEndpoint(def);
|
|
3459
4540
|
const brickApp = app;
|
|
3460
4541
|
brickApp.endpoint = (def) => {
|
|
@@ -3493,9 +4574,23 @@ function brick(options = {}) {
|
|
|
3493
4574
|
}, () => route.handler(context)) : route.handler(context);
|
|
3494
4575
|
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
3495
4576
|
};
|
|
3496
|
-
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, getPluginActionRoute(action, prefix) !== void 0))
|
|
4577
|
+
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, getPluginActionRoute(action, prefix) !== void 0)) {
|
|
4578
|
+
mountedRoutes.push(route.ir);
|
|
4579
|
+
const current = getActionRoute(action, prefix);
|
|
4580
|
+
if (current) addLegacy(route.ir.method, current.legacyPath, route.ir.path, invoke);
|
|
4581
|
+
}
|
|
3497
4582
|
}
|
|
3498
|
-
|
|
4583
|
+
for (const legacy of legacyRoutes) {
|
|
4584
|
+
const key = routeKey(legacy.method, legacy.path);
|
|
4585
|
+
if (registeredRoutes.has(key) || socketRoutes.has(key)) continue;
|
|
4586
|
+
const handle = (context) => {
|
|
4587
|
+
context.set.headers["deprecation"] = "true";
|
|
4588
|
+
context.set.headers["link"] = `<${legacy.successor.replace(/:([^/]+)/g, (match, name) => context.params?.[name] === void 0 ? match : encodeURIComponent(context.params[name]))}>; rel="successor-version"`;
|
|
4589
|
+
return legacy.handler(context);
|
|
4590
|
+
};
|
|
4591
|
+
mountRoute(legacy.method, legacy.path, telemetry ? (context) => traceHttpRequest(context, legacy.method, legacy.path, () => handle(context), { "brick.legacy_route": true }) : handle);
|
|
4592
|
+
}
|
|
4593
|
+
mountSockets(app, [...sockets, ...legacySockets], options.sockets?.broker ?? localBroker(), options.sockets?.secret);
|
|
3499
4594
|
const definition = Object.freeze({
|
|
3500
4595
|
services: Object.freeze([...services]),
|
|
3501
4596
|
prefix,
|
|
@@ -3508,10 +4603,26 @@ function brick(options = {}) {
|
|
|
3508
4603
|
telemetry,
|
|
3509
4604
|
documentation: normalizeDocumentation(options.documentation),
|
|
3510
4605
|
dashboard,
|
|
3511
|
-
...events ? { events: events.describe() } : {}
|
|
4606
|
+
...events ? { events: events.describe() } : {},
|
|
4607
|
+
plugins: Object.freeze(plugins.plugins)
|
|
3512
4608
|
});
|
|
3513
4609
|
Object.defineProperty(brickApp, "definition", { value: definition });
|
|
3514
4610
|
Object.defineProperty(brickApp, "events", { value: events });
|
|
4611
|
+
const lifecycle = pluginLifecycle(plugins.lifecycles);
|
|
4612
|
+
const listen = app.listen.bind(app);
|
|
4613
|
+
const stop = app.stop.bind(app);
|
|
4614
|
+
Object.defineProperty(brickApp, "start", { value: lifecycle.start });
|
|
4615
|
+
brickApp.listen = ((...args) => {
|
|
4616
|
+
lifecycle.start().catch((error) => console.error("[Brick-TS] A plugin failed to start:", error));
|
|
4617
|
+
return listen(...args);
|
|
4618
|
+
});
|
|
4619
|
+
brickApp.stop = (async (closeActiveConnections) => {
|
|
4620
|
+
try {
|
|
4621
|
+
await stop(closeActiveConnections);
|
|
4622
|
+
} finally {
|
|
4623
|
+
await lifecycle.stop();
|
|
4624
|
+
}
|
|
4625
|
+
});
|
|
3515
4626
|
getGlobalRegistry().setApplicationRoutes(definition);
|
|
3516
4627
|
app.get("/_brick/services", compiled ? cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
|
|
3517
4628
|
const registry = getGlobalRegistry();
|
|
@@ -3569,7 +4680,17 @@ function emitHandlerFactory(route) {
|
|
|
3569
4680
|
}
|
|
3570
4681
|
input.push("}");
|
|
3571
4682
|
}
|
|
3572
|
-
input.push(
|
|
4683
|
+
input.push("let coercedParams = params;");
|
|
4684
|
+
const numeric = route.coercions.filter(({ type }) => type === "number");
|
|
4685
|
+
if (numeric.length) {
|
|
4686
|
+
input.push("if (params) {", "coercedParams = { ...params };");
|
|
4687
|
+
for (const [index, coercion] of numeric.entries()) {
|
|
4688
|
+
const key = JSON.stringify(coercion.key);
|
|
4689
|
+
input.push(`const p${index} = params[${key}]; if (typeof p${index} === "string") { const pn${index} = Number(p${index}); if (!Number.isNaN(pn${index})) coercedParams[${key}] = pn${index}; }`);
|
|
4690
|
+
}
|
|
4691
|
+
input.push("}");
|
|
4692
|
+
}
|
|
4693
|
+
input.push(`input = mergeInput(${route.inputPrecedence.map((source) => source === "query" ? "coercedQuery" : source === "params" ? "coercedParams" : source).join(", ")});`);
|
|
3573
4694
|
if (route.inputSchema?.type === "object") input.push("input ??= {};");
|
|
3574
4695
|
}
|
|
3575
4696
|
const asyncStages = route.context || route.authorize;
|
|
@@ -3594,7 +4715,7 @@ const requestId = (headers && headers["x-request-id"]) || "req_" + seq;
|
|
|
3594
4715
|
if (set?.headers) { set.headers["x-trace-id"] = traceId; set.headers["x-request-id"] = requestId; }
|
|
3595
4716
|
${input.join("\n")}
|
|
3596
4717
|
const ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,
|
|
3597
|
-
db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };
|
|
4718
|
+
db: cachedDb ?? service.getDb(), logger, services: emptyServices, deps: service.deps ?? emptyServices, metadata: { headers }, _resolved: true };
|
|
3598
4719
|
try {
|
|
3599
4720
|
${context}
|
|
3600
4721
|
${validation}
|
|
@@ -3713,6 +4834,7 @@ function defineDatabase(options = {}) {
|
|
|
3713
4834
|
const declared = options.tables ?? {};
|
|
3714
4835
|
const tables = Array.isArray(declared) ? Object.fromEntries(declared.map((table) => [getTableName$1(table), table])) : { ...declared };
|
|
3715
4836
|
const schema = options.schema ?? tables;
|
|
4837
|
+
let frozen = Object.freeze({ ...tables });
|
|
3716
4838
|
let db;
|
|
3717
4839
|
let closeClient;
|
|
3718
4840
|
let closed = false;
|
|
@@ -3721,8 +4843,16 @@ function defineDatabase(options = {}) {
|
|
|
3721
4843
|
kind: "brick-database",
|
|
3722
4844
|
name: options.name,
|
|
3723
4845
|
engine,
|
|
3724
|
-
tables
|
|
4846
|
+
get tables() {
|
|
4847
|
+
return frozen;
|
|
4848
|
+
},
|
|
3725
4849
|
schema,
|
|
4850
|
+
addTable(key, table) {
|
|
4851
|
+
const name = getTableName$1(table);
|
|
4852
|
+
if (Object.hasOwn(tables, key) || Object.values(tables).some((item) => getTableName$1(item) === name)) throw new Error(`Database already has a table "${key}" or one named "${name}"`);
|
|
4853
|
+
tables[key] = table;
|
|
4854
|
+
frozen = Object.freeze({ ...tables });
|
|
4855
|
+
},
|
|
3726
4856
|
close() {
|
|
3727
4857
|
if (closed) return closing;
|
|
3728
4858
|
closed = true;
|
|
@@ -3981,6 +5111,217 @@ function syncSchema(tablesOrService, dbInstance) {
|
|
|
3981
5111
|
}
|
|
3982
5112
|
//#endregion
|
|
3983
5113
|
//#region src/resource.ts
|
|
5114
|
+
/** Resource actions can't take a CRUD route segment. */
|
|
5115
|
+
const CRUD_SEGMENTS = /* @__PURE__ */ new Set([
|
|
5116
|
+
"query",
|
|
5117
|
+
"count",
|
|
5118
|
+
"exists",
|
|
5119
|
+
"find-one",
|
|
5120
|
+
"bulk-create",
|
|
5121
|
+
"bulk-update",
|
|
5122
|
+
"bulk-delete"
|
|
5123
|
+
]);
|
|
5124
|
+
/**
|
|
5125
|
+
* Load the row a record action (or command) works on, through its `access`.
|
|
5126
|
+
*
|
|
5127
|
+
* @returns The row, or `undefined` when it is missing or hidden.
|
|
5128
|
+
* @throws When `access` is missing.
|
|
5129
|
+
*/
|
|
5130
|
+
async function loadRecord(resource, args) {
|
|
5131
|
+
if (!args.access) throw new Error(`Resource '${resource.name}' has no access rule for loading records: set \`access\` on the record action`);
|
|
5132
|
+
const db = args.db ?? args.ctx?.db;
|
|
5133
|
+
const id = idValue(resource.id, args.id);
|
|
5134
|
+
if (id === void 0) return void 0;
|
|
5135
|
+
if (!db) throw new Error("Record actions require a configured database");
|
|
5136
|
+
const scope = args.access === "public" ? void 0 : await args.access.scope({ ctx: args.ctx });
|
|
5137
|
+
const [row] = await db.select().from(resource.table).where(and$1(scope, eq$1(resource.id, id))).limit(1);
|
|
5138
|
+
return row;
|
|
5139
|
+
}
|
|
5140
|
+
/** Startup check: a record action needs its own `access`. */
|
|
5141
|
+
function checkRecordAccess(resource, info) {
|
|
5142
|
+
const name = `${resource.name}.${info.name}`;
|
|
5143
|
+
if (info.access === void 0) throw new Error(`Record action '${name}' needs \`access\` ("public" or { scope })`);
|
|
5144
|
+
}
|
|
5145
|
+
/** The id from the path as its column stores it: a Date or BigInt for those columns, undefined when it can't be one. */
|
|
5146
|
+
function idValue(column, id) {
|
|
5147
|
+
if (typeof id !== "string") return id;
|
|
5148
|
+
if (column.dataType === "date") {
|
|
5149
|
+
const date = new Date(id);
|
|
5150
|
+
return Number.isNaN(date.getTime()) ? void 0 : date;
|
|
5151
|
+
}
|
|
5152
|
+
if (column.dataType === "bigint") return /^-?\d+$/.test(id) ? BigInt(id) : void 0;
|
|
5153
|
+
return id;
|
|
5154
|
+
}
|
|
5155
|
+
function idSchema(column) {
|
|
5156
|
+
return column.dataType === "number" ? Type.Number() : Type.String();
|
|
5157
|
+
}
|
|
5158
|
+
function defineResourceAction(service, resource, config, command) {
|
|
5159
|
+
const { record = false, access, execute, ...rest } = config;
|
|
5160
|
+
if (!config.name || /[./]/.test(config.name)) throw new Error(`Invalid resource action name '${config.name}'`);
|
|
5161
|
+
const name = `${resource.name}.${config.name}`;
|
|
5162
|
+
const segment = kebabCase(config.name);
|
|
5163
|
+
if (CRUD_SEGMENTS.has(segment)) throw new Error(`Brick: duplicate name "${name}" in service "${service.name}": "${segment}" is a CRUD route`);
|
|
5164
|
+
if (service.getAction(name)?.plugin) throw new Error(`Brick: duplicate name "${name}" in service "${service.name}"`);
|
|
5165
|
+
if (!record && access !== void 0) throw new Error(`Only record actions take \`access\` ('${name}')`);
|
|
5166
|
+
if (record && config.path !== void 0 && !/\/:id(\/|$)/.test(config.path)) throw new Error(`Record action '${name}' needs ':id' in its path`);
|
|
5167
|
+
let input = config.input;
|
|
5168
|
+
if (record) {
|
|
5169
|
+
const own = input;
|
|
5170
|
+
if (own && own.type !== "object") throw new Error(`Record action '${name}' input must be an object`);
|
|
5171
|
+
input = Type.Object({
|
|
5172
|
+
...own?.properties,
|
|
5173
|
+
id: idSchema(resource.id)
|
|
5174
|
+
}, own?.additionalProperties === void 0 ? {} : { additionalProperties: own.additionalProperties });
|
|
5175
|
+
}
|
|
5176
|
+
const action = defineAction({
|
|
5177
|
+
...rest,
|
|
5178
|
+
name,
|
|
5179
|
+
input,
|
|
5180
|
+
execute: async ({ input, ctx, error }) => {
|
|
5181
|
+
if (command) return command({
|
|
5182
|
+
input,
|
|
5183
|
+
ctx,
|
|
5184
|
+
error
|
|
5185
|
+
});
|
|
5186
|
+
const row = record ? await loadRecord(resource, {
|
|
5187
|
+
id: input.id,
|
|
5188
|
+
ctx,
|
|
5189
|
+
access
|
|
5190
|
+
}) : void 0;
|
|
5191
|
+
if (record && row === void 0) error.NOT_FOUND(`${resource.name} '${String(input.id)}' not found`);
|
|
5192
|
+
return execute({
|
|
5193
|
+
input,
|
|
5194
|
+
ctx,
|
|
5195
|
+
error,
|
|
5196
|
+
row
|
|
5197
|
+
});
|
|
5198
|
+
}
|
|
5199
|
+
});
|
|
5200
|
+
const info = {
|
|
5201
|
+
resource: resource.name,
|
|
5202
|
+
name: config.name,
|
|
5203
|
+
record,
|
|
5204
|
+
...access === void 0 ? {} : { access }
|
|
5205
|
+
};
|
|
5206
|
+
Object.assign(action, {
|
|
5207
|
+
resource: resource.name,
|
|
5208
|
+
resourceAction: info
|
|
5209
|
+
});
|
|
5210
|
+
service.action(action);
|
|
5211
|
+
return action;
|
|
5212
|
+
}
|
|
5213
|
+
function primaryColumn(table) {
|
|
5214
|
+
const primary = Object.entries(getTableColumns$1(table)).filter(([, column]) => column.primary);
|
|
5215
|
+
return primary.length === 1 ? primary[0] : void 0;
|
|
5216
|
+
}
|
|
5217
|
+
function fieldOf(table, column) {
|
|
5218
|
+
return Object.entries(getTableColumns$1(table)).find(([, own]) => own === column)?.[0];
|
|
5219
|
+
}
|
|
5220
|
+
function childInfo(resource, name, where) {
|
|
5221
|
+
const child = resource.config.children?.[name];
|
|
5222
|
+
if (!child || !Object.hasOwn(resource.config.children ?? {}, name)) throw new Error(`${where}: resource '${resource.name}' has no child table '${name}'`);
|
|
5223
|
+
const parentField = fieldOf(child.table, child.parent);
|
|
5224
|
+
const id = child.id ?? primaryColumn(child.table)?.[1];
|
|
5225
|
+
const idField = id && fieldOf(child.table, id);
|
|
5226
|
+
if (!parentField || !id || !idField) throw new Error(`Resource '${resource.name}' child '${name}' needs a parent column and an id column of its table`);
|
|
5227
|
+
return {
|
|
5228
|
+
table: child.table,
|
|
5229
|
+
parent: child.parent,
|
|
5230
|
+
parentField,
|
|
5231
|
+
id,
|
|
5232
|
+
idField
|
|
5233
|
+
};
|
|
5234
|
+
}
|
|
5235
|
+
/** The `error` helpers of `decide`: they return the rejection, not throw it. */
|
|
5236
|
+
function commandErrors(errors) {
|
|
5237
|
+
const throwing = buildErrorHelpers(errors);
|
|
5238
|
+
return Object.fromEntries(Object.entries(throwing).map(([code, helper]) => [code, (message, details) => {
|
|
5239
|
+
try {
|
|
5240
|
+
helper(message, details);
|
|
5241
|
+
} catch (rejection) {
|
|
5242
|
+
return rejection;
|
|
5243
|
+
}
|
|
5244
|
+
}]));
|
|
5245
|
+
}
|
|
5246
|
+
function defineCommand(service, resource, name, config) {
|
|
5247
|
+
const where = `Command '${resource.name}.${name}'`;
|
|
5248
|
+
if (typeof config.decide !== "function") throw new Error(`${where} needs a decide function`);
|
|
5249
|
+
const loaded = (config.load?.children ?? []).map((child) => ({
|
|
5250
|
+
name: child,
|
|
5251
|
+
...childInfo(resource, child, where)
|
|
5252
|
+
}));
|
|
5253
|
+
const error = commandErrors(config.errors);
|
|
5254
|
+
const decide = (row, input) => config.decide(row, input, { error });
|
|
5255
|
+
const events = service.events;
|
|
5256
|
+
const run = async ({ input, ctx }) => {
|
|
5257
|
+
const db = ctx.db;
|
|
5258
|
+
if (!db) throw new Error(`${where} requires a configured database`);
|
|
5259
|
+
const recorder = service.recorder;
|
|
5260
|
+
const body = async (tx, record) => {
|
|
5261
|
+
const row = await loadRecord(resource, {
|
|
5262
|
+
id: input.id,
|
|
5263
|
+
ctx,
|
|
5264
|
+
db: tx,
|
|
5265
|
+
access: config.access
|
|
5266
|
+
});
|
|
5267
|
+
if (row === void 0) throw new ActionExecutionError("NOT_FOUND", `${resource.name} '${String(input.id)}' not found`, 404);
|
|
5268
|
+
const id = row[resource.idField];
|
|
5269
|
+
for (const child of loaded) row[child.name] = await tx.select().from(child.table).where(eq$1(child.parent, id));
|
|
5270
|
+
const decision = decide(row, input);
|
|
5271
|
+
if (decision instanceof ActionExecutionError) throw decision;
|
|
5272
|
+
const { set, children, emit } = decision ?? {};
|
|
5273
|
+
const emits = Object.entries(emit ?? {}).filter(([, payload]) => payload !== void 0).map(([key, payload]) => {
|
|
5274
|
+
const ref = Object.hasOwn(events, key) ? events[key] : void 0;
|
|
5275
|
+
if (!ref) throw new Error(`${where} emits '${key}', which is not in the event catalog of service '${service.name}'`);
|
|
5276
|
+
service.checkEvent?.(ref.name, payload);
|
|
5277
|
+
return [ref.name, payload];
|
|
5278
|
+
});
|
|
5279
|
+
if (emits.length && !record) throw new Error(`${where} emits events, but service '${service.name}' records none: give its database an outbox table and the app \`events\``);
|
|
5280
|
+
if (set && Object.keys(set).length) await tx.update(resource.table).set(set).where(eq$1(resource.id, id));
|
|
5281
|
+
for (const [childName, changes] of Object.entries(children ?? {})) {
|
|
5282
|
+
if (!changes) continue;
|
|
5283
|
+
const child = childInfo(resource, childName, where);
|
|
5284
|
+
const own = eq$1(child.parent, id);
|
|
5285
|
+
if (changes.insert?.length) await tx.insert(child.table).values(changes.insert.map((item) => ({
|
|
5286
|
+
...item,
|
|
5287
|
+
[child.parentField]: id
|
|
5288
|
+
})));
|
|
5289
|
+
for (const item of changes.update ?? []) {
|
|
5290
|
+
const { [child.idField]: childId, ...values } = item;
|
|
5291
|
+
if (childId === void 0) throw new Error(`${where}: an update of child '${childName}' needs its '${child.idField}'`);
|
|
5292
|
+
if (Object.keys(values).length) await tx.update(child.table).set(values).where(and$1(eq$1(child.id, childId), own));
|
|
5293
|
+
}
|
|
5294
|
+
if (changes.delete?.length) await tx.delete(child.table).where(and$1(inArray$1(child.id, changes.delete), own));
|
|
5295
|
+
}
|
|
5296
|
+
for (const [eventName, payload] of emits) await record(eventName, payload);
|
|
5297
|
+
if (!config.output) return { id };
|
|
5298
|
+
const [updated] = await tx.select().from(resource.table).where(eq$1(resource.id, id)).limit(1);
|
|
5299
|
+
for (const child of loaded) updated[child.name] = await tx.select().from(child.table).where(eq$1(child.parent, id));
|
|
5300
|
+
return Value.Clean(config.output, updated);
|
|
5301
|
+
};
|
|
5302
|
+
return recorder ? recorder.transaction(db, {
|
|
5303
|
+
traceId: ctx.traceId,
|
|
5304
|
+
source: `${service.name}.${resource.name}`
|
|
5305
|
+
}, body) : runInTransaction(db, (tx) => body(tx));
|
|
5306
|
+
};
|
|
5307
|
+
const action = defineResourceAction(service, resource, {
|
|
5308
|
+
name,
|
|
5309
|
+
record: true,
|
|
5310
|
+
description: config.description,
|
|
5311
|
+
tags: config.tags,
|
|
5312
|
+
input: config.input,
|
|
5313
|
+
output: config.output ?? Type.Object({ id: idSchema(resource.id) }),
|
|
5314
|
+
errors: config.errors,
|
|
5315
|
+
...config.access === void 0 ? {} : { access: config.access },
|
|
5316
|
+
...config.authorize ? { authorize: config.authorize } : {},
|
|
5317
|
+
execute: () => void 0
|
|
5318
|
+
}, run);
|
|
5319
|
+
Object.assign(action, {
|
|
5320
|
+
decide,
|
|
5321
|
+
command: true
|
|
5322
|
+
});
|
|
5323
|
+
return action;
|
|
5324
|
+
}
|
|
3984
5325
|
/** Declares a plugin host without registering actions or changing the schema. */
|
|
3985
5326
|
function defineResource(service, config) {
|
|
3986
5327
|
const columns = getTableColumns$1(config.table);
|
|
@@ -4006,11 +5347,58 @@ function defineResource(service, config) {
|
|
|
4006
5347
|
}),
|
|
4007
5348
|
use(plugin) {
|
|
4008
5349
|
return installPlugin(service, resource, plugin);
|
|
5350
|
+
},
|
|
5351
|
+
action(actionConfig) {
|
|
5352
|
+
return defineResourceAction(service, resource, actionConfig);
|
|
5353
|
+
},
|
|
5354
|
+
command(name, commandConfig) {
|
|
5355
|
+
return defineCommand(service, resource, name, commandConfig);
|
|
4009
5356
|
}
|
|
4010
5357
|
};
|
|
4011
5358
|
return resource;
|
|
4012
5359
|
}
|
|
4013
5360
|
//#endregion
|
|
5361
|
+
//#region src/events/catalog.ts
|
|
5362
|
+
function isEventRef(value) {
|
|
5363
|
+
return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.service === "string" && typeof value.schema === "object";
|
|
5364
|
+
}
|
|
5365
|
+
/** Build `service.events` from its catalog. */
|
|
5366
|
+
function eventRefs(service, catalog) {
|
|
5367
|
+
const refs = Object.create(null);
|
|
5368
|
+
for (const [key, schema] of Object.entries(catalog ?? {})) {
|
|
5369
|
+
if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key)) throw new Error(`Event "${key}" in service "${service}" must be a plain name such as shipped or itemAdded`);
|
|
5370
|
+
if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
|
|
5371
|
+
refs[key] = Object.freeze({
|
|
5372
|
+
name: `${service}.${key}`,
|
|
5373
|
+
service,
|
|
5374
|
+
schema
|
|
5375
|
+
});
|
|
5376
|
+
}
|
|
5377
|
+
return Object.freeze(refs);
|
|
5378
|
+
}
|
|
5379
|
+
const CRUD_EVENT = /^(create|update|delete)$/;
|
|
5380
|
+
/**
|
|
5381
|
+
* Check an event against the catalog of the service recording it. Without a
|
|
5382
|
+
* catalog any name goes. With one, the name must be `<service>.<event>` from it
|
|
5383
|
+
* (the payload is checked against its schema) or a CRUD event of one of the
|
|
5384
|
+
* service's resources (`<resource>.create|update|delete`).
|
|
5385
|
+
*
|
|
5386
|
+
* @throws When the name is not declared or the payload does not match.
|
|
5387
|
+
*/
|
|
5388
|
+
function checkEvent(service, name, payload) {
|
|
5389
|
+
const prefix = `${service.name}.`;
|
|
5390
|
+
const ref = name.startsWith(prefix) ? service.events[name.slice(prefix.length)] : void 0;
|
|
5391
|
+
if (ref) {
|
|
5392
|
+
const result = validateWithSchema(ref.schema, payload);
|
|
5393
|
+
if (!result.success) throw new Error(`Event "${name}" payload does not match its schema: ${result.errors.map((error) => `${error.path || "/"} ${error.message}`).join("; ")}`);
|
|
5394
|
+
return;
|
|
5395
|
+
}
|
|
5396
|
+
if (!service.hasCatalog) return;
|
|
5397
|
+
const dot = name.indexOf(".");
|
|
5398
|
+
if (dot > 0 && CRUD_EVENT.test(name.slice(dot + 1)) && service.listResources().some((r) => r.name === name.slice(0, dot))) return;
|
|
5399
|
+
throw new Error(`Event "${name}" is not in the event catalog of service "${service.name}" (declared: ${Object.values(service.events).map((ref) => ref.name).join(", ") || "none"})`);
|
|
5400
|
+
}
|
|
5401
|
+
//#endregion
|
|
4014
5402
|
//#region src/context.ts
|
|
4015
5403
|
function pickContextEnvelope(context) {
|
|
4016
5404
|
if (!context) return {};
|
|
@@ -4028,8 +5416,11 @@ const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
|
|
|
4028
5416
|
const DEFAULT_REQUEST = new Request("http://localhost");
|
|
4029
5417
|
const EMPTY_SERVICES = Object.freeze({});
|
|
4030
5418
|
const EMPTY_METADATA = Object.freeze({});
|
|
5419
|
+
const EMPTY_DEPS = Object.freeze({});
|
|
4031
5420
|
let _ctxSeq = 0;
|
|
4032
5421
|
const RESOLVED_SYMBOL = Symbol("resolved");
|
|
5422
|
+
/** The deps a resolved context was resolved with, to restore them when a plugin's copy comes back. */
|
|
5423
|
+
const OWN_DEPS = Symbol("ownDeps");
|
|
4033
5424
|
var ServiceImpl = class {
|
|
4034
5425
|
name;
|
|
4035
5426
|
options;
|
|
@@ -4039,11 +5430,17 @@ var ServiceImpl = class {
|
|
|
4039
5430
|
sockets = /* @__PURE__ */ new Map();
|
|
4040
5431
|
resources = /* @__PURE__ */ new Map();
|
|
4041
5432
|
preparations = /* @__PURE__ */ new Map();
|
|
5433
|
+
/** Where each `kind:name` was defined, to reject duplicates from another file. */
|
|
5434
|
+
sites = /* @__PURE__ */ new Map();
|
|
4042
5435
|
database;
|
|
4043
5436
|
_isBuilt = false;
|
|
5437
|
+
/** The declared events: `service.events.<name>`. */
|
|
5438
|
+
events;
|
|
4044
5439
|
constructor(name, options = {}) {
|
|
4045
5440
|
this.name = name;
|
|
4046
5441
|
this.options = options;
|
|
5442
|
+
this.events = eventRefs(name, options.events);
|
|
5443
|
+
for (const key of Object.keys(this.events)) this.claim("event", key);
|
|
4047
5444
|
if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
|
|
4048
5445
|
this.database = options.database;
|
|
4049
5446
|
}
|
|
@@ -4062,9 +5459,17 @@ var ServiceImpl = class {
|
|
|
4062
5459
|
build() {
|
|
4063
5460
|
if (isInstallingPlugin(this)) throw new Error("Cannot build a service during plugin setup");
|
|
4064
5461
|
if (this._isBuilt) return this;
|
|
5462
|
+
for (const action of this.actions.values()) {
|
|
5463
|
+
const info = action.resourceAction;
|
|
5464
|
+
const resource = info?.record && this.resources.get(info.resource);
|
|
5465
|
+
if (resource) checkRecordAccess(resource, info);
|
|
5466
|
+
}
|
|
4065
5467
|
this._isBuilt = true;
|
|
4066
5468
|
return this;
|
|
4067
5469
|
}
|
|
5470
|
+
claim(kind, name) {
|
|
5471
|
+
claimName(this.sites, `${kind} "${name}" in service "${this.name}"`, `${kind}:${name}`, definitionSite());
|
|
5472
|
+
}
|
|
4068
5473
|
contributePreparation(contribution) {
|
|
4069
5474
|
if (this._isBuilt) throw new Error("Preparations must be registered before service build");
|
|
4070
5475
|
if (this.preparations.has(contribution.name)) throw new Error(`Duplicate preparation '${contribution.name}'`);
|
|
@@ -4089,7 +5494,7 @@ var ServiceImpl = class {
|
|
|
4089
5494
|
}
|
|
4090
5495
|
resource = (config) => {
|
|
4091
5496
|
if (this._isBuilt) throw new Error("Resources must be registered before service build");
|
|
4092
|
-
|
|
5497
|
+
this.claim("resource", config.name);
|
|
4093
5498
|
const resourceInstance = defineResource(this, config);
|
|
4094
5499
|
this.resources.set(resourceInstance.name, resourceInstance);
|
|
4095
5500
|
getGlobalRegistry().touch();
|
|
@@ -4107,6 +5512,7 @@ var ServiceImpl = class {
|
|
|
4107
5512
|
if (isActionFunction) actionInstance = actionOrConfig;
|
|
4108
5513
|
else actionInstance = defineAction(actionOrConfig);
|
|
4109
5514
|
if (isInstallingPlugin(this) && this.actions.has(actionInstance.name) && this.actions.get(actionInstance.name) !== actionInstance) throw new Error(`Duplicate plugin action: ${actionInstance.name}`);
|
|
5515
|
+
if (this.actions.get(actionInstance.name) !== actionInstance) this.claim("action", actionInstance.name);
|
|
4110
5516
|
if (isTool(actionInstance)) actionInstance.config.http = true;
|
|
4111
5517
|
actionInstance.serviceName = this.name;
|
|
4112
5518
|
actionInstance.service = this;
|
|
@@ -4118,7 +5524,7 @@ var ServiceImpl = class {
|
|
|
4118
5524
|
tool(toolOrConfig) {
|
|
4119
5525
|
const existing = isTool(toolOrConfig);
|
|
4120
5526
|
const tool = existing ? toolOrConfig : defineTool(toolOrConfig);
|
|
4121
|
-
|
|
5527
|
+
this.claim("tool", tool.name);
|
|
4122
5528
|
tool.serviceName = this.name;
|
|
4123
5529
|
tool.service = this;
|
|
4124
5530
|
this.tools.set(tool.name, tool);
|
|
@@ -4131,10 +5537,18 @@ var ServiceImpl = class {
|
|
|
4131
5537
|
}
|
|
4132
5538
|
socket(config) {
|
|
4133
5539
|
if (this._isBuilt) throw new Error("Sockets must be declared before service build");
|
|
4134
|
-
|
|
4135
|
-
this.
|
|
5540
|
+
this.claim("socket", config.name);
|
|
5541
|
+
const socket = defineServiceSocket(this.name, config, async (request) => {
|
|
5542
|
+
const ctx = await resolveServiceContext(this, { request });
|
|
5543
|
+
const deps = socket[PLUGIN_DEPS];
|
|
5544
|
+
return deps ? {
|
|
5545
|
+
...ctx,
|
|
5546
|
+
deps
|
|
5547
|
+
} : ctx;
|
|
5548
|
+
});
|
|
5549
|
+
this.sockets.set(config.name, socket);
|
|
4136
5550
|
getGlobalRegistry().touch();
|
|
4137
|
-
return
|
|
5551
|
+
return socket.handle;
|
|
4138
5552
|
}
|
|
4139
5553
|
listSockets() {
|
|
4140
5554
|
return [...this.sockets.values()];
|
|
@@ -4151,13 +5565,30 @@ var ServiceImpl = class {
|
|
|
4151
5565
|
getDb() {
|
|
4152
5566
|
return this.database?.getDb();
|
|
4153
5567
|
}
|
|
5568
|
+
/** The handle from `defineDatabase`, without connecting. */
|
|
5569
|
+
getDatabaseHandle() {
|
|
5570
|
+
return this.database;
|
|
5571
|
+
}
|
|
4154
5572
|
/** What a write needs to record events. Set by `brick({ events })`. */
|
|
4155
|
-
|
|
5573
|
+
recorder;
|
|
4156
5574
|
getOutbox() {
|
|
4157
5575
|
return Object.values(this.database?.tables ?? {}).find(isOutboxTable);
|
|
4158
5576
|
}
|
|
4159
|
-
|
|
4160
|
-
this.
|
|
5577
|
+
setRecorder(recorder) {
|
|
5578
|
+
this.recorder = recorder;
|
|
5579
|
+
}
|
|
5580
|
+
/** Whether the service declares an event catalog. */
|
|
5581
|
+
get hasCatalog() {
|
|
5582
|
+
return this.options.events !== void 0;
|
|
5583
|
+
}
|
|
5584
|
+
/** @throws When the event is not in the catalog or its payload does not match. */
|
|
5585
|
+
checkEvent(name, payload) {
|
|
5586
|
+
checkEvent(this, name, payload);
|
|
5587
|
+
}
|
|
5588
|
+
/** The values of this service's `deps`. Set by `brick({ deps })`. */
|
|
5589
|
+
deps;
|
|
5590
|
+
setDeps(deps) {
|
|
5591
|
+
this.deps = deps;
|
|
4161
5592
|
}
|
|
4162
5593
|
setDb(database) {
|
|
4163
5594
|
if (!isDatabaseHandle(database)) throw new Error("Use defineDatabase() to set a service database");
|
|
@@ -4176,9 +5607,10 @@ var ServiceImpl = class {
|
|
|
4176
5607
|
const databaseConfig = this.database ? {
|
|
4177
5608
|
name: this.database.name,
|
|
4178
5609
|
engine: this.database.engine,
|
|
4179
|
-
tables: Object.keys(this.database.tables)
|
|
5610
|
+
tables: Object.keys(this.database.tables),
|
|
5611
|
+
...pluginTables(this.database.tables)
|
|
4180
5612
|
} : void 0;
|
|
4181
|
-
const { database: _database, ...config } = this.options;
|
|
5613
|
+
const { database: _database, events: _events, ...config } = this.options;
|
|
4182
5614
|
const options = JSON.parse(JSON.stringify(config));
|
|
4183
5615
|
return {
|
|
4184
5616
|
name: this.name,
|
|
@@ -4205,43 +5637,75 @@ var ServiceImpl = class {
|
|
|
4205
5637
|
};
|
|
4206
5638
|
}),
|
|
4207
5639
|
tools: this.listTools().map((tool) => ({ name: tool.name })),
|
|
5640
|
+
...this.hasCatalog || Object.keys(this.events).length ? { events: Object.values(this.events).map((ref) => ({
|
|
5641
|
+
name: ref.name,
|
|
5642
|
+
schema: JSON.parse(JSON.stringify(ref.schema)),
|
|
5643
|
+
...ref.plugin ? { plugin: ref.plugin } : {}
|
|
5644
|
+
})) } : {},
|
|
4208
5645
|
resources: this.listResources().map((res) => ({ name: res.name }))
|
|
4209
5646
|
};
|
|
4210
5647
|
}
|
|
4211
5648
|
};
|
|
5649
|
+
/** `plugins`: which plugin owns each table it contributed, by table key. */
|
|
5650
|
+
function pluginTables(tables) {
|
|
5651
|
+
const owners = Object.entries(tables).flatMap(([key, table]) => {
|
|
5652
|
+
const plugin = pluginOwner(table);
|
|
5653
|
+
return plugin ? [[key, plugin]] : [];
|
|
5654
|
+
});
|
|
5655
|
+
return owners.length ? { plugins: Object.fromEntries(owners) } : {};
|
|
5656
|
+
}
|
|
4212
5657
|
async function resolveServiceContext(service, callCtx) {
|
|
4213
|
-
if (callCtx?.[RESOLVED_SYMBOL] === service)
|
|
5658
|
+
if (callCtx?.[RESOLVED_SYMBOL] === service) {
|
|
5659
|
+
const own = callCtx[OWN_DEPS];
|
|
5660
|
+
return callCtx.deps === own ? callCtx : {
|
|
5661
|
+
...callCtx,
|
|
5662
|
+
deps: own
|
|
5663
|
+
};
|
|
5664
|
+
}
|
|
4214
5665
|
const seq = ++_ctxSeq;
|
|
5666
|
+
const req = callCtx?.request ?? DEFAULT_REQUEST;
|
|
5667
|
+
const db = service.getDb();
|
|
5668
|
+
const logger = callCtx?.logger ?? defaultLogger;
|
|
5669
|
+
const traceId = callCtx?.traceId ?? `tr_${seq.toString(36)}`;
|
|
5670
|
+
const requestId = callCtx?.requestId ?? `req_${seq.toString(36)}`;
|
|
5671
|
+
const services = callCtx?.services ?? EMPTY_SERVICES;
|
|
5672
|
+
const metadata = callCtx?.metadata ?? EMPTY_METADATA;
|
|
5673
|
+
const deps = service.deps ?? (callCtx?.[RESOLVED_SYMBOL] ? void 0 : callCtx?.deps) ?? EMPTY_DEPS;
|
|
4215
5674
|
const fullBaseCtx = {
|
|
4216
|
-
request:
|
|
4217
|
-
db
|
|
4218
|
-
logger
|
|
4219
|
-
traceId
|
|
4220
|
-
requestId
|
|
4221
|
-
services
|
|
4222
|
-
metadata
|
|
5675
|
+
request: req,
|
|
5676
|
+
db,
|
|
5677
|
+
logger,
|
|
5678
|
+
traceId,
|
|
5679
|
+
requestId,
|
|
5680
|
+
services,
|
|
5681
|
+
metadata,
|
|
4223
5682
|
...pickContextEnvelope(callCtx)
|
|
4224
5683
|
};
|
|
4225
5684
|
const resolvedExtra = service.options.context ? await service.options.context(fullBaseCtx) : {};
|
|
4226
5685
|
return {
|
|
4227
5686
|
...fullBaseCtx,
|
|
4228
5687
|
...resolvedExtra,
|
|
4229
|
-
|
|
5688
|
+
deps,
|
|
5689
|
+
[RESOLVED_SYMBOL]: service,
|
|
5690
|
+
[OWN_DEPS]: deps
|
|
4230
5691
|
};
|
|
4231
5692
|
}
|
|
4232
5693
|
/**
|
|
4233
5694
|
* Declare a service: a named group of actions, tools, and resources with its own
|
|
4234
5695
|
* database and request context. It is registered globally, so `brick()`, the
|
|
4235
|
-
* OpenAPI generator, and `
|
|
5696
|
+
* OpenAPI generator, and `useService` find it by name.
|
|
4236
5697
|
*
|
|
4237
5698
|
* Add actions with `service.action(...)`, tools with `service.tool(...)`,
|
|
4238
5699
|
* resources with `service.resource(...)`, and plugins with `service.use(...)`.
|
|
4239
5700
|
*
|
|
4240
5701
|
* @param name - Unique name. It is the service's segment of every action route
|
|
4241
|
-
* (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining
|
|
4242
|
-
*
|
|
4243
|
-
* @param options - `database` (a handle from `defineDatabase`), `
|
|
4244
|
-
*
|
|
5702
|
+
* (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it
|
|
5703
|
+
* again from the same file (a dev reload) replaces it; from another file throws.
|
|
5704
|
+
* @param options - `database` (a handle from `defineDatabase`), `deps` (typed
|
|
5705
|
+
* slots from `port<T>()` that `brick({ deps })` fills, read as `ctx.deps`),
|
|
5706
|
+
* `context` (adds fields such as the signed-in user to every action's `ctx`),
|
|
5707
|
+
* `events` (the event catalog: a payload schema per event name, recorded as
|
|
5708
|
+
* `<service>.<name>` and offered as `service.events.<name>`), and `auth`,
|
|
4245
5709
|
* `rateLimit`, `cache`, `resilience`, `telemetry`, and `lifecycle`.
|
|
4246
5710
|
* @returns The service.
|
|
4247
5711
|
* @example
|
|
@@ -4269,53 +5733,252 @@ function defineService(name, options) {
|
|
|
4269
5733
|
return service;
|
|
4270
5734
|
}
|
|
4271
5735
|
//#endregion
|
|
5736
|
+
//#region src/socket-redis.ts
|
|
5737
|
+
/** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */
|
|
5738
|
+
function reconnectDelay(failures) {
|
|
5739
|
+
const ceiling = Math.min(3e4, 500 * 2 ** failures);
|
|
5740
|
+
return ceiling / 2 + Math.random() * (ceiling / 2);
|
|
5741
|
+
}
|
|
5742
|
+
/** One Redis connection that reconnects by itself and reports each fresh connection. */
|
|
5743
|
+
function connection(url, connected) {
|
|
5744
|
+
let redis;
|
|
5745
|
+
let timer;
|
|
5746
|
+
let closed = false;
|
|
5747
|
+
let failures = 0;
|
|
5748
|
+
const waiters = [];
|
|
5749
|
+
const lost = (client) => {
|
|
5750
|
+
if (redis !== client) return;
|
|
5751
|
+
redis = void 0;
|
|
5752
|
+
if (closed || timer) return;
|
|
5753
|
+
timer = setTimeout(() => {
|
|
5754
|
+
timer = void 0;
|
|
5755
|
+
start();
|
|
5756
|
+
}, reconnectDelay(failures++));
|
|
5757
|
+
};
|
|
5758
|
+
const start = () => {
|
|
5759
|
+
if (closed || redis || timer) return;
|
|
5760
|
+
const client = new Bun.RedisClient(url, {
|
|
5761
|
+
autoReconnect: false,
|
|
5762
|
+
enableOfflineQueue: false
|
|
5763
|
+
});
|
|
5764
|
+
redis = client;
|
|
5765
|
+
client.onclose = () => lost(client);
|
|
5766
|
+
client.connect().then(() => {
|
|
5767
|
+
if (redis !== client) return;
|
|
5768
|
+
failures = 0;
|
|
5769
|
+
connected(client);
|
|
5770
|
+
for (const wake of waiters.splice(0)) wake();
|
|
5771
|
+
}, () => lost(client));
|
|
5772
|
+
};
|
|
5773
|
+
return {
|
|
5774
|
+
/** The connected client, starting a connection when there is none. */
|
|
5775
|
+
get() {
|
|
5776
|
+
start();
|
|
5777
|
+
return redis?.connected ? redis : void 0;
|
|
5778
|
+
},
|
|
5779
|
+
/** Resolves after the next connection is made and announced, or after `ms`. */
|
|
5780
|
+
opened(ms) {
|
|
5781
|
+
if (redis?.connected) return Promise.resolve();
|
|
5782
|
+
start();
|
|
5783
|
+
return new Promise((resolve) => {
|
|
5784
|
+
waiters.push(resolve);
|
|
5785
|
+
setTimeout(resolve, ms);
|
|
5786
|
+
});
|
|
5787
|
+
},
|
|
5788
|
+
close() {
|
|
5789
|
+
closed = true;
|
|
5790
|
+
clearTimeout(timer);
|
|
5791
|
+
for (const wake of waiters.splice(0)) wake();
|
|
5792
|
+
const client = redis;
|
|
5793
|
+
redis = void 0;
|
|
5794
|
+
client?.close();
|
|
5795
|
+
}
|
|
5796
|
+
};
|
|
5797
|
+
}
|
|
5798
|
+
/**
|
|
5799
|
+
* Fans socket emits and kicks out across processes through Redis pub/sub, one
|
|
5800
|
+
* channel per room topic. An emit is a PUBLISH only: every process, the emitting
|
|
5801
|
+
* one included, delivers it once to its own connections. Uses Bun's built-in
|
|
5802
|
+
* Redis client and two connections, one to publish and one to subscribe.
|
|
5803
|
+
*/
|
|
5804
|
+
function redisBroker(options = {}) {
|
|
5805
|
+
const limit = options.queue ?? 1e3;
|
|
5806
|
+
if (!Number.isInteger(limit) || limit < 0) throw new Error("redisBroker queue must be a nonnegative integer");
|
|
5807
|
+
const channel = (topic) => `brick:socket:${topic}`;
|
|
5808
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
5809
|
+
const pending = /* @__PURE__ */ new Map();
|
|
5810
|
+
const stream = (topic) => `brick:socket:stream:${topic}`;
|
|
5811
|
+
const queue = [];
|
|
5812
|
+
const send = (work) => {
|
|
5813
|
+
const redis = publisher.get();
|
|
5814
|
+
if (redis) return work(redis);
|
|
5815
|
+
queue.push(work);
|
|
5816
|
+
if (queue.length > limit) queue.shift();
|
|
5817
|
+
};
|
|
5818
|
+
const receive = (payload, name) => {
|
|
5819
|
+
let message;
|
|
5820
|
+
try {
|
|
5821
|
+
message = JSON.parse(payload);
|
|
5822
|
+
} catch {
|
|
5823
|
+
return;
|
|
5824
|
+
}
|
|
5825
|
+
for (const deliver of listeners.get(name) ?? []) deliver(message);
|
|
5826
|
+
};
|
|
5827
|
+
const subscribe = (redis, name) => {
|
|
5828
|
+
const done = redis.subscribe(name, receive).catch(() => {});
|
|
5829
|
+
pending.set(name, done);
|
|
5830
|
+
done.then(() => {
|
|
5831
|
+
if (pending.get(name) === done) pending.delete(name);
|
|
5832
|
+
});
|
|
5833
|
+
};
|
|
5834
|
+
const publisher = connection(options.url, (redis) => {
|
|
5835
|
+
for (const work of queue.splice(0)) work(redis);
|
|
5836
|
+
});
|
|
5837
|
+
const subscriber = connection(options.url, (redis) => {
|
|
5838
|
+
for (const name of listeners.keys()) subscribe(redis, name);
|
|
5839
|
+
});
|
|
5840
|
+
return {
|
|
5841
|
+
publish(message, replay) {
|
|
5842
|
+
const name = channel(message.topic);
|
|
5843
|
+
if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(() => {}));
|
|
5844
|
+
const key = stream(message.topic);
|
|
5845
|
+
send((redis) => {
|
|
5846
|
+
redis.send("XADD", [
|
|
5847
|
+
key,
|
|
5848
|
+
"MAXLEN",
|
|
5849
|
+
"~",
|
|
5850
|
+
String(replay.keep),
|
|
5851
|
+
"*",
|
|
5852
|
+
"m",
|
|
5853
|
+
message.frame
|
|
5854
|
+
]).then((seq) => {
|
|
5855
|
+
redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(() => {});
|
|
5856
|
+
return redis.publish(name, JSON.stringify({
|
|
5857
|
+
...message,
|
|
5858
|
+
seq
|
|
5859
|
+
}));
|
|
5860
|
+
}).catch(() => {});
|
|
5861
|
+
});
|
|
5862
|
+
},
|
|
5863
|
+
async head() {
|
|
5864
|
+
try {
|
|
5865
|
+
await publisher.opened(1e3);
|
|
5866
|
+
const [seconds, micros] = await publisher.get().send("TIME", []);
|
|
5867
|
+
return `${Number(seconds) * 1e3 + Math.floor(Number(micros) / 1e3) - 1}-0`;
|
|
5868
|
+
} catch {
|
|
5869
|
+
return `${Date.now() - 1}-0`;
|
|
5870
|
+
}
|
|
5871
|
+
},
|
|
5872
|
+
async history(topic, since, replay) {
|
|
5873
|
+
let raw;
|
|
5874
|
+
try {
|
|
5875
|
+
await publisher.opened(1e3);
|
|
5876
|
+
raw = await publisher.get().send("XRANGE", [
|
|
5877
|
+
stream(topic),
|
|
5878
|
+
"-",
|
|
5879
|
+
"+"
|
|
5880
|
+
]);
|
|
5881
|
+
} catch {
|
|
5882
|
+
return;
|
|
5883
|
+
}
|
|
5884
|
+
const ms = (seq) => Number(seq.split("-")[0]);
|
|
5885
|
+
const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);
|
|
5886
|
+
if (after.length === raw.length && (raw.length >= replay.keep || (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)) return void 0;
|
|
5887
|
+
return after.map(([seq, fields]) => ({
|
|
5888
|
+
type: "emit",
|
|
5889
|
+
topic,
|
|
5890
|
+
frame: fields[fields.indexOf("m") + 1],
|
|
5891
|
+
seq
|
|
5892
|
+
}));
|
|
5893
|
+
},
|
|
5894
|
+
subscribe(topic, deliver) {
|
|
5895
|
+
const name = channel(topic);
|
|
5896
|
+
let local = listeners.get(name);
|
|
5897
|
+
if (!local) {
|
|
5898
|
+
local = /* @__PURE__ */ new Set();
|
|
5899
|
+
listeners.set(name, local);
|
|
5900
|
+
const redis = subscriber.get();
|
|
5901
|
+
if (redis) subscribe(redis, name);
|
|
5902
|
+
}
|
|
5903
|
+
local.add(deliver);
|
|
5904
|
+
return () => {
|
|
5905
|
+
local.delete(deliver);
|
|
5906
|
+
if (local.size || listeners.get(name) !== local) return;
|
|
5907
|
+
listeners.delete(name);
|
|
5908
|
+
pending.delete(name);
|
|
5909
|
+
subscriber.get()?.unsubscribe(name).catch(() => {});
|
|
5910
|
+
};
|
|
5911
|
+
},
|
|
5912
|
+
async ready(topic) {
|
|
5913
|
+
const name = channel(topic);
|
|
5914
|
+
if (!pending.has(name)) await subscriber.opened(1e3);
|
|
5915
|
+
await pending.get(name);
|
|
5916
|
+
},
|
|
5917
|
+
close() {
|
|
5918
|
+
publisher.close();
|
|
5919
|
+
subscriber.close();
|
|
5920
|
+
}
|
|
5921
|
+
};
|
|
5922
|
+
}
|
|
5923
|
+
//#endregion
|
|
4272
5924
|
//#region src/rpc.ts
|
|
4273
5925
|
/**
|
|
4274
|
-
*
|
|
4275
|
-
*
|
|
4276
|
-
*
|
|
5926
|
+
* Call another service's actions in-process, typed from that service. Each
|
|
5927
|
+
* action is a method, and each resource's actions sit under the resource's
|
|
5928
|
+
* name: `billing.charge(input)`, `billing.invoice.list()`.
|
|
5929
|
+
*
|
|
5930
|
+
* The types come from the app's generated contract (`_brick/contract.ts`, which
|
|
5931
|
+
* `brick dev` and `brick gen client` keep current), so renaming an action or
|
|
5932
|
+
* changing its input is a compile error at every caller. Until the contract
|
|
5933
|
+
* describes the service, the client is untyped.
|
|
4277
5934
|
*
|
|
4278
|
-
*
|
|
4279
|
-
* target's database and
|
|
4280
|
-
* span in the trace.
|
|
4281
|
-
* a call throws. Use the typed client to call a service over HTTP.
|
|
5935
|
+
* A call runs through the target's own validation and authorization, with the
|
|
5936
|
+
* target's database, context and deps (never the caller's), and shows as an
|
|
5937
|
+
* `rpc` span in the trace.
|
|
4282
5938
|
*
|
|
4283
|
-
* @param
|
|
5939
|
+
* @param service - The service to call, as `defineService` returned it.
|
|
4284
5940
|
* @param options - `from` (the calling service's name, which becomes `ctx.caller`
|
|
4285
|
-
* in the target and cannot be spoofed)
|
|
4286
|
-
*
|
|
4287
|
-
* @returns
|
|
4288
|
-
* @throws On a call, when the service or
|
|
5941
|
+
* in the target and cannot be spoofed) and `context` (defaults for every call).
|
|
5942
|
+
* Each call also takes an optional call context after its input.
|
|
5943
|
+
* @returns The client.
|
|
5944
|
+
* @throws On a call, when the service is not registered or has no such action.
|
|
4289
5945
|
* @example
|
|
4290
|
-
* import {
|
|
5946
|
+
* import { useService } from "@brickkit/core";
|
|
5947
|
+
* import { billingService } from "../billing/billing.service";
|
|
4291
5948
|
*
|
|
4292
|
-
* const
|
|
4293
|
-
*
|
|
4294
|
-
*
|
|
4295
|
-
* );
|
|
4296
|
-
* const page = await pages.get({ id: "p_1" });
|
|
5949
|
+
* const billing = useService(billingService, { from: "orders" });
|
|
5950
|
+
* await billing.charge({ orderId, amountCents });
|
|
5951
|
+
* await billing.invoice.list({ limit: 10 });
|
|
4297
5952
|
*/
|
|
4298
|
-
function
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
4318
|
-
} });
|
|
5953
|
+
function useService(service, options = {}) {
|
|
5954
|
+
return serviceRef(service.name, options, []);
|
|
5955
|
+
}
|
|
5956
|
+
function serviceRef(serviceName, options, path) {
|
|
5957
|
+
return new Proxy(function() {}, {
|
|
5958
|
+
get(_, key) {
|
|
5959
|
+
if (typeof key !== "string" || key === "then") return void 0;
|
|
5960
|
+
return serviceRef(serviceName, options, [...path, key]);
|
|
5961
|
+
},
|
|
5962
|
+
apply(_, __, [payload, callCtx]) {
|
|
5963
|
+
const name = path.join(".");
|
|
5964
|
+
const clientPath = [serviceName, ...path].join(".");
|
|
5965
|
+
return callAction(serviceName, name, (service) => service.getAction(name) ?? service.listActions().find((action) => (getPluginActionRoute(action) || void 0)?.clientPath?.join(".") === clientPath), payload, callCtx, options);
|
|
5966
|
+
}
|
|
5967
|
+
});
|
|
5968
|
+
}
|
|
5969
|
+
async function callAction(serviceName, actionName, find, payload, callCtx, options) {
|
|
5970
|
+
const service = getGlobalRegistry().get(serviceName);
|
|
5971
|
+
if (!service) throw new Error(`[Brick-TS RPC] Service '${serviceName}' is not registered in the local runtime.`);
|
|
5972
|
+
const action = find(service);
|
|
5973
|
+
if (!action) throw new Error(`[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`);
|
|
5974
|
+
const envelopeCtx = createRpcEnvelope(options.from, options.context, callCtx);
|
|
5975
|
+
return withCallSpan(`rpc ${serviceName}.${actionName}`, {
|
|
5976
|
+
"brick.service": serviceName,
|
|
5977
|
+
"brick.action": actionName
|
|
5978
|
+
}, () => action.execute({
|
|
5979
|
+
input: payload,
|
|
5980
|
+
ctx: envelopeCtx
|
|
5981
|
+
}));
|
|
4319
5982
|
}
|
|
4320
5983
|
/** Build the trusted envelope for a proxy call.
|
|
4321
5984
|
*
|
|
@@ -4335,94 +5998,38 @@ function createRpcEnvelope(from, defaultContext, callContext) {
|
|
|
4335
5998
|
}
|
|
4336
5999
|
//#endregion
|
|
4337
6000
|
//#region src/events/listener.ts
|
|
4338
|
-
/**
|
|
4339
|
-
* Define a listener: code that runs for each event it listens for, after the write
|
|
4340
|
-
* that caused the event has been committed. Pass it to `brick({ events: {
|
|
4341
|
-
* listeners } })`.
|
|
4342
|
-
*
|
|
4343
|
-
* It either runs a handler (`run`) in the process that delivers events, or starts
|
|
4344
|
-
* a durable workflow (`workflow`) on the app's `events.world`. Delivery is at
|
|
4345
|
-
* least once. A handler that throws is retried later with a growing delay, then
|
|
4346
|
-
* parked as dead, so it can run again for the same event: use
|
|
4347
|
-
* `delivery.deliveryId` to make its work idempotent. A workflow needs no such
|
|
4348
|
-
* care: a delivery starts one run however often it is tried, and the workflow
|
|
4349
|
-
* retries its own steps.
|
|
4350
|
-
*
|
|
4351
|
-
* @param config - `name` (unique; it is part of each delivery's id), `on` (an
|
|
4352
|
-
* event name or a list of them; a trailing `*` matches a prefix, as in
|
|
4353
|
-
* `user.*`), `run` or `workflow`, and optionally `maxAttempts`.
|
|
4354
|
-
* @returns The listener.
|
|
4355
|
-
* @throws When the name is empty or contains `:`, `on` is empty, or the listener
|
|
4356
|
-
* has both or neither of `run` and `workflow`.
|
|
4357
|
-
* @example
|
|
4358
|
-
* import { brick, defineListener } from "@brickkit/core";
|
|
4359
|
-
*
|
|
4360
|
-
* const welcome = defineListener({
|
|
4361
|
-
* name: "welcome-email",
|
|
4362
|
-
* on: "user.create",
|
|
4363
|
-
* run: async ({ payload, deliveryId }) => {
|
|
4364
|
-
* await mailer.sendWelcome(payload.row.email, { idempotencyKey: deliveryId });
|
|
4365
|
-
* },
|
|
4366
|
-
* });
|
|
4367
|
-
*
|
|
4368
|
-
* export default brick({ services, events: { listeners: [welcome] } });
|
|
4369
|
-
* @example
|
|
4370
|
-
* // src/workflows/onboard.ts
|
|
4371
|
-
* export async function onboard(event: WorkflowEvent<CrudEventPayload>) {
|
|
4372
|
-
* "use workflow";
|
|
4373
|
-
* await sendWelcome(event.payload.row.email);
|
|
4374
|
-
* }
|
|
4375
|
-
*
|
|
4376
|
-
* defineListener({ name: "onboard", on: "user.create", workflow: onboard });
|
|
4377
|
-
*/
|
|
4378
6001
|
function defineListener(config) {
|
|
4379
6002
|
if (typeof config.name !== "string" || !config.name) throw new Error("An event listener needs a name");
|
|
4380
6003
|
if (config.name.includes(":")) throw new Error(`Event listener name '${config.name}' must not contain ':'`);
|
|
4381
|
-
const on =
|
|
4382
|
-
if (!on.length || on.some((pattern) => !pattern)) throw new Error(`Event listener '${config.name}' listens for nothing`);
|
|
6004
|
+
const on = (Array.isArray(config.on) ? config.on : [config.on]).map((item) => isEventRef(item) ? item.name : item);
|
|
6005
|
+
if (!on.length || on.some((pattern) => !pattern || typeof pattern !== "string")) throw new Error(`Event listener '${config.name}' listens for nothing`);
|
|
4383
6006
|
if (config.maxAttempts !== void 0 && (!Number.isInteger(config.maxAttempts) || config.maxAttempts < 1)) throw new Error(`Event listener '${config.name}': maxAttempts must be a positive integer`);
|
|
4384
6007
|
const { name, run, workflow } = config;
|
|
4385
6008
|
if (run !== void 0 && workflow !== void 0) throw new Error(`Event listener '${name}' has both run and workflow; give it one`);
|
|
4386
6009
|
if (run === void 0 && workflow === void 0) throw new Error(`Event listener '${name}' needs a run handler or a workflow`);
|
|
4387
6010
|
if (run !== void 0 && typeof run !== "function") throw new Error(`Event listener '${name}': run must be a function`);
|
|
4388
6011
|
if (workflow !== void 0 && typeof workflow !== "function") throw new Error(`Event listener '${name}': workflow must be a function marked "use workflow"`);
|
|
6012
|
+
const helpers = buildErrorHelpers(config.errors);
|
|
4389
6013
|
return Object.freeze({
|
|
4390
6014
|
name: config.name,
|
|
4391
6015
|
on: Object.freeze(on),
|
|
4392
|
-
...config.run !== void 0 ? { run: config.run } : {},
|
|
6016
|
+
...config.run !== void 0 ? { run: ((delivery) => config.run(delivery, { error: helpers })) } : {},
|
|
6017
|
+
...config.errors ? { errors: config.errors } : {},
|
|
6018
|
+
...config.retry ? { retry: config.retry } : {},
|
|
4393
6019
|
...config.workflow !== void 0 ? { workflow: config.workflow } : {},
|
|
4394
6020
|
...config.maxAttempts !== void 0 ? { maxAttempts: config.maxAttempts } : {}
|
|
4395
6021
|
});
|
|
4396
6022
|
}
|
|
4397
6023
|
//#endregion
|
|
4398
6024
|
//#region src/events/emit.ts
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
*
|
|
4408
|
-
* @param ctx - The action context: its `db` finds the service's outbox, and its
|
|
4409
|
-
* `traceId` follows the event to its listeners.
|
|
4410
|
-
* @param name - The event name, such as `order.refunded`.
|
|
4411
|
-
* @param payload - JSON data for the listeners.
|
|
4412
|
-
* @param options - `tx`: an open transaction on the service's database. `source`:
|
|
4413
|
-
* what emitted it, shown to listeners.
|
|
4414
|
-
* @throws When the context's database has no outbox table, or the app has no
|
|
4415
|
-
* `events`.
|
|
4416
|
-
* @example
|
|
4417
|
-
* refund: service.action({
|
|
4418
|
-
* name: "refund",
|
|
4419
|
-
* execute: async ({ ctx, input }) => {
|
|
4420
|
-
* await ctx.db.update(orders).set({ status: "refunded" }).where(eq(orders.id, input.id));
|
|
4421
|
-
* await emitEvent(ctx, "order.refunded", { id: input.id });
|
|
4422
|
-
* },
|
|
4423
|
-
* });
|
|
4424
|
-
*/
|
|
4425
|
-
async function emitEvent(ctx, name, payload, options = {}) {
|
|
6025
|
+
async function emitEvent(ctx, event, payload, options = {}) {
|
|
6026
|
+
const name = typeof event === "string" ? event : event.name;
|
|
6027
|
+
if (typeof event !== "string") checkEvent({
|
|
6028
|
+
name: event.service,
|
|
6029
|
+
events: { [name.slice(event.service.length + 1)]: event },
|
|
6030
|
+
hasCatalog: true,
|
|
6031
|
+
listResources: () => []
|
|
6032
|
+
}, name, payload);
|
|
4426
6033
|
const events = ctx.db && typeof ctx.db === "object" ? recorders.get(ctx.db) : void 0;
|
|
4427
6034
|
if (!events) throw new Error(`Cannot emit '${name}': ctx.db is not the database of a service with an outbox table (the app needs events, and ctx.db must be the service's own database, not a transaction)`);
|
|
4428
6035
|
const context = {
|
|
@@ -4556,6 +6163,6 @@ function createMcpHandler(options) {
|
|
|
4556
6163
|
};
|
|
4557
6164
|
}
|
|
4558
6165
|
//#endregion
|
|
4559
|
-
export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, Dispatcher, EventsHub, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase,
|
|
6166
|
+
export { ACTION_ACCESS_KEY, ActionExecutionError, BrickServerError, BrickTransportError, Dispatcher, EventsHub, SecretRef, ServiceImpl, ServiceRegistry, Table, Type, UnknownToolError, ValidationError, and, asc, attachDatabase, bindCompiledApplication, blob, brick, brickVersion, buildErrorHelpers, buildFtsMatchQuery, compileBrickApplication, compileRoutePlan, compilerRuntime, createActionHandler, createBrickClient, createDatabase, createEndpointHandler, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, defineAction, defineDatabase, defineError, defineListener, definePlugin, defineResource, defineResourcePlugin, defineSecret, defineService, defineServicePlugin, defineTool, desc, emitEvent, emitHandlerFactory, endpointPaths, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, errorsOf, executeCompiledRoute, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getActionRoute, getCompiledCheck, getGlobalRegistry, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, hoistAnchoredSchemas, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isDatabaseHandle, isEventRef, isNotNull, isNull, isOutboxTable, isPluginInstance, isTool, kebabCase, like, listSecrets, loadCompiledBrickApp, loadRecord, lt, lte, ne, not, notInArray, onTransactionCommit, or, outboxTable, overrideSecret, overrideSecrets, port, primaryKey, real, redisBroker, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveEndpointDb, resolveSecrets, resolveWorkflowPaths, runInTransaction, satisfiesRange, scalarDocsHTML, serializeSocketSchema, setActionAccess, sql, sqliteTable, stopAllEvents, swaggerDocsHTML, syncSchema, t, text, toErrorResponse, toOpenApiPath, traceRoute, uniqueIndex, useDeps, useService, validateWithSchema };
|
|
4560
6167
|
|
|
4561
6168
|
//# sourceMappingURL=index.js.map
|