@brickkit/core 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/client.d.ts +52 -2769
- package/dist/chunks/client.js +397 -101
- package/dist/chunks/client.js.map +1 -1
- package/dist/chunks/server.d.ts +444 -0
- package/dist/chunks/server.js +4018 -0
- package/dist/chunks/server.js.map +1 -0
- package/dist/chunks/types.d.ts +2505 -0
- package/dist/client.d.ts +3 -2
- package/dist/client.js +1 -1
- package/dist/index.d.ts +332 -717
- package/dist/index.js +612 -4959
- package/dist/index.js.map +1 -1
- package/dist/pg.d.ts +0 -2
- package/dist/tanstack-query.d.ts +2 -3
- package/dist/tanstack-query.js +1 -2
- package/dist/tanstack-query.js.map +1 -1
- package/dist/testing.d.ts +31 -0
- package/dist/testing.js +46 -0
- package/dist/testing.js.map +1 -0
- package/dist/workflow.d.ts +74 -0
- package/dist/workflow.js +93 -0
- package/dist/workflow.js.map +1 -0
- package/package.json +32 -17
- package/dist/chunks/client.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/pg.d.ts.map +0 -1
- package/dist/tanstack-query.d.ts.map +0 -1
|
@@ -0,0 +1,4018 @@
|
|
|
1
|
+
import { A as byteLength, B as splitSeq, C as SOCKET_BUFFER_BYTES, D as SOCKET_PROTOCOL, E as SOCKET_MAX_BYTES, F as isSocketRoom, G as DuplicateNameError, H as GLOBAL_SYMBOL, I as isSocketSeq, K as ValidationError, L as replayFrame, M as encodeFrame, N as isControlEvent, O as SOCKET_TOKEN_PROTOCOL, P as isSocketEnvelope, R as replayHeadroom, S as actionMeta, T as SOCKET_CONTROL, U as SPAN, V as ATTR, W as ActionExecutionError, _ as pathParamNames, b as toOpenApiPath, c as DEFAULT_PREFIX, d as getActionRoute, g as ownerPath, h as joinRoute, k as STANDARD_ERRORS, l as actionOwners, m as isReadLike, p as inputSource, s as serializeSocketSchema, u as checkSegments, v as pluginRoutePath, w as SOCKET_CLOSE, x as kebabCase, y as routeKey, z as signSeq } from "./client.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
4
|
+
import { Type, Type as t } from "@sinclair/typebox";
|
|
5
|
+
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
6
|
+
import { formatWithOptions } from "node:util";
|
|
7
|
+
import { join, resolve } from "node:path";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
+
import { and, asc, eq, inArray, lt, lte, or, sql } from "drizzle-orm";
|
|
10
|
+
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
11
|
+
import { bigserial, index as index$1, integer as integer$1, jsonb, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
|
|
12
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
13
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
14
|
+
import { Elysia } from "elysia";
|
|
15
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
16
|
+
import { websocket } from "elysia/websocket";
|
|
17
|
+
// src/plugin-types.ts
|
|
18
|
+
/** Where a plugin route mounts: under the app prefix, its service, or its resource. */
|
|
19
|
+
const PLUGIN_ROUTE_SCOPES = [
|
|
20
|
+
"app",
|
|
21
|
+
"service",
|
|
22
|
+
"resource"
|
|
23
|
+
];
|
|
24
|
+
/** Which host a plugin descriptor installs on. Process-global, so descriptors survive a second core copy. */
|
|
25
|
+
const PLUGIN_KIND = Symbol.for("brickkit.plugin.kind");
|
|
26
|
+
/**
|
|
27
|
+
* The setup context's slot where a `definePlugin` setup hands over what to do
|
|
28
|
+
* once its install succeeds; a failed install drops it.
|
|
29
|
+
*/
|
|
30
|
+
const PLUGIN_COMMIT = Symbol.for("brickkit.plugin.commit");
|
|
31
|
+
// src/telemetry.ts
|
|
32
|
+
const INSTRUMENTATION_SCOPE = "@brickkit/core";
|
|
33
|
+
const MAX_TEXT_LENGTH = 500;
|
|
34
|
+
const MAX_STATEMENT_LENGTH = 2e3;
|
|
35
|
+
const DATABASE_INSTRUMENTED = Symbol.for("brickkit.telemetry.database");
|
|
36
|
+
const SQLITE_STATEMENT_METHODS = [
|
|
37
|
+
"all",
|
|
38
|
+
"get",
|
|
39
|
+
"run",
|
|
40
|
+
"values"
|
|
41
|
+
];
|
|
42
|
+
/** Run `fn` as a child of the active span, ending the span when its result settles. */
|
|
43
|
+
function withSpan(name, attributes, fn, kind = SpanKind.INTERNAL) {
|
|
44
|
+
return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(name, {
|
|
45
|
+
kind,
|
|
46
|
+
attributes
|
|
47
|
+
}, (span) => settle(fn, (outcome) => {
|
|
48
|
+
if (outcome.failed) recordThrown(span, outcome.error);
|
|
49
|
+
span.end();
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Add a child span for an in-process call, but only inside a request that is
|
|
54
|
+
* already traced. Calls made outside instrumented requests run unchanged.
|
|
55
|
+
*/
|
|
56
|
+
function withCallSpan(name, attributes, fn) {
|
|
57
|
+
return trace.getActiveSpan() ? withSpan(name, attributes, fn) : fn();
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Wrap a raw route handler so each of its requests gets a server span. Use it
|
|
61
|
+
* for routes registered directly on the app, outside actions and endpoints,
|
|
62
|
+
* such as auth or webhook routes. Spans are recorded whenever a tracer provider
|
|
63
|
+
* is registered; `brick({ telemetry })` does not apply to these routes.
|
|
64
|
+
*
|
|
65
|
+
* The wrapper forwards only the fields listed in `RawRouteContext`. Elysia
|
|
66
|
+
* decides what to parse from the handler's destructuring, and forwarding the
|
|
67
|
+
* whole context would parse the body and leave `request.json()` with nothing.
|
|
68
|
+
*/
|
|
69
|
+
function traceRoute(route, handler) {
|
|
70
|
+
return ({ request, headers, set, params, query }) => traceHttpRequest({
|
|
71
|
+
request,
|
|
72
|
+
headers,
|
|
73
|
+
set
|
|
74
|
+
}, request.method, route, () => handler({
|
|
75
|
+
request,
|
|
76
|
+
headers,
|
|
77
|
+
set,
|
|
78
|
+
params,
|
|
79
|
+
query
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Wrap one HTTP request in a server span. The span continues the caller's
|
|
84
|
+
* trace when a W3C `traceparent` arrives. Without an `x-trace-id` header, the
|
|
85
|
+
* request id Brick returns is the span's trace id, so clients can find the
|
|
86
|
+
* request in the dashboard.
|
|
87
|
+
*/
|
|
88
|
+
function traceHttpRequest(request, method, route, fn) {
|
|
89
|
+
const attributes = {
|
|
90
|
+
[ATTR.httpMethod]: method,
|
|
91
|
+
[ATTR.httpRoute]: route
|
|
92
|
+
};
|
|
93
|
+
if (request.request) attributes[ATTR.urlPath] = new URL(request.request.url).pathname;
|
|
94
|
+
const headers = request.headers ?? {};
|
|
95
|
+
const parent = propagation.extract(context.active(), headers);
|
|
96
|
+
return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(`${method} ${route}`, {
|
|
97
|
+
kind: SpanKind.SERVER,
|
|
98
|
+
attributes
|
|
99
|
+
}, parent, (span) => {
|
|
100
|
+
if (!headers["x-trace-id"]) headers["x-trace-id"] = span.spanContext().traceId;
|
|
101
|
+
const outgoing = {};
|
|
102
|
+
propagation.inject(context.active(), outgoing);
|
|
103
|
+
if (request.set?.headers) Object.assign(request.set.headers, outgoing);
|
|
104
|
+
return settle(fn, (outcome) => {
|
|
105
|
+
const status = outcome.failed ? 500 : outcome.value instanceof Response ? outcome.value.status : responseStatus(request.set?.status);
|
|
106
|
+
if (outcome.failed) recordThrown(span, outcome.error);
|
|
107
|
+
span.setAttribute(ATTR.httpStatus, status);
|
|
108
|
+
const traceId = headers["x-trace-id"];
|
|
109
|
+
if (traceId) span.setAttribute(ATTR.traceId, traceId);
|
|
110
|
+
if (status >= 500) span.setStatus({
|
|
111
|
+
code: SpanStatusCode.ERROR,
|
|
112
|
+
message: `HTTP ${status}`
|
|
113
|
+
});
|
|
114
|
+
span.end();
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Attach a handled failure to the active span. Brick returns these as
|
|
120
|
+
* responses rather than throwing, so only server faults (5xx) mark the span
|
|
121
|
+
* as errored; client errors keep their code as an attribute.
|
|
122
|
+
*/
|
|
123
|
+
function recordFailure(error, failure) {
|
|
124
|
+
const span = trace.getActiveSpan();
|
|
125
|
+
if (!span) return;
|
|
126
|
+
span.setAttributes({
|
|
127
|
+
[ATTR.errorCode]: failure.code,
|
|
128
|
+
[ATTR.errorStatus]: failure.status,
|
|
129
|
+
[ATTR.errorMessage]: truncate(failure.message)
|
|
130
|
+
});
|
|
131
|
+
if (failure.status >= 500) recordThrown(span, error);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Record SQL statements as client spans for the database behind a service.
|
|
135
|
+
* Drizzle's logger has no timing, so the hook sits on the driver: each
|
|
136
|
+
* statement is timed where the driver runs it. Statements outside traced
|
|
137
|
+
* requests are not recorded. Calling this again on the same client is a no-op.
|
|
138
|
+
*/
|
|
139
|
+
function instrumentDatabase(db) {
|
|
140
|
+
const client = db?.$client;
|
|
141
|
+
if (typeof client !== "object" && typeof client !== "function" || client === null) return;
|
|
142
|
+
const driver = client;
|
|
143
|
+
if (driver[DATABASE_INSTRUMENTED]) return;
|
|
144
|
+
if (typeof driver.prepare === "function") instrumentBunSqlite(driver);
|
|
145
|
+
else if (typeof driver.unsafe === "function") instrumentPostgres(driver);
|
|
146
|
+
else return;
|
|
147
|
+
driver[DATABASE_INSTRUMENTED] = true;
|
|
148
|
+
}
|
|
149
|
+
function instrumentBunSqlite(client) {
|
|
150
|
+
const prepare = client.prepare.bind(client);
|
|
151
|
+
client.prepare = (sql) => {
|
|
152
|
+
const statement = prepare(sql);
|
|
153
|
+
for (const method of SQLITE_STATEMENT_METHODS) {
|
|
154
|
+
const original = statement[method];
|
|
155
|
+
if (typeof original !== "function") continue;
|
|
156
|
+
statement[method] = (...args) => recordStatement(sql, "sqlite", () => original.apply(statement, args));
|
|
157
|
+
}
|
|
158
|
+
return statement;
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* postgres.js returns a query that runs when awaited, and `values()` returns
|
|
163
|
+
* that same object, so overriding `then` on it times the whole round trip.
|
|
164
|
+
*/
|
|
165
|
+
function instrumentPostgres(client) {
|
|
166
|
+
const unsafe = client.unsafe.bind(client);
|
|
167
|
+
client.unsafe = (sql, ...rest) => {
|
|
168
|
+
const query = unsafe(sql, ...rest);
|
|
169
|
+
if (!trace.getActiveSpan() || typeof query?.then !== "function") return query;
|
|
170
|
+
const span = startStatementSpan(sql, "postgresql");
|
|
171
|
+
let finished = false;
|
|
172
|
+
const finish = (outcome) => {
|
|
173
|
+
if (finished) return;
|
|
174
|
+
finished = true;
|
|
175
|
+
if (outcome.failed) recordThrown(span, outcome.error);
|
|
176
|
+
span.end();
|
|
177
|
+
};
|
|
178
|
+
const then = query.then.bind(query);
|
|
179
|
+
query.then = (onFulfilled, onRejected) => then((value) => {
|
|
180
|
+
finish({
|
|
181
|
+
failed: false,
|
|
182
|
+
value
|
|
183
|
+
});
|
|
184
|
+
return onFulfilled ? onFulfilled(value) : value;
|
|
185
|
+
}, (error) => {
|
|
186
|
+
finish({
|
|
187
|
+
failed: true,
|
|
188
|
+
error
|
|
189
|
+
});
|
|
190
|
+
if (onRejected) return onRejected(error);
|
|
191
|
+
throw error;
|
|
192
|
+
});
|
|
193
|
+
return query;
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function recordStatement(sql, system, fn) {
|
|
197
|
+
if (!trace.getActiveSpan()) return fn();
|
|
198
|
+
return withSpan(statementName(sql), statementAttributes(sql, system), fn, SpanKind.CLIENT);
|
|
199
|
+
}
|
|
200
|
+
function startStatementSpan(sql, system) {
|
|
201
|
+
return trace.getTracer(INSTRUMENTATION_SCOPE).startSpan(statementName(sql), {
|
|
202
|
+
kind: SpanKind.CLIENT,
|
|
203
|
+
attributes: statementAttributes(sql, system)
|
|
204
|
+
}, context.active());
|
|
205
|
+
}
|
|
206
|
+
function statementName(sql) {
|
|
207
|
+
return `SQL ${operationOf(sql)}`;
|
|
208
|
+
}
|
|
209
|
+
function statementAttributes(sql, system) {
|
|
210
|
+
return {
|
|
211
|
+
[ATTR.dbSystem]: system,
|
|
212
|
+
[ATTR.dbOperation]: operationOf(sql),
|
|
213
|
+
[ATTR.dbStatement]: truncate(sql, MAX_STATEMENT_LENGTH)
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function operationOf(sql) {
|
|
217
|
+
return sql.trim().split(/\s+/, 1)[0]?.toUpperCase() || "SQL";
|
|
218
|
+
}
|
|
219
|
+
function settle(fn, done) {
|
|
220
|
+
let result;
|
|
221
|
+
try {
|
|
222
|
+
result = fn();
|
|
223
|
+
} catch (error) {
|
|
224
|
+
done({
|
|
225
|
+
failed: true,
|
|
226
|
+
error
|
|
227
|
+
});
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
if (isPromiseLike(result)) return result.then((value) => {
|
|
231
|
+
done({
|
|
232
|
+
failed: false,
|
|
233
|
+
value
|
|
234
|
+
});
|
|
235
|
+
return value;
|
|
236
|
+
}, (error) => {
|
|
237
|
+
done({
|
|
238
|
+
failed: true,
|
|
239
|
+
error
|
|
240
|
+
});
|
|
241
|
+
throw error;
|
|
242
|
+
});
|
|
243
|
+
done({
|
|
244
|
+
failed: false,
|
|
245
|
+
value: result
|
|
246
|
+
});
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
249
|
+
function recordThrown(span, error) {
|
|
250
|
+
span.recordException(error instanceof Error ? error : String(error));
|
|
251
|
+
span.setStatus({
|
|
252
|
+
code: SpanStatusCode.ERROR,
|
|
253
|
+
message: truncate(messageOf(error))
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
function responseStatus(value) {
|
|
257
|
+
const status = typeof value === "number" ? value : Number(value ?? 200);
|
|
258
|
+
return Number.isInteger(status) ? status : 200;
|
|
259
|
+
}
|
|
260
|
+
function isPromiseLike(value) {
|
|
261
|
+
return typeof value === "object" && value !== null && typeof value.then === "function";
|
|
262
|
+
}
|
|
263
|
+
function messageOf(error) {
|
|
264
|
+
return error instanceof Error ? error.message : String(error);
|
|
265
|
+
}
|
|
266
|
+
function truncate(text, limit = MAX_TEXT_LENGTH) {
|
|
267
|
+
return text.length > limit ? `${text.slice(0, limit)}…` : text;
|
|
268
|
+
}
|
|
269
|
+
// src/error-response.ts
|
|
270
|
+
/** Preserve declared failures, log and wrap unexpected throws without exposing internals. */
|
|
271
|
+
function normalizeActionError(err, { logger, requestId }) {
|
|
272
|
+
if (err instanceof ActionExecutionError || err instanceof ValidationError) return err;
|
|
273
|
+
logger.error("Unexpected action error", { requestId }, err);
|
|
274
|
+
const failure = new ActionExecutionError("INTERNAL_SERVER_ERROR", "Internal Server Error", 500, void 0, { cause: err });
|
|
275
|
+
failure.name = "InternalServerError";
|
|
276
|
+
return failure;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Turn what an action threw into the JSON body of its HTTP response, and record
|
|
280
|
+
* the failure on the active trace. Declared failures and validation errors keep
|
|
281
|
+
* their code, status, and details; anything else is logged and answered as a
|
|
282
|
+
* generic `INTERNAL_SERVER_ERROR` (500) so internals are never exposed.
|
|
283
|
+
*
|
|
284
|
+
* @param err - Whatever was thrown.
|
|
285
|
+
* @param context - A `logger` with `error()`, and the `requestId` to put in the body.
|
|
286
|
+
* @returns The envelope: `name`, `code`, `message`, `status`, `requestId`, and
|
|
287
|
+
* `details` or `errors` when there are any.
|
|
288
|
+
*/
|
|
289
|
+
function toErrorResponse(err, context) {
|
|
290
|
+
const envelope = buildErrorEnvelope(err, context);
|
|
291
|
+
recordFailure(err, envelope);
|
|
292
|
+
return envelope;
|
|
293
|
+
}
|
|
294
|
+
function buildErrorEnvelope(err, context) {
|
|
295
|
+
const failure = normalizeActionError(err, context);
|
|
296
|
+
if (failure.status >= 500 && (err instanceof ActionExecutionError || err instanceof ValidationError)) context.logger.error("Server action error", { requestId: context.requestId }, err);
|
|
297
|
+
if (failure instanceof ValidationError && failure.status >= 500) return {
|
|
298
|
+
name: failure.name,
|
|
299
|
+
code: failure.code,
|
|
300
|
+
message: failure.message,
|
|
301
|
+
status: failure.status,
|
|
302
|
+
requestId: context.requestId
|
|
303
|
+
};
|
|
304
|
+
return {
|
|
305
|
+
...failure.toJSON(),
|
|
306
|
+
requestId: context.requestId
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
// src/typebox.ts
|
|
310
|
+
const compilerCache = /* @__PURE__ */ new WeakMap();
|
|
311
|
+
/**
|
|
312
|
+
* The compiled validator for a TypeBox schema. Compiling is slow and checking
|
|
313
|
+
* is fast, so each schema is compiled once and kept for as long as the schema
|
|
314
|
+
* object lives.
|
|
315
|
+
*
|
|
316
|
+
* @param schema - A TypeBox schema.
|
|
317
|
+
* @returns Its `TypeCheck`, with `Check(value)` and `Errors(value)`.
|
|
318
|
+
*/
|
|
319
|
+
function getCompiledCheck(schema) {
|
|
320
|
+
let compiled = compilerCache.get(schema);
|
|
321
|
+
if (!compiled) {
|
|
322
|
+
compiled = TypeCompiler.Compile(schema);
|
|
323
|
+
compilerCache.set(schema, compiled);
|
|
324
|
+
}
|
|
325
|
+
return compiled;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Check a value against a schema, the way actions check their input and output.
|
|
329
|
+
*
|
|
330
|
+
* @param schema - A TypeBox schema, or `undefined` to accept anything.
|
|
331
|
+
* @param value - The value to check.
|
|
332
|
+
* @returns `{ success: true, data }`, or `{ success: false, errors }` with a
|
|
333
|
+
* `path`, `message`, `type`, and the offending `value` for each problem.
|
|
334
|
+
*/
|
|
335
|
+
function validateWithSchema(schema, value) {
|
|
336
|
+
if (!schema) return {
|
|
337
|
+
success: true,
|
|
338
|
+
data: value
|
|
339
|
+
};
|
|
340
|
+
const check = getCompiledCheck(schema);
|
|
341
|
+
if (check.Check(value)) return {
|
|
342
|
+
success: true,
|
|
343
|
+
data: value
|
|
344
|
+
};
|
|
345
|
+
const errors = [];
|
|
346
|
+
for (const error of check.Errors(value)) errors.push({
|
|
347
|
+
path: error.path,
|
|
348
|
+
message: error.message,
|
|
349
|
+
value: error.value,
|
|
350
|
+
type: error.type
|
|
351
|
+
});
|
|
352
|
+
return {
|
|
353
|
+
success: false,
|
|
354
|
+
errors
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
// src/logger.ts
|
|
358
|
+
/**
|
|
359
|
+
* Set by the CLI when a dashboard is collecting logs, in `brick dev` or in
|
|
360
|
+
* `brick start` with the `dashboard` option. A shared symbol, not an option or
|
|
361
|
+
* an export: the CLI and the app may each hold their own copy of this package,
|
|
362
|
+
* and nothing but a dashboard turns it on.
|
|
363
|
+
*/
|
|
364
|
+
const CAPTURE = Symbol.for(GLOBAL_SYMBOL.logsCapture);
|
|
365
|
+
const MAX_MESSAGE_LENGTH = 4e3;
|
|
366
|
+
/**
|
|
367
|
+
* Logs one span keeps. OpenTelemetry keeps 128 events per span by default,
|
|
368
|
+
* exceptions among them, so a chatty action must not use them all up and
|
|
369
|
+
* lose the stack trace of the error that ends it.
|
|
370
|
+
*/
|
|
371
|
+
const MAX_LOGS_PER_SPAN = 100;
|
|
372
|
+
const logged = /* @__PURE__ */ new WeakMap();
|
|
373
|
+
/**
|
|
374
|
+
* Terminal formatting: colors and styles (`ESC [ … m`, and other CSI codes) and
|
|
375
|
+
* titles or links (`ESC ] … BEL`). Libraries such as Better Auth color their
|
|
376
|
+
* console output, which in a web page shows as stray characters.
|
|
377
|
+
*/
|
|
378
|
+
const ANSI = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\))/g;
|
|
379
|
+
function stripAnsi(text) {
|
|
380
|
+
return text.includes("\x1B") ? text.replace(ANSI, "") : text;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* What `console.log` would print, without terminal colors, with objects cut off
|
|
384
|
+
* at a sensible size.
|
|
385
|
+
*/
|
|
386
|
+
function render(args) {
|
|
387
|
+
const text = stripAnsi(formatWithOptions({
|
|
388
|
+
depth: 3,
|
|
389
|
+
breakLength: 120,
|
|
390
|
+
maxArrayLength: 50,
|
|
391
|
+
maxStringLength: 1e3
|
|
392
|
+
}, ...args));
|
|
393
|
+
return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text;
|
|
394
|
+
}
|
|
395
|
+
function record(span, level, args) {
|
|
396
|
+
const count = (logged.get(span) ?? 0) + 1;
|
|
397
|
+
logged.set(span, count);
|
|
398
|
+
if (count > MAX_LOGS_PER_SPAN) {
|
|
399
|
+
span.setAttribute(ATTR.logsDropped, count - MAX_LOGS_PER_SPAN);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
span.addEvent(SPAN.logEvent, {
|
|
403
|
+
[ATTR.logLevel]: level,
|
|
404
|
+
[ATTR.logMessage]: render(args)
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Record a line on the running span, if a recording one is running. Returns
|
|
409
|
+
* whether it did, so the caller prints only when it did not.
|
|
410
|
+
*/
|
|
411
|
+
function recordActive(level, args) {
|
|
412
|
+
const span = trace.getActiveSpan();
|
|
413
|
+
if (!span?.isRecording()) return false;
|
|
414
|
+
record(span, level, args);
|
|
415
|
+
return true;
|
|
416
|
+
}
|
|
417
|
+
globalThis[Symbol.for(GLOBAL_SYMBOL.logsRecord)] = recordActive;
|
|
418
|
+
/**
|
|
419
|
+
* A logger for actions, tools, and endpoints. While a dashboard is on, a line
|
|
420
|
+
* logged while a request is being traced becomes an event on the span that is
|
|
421
|
+
* running, which the dashboard shows with that request (and in its Logs tab);
|
|
422
|
+
* it is not printed. Everywhere else, and for lines logged outside a request,
|
|
423
|
+
* it prints to the console, prefixed by `prefix`: one for all levels, or one
|
|
424
|
+
* per level.
|
|
425
|
+
*
|
|
426
|
+
* Capturing costs one context lookup and a span event per line, and nothing
|
|
427
|
+
* is serialized for the dashboard until the span ends, so it is cheaper than
|
|
428
|
+
* a console write. Lines are cut at 4,000 characters and a span keeps 100.
|
|
429
|
+
*/
|
|
430
|
+
function createLogger(prefix) {
|
|
431
|
+
const level = (name, print) => (...args) => {
|
|
432
|
+
if (globalThis[CAPTURE] === true && recordActive(name, args)) return;
|
|
433
|
+
print(typeof prefix === "string" ? prefix : prefix[name], ...args);
|
|
434
|
+
};
|
|
435
|
+
return {
|
|
436
|
+
info: level("info", (...args) => console.log(...args)),
|
|
437
|
+
warn: level("warn", (...args) => console.warn(...args)),
|
|
438
|
+
error: level("error", (...args) => console.error(...args)),
|
|
439
|
+
debug: level("debug", (...args) => console.debug(...args))
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
/** The prefixes of loggers a caller did not supply. */
|
|
443
|
+
const DEFAULT_LOG_PREFIXES = {
|
|
444
|
+
info: "[INFO]",
|
|
445
|
+
warn: "[WARN]",
|
|
446
|
+
error: "[ERROR]",
|
|
447
|
+
debug: "[DEBUG]"
|
|
448
|
+
};
|
|
449
|
+
// src/context.ts
|
|
450
|
+
const DEFAULT_REQUEST = new Request("http://localhost");
|
|
451
|
+
const EMPTY = Object.freeze({});
|
|
452
|
+
const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
|
|
453
|
+
/** Random, so ids never repeat across restarts or processes. */
|
|
454
|
+
const newId = (kind) => `${kind}_${crypto.randomUUID()}`;
|
|
455
|
+
/**
|
|
456
|
+
* The trace and request ids of an HTTP request: the caller's `x-trace-id` and
|
|
457
|
+
* `x-request-id` headers, else fresh ones. Both are echoed on the response.
|
|
458
|
+
*/
|
|
459
|
+
function requestIds(headers, set) {
|
|
460
|
+
const traceId = headers?.["x-trace-id"] || newId("tr");
|
|
461
|
+
const requestId = headers?.["x-request-id"] || newId("req");
|
|
462
|
+
if (set?.headers) {
|
|
463
|
+
set.headers["x-trace-id"] = traceId;
|
|
464
|
+
set.headers["x-request-id"] = requestId;
|
|
465
|
+
}
|
|
466
|
+
return {
|
|
467
|
+
traceId,
|
|
468
|
+
requestId
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* The framework fields of an action context: what the caller gave, the rest
|
|
473
|
+
* defaulted. A missing trace or request id gets a fresh `tr_`/`req_` one.
|
|
474
|
+
*/
|
|
475
|
+
function baseContext(fields) {
|
|
476
|
+
return {
|
|
477
|
+
request: fields.request ?? DEFAULT_REQUEST,
|
|
478
|
+
db: fields.db,
|
|
479
|
+
logger: fields.logger ?? defaultLogger,
|
|
480
|
+
traceId: fields.traceId ?? newId("tr"),
|
|
481
|
+
requestId: fields.requestId ?? newId("req"),
|
|
482
|
+
services: fields.services ?? EMPTY,
|
|
483
|
+
metadata: fields.metadata ?? EMPTY,
|
|
484
|
+
deps: fields.deps ?? EMPTY
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
function pickContextEnvelope(context) {
|
|
488
|
+
if (!context) return {};
|
|
489
|
+
const envelope = {};
|
|
490
|
+
if (context.caller !== void 0) envelope.caller = context.caller;
|
|
491
|
+
if (context.user !== void 0) envelope.user = context.user;
|
|
492
|
+
if (context.traceId !== void 0) envelope.traceId = context.traceId;
|
|
493
|
+
if (context.requestId !== void 0) envelope.requestId = context.requestId;
|
|
494
|
+
if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
|
|
495
|
+
return envelope;
|
|
496
|
+
}
|
|
497
|
+
// src/compiler/runtime.ts
|
|
498
|
+
function isNonEmpty(value) {
|
|
499
|
+
if (value == null) return false;
|
|
500
|
+
for (const _ in value) return true;
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
/** One source alone is the input as it is; several merge, later ones winning. */
|
|
504
|
+
function mergeInput(first, second, third) {
|
|
505
|
+
const a = isNonEmpty(first), b = isNonEmpty(second), c = isNonEmpty(third);
|
|
506
|
+
if (a && !b && !c) return first;
|
|
507
|
+
if (b && !a && !c) return second;
|
|
508
|
+
if (c && !a && !b) return third;
|
|
509
|
+
if (a || b || c) return Object.assign({}, first, second, third);
|
|
510
|
+
}
|
|
511
|
+
function coerceQueryValue(value, type, request, key) {
|
|
512
|
+
if (type === "number") {
|
|
513
|
+
const number = Number(value);
|
|
514
|
+
return Number.isNaN(number) ? value : number;
|
|
515
|
+
}
|
|
516
|
+
if (type === "array") {
|
|
517
|
+
const values = request ? new URL(request.url).searchParams.getAll(key) : [];
|
|
518
|
+
return values.length ? values : Array.isArray(value) ? value : [value];
|
|
519
|
+
}
|
|
520
|
+
if (value === "true" || value === "1") return true;
|
|
521
|
+
if (value === "false" || value === "0") return false;
|
|
522
|
+
return value;
|
|
523
|
+
}
|
|
524
|
+
/** The action's input from the path, query and body, coerced by its schema. */
|
|
525
|
+
function readInput(route, { params, body, query, request }) {
|
|
526
|
+
if (!route.input) return void 0;
|
|
527
|
+
let coercedQuery = query;
|
|
528
|
+
let coercedParams = params;
|
|
529
|
+
if (route.coercions.length) {
|
|
530
|
+
if (query) {
|
|
531
|
+
coercedQuery = { ...query };
|
|
532
|
+
for (const { key, type } of route.coercions) if (query[key] !== void 0) coercedQuery[key] = coerceQueryValue(query[key], type, request, key);
|
|
533
|
+
}
|
|
534
|
+
for (const { key, type } of route.coercions) {
|
|
535
|
+
if (type !== "number" || typeof params?.[key] !== "string") continue;
|
|
536
|
+
const value = Number(params[key]);
|
|
537
|
+
if (Number.isNaN(value)) continue;
|
|
538
|
+
if (coercedParams === params) coercedParams = { ...params };
|
|
539
|
+
coercedParams[key] = value;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const input = route.readLike ? mergeInput(coercedQuery, coercedParams, body) : mergeInput(coercedParams, body, coercedQuery);
|
|
543
|
+
return input === void 0 && route.inputSchema?.type === "object" ? {} : input;
|
|
544
|
+
}
|
|
545
|
+
const MAX_INPUT_DEPTH = 128;
|
|
546
|
+
function inputTooDeep(value) {
|
|
547
|
+
if (!value || typeof value !== "object") return false;
|
|
548
|
+
const stack = [{
|
|
549
|
+
node: value,
|
|
550
|
+
depth: 0
|
|
551
|
+
}];
|
|
552
|
+
while (stack.length > 0) {
|
|
553
|
+
const { node, depth } = stack.pop();
|
|
554
|
+
if (depth > MAX_INPUT_DEPTH) return true;
|
|
555
|
+
if (node && typeof node === "object") {
|
|
556
|
+
const children = Array.isArray(node) ? node : Object.values(node);
|
|
557
|
+
for (const child of children) if (child && typeof child === "object") stack.push({
|
|
558
|
+
node: child,
|
|
559
|
+
depth: depth + 1
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return false;
|
|
564
|
+
}
|
|
565
|
+
/** The error for input (400) or output (500) that fails its schema. */
|
|
566
|
+
function invalid(action, stage, errors) {
|
|
567
|
+
return new ValidationError(`Validation failed for action '${action}' ${stage}`, errors, stage === "output" ? 500 : 400);
|
|
568
|
+
}
|
|
569
|
+
function validate(check, value, action, stage) {
|
|
570
|
+
if (check.Check(value)) return;
|
|
571
|
+
throw invalid(action, stage, Array.from(check.Errors(value)).map((err) => ({
|
|
572
|
+
path: err.path,
|
|
573
|
+
message: err.message,
|
|
574
|
+
value: err.value
|
|
575
|
+
})));
|
|
576
|
+
}
|
|
577
|
+
function validateInput(check, input, action, checkInput) {
|
|
578
|
+
const errors = checkInput?.(input);
|
|
579
|
+
if (errors) throw invalid(action, "input", errors);
|
|
580
|
+
if (inputTooDeep(input)) throw invalid(action, "input", [{
|
|
581
|
+
path: "",
|
|
582
|
+
message: "Input exceeds maximum nesting depth"
|
|
583
|
+
}]);
|
|
584
|
+
validate(check, input, action, "input");
|
|
585
|
+
}
|
|
586
|
+
/** A refused `authorize`: 401 without a user, 403 with one. */
|
|
587
|
+
function deny(action, user) {
|
|
588
|
+
throw new ActionExecutionError(user == null ? "UNAUTHORIZED" : "FORBIDDEN", `Access denied for action '${action}'`, user == null ? 401 : 403);
|
|
589
|
+
}
|
|
590
|
+
/** Runs `authorize`, if any, and denies the call when it refuses. */
|
|
591
|
+
async function authorizeCall(authorize, ctx, input, action) {
|
|
592
|
+
if (authorize && !await authorize({
|
|
593
|
+
ctx,
|
|
594
|
+
input,
|
|
595
|
+
user: ctx.user
|
|
596
|
+
})) deny(action, ctx.user);
|
|
597
|
+
}
|
|
598
|
+
/** The stage order of every call, over HTTP and in-process: check input → authorize → execute → check output. */
|
|
599
|
+
async function runStages(stages, input, ctx) {
|
|
600
|
+
stages.checkInput(input);
|
|
601
|
+
await authorizeCall(stages.authorize, ctx, input, stages.name);
|
|
602
|
+
return stages.checkOutput(await stages.execute({
|
|
603
|
+
input,
|
|
604
|
+
ctx,
|
|
605
|
+
error: stages.errorBuilder
|
|
606
|
+
}));
|
|
607
|
+
}
|
|
608
|
+
function mapError(err, set, options) {
|
|
609
|
+
const response = toErrorResponse(err, options);
|
|
610
|
+
set.status = response.status;
|
|
611
|
+
return response;
|
|
612
|
+
}
|
|
613
|
+
const isThenable = (value) => value != null && typeof value.then === "function";
|
|
614
|
+
/** The context of one HTTP request, with the trace and request id headers set. */
|
|
615
|
+
function requestContext(plan, { headers, request, set }) {
|
|
616
|
+
return baseContext({
|
|
617
|
+
...requestIds(headers, set),
|
|
618
|
+
request: request instanceof Request ? request : void 0,
|
|
619
|
+
db: plan.cachedDb ?? plan.service.getDb(),
|
|
620
|
+
logger: plan.logger,
|
|
621
|
+
metadata: { headers },
|
|
622
|
+
deps: plan.contextHook ? plan.service.deps : plan.deps ?? plan.service.deps
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
/** The HTTP handler of one route: the pipeline's stages, synchronous when no stage needs to wait. */
|
|
626
|
+
function bindRoute(plan) {
|
|
627
|
+
const { route, execute, contextHook, authorize, inputChecker, outputChecker, checkInput, errorBuilder } = plan;
|
|
628
|
+
const name = route.action;
|
|
629
|
+
const stages = {
|
|
630
|
+
name,
|
|
631
|
+
checkInput: (input) => {
|
|
632
|
+
if (inputChecker) validateInput(inputChecker, input, name, checkInput);
|
|
633
|
+
},
|
|
634
|
+
authorize,
|
|
635
|
+
execute,
|
|
636
|
+
errorBuilder,
|
|
637
|
+
checkOutput: (result) => {
|
|
638
|
+
if (outputChecker) validate(outputChecker, result, name, "output");
|
|
639
|
+
return result;
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
if (contextHook || authorize) return async function brickAction(context) {
|
|
643
|
+
const input = readInput(route, context);
|
|
644
|
+
const ctx = requestContext(plan, context);
|
|
645
|
+
try {
|
|
646
|
+
if (contextHook) {
|
|
647
|
+
const extra = await contextHook(ctx);
|
|
648
|
+
if (extra) Object.assign(ctx, extra);
|
|
649
|
+
if (plan.deps) ctx.deps = plan.deps;
|
|
650
|
+
}
|
|
651
|
+
return await runStages(stages, input, ctx);
|
|
652
|
+
} catch (err) {
|
|
653
|
+
return mapError(err, context.set, ctx);
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
return function brickAction(context) {
|
|
657
|
+
const input = readInput(route, context);
|
|
658
|
+
const ctx = requestContext(plan, context);
|
|
659
|
+
try {
|
|
660
|
+
stages.checkInput(input);
|
|
661
|
+
const result = execute({
|
|
662
|
+
input,
|
|
663
|
+
ctx,
|
|
664
|
+
error: errorBuilder
|
|
665
|
+
});
|
|
666
|
+
if (isThenable(result)) return Promise.resolve(result).then(stages.checkOutput).catch((err) => mapError(err, context.set, ctx));
|
|
667
|
+
return stages.checkOutput(result);
|
|
668
|
+
} catch (err) {
|
|
669
|
+
return mapError(err, context.set, ctx);
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
/** What `bindCompiledApplication`'s handler factories receive. */
|
|
674
|
+
const compilerRuntime = Object.freeze({ bindRoute });
|
|
675
|
+
// src/action.ts
|
|
676
|
+
/**
|
|
677
|
+
* The `error` helpers an action receives: one function per error code that
|
|
678
|
+
* throws an `ActionExecutionError` with that code and status. The standard HTTP
|
|
679
|
+
* codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
|
|
680
|
+
* `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
|
|
681
|
+
* them or replace one.
|
|
682
|
+
*
|
|
683
|
+
* @param errorsDef - The action's `errors`: for each code, its `message` and
|
|
684
|
+
* `status` (default 400).
|
|
685
|
+
* @returns Helpers that take an optional message, `details`, and `ErrorOptions`,
|
|
686
|
+
* and always throw.
|
|
687
|
+
*/
|
|
688
|
+
function buildErrorHelpers(errorsDef) {
|
|
689
|
+
const helpers = {};
|
|
690
|
+
for (const [code, def] of Object.entries({
|
|
691
|
+
...STANDARD_ERRORS,
|
|
692
|
+
...errorsDef
|
|
693
|
+
})) helpers[code] = (overrideMessage, details, options) => {
|
|
694
|
+
throw new ActionExecutionError(code, overrideMessage || def.message, def.status || 400, details, options);
|
|
695
|
+
};
|
|
696
|
+
return helpers;
|
|
697
|
+
}
|
|
698
|
+
/** The `errors` map of an action, to re-declare in another action or listener: `errors: { ...errorsOf(charge) }`. */
|
|
699
|
+
function errorsOf(action) {
|
|
700
|
+
return action.config.errors ?? {};
|
|
701
|
+
}
|
|
702
|
+
function defineAction(config) {
|
|
703
|
+
const errorHelpers = buildErrorHelpers(config.errors);
|
|
704
|
+
const actionFn = (async (params) => {
|
|
705
|
+
return actionFn.execute(params);
|
|
706
|
+
});
|
|
707
|
+
Object.defineProperty(actionFn, "name", {
|
|
708
|
+
value: config.name,
|
|
709
|
+
configurable: true
|
|
710
|
+
});
|
|
711
|
+
actionFn.config = config;
|
|
712
|
+
actionFn.errorHelpers = errorHelpers;
|
|
713
|
+
actionFn.validateInput = (input) => {
|
|
714
|
+
const errors = actionMeta(actionFn).checkInput?.(input);
|
|
715
|
+
return errors ? {
|
|
716
|
+
success: false,
|
|
717
|
+
errors
|
|
718
|
+
} : validateWithSchema(config.input, input);
|
|
719
|
+
};
|
|
720
|
+
actionFn.validateOutput = (output) => validateWithSchema(actionMeta(actionFn).runtimeOutput ?? config.output, output);
|
|
721
|
+
actionFn.run = async (input, ctx) => {
|
|
722
|
+
return actionFn.execute({
|
|
723
|
+
input,
|
|
724
|
+
ctx
|
|
725
|
+
});
|
|
726
|
+
};
|
|
727
|
+
const stages = {
|
|
728
|
+
name: config.name,
|
|
729
|
+
checkInput: (input) => {
|
|
730
|
+
if (!config.input) return;
|
|
731
|
+
const checked = actionFn.validateInput(input);
|
|
732
|
+
if (!checked.success) throw invalid(config.name, "input", checked.errors);
|
|
733
|
+
},
|
|
734
|
+
authorize: config.authorize,
|
|
735
|
+
execute: config.execute,
|
|
736
|
+
errorBuilder: errorHelpers,
|
|
737
|
+
checkOutput: (result) => {
|
|
738
|
+
if (!(actionMeta(actionFn).runtimeOutput ?? config.output)) return result;
|
|
739
|
+
const checked = actionFn.validateOutput(result);
|
|
740
|
+
if (!checked.success) throw invalid(config.name, "output", checked.errors);
|
|
741
|
+
return result;
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
actionFn.execute = async (params) => {
|
|
745
|
+
const meta = actionMeta(actionFn);
|
|
746
|
+
const ctx = meta.service ? await meta.service.resolveContext(params?.ctx, meta.deps?.values) : {
|
|
747
|
+
...baseContext(params?.ctx ?? {}),
|
|
748
|
+
...params?.ctx
|
|
749
|
+
};
|
|
750
|
+
try {
|
|
751
|
+
return await runStages(stages, params?.input, ctx);
|
|
752
|
+
} catch (err) {
|
|
753
|
+
throw normalizeActionError(err, ctx);
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
return actionFn;
|
|
757
|
+
}
|
|
758
|
+
// src/http.ts
|
|
759
|
+
/** The HTTP methods an action, endpoint or plugin route can use. */
|
|
760
|
+
const HTTP_METHODS = [
|
|
761
|
+
"GET",
|
|
762
|
+
"POST",
|
|
763
|
+
"PUT",
|
|
764
|
+
"PATCH",
|
|
765
|
+
"DELETE"
|
|
766
|
+
];
|
|
767
|
+
// src/service-port.ts
|
|
768
|
+
/** The port of a service: every `Service` is a `ServicePort`. */
|
|
769
|
+
function portOf(service) {
|
|
770
|
+
return service;
|
|
771
|
+
}
|
|
772
|
+
// src/plugin.ts
|
|
773
|
+
/**
|
|
774
|
+
* Define a plugin that installs onto a service with `service.use(plugin)`. Its
|
|
775
|
+
* `setup` receives the service and a `routes` registrar for adding actions and
|
|
776
|
+
* raw HTTP endpoints, and returns the typed API that `service.use` hands back.
|
|
777
|
+
*
|
|
778
|
+
* @param definition - A unique `name`, optional `routes` controls that let the
|
|
779
|
+
* user move or switch off the plugin's routes, and `setup`, which must be
|
|
780
|
+
* synchronous.
|
|
781
|
+
* @returns The plugin descriptor, frozen.
|
|
782
|
+
* @throws When the name is empty or has surrounding whitespace.
|
|
783
|
+
* @example
|
|
784
|
+
* import { defineServicePlugin, t } from "@brickkit/core";
|
|
785
|
+
*
|
|
786
|
+
* export const greeting = (salutation = "Hello") =>
|
|
787
|
+
* defineServicePlugin({
|
|
788
|
+
* name: "example/greeting",
|
|
789
|
+
* setup({ routes }) {
|
|
790
|
+
* const hello = routes.action({
|
|
791
|
+
* name: "hello",
|
|
792
|
+
* input: t.Object({ name: t.String() }),
|
|
793
|
+
* output: t.String(),
|
|
794
|
+
* execute: ({ input }) => `${salutation}, ${input.name}!`,
|
|
795
|
+
* });
|
|
796
|
+
* return { hello };
|
|
797
|
+
* },
|
|
798
|
+
* });
|
|
799
|
+
*
|
|
800
|
+
* const api = greeterService.use(greeting("Welcome"));
|
|
801
|
+
* await api.hello({ input: { name: "Ada" } });
|
|
802
|
+
*/
|
|
803
|
+
function defineServicePlugin(definition) {
|
|
804
|
+
validateName(definition.name);
|
|
805
|
+
return Object.freeze({
|
|
806
|
+
...definition,
|
|
807
|
+
routes: copyControls(definition.routes),
|
|
808
|
+
[PLUGIN_KIND]: "service"
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Define a plugin that installs onto a resource (a table and its entity) with
|
|
813
|
+
* `resource.use(plugin)`. Its `setup` receives the service, the resource, and a
|
|
814
|
+
* `routes` registrar, whose routes mount under `${prefix}/${service}/${resource}`, and
|
|
815
|
+
* returns the typed API that `resource.use` hands back. `crud` is built this way.
|
|
816
|
+
*
|
|
817
|
+
* @param definition - A unique `name`, optional `routes` controls, and `setup`,
|
|
818
|
+
* which must be synchronous.
|
|
819
|
+
* @returns The plugin descriptor, frozen.
|
|
820
|
+
* @throws When the name is empty or has surrounding whitespace.
|
|
821
|
+
*/
|
|
822
|
+
function defineResourcePlugin(definition) {
|
|
823
|
+
validateName(definition.name);
|
|
824
|
+
return Object.freeze({
|
|
825
|
+
...definition,
|
|
826
|
+
routes: copyControls(definition.routes),
|
|
827
|
+
[PLUGIN_KIND]: "resource"
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
function validateName(name) {
|
|
831
|
+
if (!name || name.trim() !== name) throw new Error("Plugin and route names must be nonempty and have no surrounding whitespace");
|
|
832
|
+
}
|
|
833
|
+
function validatePath(path) {
|
|
834
|
+
if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("//") || path.split("/").some((part) => part === "." || part === "..")) throw new Error(`Invalid plugin route path '${path}'`);
|
|
835
|
+
}
|
|
836
|
+
function copyControls(controls) {
|
|
837
|
+
if (controls === void 0 || controls === false) return controls;
|
|
838
|
+
const result = Object.create(null);
|
|
839
|
+
for (const [name, value] of Object.entries(controls)) {
|
|
840
|
+
validateName(name);
|
|
841
|
+
if (value === false) {
|
|
842
|
+
result[name] = false;
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
if (value.path !== void 0) validatePath(value.path);
|
|
846
|
+
if (value.scope !== void 0 && !PLUGIN_ROUTE_SCOPES.includes(value.scope)) throw new Error(`Invalid plugin route scope '${value.scope}'`);
|
|
847
|
+
result[name] = Object.freeze({ ...value });
|
|
848
|
+
}
|
|
849
|
+
return Object.freeze(result);
|
|
850
|
+
}
|
|
851
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
852
|
+
/** Records the plugin state; the returned function puts all of it back (a failed install's rollback). */
|
|
853
|
+
function snapshotState(state) {
|
|
854
|
+
const copy = (maps) => new Map([...maps].map(([key, inner]) => [key, new Map(inner)]));
|
|
855
|
+
const saved = {
|
|
856
|
+
hosts: copy(state.hosts),
|
|
857
|
+
actions: new Map(state.actions),
|
|
858
|
+
endpoints: [...state.endpoints],
|
|
859
|
+
claims: copy(state.claims)
|
|
860
|
+
};
|
|
861
|
+
return () => {
|
|
862
|
+
for (const action of state.actions.keys()) if (!saved.actions.has(action)) delete actionMeta(action).route;
|
|
863
|
+
Object.assign(state, saved);
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
function stateOf(service) {
|
|
867
|
+
let state = states.get(service);
|
|
868
|
+
if (!state) {
|
|
869
|
+
state = {
|
|
870
|
+
hosts: /* @__PURE__ */ new Map(),
|
|
871
|
+
actions: /* @__PURE__ */ new Map(),
|
|
872
|
+
endpoints: [],
|
|
873
|
+
claims: /* @__PURE__ */ new Map()
|
|
874
|
+
};
|
|
875
|
+
states.set(service, state);
|
|
876
|
+
}
|
|
877
|
+
return state;
|
|
878
|
+
}
|
|
879
|
+
function isInstallingPlugin(service) {
|
|
880
|
+
return [...states.get(service)?.hosts.values() ?? []].some((installations) => [...installations.values()].some((item) => item.status === "installing"));
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* The raw HTTP endpoints plugins registered on a service, ready to mount on the
|
|
884
|
+
* application. Each handler resolves the service's context before it runs.
|
|
885
|
+
*
|
|
886
|
+
* @param service - The service plugins were installed on.
|
|
887
|
+
* @param prefix - The application's route prefix (default `/api`).
|
|
888
|
+
* @returns The enabled endpoints: `path`, `method`, `handler`, and the
|
|
889
|
+
* `summary`, `description`, and `tags` for OpenAPI.
|
|
890
|
+
*/
|
|
891
|
+
function getPluginEndpoints(service, prefix = DEFAULT_PREFIX) {
|
|
892
|
+
return stateOf(service).endpoints.filter((binding) => binding.enabled).map((binding) => ({
|
|
893
|
+
path: pluginRoutePath(binding, prefix),
|
|
894
|
+
method: binding.method,
|
|
895
|
+
service,
|
|
896
|
+
plugin: binding.plugin,
|
|
897
|
+
summary: binding.summary,
|
|
898
|
+
description: binding.description,
|
|
899
|
+
tags: binding.tags,
|
|
900
|
+
handler: async (context) => binding.handler({
|
|
901
|
+
...context,
|
|
902
|
+
ctx: await service.resolveContext({ request: context.request })
|
|
903
|
+
})
|
|
904
|
+
}));
|
|
905
|
+
}
|
|
906
|
+
/** The plugin that claimed `segment` under `resource`, if one did. */
|
|
907
|
+
function segmentClaimant(service, resource, segment) {
|
|
908
|
+
return states.get(service)?.claims.get(resource)?.get(segment);
|
|
909
|
+
}
|
|
910
|
+
/** Descriptor identity is scoped to the service or resource installation host. */
|
|
911
|
+
function installPlugin(service, resource, descriptor) {
|
|
912
|
+
if (service.isBuilt) throw new Error("Plugins must be installed before service build");
|
|
913
|
+
if (descriptor[PLUGIN_KIND] !== (resource ? "resource" : "service") && descriptor[PLUGIN_KIND] !== "plugin") throw new Error("Plugin does not support this installation host");
|
|
914
|
+
const state = stateOf(service);
|
|
915
|
+
const host = resource ?? service;
|
|
916
|
+
const existing = state.hosts.get(host)?.get(descriptor.name);
|
|
917
|
+
if (existing) {
|
|
918
|
+
if (existing.status === "installing") throw new Error(`Plugin dependency cycle at '${descriptor.name}'`);
|
|
919
|
+
if (existing.descriptor !== descriptor) throw new Error(`Plugin '${descriptor.name}' already installed with a different descriptor; reuse the original descriptor`);
|
|
920
|
+
return resource ?? existing.api;
|
|
921
|
+
}
|
|
922
|
+
const restoreService = portOf(service).snapshot();
|
|
923
|
+
const restoreState = snapshotState(state);
|
|
924
|
+
const installations = state.hosts.get(host) ?? /* @__PURE__ */ new Map();
|
|
925
|
+
state.hosts.set(host, installations);
|
|
926
|
+
installations.set(descriptor.name, {
|
|
927
|
+
descriptor,
|
|
928
|
+
status: "installing"
|
|
929
|
+
});
|
|
930
|
+
const names = /* @__PURE__ */ new Set();
|
|
931
|
+
const commits = [];
|
|
932
|
+
const ownedActions = /* @__PURE__ */ new Set();
|
|
933
|
+
let active = true;
|
|
934
|
+
const claim = (segment) => {
|
|
935
|
+
if (!resource) throw new Error("Only resource plugins claim URL segments");
|
|
936
|
+
const claims = state.claims.get(resource) ?? /* @__PURE__ */ new Map();
|
|
937
|
+
state.claims.set(resource, claims);
|
|
938
|
+
if (claims.has(segment)) return;
|
|
939
|
+
const taken = service.listActions().find((action) => {
|
|
940
|
+
const info = actionMeta(action).resourceAction;
|
|
941
|
+
return info?.resource === resource.name && kebabCase(info.name) === segment;
|
|
942
|
+
});
|
|
943
|
+
if (taken) throw new DuplicateNameError(`Brick: duplicate name "${taken.name}" in service "${service.name}": "${segment}" is a ${descriptor.name} route`);
|
|
944
|
+
claims.set(segment, descriptor.name);
|
|
945
|
+
};
|
|
946
|
+
const bindingFor = (config) => {
|
|
947
|
+
if (!active || service.isBuilt) throw new Error("Plugin routes can only be registered during setup");
|
|
948
|
+
validateName(config.name);
|
|
949
|
+
validatePath(config.path);
|
|
950
|
+
if (names.has(config.name)) throw new DuplicateNameError(`Duplicate plugin route name '${config.name}'`);
|
|
951
|
+
names.add(config.name);
|
|
952
|
+
const control = descriptor.routes === false ? false : descriptor.routes?.[config.name];
|
|
953
|
+
const scope = control && control.scope || config.scope || (resource ? "resource" : "service");
|
|
954
|
+
if (scope === "resource" && !resource) throw new Error("Service plugin routes cannot use resource scope");
|
|
955
|
+
if (!PLUGIN_ROUTE_SCOPES.includes(scope)) throw new Error(`Invalid plugin route scope '${scope}'`);
|
|
956
|
+
if (!HTTP_METHODS.includes(config.method)) throw new Error(`Invalid plugin route method '${config.method}'`);
|
|
957
|
+
const path = control && control.path || config.path;
|
|
958
|
+
validatePath(path);
|
|
959
|
+
const segment = path.split("/")[1];
|
|
960
|
+
if (scope === "resource" && segment && !segment.startsWith(":")) claim(segment);
|
|
961
|
+
return {
|
|
962
|
+
service: service.name,
|
|
963
|
+
resource: resource?.name,
|
|
964
|
+
plugin: descriptor.name,
|
|
965
|
+
path,
|
|
966
|
+
method: config.method,
|
|
967
|
+
scope,
|
|
968
|
+
enabled: control !== false
|
|
969
|
+
};
|
|
970
|
+
};
|
|
971
|
+
const routes = {
|
|
972
|
+
action(config) {
|
|
973
|
+
const binding = bindingFor(config);
|
|
974
|
+
for (const name of pathParamNames(binding.path)) if (!config.input?.properties || !Object.hasOwn(config.input.properties, name)) throw new Error(`Plugin action path parameter '${name}' must be declared in its input schema`);
|
|
975
|
+
const name = `${resource ? `${resource.name}.` : ""}${config.name}`;
|
|
976
|
+
if (service.getAction(name)) throw new DuplicateNameError(`Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`);
|
|
977
|
+
const { scope: _scope, runtimeOutput, checkInput, ...actionConfig } = config;
|
|
978
|
+
const action = defineAction({
|
|
979
|
+
...actionConfig,
|
|
980
|
+
name
|
|
981
|
+
});
|
|
982
|
+
Object.assign(actionMeta(action), {
|
|
983
|
+
route: binding,
|
|
984
|
+
runtimeOutput,
|
|
985
|
+
checkInput
|
|
986
|
+
});
|
|
987
|
+
service.action(action);
|
|
988
|
+
ownedActions.add(action);
|
|
989
|
+
state.actions.set(action, binding);
|
|
990
|
+
return action;
|
|
991
|
+
},
|
|
992
|
+
endpoint(config) {
|
|
993
|
+
const binding = bindingFor(config);
|
|
994
|
+
state.endpoints.push({
|
|
995
|
+
...binding,
|
|
996
|
+
handler: config.handler,
|
|
997
|
+
summary: config.summary,
|
|
998
|
+
description: config.description,
|
|
999
|
+
tags: config.tags
|
|
1000
|
+
});
|
|
1001
|
+
},
|
|
1002
|
+
claim
|
|
1003
|
+
};
|
|
1004
|
+
try {
|
|
1005
|
+
const context = {
|
|
1006
|
+
service,
|
|
1007
|
+
...resource ? { resource } : {},
|
|
1008
|
+
routes,
|
|
1009
|
+
[PLUGIN_COMMIT]: (commit) => commits.push(commit)
|
|
1010
|
+
};
|
|
1011
|
+
const api = resource ? descriptor.setup(context) : descriptor.setup(context);
|
|
1012
|
+
if (api && typeof api === "object" && "then" in api) throw new Error("Plugin setup must be synchronous");
|
|
1013
|
+
if (descriptor.routes && Object.keys(descriptor.routes).some((name) => !names.has(name))) throw new Error(`Plugin '${descriptor.name}' has an override for an unknown route`);
|
|
1014
|
+
const walk = (value, path, ancestors) => {
|
|
1015
|
+
if (typeof value === "function") {
|
|
1016
|
+
const binding = state.actions.get(value);
|
|
1017
|
+
if (binding && ownedActions.has(value)) {
|
|
1018
|
+
if (binding.clientPath) throw new Error("Plugin actions must have one returned API path");
|
|
1019
|
+
binding.clientPath = resource ? [
|
|
1020
|
+
service.name,
|
|
1021
|
+
resource.name,
|
|
1022
|
+
...path
|
|
1023
|
+
] : [service.name, ...path];
|
|
1024
|
+
}
|
|
1025
|
+
} else if (value && typeof value === "object" && !ancestors.has(value)) {
|
|
1026
|
+
const next = new Set(ancestors).add(value);
|
|
1027
|
+
for (const [key, child] of Object.entries(value)) walk(child, [...path, key], next);
|
|
1028
|
+
}
|
|
1029
|
+
};
|
|
1030
|
+
walk(api, [], /* @__PURE__ */ new Set());
|
|
1031
|
+
if (resource) {
|
|
1032
|
+
if (!api || typeof api !== "object" || Array.isArray(api)) throw new Error("Resource plugins must return named API contributions");
|
|
1033
|
+
for (const key of Object.keys(api)) if (key in resource || [
|
|
1034
|
+
"__proto__",
|
|
1035
|
+
"prototype",
|
|
1036
|
+
"constructor"
|
|
1037
|
+
].includes(key)) throw new Error(`Resource plugin contribution '${key}' collides with an existing property`);
|
|
1038
|
+
Object.assign(resource, api);
|
|
1039
|
+
}
|
|
1040
|
+
state.hosts.get(host).set(descriptor.name, {
|
|
1041
|
+
descriptor,
|
|
1042
|
+
status: "installed",
|
|
1043
|
+
api
|
|
1044
|
+
});
|
|
1045
|
+
for (const commit of commits) commit();
|
|
1046
|
+
return resource ?? api;
|
|
1047
|
+
} catch (error) {
|
|
1048
|
+
restoreService();
|
|
1049
|
+
restoreState();
|
|
1050
|
+
throw error;
|
|
1051
|
+
} finally {
|
|
1052
|
+
active = false;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
/** Whether a plugin named `name` is installed on `host` (the service or a resource). */
|
|
1056
|
+
function hasPlugin(service, host, name) {
|
|
1057
|
+
return states.get(service)?.hosts.get(host)?.get(name)?.status === "installed";
|
|
1058
|
+
}
|
|
1059
|
+
/** Every descriptor installed on the service or its resources, in install order per host. */
|
|
1060
|
+
function installedPlugins(service) {
|
|
1061
|
+
return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
|
|
1062
|
+
}
|
|
1063
|
+
// src/deps.ts
|
|
1064
|
+
/**
|
|
1065
|
+
* Declare a dependency a service needs, without creating it. The app provides
|
|
1066
|
+
* the value with `brick({ deps })`, and the service's code reads it as
|
|
1067
|
+
* `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).
|
|
1068
|
+
*
|
|
1069
|
+
* @returns A slot typed as `T`. It holds nothing at runtime.
|
|
1070
|
+
* @example
|
|
1071
|
+
* import { defineService, port } from "@brickkit/core";
|
|
1072
|
+
*
|
|
1073
|
+
* export const orders = defineService("orders", {
|
|
1074
|
+
* database,
|
|
1075
|
+
* deps: { carrier: port<Carrier>() },
|
|
1076
|
+
* });
|
|
1077
|
+
*
|
|
1078
|
+
* // app.ts
|
|
1079
|
+
* export default brick({ services: [orders], deps: { carrier: createCarrier() } });
|
|
1080
|
+
*/
|
|
1081
|
+
function port() {
|
|
1082
|
+
return Object.freeze({});
|
|
1083
|
+
}
|
|
1084
|
+
/** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */
|
|
1085
|
+
const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
|
|
1086
|
+
const running = new AsyncLocalStorage();
|
|
1087
|
+
/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
|
|
1088
|
+
function runWithDeps(deps, fn) {
|
|
1089
|
+
return running.run(deps, fn);
|
|
1090
|
+
}
|
|
1091
|
+
function useDeps() {
|
|
1092
|
+
const deps = running.getStore();
|
|
1093
|
+
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).");
|
|
1094
|
+
return deps;
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Check `brick({ deps })` against what the services declare, and give each
|
|
1098
|
+
* service the values of its own ports.
|
|
1099
|
+
*
|
|
1100
|
+
* @throws When a service declares a dep the app does not provide, or the app
|
|
1101
|
+
* provides one that no service declares.
|
|
1102
|
+
*/
|
|
1103
|
+
function bindDeps(services, provided = {}) {
|
|
1104
|
+
const declared = /* @__PURE__ */ new Set();
|
|
1105
|
+
for (const service of services) {
|
|
1106
|
+
const own = {};
|
|
1107
|
+
for (const name of Object.keys(service.options.deps ?? {})) {
|
|
1108
|
+
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`);
|
|
1109
|
+
declared.add(name);
|
|
1110
|
+
own[name] = provided[name];
|
|
1111
|
+
}
|
|
1112
|
+
portOf(service).setDeps(Object.freeze(own));
|
|
1113
|
+
}
|
|
1114
|
+
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"})`);
|
|
1115
|
+
}
|
|
1116
|
+
// src/plugin-app.ts
|
|
1117
|
+
const INTERNALS = Symbol.for("brickkit.plugin.internals");
|
|
1118
|
+
function isPluginInstance(value) {
|
|
1119
|
+
return typeof value === "object" && value !== null && INTERNALS in value;
|
|
1120
|
+
}
|
|
1121
|
+
function internalsOf(value) {
|
|
1122
|
+
return isPluginInstance(value) ? value[INTERNALS] ?? void 0 : void 0;
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* What `brick()` does with plugins: install those given in `plugins` on the
|
|
1126
|
+
* app, run every plugin's `app` part in install order, and return the
|
|
1127
|
+
* lifecycle, middleware and listeners they contributed.
|
|
1128
|
+
*/
|
|
1129
|
+
function setupAppPlugins(installedOnServices, appPlugins) {
|
|
1130
|
+
const instances = /* @__PURE__ */ new Set();
|
|
1131
|
+
for (const descriptor of installedOnServices) if (isPluginInstance(descriptor)) instances.add(descriptor);
|
|
1132
|
+
const ordered = [...instances].sort((a, b) => (internalsOf(a).order ?? 0) - (internalsOf(b).order ?? 0));
|
|
1133
|
+
const onApp = /* @__PURE__ */ new Set();
|
|
1134
|
+
for (const plugin of appPlugins) {
|
|
1135
|
+
const internals = internalsOf(plugin);
|
|
1136
|
+
if (!internals) throw new Error("brick({ plugins }) takes instances from definePlugin(), such as audit()");
|
|
1137
|
+
const { manifest } = internals;
|
|
1138
|
+
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()"}`);
|
|
1139
|
+
for (const required of manifest.requires ?? []) if (!onApp.has(required)) throw new Error(`${manifest.name} requires ${required}, installed in brick({ plugins }) before it`);
|
|
1140
|
+
if (onApp.has(manifest.name)) throw new Error(`Plugin ${manifest.name} is installed on the app twice`);
|
|
1141
|
+
const installed = ordered.find((other) => internalsOf(other).manifest.name === manifest.name);
|
|
1142
|
+
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 })`);
|
|
1143
|
+
onApp.add(manifest.name);
|
|
1144
|
+
if (!internals.installs.some((item) => item.scope === "app")) internals.installs.push({ scope: "app" });
|
|
1145
|
+
ordered.push(plugin);
|
|
1146
|
+
}
|
|
1147
|
+
const lifecycles = [];
|
|
1148
|
+
const middleware = [];
|
|
1149
|
+
const listeners = [];
|
|
1150
|
+
const listed = [];
|
|
1151
|
+
for (const plugin of ordered) {
|
|
1152
|
+
const { manifest, options, deps, installs, dashboard } = internalsOf(plugin);
|
|
1153
|
+
for (const install of installs) listed.push(Object.freeze({
|
|
1154
|
+
name: manifest.name,
|
|
1155
|
+
...manifest.brick ? { brick: manifest.brick } : {},
|
|
1156
|
+
...install,
|
|
1157
|
+
...dashboard ? { dashboard } : {}
|
|
1158
|
+
}));
|
|
1159
|
+
if (!manifest.app) continue;
|
|
1160
|
+
const lifecycle = {
|
|
1161
|
+
options,
|
|
1162
|
+
secrets: manifest.secrets ?? {},
|
|
1163
|
+
deps
|
|
1164
|
+
};
|
|
1165
|
+
const own = {
|
|
1166
|
+
start: [],
|
|
1167
|
+
stop: []
|
|
1168
|
+
};
|
|
1169
|
+
manifest.app({
|
|
1170
|
+
...lifecycle,
|
|
1171
|
+
on(event, handler) {
|
|
1172
|
+
if (event !== "start" && event !== "stop") throw new Error(`${manifest.name}: on() takes "start" or "stop"`);
|
|
1173
|
+
own[event].push(handler);
|
|
1174
|
+
},
|
|
1175
|
+
middleware(handler) {
|
|
1176
|
+
middleware.push(handler);
|
|
1177
|
+
},
|
|
1178
|
+
listeners(...items) {
|
|
1179
|
+
listeners.push(...items.map((listener) => ({
|
|
1180
|
+
...listener,
|
|
1181
|
+
[PLUGIN_DEPS]: deps
|
|
1182
|
+
})));
|
|
1183
|
+
}
|
|
1184
|
+
});
|
|
1185
|
+
lifecycles.push({
|
|
1186
|
+
start: async () => {
|
|
1187
|
+
for (const handler of own.start) await handler(lifecycle);
|
|
1188
|
+
},
|
|
1189
|
+
stop: async () => {
|
|
1190
|
+
for (const handler of own.stop) await handler(lifecycle);
|
|
1191
|
+
}
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
return {
|
|
1195
|
+
lifecycles,
|
|
1196
|
+
middleware,
|
|
1197
|
+
listeners,
|
|
1198
|
+
plugins: listed
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Start in install order. Stop what started, in reverse order; a start that
|
|
1203
|
+
* fails stops those before it and rethrows.
|
|
1204
|
+
*/
|
|
1205
|
+
function pluginLifecycle(lifecycles) {
|
|
1206
|
+
let started;
|
|
1207
|
+
const running = [];
|
|
1208
|
+
const stopAll = async () => {
|
|
1209
|
+
const errors = [];
|
|
1210
|
+
for (const item of running.splice(0).reverse()) try {
|
|
1211
|
+
await item.stop();
|
|
1212
|
+
} catch (error) {
|
|
1213
|
+
errors.push(error);
|
|
1214
|
+
}
|
|
1215
|
+
if (errors.length === 1) throw errors[0];
|
|
1216
|
+
if (errors.length) throw new AggregateError(errors, "Plugins failed to stop");
|
|
1217
|
+
};
|
|
1218
|
+
return {
|
|
1219
|
+
start() {
|
|
1220
|
+
return started ??= (async () => {
|
|
1221
|
+
for (const item of lifecycles) {
|
|
1222
|
+
try {
|
|
1223
|
+
await item.start();
|
|
1224
|
+
} catch (error) {
|
|
1225
|
+
await stopAll().catch(() => void 0);
|
|
1226
|
+
started = void 0;
|
|
1227
|
+
throw error;
|
|
1228
|
+
}
|
|
1229
|
+
running.push(item);
|
|
1230
|
+
}
|
|
1231
|
+
})();
|
|
1232
|
+
},
|
|
1233
|
+
async stop() {
|
|
1234
|
+
await started?.catch(() => void 0);
|
|
1235
|
+
started = void 0;
|
|
1236
|
+
await stopAll();
|
|
1237
|
+
}
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
// src/definition-site.ts
|
|
1241
|
+
const brickRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
1242
|
+
/**
|
|
1243
|
+
* The first `file:line` outside Brick on the current stack: where a name is
|
|
1244
|
+
* being defined. Best-effort: `undefined` when there is no stack.
|
|
1245
|
+
*/
|
|
1246
|
+
function definitionSite() {
|
|
1247
|
+
const limit = Error.stackTraceLimit;
|
|
1248
|
+
Error.stackTraceLimit = 50;
|
|
1249
|
+
const stack = (/* @__PURE__ */ new Error()).stack;
|
|
1250
|
+
Error.stackTraceLimit = limit;
|
|
1251
|
+
for (const line of stack?.split("\n").slice(1) ?? []) {
|
|
1252
|
+
const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
|
|
1253
|
+
if (!match) continue;
|
|
1254
|
+
const [, file, row] = match;
|
|
1255
|
+
if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
|
|
1256
|
+
return `${file}:${row}`;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Records where `name` is defined. The same file defining it again (a dev
|
|
1261
|
+
* reload) replaces the old definition.
|
|
1262
|
+
*
|
|
1263
|
+
* @throws When a different file already defined `name`.
|
|
1264
|
+
*/
|
|
1265
|
+
function claimName(sites, label, name, site) {
|
|
1266
|
+
const file = (at) => at?.replace(/:\d+$/, "");
|
|
1267
|
+
if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new DuplicateNameError(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
|
|
1268
|
+
sites.set(name, site);
|
|
1269
|
+
}
|
|
1270
|
+
// src/compiler/ir.ts
|
|
1271
|
+
function freezeIR(value) {
|
|
1272
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
1273
|
+
for (const child of Object.values(value)) freezeIR(child);
|
|
1274
|
+
Object.freeze(value);
|
|
1275
|
+
}
|
|
1276
|
+
return value;
|
|
1277
|
+
}
|
|
1278
|
+
function schemaSnapshot(schema) {
|
|
1279
|
+
return schema === void 0 ? void 0 : JSON.parse(JSON.stringify(schema));
|
|
1280
|
+
}
|
|
1281
|
+
function analyzeApplication(services, prefix = DEFAULT_PREFIX) {
|
|
1282
|
+
for (const service of services) service.build();
|
|
1283
|
+
return analyzeDeclaredApplication(services, prefix);
|
|
1284
|
+
}
|
|
1285
|
+
/** Inspect current declarations without closing service/plugin setup. */
|
|
1286
|
+
function analyzeDeclaredApplication(services, prefix = DEFAULT_PREFIX) {
|
|
1287
|
+
if (!prefix.startsWith("/")) throw new Error("Brick compiler: prefix must start with '/'");
|
|
1288
|
+
const names = /* @__PURE__ */ new Set();
|
|
1289
|
+
for (const service of services) {
|
|
1290
|
+
if (names.has(service.name)) throw new DuplicateNameError(`Brick compiler: duplicate service '${service.name}'`);
|
|
1291
|
+
names.add(service.name);
|
|
1292
|
+
}
|
|
1293
|
+
const routes = [];
|
|
1294
|
+
const bindings = [];
|
|
1295
|
+
const registered = /* @__PURE__ */ new Map();
|
|
1296
|
+
const diagnostics = [];
|
|
1297
|
+
const add = (service, action, method, path) => {
|
|
1298
|
+
if (!path.startsWith("/")) throw new Error(`Brick compiler: invalid route '${method} ${path}'`);
|
|
1299
|
+
const route = describeRoute(service, action, method, path);
|
|
1300
|
+
const key = routeKey(method, path);
|
|
1301
|
+
const previous = registered.get(key);
|
|
1302
|
+
if (previous) {
|
|
1303
|
+
if (route.plugin || previous.plugin) throw new DuplicateNameError(`Brick compiler: duplicate plugin route '${method} ${path}'`);
|
|
1304
|
+
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (first registration wins)`);
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
1308
|
+
registered.set(key, {
|
|
1309
|
+
name: `${service.name}.${action.name}`,
|
|
1310
|
+
plugin: Boolean(route.plugin)
|
|
1311
|
+
});
|
|
1312
|
+
routes.push(route);
|
|
1313
|
+
bindings.push({
|
|
1314
|
+
service,
|
|
1315
|
+
action
|
|
1316
|
+
});
|
|
1317
|
+
};
|
|
1318
|
+
for (const service of services) {
|
|
1319
|
+
checkSegments(service);
|
|
1320
|
+
for (const action of service.listActions()) {
|
|
1321
|
+
const route = getActionRoute(action, prefix);
|
|
1322
|
+
if (route === false) continue;
|
|
1323
|
+
add(service, action, route.method, route.path);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
const preparations = services.flatMap((service) => portOf(service).listPreparations().map((contribution) => ({
|
|
1327
|
+
service: service.name,
|
|
1328
|
+
name: contribution.name,
|
|
1329
|
+
metadata: schemaSnapshot(contribution.describe?.())
|
|
1330
|
+
})));
|
|
1331
|
+
return {
|
|
1332
|
+
ir: freezeIR({
|
|
1333
|
+
version: 1,
|
|
1334
|
+
target: "bun-elysia",
|
|
1335
|
+
prefix,
|
|
1336
|
+
services: [...names],
|
|
1337
|
+
routes,
|
|
1338
|
+
preparations,
|
|
1339
|
+
diagnostics
|
|
1340
|
+
}),
|
|
1341
|
+
bindings
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
/** What the compiler records about one action route. */
|
|
1345
|
+
function describeRoute(service, action, method, path) {
|
|
1346
|
+
const coercions = [];
|
|
1347
|
+
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) if (prop.type === "number" || prop.type === "integer") coercions.push({
|
|
1348
|
+
key,
|
|
1349
|
+
type: "number"
|
|
1350
|
+
});
|
|
1351
|
+
else if (prop.type === "boolean") coercions.push({
|
|
1352
|
+
key,
|
|
1353
|
+
type: "boolean"
|
|
1354
|
+
});
|
|
1355
|
+
else if (prop.type === "array") coercions.push({
|
|
1356
|
+
key,
|
|
1357
|
+
type: "array"
|
|
1358
|
+
});
|
|
1359
|
+
const plugin = actionMeta(action).route?.plugin;
|
|
1360
|
+
return {
|
|
1361
|
+
method,
|
|
1362
|
+
path,
|
|
1363
|
+
service: service.name,
|
|
1364
|
+
action: action.name,
|
|
1365
|
+
kind: "action",
|
|
1366
|
+
...plugin ? { plugin } : {},
|
|
1367
|
+
input: Boolean(action.config.input),
|
|
1368
|
+
output: Boolean(action.config.output),
|
|
1369
|
+
context: typeof service.options.context === "function",
|
|
1370
|
+
authorize: typeof action.config.authorize === "function",
|
|
1371
|
+
readLike: isReadLike(method, action.name),
|
|
1372
|
+
inputSource: inputSource(method),
|
|
1373
|
+
coercions,
|
|
1374
|
+
inputSchema: schemaSnapshot(action.config.input),
|
|
1375
|
+
outputSchema: schemaSnapshot(action.config.output)
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
// src/action-handler.ts
|
|
1379
|
+
/** The plan of an analyzed route: its callbacks, validators and logger. */
|
|
1380
|
+
function planRoute(route, service, action) {
|
|
1381
|
+
const meta = actionMeta(action);
|
|
1382
|
+
const outputSchema = meta.runtimeOutput ?? action.config.output;
|
|
1383
|
+
return {
|
|
1384
|
+
route,
|
|
1385
|
+
service: portOf(service),
|
|
1386
|
+
action,
|
|
1387
|
+
execute: action.config.execute,
|
|
1388
|
+
authorize: action.config.authorize,
|
|
1389
|
+
contextHook: service.options.context,
|
|
1390
|
+
inputChecker: action.config.input ? getCompiledCheck(action.config.input) : void 0,
|
|
1391
|
+
outputChecker: outputSchema ? getCompiledCheck(outputSchema) : void 0,
|
|
1392
|
+
errorBuilder: action.errorHelpers,
|
|
1393
|
+
logger: createLogger(`[${service.name}:${action.name}]`),
|
|
1394
|
+
cachedDb: service.getDb(),
|
|
1395
|
+
checkInput: meta.checkInput,
|
|
1396
|
+
deps: meta.deps?.values
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* An Elysia handler for one action. Use it to mount an action on your own
|
|
1401
|
+
* Elysia app; `brick()` does it for you.
|
|
1402
|
+
*
|
|
1403
|
+
* @deprecated Serve actions with `brick()`, or bind every route at once with
|
|
1404
|
+
* `compileBrickApplication`.
|
|
1405
|
+
* @param service - The service the action belongs to.
|
|
1406
|
+
* @param action - The action.
|
|
1407
|
+
* @param routePath - The route's path.
|
|
1408
|
+
* @param method - The HTTP method (POST by default).
|
|
1409
|
+
* @returns A function from the Elysia context to the response.
|
|
1410
|
+
*/
|
|
1411
|
+
function createActionHandler(service, action, routePath, method) {
|
|
1412
|
+
return bindRoute(planRoute(describeRoute(service, action, method ?? "POST", routePath), service, action));
|
|
1413
|
+
}
|
|
1414
|
+
// src/app-entry.ts
|
|
1415
|
+
/**
|
|
1416
|
+
* Whether a value is an application made by `brick()`. It checks for the
|
|
1417
|
+
* methods and `definition` a `BrickApp` has, so it also recognizes one built by
|
|
1418
|
+
* another copy of the package.
|
|
1419
|
+
*
|
|
1420
|
+
* @param app - Anything, such as the default export of an entry file.
|
|
1421
|
+
* @returns `true` for a `BrickApp`, narrowing its type.
|
|
1422
|
+
*/
|
|
1423
|
+
function isBrickApp(app) {
|
|
1424
|
+
if (!app || typeof app !== "object") return false;
|
|
1425
|
+
return "endpoint" in app && typeof app.endpoint === "function" && "fetch" in app && typeof app.fetch === "function" && "listen" in app && typeof app.listen === "function" && "definition" in app && !!app.definition && typeof app.definition === "object" && "services" in app.definition && Array.isArray(app.definition.services) && "prefix" in app.definition && typeof app.definition.prefix === "string";
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* Check that a module's default export is an application ready to be served,
|
|
1429
|
+
* for tools that load an entry file.
|
|
1430
|
+
*
|
|
1431
|
+
* @param app - The default export of an entry file.
|
|
1432
|
+
* @returns The app.
|
|
1433
|
+
* @throws When it is not a `BrickApp`, or it already called `.listen()`: the
|
|
1434
|
+
* entry must only build the app, and leave listening to the server bootstrap.
|
|
1435
|
+
*/
|
|
1436
|
+
function requireBrickApp(app) {
|
|
1437
|
+
if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
|
|
1438
|
+
if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
|
|
1439
|
+
return app;
|
|
1440
|
+
}
|
|
1441
|
+
// src/compiler.ts
|
|
1442
|
+
/** @throws When the services no longer analyze to `ir`, so the build is stale. */
|
|
1443
|
+
function analyzeMatching(services, ir) {
|
|
1444
|
+
const analyzed = analyzeApplication(services, ir.prefix);
|
|
1445
|
+
if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir)) throw new Error("Brick compiler: application definitions differ from the compiled IR; rebuild the application");
|
|
1446
|
+
return analyzed;
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Build artifact bootstrap: import the app and check that its definitions
|
|
1450
|
+
* still match the IR `brick build` compiled.
|
|
1451
|
+
*
|
|
1452
|
+
* @throws When the app's definitions differ from `ir`.
|
|
1453
|
+
*/
|
|
1454
|
+
async function loadCompiledBrickApp(load, ir) {
|
|
1455
|
+
const app = requireBrickApp((await load()).default);
|
|
1456
|
+
analyzeMatching([...app.definition.services], ir);
|
|
1457
|
+
return app;
|
|
1458
|
+
}
|
|
1459
|
+
function bindAnalyzed(ir, bindings, bind = bindRoute) {
|
|
1460
|
+
const routes = ir.routes.map((route, index) => {
|
|
1461
|
+
const { service, action } = bindings[index];
|
|
1462
|
+
const plan = Object.freeze(planRoute(route, service, action));
|
|
1463
|
+
return Object.freeze({
|
|
1464
|
+
ir: route,
|
|
1465
|
+
handler: bind(plan, index)
|
|
1466
|
+
});
|
|
1467
|
+
});
|
|
1468
|
+
return Object.freeze({
|
|
1469
|
+
ir: freezeIR(ir),
|
|
1470
|
+
routes: Object.freeze(routes)
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
/** Startup compiler: analyzes once, then binds live callbacks. */
|
|
1474
|
+
function compileBrickApplication(options) {
|
|
1475
|
+
const { ir, bindings } = analyzeApplication(options.services, options.prefix);
|
|
1476
|
+
if (options.mode !== "generic") for (const service of options.services) portOf(service).prepareContributions();
|
|
1477
|
+
return bindAnalyzed(ir, bindings);
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Build artifact binder: consumes emitted functions, with no runtime handler code generation.
|
|
1481
|
+
*
|
|
1482
|
+
* @deprecated `brick build` no longer emits handler factories; built servers
|
|
1483
|
+
* use `loadCompiledBrickApp`. Pass `compileBrickApplication(...)` as
|
|
1484
|
+
* `brick({ compilation })` instead.
|
|
1485
|
+
*/
|
|
1486
|
+
function bindCompiledApplication(ir, services, factories) {
|
|
1487
|
+
if (ir.version !== 1 || ir.target !== "bun-elysia") throw new Error("Brick compiler: unsupported IR version or target; rebuild the application");
|
|
1488
|
+
const analyzed = analyzeMatching(services, ir);
|
|
1489
|
+
if (factories.length !== ir.routes.length) throw new Error("Brick compiler: handler factory count does not match IR");
|
|
1490
|
+
for (const service of services) portOf(service).prepareContributions();
|
|
1491
|
+
return bindAnalyzed(ir, analyzed.bindings, (plan, index) => factories[index](plan, compilerRuntime));
|
|
1492
|
+
}
|
|
1493
|
+
// src/registry.ts
|
|
1494
|
+
var ServiceRegistry = class {
|
|
1495
|
+
_revision = 0;
|
|
1496
|
+
/** Definition revision for invalidating serialized architecture snapshots. */
|
|
1497
|
+
get revision() {
|
|
1498
|
+
return this._revision;
|
|
1499
|
+
}
|
|
1500
|
+
touch() {
|
|
1501
|
+
this._revision++;
|
|
1502
|
+
}
|
|
1503
|
+
services = /* @__PURE__ */ new Map();
|
|
1504
|
+
sites = /* @__PURE__ */ new Map();
|
|
1505
|
+
/** @throws When a different file already registered a service with this name. */
|
|
1506
|
+
register(service, site = definitionSite()) {
|
|
1507
|
+
claimName(this.sites, `service "${service.name}"`, service.name, site);
|
|
1508
|
+
this.services.set(service.name, service);
|
|
1509
|
+
this.touch();
|
|
1510
|
+
}
|
|
1511
|
+
get(name) {
|
|
1512
|
+
return this.services.get(name);
|
|
1513
|
+
}
|
|
1514
|
+
has(name) {
|
|
1515
|
+
return this.services.has(name);
|
|
1516
|
+
}
|
|
1517
|
+
list() {
|
|
1518
|
+
return Array.from(this.services.values());
|
|
1519
|
+
}
|
|
1520
|
+
/**
|
|
1521
|
+
* The architecture of an app (`app.definition`): its mounted routes. Without
|
|
1522
|
+
* one, every registered service with its default routes under `/api`.
|
|
1523
|
+
*/
|
|
1524
|
+
exportArchitecture(application) {
|
|
1525
|
+
return {
|
|
1526
|
+
version: "1.0.0",
|
|
1527
|
+
...application?.events ? { events: application.events } : {},
|
|
1528
|
+
...application?.plugins?.length ? { plugins: [...application.plugins] } : {},
|
|
1529
|
+
services: (application?.services ?? this.list()).map((service) => {
|
|
1530
|
+
const byAction = new Map(application ? application.routes.filter((route) => route.service === service.name).map((route) => [route.action, route]) : service.listActions().flatMap((action) => {
|
|
1531
|
+
const route = getActionRoute(action);
|
|
1532
|
+
return route ? [[action.name, route]] : [];
|
|
1533
|
+
}));
|
|
1534
|
+
const schema = service.introspect();
|
|
1535
|
+
return {
|
|
1536
|
+
...schema,
|
|
1537
|
+
...application?.sockets ? { sockets: application.sockets.filter((socket) => socket.service === service.name) } : {},
|
|
1538
|
+
actions: schema.actions.map((action) => {
|
|
1539
|
+
const route = byAction.get(action.name);
|
|
1540
|
+
return route ? {
|
|
1541
|
+
...action,
|
|
1542
|
+
method: route.method,
|
|
1543
|
+
path: route.path
|
|
1544
|
+
} : action;
|
|
1545
|
+
})
|
|
1546
|
+
};
|
|
1547
|
+
})
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
};
|
|
1551
|
+
let globalRegistry = new ServiceRegistry();
|
|
1552
|
+
/**
|
|
1553
|
+
* The registry every `defineService` adds to: it is how `brick()`, the OpenAPI
|
|
1554
|
+
* generator, `useService`, and the dashboard find services by name.
|
|
1555
|
+
*
|
|
1556
|
+
* @returns The current global registry.
|
|
1557
|
+
*/
|
|
1558
|
+
function getGlobalRegistry() {
|
|
1559
|
+
return globalRegistry;
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* Start over with an empty global registry. For tests, which define the same
|
|
1563
|
+
* services again in each case; an application never needs it.
|
|
1564
|
+
*/
|
|
1565
|
+
function resetGlobalRegistry() {
|
|
1566
|
+
globalRegistry = new ServiceRegistry();
|
|
1567
|
+
}
|
|
1568
|
+
// src/access.ts
|
|
1569
|
+
/**
|
|
1570
|
+
* Record how an action is protected, for tools that cannot read it from the
|
|
1571
|
+
* configuration: plugins such as `crud` enforce access inside `execute`, so the
|
|
1572
|
+
* action has no `authorize` to find. Introspection, OpenAPI, and the dashboard
|
|
1573
|
+
* read what is recorded here.
|
|
1574
|
+
*
|
|
1575
|
+
* @param action - The action to describe.
|
|
1576
|
+
* @param info - Whether it checks authorization and whether it scopes queries,
|
|
1577
|
+
* and the resulting policy.
|
|
1578
|
+
*/
|
|
1579
|
+
function setActionAccess(action, info) {
|
|
1580
|
+
actionMeta(action).access = {
|
|
1581
|
+
hasAuthorize: info.hasAuthorize,
|
|
1582
|
+
hasScope: info.hasScope,
|
|
1583
|
+
policy: info.policy
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
/**
|
|
1587
|
+
* How an action is protected: `"public"` when nothing checks the caller,
|
|
1588
|
+
* `"authorized"` when an `authorize` does, and `"scoped"` when the action also
|
|
1589
|
+
* limits what rows the caller can reach. It reads what a plugin recorded with
|
|
1590
|
+
* `setActionAccess`, else the action's own `authorize`, and keeps the policy
|
|
1591
|
+
* consistent with the flags.
|
|
1592
|
+
*
|
|
1593
|
+
* @param action - An action, or any object a plugin described.
|
|
1594
|
+
* @returns `hasAuthorize`, `hasScope`, and `policy`.
|
|
1595
|
+
*/
|
|
1596
|
+
function getActionAccess(action) {
|
|
1597
|
+
const meta = actionMeta(action).access;
|
|
1598
|
+
const configAuthorize = typeof action.config?.authorize === "function";
|
|
1599
|
+
if (!meta) return {
|
|
1600
|
+
hasAuthorize: configAuthorize,
|
|
1601
|
+
hasScope: false,
|
|
1602
|
+
policy: configAuthorize ? "authorized" : "public"
|
|
1603
|
+
};
|
|
1604
|
+
const hasAuthorize = configAuthorize || Boolean(meta.hasAuthorize);
|
|
1605
|
+
const hasScope = Boolean(meta.hasScope);
|
|
1606
|
+
let policy = meta.policy ?? (hasAuthorize ? hasScope ? "scoped" : "authorized" : "public");
|
|
1607
|
+
if (policy === "public" && hasAuthorize) policy = hasScope ? "scoped" : "authorized";
|
|
1608
|
+
else if (policy !== "public" && !hasAuthorize) policy = "public";
|
|
1609
|
+
else if (policy === "scoped" && !hasScope) policy = "authorized";
|
|
1610
|
+
return {
|
|
1611
|
+
hasAuthorize,
|
|
1612
|
+
hasScope,
|
|
1613
|
+
policy
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1616
|
+
// src/openapi.ts
|
|
1617
|
+
/** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */
|
|
1618
|
+
const OPENAPI_DEFAULTS = Object.freeze({
|
|
1619
|
+
title: "Brick-TS API Mesh",
|
|
1620
|
+
version: "1.0.0",
|
|
1621
|
+
path: "/openapi.json"
|
|
1622
|
+
});
|
|
1623
|
+
function isAnchor(node) {
|
|
1624
|
+
return typeof node === "object" && node !== null && typeof node.$id === "string";
|
|
1625
|
+
}
|
|
1626
|
+
function isBareRef(node) {
|
|
1627
|
+
return typeof node === "object" && node !== null && typeof node.$ref === "string" && !node.$ref.startsWith("#");
|
|
1628
|
+
}
|
|
1629
|
+
function toComponentKey(id) {
|
|
1630
|
+
return id.replace(/[^A-Za-z0-9.\-_]+/g, "_");
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* TypeBox expresses recursive schemas with bare `$id`/`$ref` anchors
|
|
1634
|
+
* (`{ $id: "T0", ..., { $ref: "T0" } }`). OpenAPI interprets a bare `$ref`
|
|
1635
|
+
* as an external file reference, so downstream tooling tries to load a
|
|
1636
|
+
* file named `T0` and fails. Hoist every anchored subschema into
|
|
1637
|
+
* `#/components/schemas/` and rewrite the refs to local pointers.
|
|
1638
|
+
* First definition wins when one `$id` is declared twice.
|
|
1639
|
+
*/
|
|
1640
|
+
function hoistAnchoredSchemas(spec) {
|
|
1641
|
+
const anchored = /* @__PURE__ */ new Map();
|
|
1642
|
+
const collect = (node) => {
|
|
1643
|
+
if (Array.isArray(node)) return node.map(collect);
|
|
1644
|
+
if (typeof node !== "object" || node === null) return node;
|
|
1645
|
+
if (isAnchor(node)) {
|
|
1646
|
+
const id = node.$id;
|
|
1647
|
+
const { $id: _dropped, ...rest } = node;
|
|
1648
|
+
const collected = collect(rest);
|
|
1649
|
+
if (!anchored.has(id)) anchored.set(id, collected);
|
|
1650
|
+
return { $ref: `#/components/schemas/${toComponentKey(id)}` };
|
|
1651
|
+
}
|
|
1652
|
+
for (const key of Object.keys(node)) node[key] = collect(node[key]);
|
|
1653
|
+
return node;
|
|
1654
|
+
};
|
|
1655
|
+
const rewrite = (node) => {
|
|
1656
|
+
if (Array.isArray(node)) {
|
|
1657
|
+
for (const child of node) rewrite(child);
|
|
1658
|
+
return;
|
|
1659
|
+
}
|
|
1660
|
+
if (typeof node !== "object" || node === null) return;
|
|
1661
|
+
if (isBareRef(node)) node.$ref = `#/components/schemas/${toComponentKey(node.$ref)}`;
|
|
1662
|
+
for (const key of Object.keys(node)) rewrite(node[key]);
|
|
1663
|
+
};
|
|
1664
|
+
collect(spec);
|
|
1665
|
+
const components = spec.components ??= {};
|
|
1666
|
+
const schemas = components.schemas ??= {};
|
|
1667
|
+
for (const [id, schema] of anchored) schemas[toComponentKey(id)] = schema;
|
|
1668
|
+
rewrite(spec);
|
|
1669
|
+
}
|
|
1670
|
+
/**
|
|
1671
|
+
* Build the OpenAPI 3.1 document for the services: one path per action route,
|
|
1672
|
+
* with request and response schemas from the actions' TypeBox schemas, their
|
|
1673
|
+
* declared errors, tags by service, and a bearer security scheme where any
|
|
1674
|
+
* action needs authorization. Declared events are listed under `x-brick-events`,
|
|
1675
|
+
* by wire name, with their service and payload schema.
|
|
1676
|
+
*
|
|
1677
|
+
* `brick()` calls this for `/openapi.json`; call it yourself to write the
|
|
1678
|
+
* document to a file or feed another tool.
|
|
1679
|
+
*
|
|
1680
|
+
* @param options - `title`, `version`, and `description` for the `info` block,
|
|
1681
|
+
* `prefix` (default `/api`), and the `services` to describe (the global
|
|
1682
|
+
* registry's by default).
|
|
1683
|
+
* @returns The document as a plain object.
|
|
1684
|
+
*/
|
|
1685
|
+
function generateOpenApiSpec(options = {}) {
|
|
1686
|
+
const title = options.title ?? OPENAPI_DEFAULTS.title;
|
|
1687
|
+
const version = options.version ?? OPENAPI_DEFAULTS.version;
|
|
1688
|
+
const description = options.description ?? "Automated OpenAPI 3.1.0 specification for Brick-TS modular service mesh.";
|
|
1689
|
+
const prefix = options.prefix ?? "/api";
|
|
1690
|
+
const services = options.services ?? getGlobalRegistry().list();
|
|
1691
|
+
const paths = {};
|
|
1692
|
+
const tags = /* @__PURE__ */ new Map();
|
|
1693
|
+
let hasAnyAuthorizedAction = false;
|
|
1694
|
+
const { ir, bindings } = analyzeDeclaredApplication([...services], prefix);
|
|
1695
|
+
for (const service of services) {
|
|
1696
|
+
tags.set(service.name, `Actions exposed by '${service.name}' service`);
|
|
1697
|
+
for (const [index, route] of ir.routes.entries()) {
|
|
1698
|
+
if (route.service !== service.name) continue;
|
|
1699
|
+
const { action } = bindings[index];
|
|
1700
|
+
const routePath = route.path;
|
|
1701
|
+
const method = route.method.toLowerCase();
|
|
1702
|
+
const pathParams = pathParamNames(routePath);
|
|
1703
|
+
const actionPath = toOpenApiPath(routePath);
|
|
1704
|
+
if (!paths[actionPath]) paths[actionPath] = {};
|
|
1705
|
+
const { plugin, resource } = actionOwners(action);
|
|
1706
|
+
const group = resource ? `${service.name} · ${resource}` : service.name;
|
|
1707
|
+
if (resource) tags.set(group, `Routes of resource '${resource}' in service '${service.name}'`);
|
|
1708
|
+
const hasAuth = getActionAccess(action).hasAuthorize;
|
|
1709
|
+
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
1710
|
+
const responses = {};
|
|
1711
|
+
if (action.config.output) responses["200"] = {
|
|
1712
|
+
description: "Successful response",
|
|
1713
|
+
content: { "application/json": { schema: action.config.output } }
|
|
1714
|
+
};
|
|
1715
|
+
else responses["200"] = { description: "Successful response" };
|
|
1716
|
+
const errorAlternatives = /* @__PURE__ */ new Set();
|
|
1717
|
+
const addError = (code, status, message, details) => {
|
|
1718
|
+
const key = `${status}:${code}`;
|
|
1719
|
+
if (errorAlternatives.has(key)) return;
|
|
1720
|
+
errorAlternatives.add(key);
|
|
1721
|
+
const schema = { allOf: [{ $ref: "#/components/schemas/ErrorEnvelope" }, {
|
|
1722
|
+
type: "object",
|
|
1723
|
+
properties: {
|
|
1724
|
+
code: { const: code },
|
|
1725
|
+
status: { const: status },
|
|
1726
|
+
...details ? { details } : {}
|
|
1727
|
+
}
|
|
1728
|
+
}] };
|
|
1729
|
+
const existing = responses[String(status)];
|
|
1730
|
+
if (existing) {
|
|
1731
|
+
existing.description += "; " + message;
|
|
1732
|
+
existing.content["application/json"].schema.oneOf.push(schema);
|
|
1733
|
+
} else responses[String(status)] = {
|
|
1734
|
+
description: message,
|
|
1735
|
+
content: { "application/json": { schema: { oneOf: [schema] } } }
|
|
1736
|
+
};
|
|
1737
|
+
};
|
|
1738
|
+
if (action.config.input) addError("VALIDATION_FAILED", 400, "Validation error");
|
|
1739
|
+
if (hasAuth) {
|
|
1740
|
+
addError("UNAUTHORIZED", 401, "Authentication required");
|
|
1741
|
+
addError("FORBIDDEN", 403, "Access denied");
|
|
1742
|
+
}
|
|
1743
|
+
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
1744
|
+
const def = errorDef;
|
|
1745
|
+
addError(code, def.status || 400, def.message || code, def.details);
|
|
1746
|
+
}
|
|
1747
|
+
addError("INTERNAL_SERVER_ERROR", 500, "Internal server error");
|
|
1748
|
+
if (action.config.output) addError("VALIDATION_FAILED", 500, "Output validation error");
|
|
1749
|
+
const operation = {
|
|
1750
|
+
operationId: `${service.name}_${action.name}_${method}`,
|
|
1751
|
+
summary: `${service.name}.${action.name}`,
|
|
1752
|
+
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
1753
|
+
tags: [.../* @__PURE__ */ new Set([group, ...action.config.tags ?? []])],
|
|
1754
|
+
...plugin ? { "x-brick-plugin": plugin } : {},
|
|
1755
|
+
...resource ? { "x-brick-resource": resource } : {},
|
|
1756
|
+
responses
|
|
1757
|
+
};
|
|
1758
|
+
const inputSchema = action.config.input;
|
|
1759
|
+
const properties = inputSchema?.properties ?? {};
|
|
1760
|
+
const parameters = [...new Set(pathParams)].map((key) => ({
|
|
1761
|
+
name: key,
|
|
1762
|
+
in: "path",
|
|
1763
|
+
required: true,
|
|
1764
|
+
schema: properties[key] ?? { type: "string" }
|
|
1765
|
+
}));
|
|
1766
|
+
if (route.inputSource === "query") for (const [key, schema] of Object.entries(properties)) {
|
|
1767
|
+
if (pathParams.includes(key)) continue;
|
|
1768
|
+
parameters.push({
|
|
1769
|
+
name: key,
|
|
1770
|
+
in: "query",
|
|
1771
|
+
required: inputSchema?.required?.includes(key) ?? false,
|
|
1772
|
+
schema
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
else if (inputSchema) operation.requestBody = {
|
|
1776
|
+
required: true,
|
|
1777
|
+
content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
|
|
1778
|
+
...inputSchema,
|
|
1779
|
+
properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
|
|
1780
|
+
required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
|
|
1781
|
+
} : inputSchema } }
|
|
1782
|
+
};
|
|
1783
|
+
if (parameters.length) operation.parameters = parameters;
|
|
1784
|
+
if (hasAuth) operation.security = [{ bearerAuth: [] }];
|
|
1785
|
+
paths[actionPath][method] = operation;
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
const spec = {
|
|
1789
|
+
openapi: "3.1.0",
|
|
1790
|
+
info: {
|
|
1791
|
+
title,
|
|
1792
|
+
version,
|
|
1793
|
+
description
|
|
1794
|
+
},
|
|
1795
|
+
paths,
|
|
1796
|
+
tags: Array.from(tags, ([name, description]) => ({
|
|
1797
|
+
name,
|
|
1798
|
+
description
|
|
1799
|
+
}))
|
|
1800
|
+
};
|
|
1801
|
+
spec.components = { schemas: { ErrorEnvelope: {
|
|
1802
|
+
type: "object",
|
|
1803
|
+
required: [
|
|
1804
|
+
"name",
|
|
1805
|
+
"code",
|
|
1806
|
+
"message",
|
|
1807
|
+
"status",
|
|
1808
|
+
"requestId"
|
|
1809
|
+
],
|
|
1810
|
+
properties: {
|
|
1811
|
+
name: { type: "string" },
|
|
1812
|
+
code: { type: "string" },
|
|
1813
|
+
message: { type: "string" },
|
|
1814
|
+
status: { type: "integer" },
|
|
1815
|
+
requestId: { type: "string" },
|
|
1816
|
+
details: {},
|
|
1817
|
+
errors: {
|
|
1818
|
+
type: "array",
|
|
1819
|
+
items: {
|
|
1820
|
+
type: "object",
|
|
1821
|
+
required: ["path", "message"],
|
|
1822
|
+
properties: {
|
|
1823
|
+
path: { type: "string" },
|
|
1824
|
+
message: { type: "string" },
|
|
1825
|
+
value: {}
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
} } };
|
|
1831
|
+
if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
|
|
1832
|
+
type: "http",
|
|
1833
|
+
scheme: "bearer",
|
|
1834
|
+
bearerFormat: "JWT",
|
|
1835
|
+
description: "Enter your Bearer authentication token"
|
|
1836
|
+
} } });
|
|
1837
|
+
const events = Object.fromEntries(services.flatMap((service) => Object.values(service.events ?? {}).map((ref) => [ref.name, {
|
|
1838
|
+
service: service.name,
|
|
1839
|
+
payload: ref.schema,
|
|
1840
|
+
...ref.plugin ? { "x-brick-plugin": ref.plugin } : {}
|
|
1841
|
+
}])));
|
|
1842
|
+
if (Object.keys(events).length) spec["x-brick-events"] = events;
|
|
1843
|
+
const document = JSON.parse(JSON.stringify(spec));
|
|
1844
|
+
hoistAnchoredSchemas(document);
|
|
1845
|
+
return document;
|
|
1846
|
+
}
|
|
1847
|
+
// src/secrets.ts
|
|
1848
|
+
/**
|
|
1849
|
+
* Type-safe secrets & environment variables.
|
|
1850
|
+
*
|
|
1851
|
+
* Declare each secret once at module scope instead of scattering untyped
|
|
1852
|
+
* `process.env.FOO` reads:
|
|
1853
|
+
*
|
|
1854
|
+
* const port = defineSecret("PORT").default("3333").transform(Number).require();
|
|
1855
|
+
* const baseUrl = defineSecret("BASE_URL").url().require();
|
|
1856
|
+
* const key = defineSecret("STRIPE_KEY").validate((v) =>
|
|
1857
|
+
* v.startsWith("sk_") || "must start with sk_"
|
|
1858
|
+
* ).require();
|
|
1859
|
+
*
|
|
1860
|
+
* Values resolve from the environment (Bun populates `process.env` from
|
|
1861
|
+
* `.env` locally; in prod the same env source applies — a future
|
|
1862
|
+
* `SecretSource` such as AWS can slot in without touching call sites).
|
|
1863
|
+
*
|
|
1864
|
+
* Resolution order per secret: test/session override → source (`process.env`
|
|
1865
|
+
* by default) → declared `default`. `resolveSecrets()` validates every
|
|
1866
|
+
* registered secret at boot and throws listing all missing required ones.
|
|
1867
|
+
*/
|
|
1868
|
+
/** Default source: `process.env` (Bun loads `.env` into it automatically). */
|
|
1869
|
+
const envSource = { get: (name) => process.env[name] };
|
|
1870
|
+
const registry = /* @__PURE__ */ new Map();
|
|
1871
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
1872
|
+
/** Where each secret was first declared. */
|
|
1873
|
+
const sites = /* @__PURE__ */ new Map();
|
|
1874
|
+
var SecretRef = class {
|
|
1875
|
+
name;
|
|
1876
|
+
options;
|
|
1877
|
+
transformFn;
|
|
1878
|
+
validators = [];
|
|
1879
|
+
constructor(name, options = {}) {
|
|
1880
|
+
this.name = name;
|
|
1881
|
+
this.options = options;
|
|
1882
|
+
}
|
|
1883
|
+
/** True when a default was declared (i.e. the secret is optional). */
|
|
1884
|
+
get hasDefault() {
|
|
1885
|
+
return this.options.default !== void 0;
|
|
1886
|
+
}
|
|
1887
|
+
/** Fallback used when the source has no value. Makes the secret optional. */
|
|
1888
|
+
default(value) {
|
|
1889
|
+
this.options.default = value;
|
|
1890
|
+
return this;
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
|
|
1894
|
+
* Runs before validators; a throwing transform fails resolution.
|
|
1895
|
+
*/
|
|
1896
|
+
transform(fn) {
|
|
1897
|
+
this.transformFn = fn;
|
|
1898
|
+
return this;
|
|
1899
|
+
}
|
|
1900
|
+
/** Run a custom check on the (transformed) value at every resolution. */
|
|
1901
|
+
validate(fn) {
|
|
1902
|
+
this.validators.push(fn);
|
|
1903
|
+
return this;
|
|
1904
|
+
}
|
|
1905
|
+
/** Shorthand validator: value must parse as a URL. String refs only. */
|
|
1906
|
+
url() {
|
|
1907
|
+
this.validators.push((v) => {
|
|
1908
|
+
try {
|
|
1909
|
+
new URL(v);
|
|
1910
|
+
} catch {
|
|
1911
|
+
return "must be a valid URL";
|
|
1912
|
+
}
|
|
1913
|
+
});
|
|
1914
|
+
return this;
|
|
1915
|
+
}
|
|
1916
|
+
resolveRaw(source) {
|
|
1917
|
+
return overrides.get(this.name) ?? source.get(this.name) ?? this.options.default;
|
|
1918
|
+
}
|
|
1919
|
+
coerce(raw) {
|
|
1920
|
+
let value;
|
|
1921
|
+
if (this.transformFn) try {
|
|
1922
|
+
value = this.transformFn(raw);
|
|
1923
|
+
} catch (err) {
|
|
1924
|
+
throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
|
|
1925
|
+
}
|
|
1926
|
+
else value = raw;
|
|
1927
|
+
for (const fn of this.validators) {
|
|
1928
|
+
let result;
|
|
1929
|
+
try {
|
|
1930
|
+
result = fn(value);
|
|
1931
|
+
} catch (err) {
|
|
1932
|
+
throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
|
|
1933
|
+
}
|
|
1934
|
+
if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
|
|
1935
|
+
if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
|
|
1936
|
+
}
|
|
1937
|
+
return value;
|
|
1938
|
+
}
|
|
1939
|
+
/** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
|
|
1940
|
+
value(source = envSource) {
|
|
1941
|
+
const raw = this.resolveRaw(source);
|
|
1942
|
+
if (raw === void 0) return void 0;
|
|
1943
|
+
return this.coerce(raw);
|
|
1944
|
+
}
|
|
1945
|
+
/** Resolved value, or throws naming the missing/invalid secret. */
|
|
1946
|
+
require(source = envSource) {
|
|
1947
|
+
const raw = this.resolveRaw(source);
|
|
1948
|
+
if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
|
|
1949
|
+
return this.coerce(raw);
|
|
1950
|
+
}
|
|
1951
|
+
/** True when a value would resolve (override, source, or default). */
|
|
1952
|
+
isSet(source = envSource) {
|
|
1953
|
+
return this.resolveRaw(source) !== void 0;
|
|
1954
|
+
}
|
|
1955
|
+
};
|
|
1956
|
+
/**
|
|
1957
|
+
* Declare a secret. Calling it again for the name returns the same ref. From
|
|
1958
|
+
* the same line (a module evaluated again) it starts the declaration over, so
|
|
1959
|
+
* its builder calls replace the earlier ones instead of adding to them.
|
|
1960
|
+
*/
|
|
1961
|
+
function defineSecret(name, options = {}) {
|
|
1962
|
+
const site = definitionSite();
|
|
1963
|
+
const existing = registry.get(name);
|
|
1964
|
+
if (existing) {
|
|
1965
|
+
if (site !== void 0 && sites.get(name) === site) {
|
|
1966
|
+
existing.options = options;
|
|
1967
|
+
existing["validators"] = [];
|
|
1968
|
+
existing["transformFn"] = void 0;
|
|
1969
|
+
}
|
|
1970
|
+
return existing;
|
|
1971
|
+
}
|
|
1972
|
+
sites.set(name, site);
|
|
1973
|
+
const ref = new SecretRef(name, options);
|
|
1974
|
+
registry.set(name, ref);
|
|
1975
|
+
return ref;
|
|
1976
|
+
}
|
|
1977
|
+
/**
|
|
1978
|
+
* Validate every registered secret at boot. Throws a single error listing
|
|
1979
|
+
* all missing required secrets. Returns the resolved values.
|
|
1980
|
+
*/
|
|
1981
|
+
function resolveSecrets(opts = {}) {
|
|
1982
|
+
const source = opts.source ?? envSource;
|
|
1983
|
+
const missing = [];
|
|
1984
|
+
const resolved = {};
|
|
1985
|
+
for (const ref of registry.values()) {
|
|
1986
|
+
const v = ref.value(source);
|
|
1987
|
+
if (v === void 0) missing.push(ref.name);
|
|
1988
|
+
else resolved[ref.name] = v;
|
|
1989
|
+
}
|
|
1990
|
+
if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
|
|
1991
|
+
return resolved;
|
|
1992
|
+
}
|
|
1993
|
+
/** Metadata for introspection (values never exposed — future dashboard use). */
|
|
1994
|
+
function listSecrets(opts = {}) {
|
|
1995
|
+
const source = opts.source ?? envSource;
|
|
1996
|
+
return [...registry.values()].map((ref) => ({
|
|
1997
|
+
hasDefault: ref.hasDefault,
|
|
1998
|
+
isSet: ref.isSet(source),
|
|
1999
|
+
name: ref.name
|
|
2000
|
+
}));
|
|
2001
|
+
}
|
|
2002
|
+
/** Test/session override for one secret (`undefined` clears the override). */
|
|
2003
|
+
function overrideSecret(name, value) {
|
|
2004
|
+
if (value === void 0) overrides.delete(name);
|
|
2005
|
+
else overrides.set(name, value);
|
|
2006
|
+
}
|
|
2007
|
+
/** Clear registry and overrides. Test-only. */
|
|
2008
|
+
function resetSecrets() {
|
|
2009
|
+
registry.clear();
|
|
2010
|
+
overrides.clear();
|
|
2011
|
+
sites.clear();
|
|
2012
|
+
}
|
|
2013
|
+
// src/request-logger.ts
|
|
2014
|
+
function formatLog(method, path, status, elapsedMs) {
|
|
2015
|
+
return `${method} ${path} → ${String(status)} (${elapsedMs}ms)`;
|
|
2016
|
+
}
|
|
2017
|
+
/**
|
|
2018
|
+
* Status carried by the thrown error (Elysia sets e.g. 404 on NotFoundError
|
|
2019
|
+
* while `set.status` may still hold the 200 default when onError runs).
|
|
2020
|
+
*/
|
|
2021
|
+
function thrownStatus(error) {
|
|
2022
|
+
if (typeof error === "object" && error !== null && "status" in error) {
|
|
2023
|
+
const status = error.status;
|
|
2024
|
+
if (typeof status === "number") return status;
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
2027
|
+
/**
|
|
2028
|
+
* Elysia plugin that logs each request as `METHOD path → status (elapsedms)`.
|
|
2029
|
+
* Timing is tracked per-Request via a WeakMap. The onError hook only logs and
|
|
2030
|
+
* returns undefined so existing error mapping is preserved.
|
|
2031
|
+
*
|
|
2032
|
+
* Hooks are registered with the "global" scope so they propagate to the
|
|
2033
|
+
* parent app when mounted via `app.use(...)` — Elysia scopes plain instance
|
|
2034
|
+
* hooks to the plugin's own routes. Timing is captured in beforeHandle
|
|
2035
|
+
* because request hooks are not propagated from a
|
|
2036
|
+
* used instance. Unmatched routes (no beforeHandle) fall back to Date.now().
|
|
2037
|
+
*/
|
|
2038
|
+
function requestLoggingPlugin(opts = {}) {
|
|
2039
|
+
const plugin = new Elysia();
|
|
2040
|
+
if (!(opts.enabled ?? true)) return plugin;
|
|
2041
|
+
const logger = opts.logger ?? console.log;
|
|
2042
|
+
const startedAt = /* @__PURE__ */ new WeakMap();
|
|
2043
|
+
const markStarted = ({ request }) => {
|
|
2044
|
+
startedAt.set(request, Date.now());
|
|
2045
|
+
};
|
|
2046
|
+
const logSuccess = ({ request, set }) => {
|
|
2047
|
+
const start = startedAt.get(request) ?? Date.now();
|
|
2048
|
+
const path = new URL(request.url).pathname;
|
|
2049
|
+
logger(formatLog(request.method, path, set.status ?? 200, Date.now() - start));
|
|
2050
|
+
};
|
|
2051
|
+
const logError = ({ request, set, error }) => {
|
|
2052
|
+
if (request) {
|
|
2053
|
+
const start = startedAt.get(request) ?? Date.now();
|
|
2054
|
+
const path = new URL(request.url).pathname;
|
|
2055
|
+
const status = thrownStatus(error) ?? set.status ?? 500;
|
|
2056
|
+
logger(formatLog(request.method, path, status, Date.now() - start));
|
|
2057
|
+
}
|
|
2058
|
+
};
|
|
2059
|
+
plugin.onBeforeHandle("global", markStarted);
|
|
2060
|
+
plugin.onAfterHandle("global", logSuccess);
|
|
2061
|
+
plugin.onError("global", logError);
|
|
2062
|
+
return plugin;
|
|
2063
|
+
}
|
|
2064
|
+
// src/docs.ts
|
|
2065
|
+
/** Renders the Scalar API reference page for the given OpenAPI URL. */
|
|
2066
|
+
function scalarDocsHTML(specUrl, title) {
|
|
2067
|
+
return `<!doctype html>
|
|
2068
|
+
<html>
|
|
2069
|
+
<head>
|
|
2070
|
+
<title>${title} — API Reference</title>
|
|
2071
|
+
<meta charset="utf-8" />
|
|
2072
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
2073
|
+
<link rel="icon" type="image/svg+xml" href="https://scalar.com/favicon.svg" />
|
|
2074
|
+
<style>
|
|
2075
|
+
body { margin: 0; padding: 0; height: 100vh; }
|
|
2076
|
+
</style>
|
|
2077
|
+
</head>
|
|
2078
|
+
<body>
|
|
2079
|
+
<script
|
|
2080
|
+
id="api-reference"
|
|
2081
|
+
data-url="${specUrl}"
|
|
2082
|
+
data-configuration='{"theme": "purple", "layout": "modern"}'
|
|
2083
|
+
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference">
|
|
2084
|
+
<\/script>
|
|
2085
|
+
</body>
|
|
2086
|
+
</html>`;
|
|
2087
|
+
}
|
|
2088
|
+
/**
|
|
2089
|
+
* Standalone Elysia plugin serving GET <path> with the Scalar HTML page.
|
|
2090
|
+
*
|
|
2091
|
+
* @deprecated Use `brick({ reference: true })` or `reference: { path }`.
|
|
2092
|
+
*/
|
|
2093
|
+
function referencePlugin(opts = {}) {
|
|
2094
|
+
const path = opts.path ?? "/reference";
|
|
2095
|
+
const title = opts.title ?? OPENAPI_DEFAULTS.title;
|
|
2096
|
+
const specUrl = opts.specUrl ?? OPENAPI_DEFAULTS.path;
|
|
2097
|
+
const plugin = new Elysia();
|
|
2098
|
+
plugin.get(path, ({ set }) => {
|
|
2099
|
+
set.headers["content-type"] = "text/html; charset=utf-8";
|
|
2100
|
+
return scalarDocsHTML(specUrl, title);
|
|
2101
|
+
});
|
|
2102
|
+
return plugin;
|
|
2103
|
+
}
|
|
2104
|
+
/**
|
|
2105
|
+
* Mounts the Scalar reference route onto an existing app.
|
|
2106
|
+
*
|
|
2107
|
+
* @deprecated Use `brick({ reference: true })` or `reference: { path }`.
|
|
2108
|
+
*/
|
|
2109
|
+
function registerReferenceRoute(app, opts = {}) {
|
|
2110
|
+
return app.use(referencePlugin(opts));
|
|
2111
|
+
}
|
|
2112
|
+
/** Renders the Swagger UI page. */
|
|
2113
|
+
function swaggerDocsHTML(specUrl, title) {
|
|
2114
|
+
return `<!DOCTYPE html>
|
|
2115
|
+
<html lang="en">
|
|
2116
|
+
<head>
|
|
2117
|
+
<meta charset="UTF-8">
|
|
2118
|
+
<title>${title} — Swagger UI</title>
|
|
2119
|
+
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css" />
|
|
2120
|
+
<style>
|
|
2121
|
+
html { box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }
|
|
2122
|
+
*, *:before, *:after { box-sizing: inherit; }
|
|
2123
|
+
body { margin:0; background: #fafafa; }
|
|
2124
|
+
</style>
|
|
2125
|
+
</head>
|
|
2126
|
+
<body>
|
|
2127
|
+
<div id="swagger-ui"></div>
|
|
2128
|
+
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" charset="UTF-8"><\/script>
|
|
2129
|
+
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js" charset="UTF-8"><\/script>
|
|
2130
|
+
<script>
|
|
2131
|
+
window.onload = function() {
|
|
2132
|
+
SwaggerUIBundle({
|
|
2133
|
+
url: "${specUrl}",
|
|
2134
|
+
dom_id: '#swagger-ui',
|
|
2135
|
+
deepLinking: true,
|
|
2136
|
+
presets: [
|
|
2137
|
+
SwaggerUIBundle.presets.apis,
|
|
2138
|
+
SwaggerUIStandalonePreset
|
|
2139
|
+
],
|
|
2140
|
+
plugins: [
|
|
2141
|
+
SwaggerUIBundle.plugins.DownloadUrl
|
|
2142
|
+
],
|
|
2143
|
+
layout: "StandaloneLayout"
|
|
2144
|
+
});
|
|
2145
|
+
};
|
|
2146
|
+
<\/script>
|
|
2147
|
+
</body>
|
|
2148
|
+
</html>`;
|
|
2149
|
+
}
|
|
2150
|
+
// src/dashboard.ts
|
|
2151
|
+
const MIN_TOKEN_LENGTH = 16;
|
|
2152
|
+
/**
|
|
2153
|
+
* Check what `brick()` was given, and freeze it. The secrets sit behind a getter
|
|
2154
|
+
* that is not enumerable, so logging or serializing the application definition
|
|
2155
|
+
* does not print them.
|
|
2156
|
+
*/
|
|
2157
|
+
function normalizeDashboard(options) {
|
|
2158
|
+
if (options === void 0) return void 0;
|
|
2159
|
+
const { port, host, auth, historyDays } = options;
|
|
2160
|
+
if (port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new Error(`Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`);
|
|
2161
|
+
if (host !== void 0 && (typeof host !== "string" || host.trim() === "")) throw new Error("Brick: dashboard host must be an address, such as '0.0.0.0'.");
|
|
2162
|
+
if (historyDays !== void 0 && (!Number.isInteger(historyDays) || historyDays < 0)) throw new Error(`Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`);
|
|
2163
|
+
const normalized = {
|
|
2164
|
+
...port !== void 0 ? { port } : {},
|
|
2165
|
+
...host !== void 0 ? { host: host.trim() } : {},
|
|
2166
|
+
...historyDays !== void 0 ? { historyDays } : {}
|
|
2167
|
+
};
|
|
2168
|
+
if (auth !== void 0) {
|
|
2169
|
+
const tokens = auth.token === void 0 ? void 0 : typeof auth.token === "string" ? [auth.token] : [...auth.token];
|
|
2170
|
+
if (tokens?.some((token) => typeof token !== "string" || token.length < MIN_TOKEN_LENGTH)) throw new Error(`Brick: a dashboard token must be at least ${MIN_TOKEN_LENGTH} characters. Try: openssl rand -base64 32`);
|
|
2171
|
+
if (auth.authorize !== void 0 && typeof auth.authorize !== "function") throw new Error("Brick: dashboard authorize must be a function.");
|
|
2172
|
+
if ((tokens === void 0 || tokens.length === 0) && !auth.authorize) throw new Error("Brick: dashboard auth needs a token or an authorize function.");
|
|
2173
|
+
const secrets = Object.freeze({
|
|
2174
|
+
...tokens ? { token: Object.freeze(tokens) } : {},
|
|
2175
|
+
...auth.authorize ? { authorize: auth.authorize } : {}
|
|
2176
|
+
});
|
|
2177
|
+
Object.defineProperty(normalized, "auth", {
|
|
2178
|
+
enumerable: false,
|
|
2179
|
+
get: () => secrets
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
return Object.freeze(normalized);
|
|
2183
|
+
}
|
|
2184
|
+
// src/endpoints.ts
|
|
2185
|
+
/** Resolve the db for an endpoint: explicit service first, else first service holding one. */
|
|
2186
|
+
function resolveEndpointDb(service, services) {
|
|
2187
|
+
if (service) return (typeof service === "string" ? services.find((s) => s.name === service) : service)?.getDb();
|
|
2188
|
+
for (const svc of services) {
|
|
2189
|
+
const db = svc.getDb();
|
|
2190
|
+
if (db) return db;
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
/** Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping. */
|
|
2194
|
+
function createEndpointHandler(def, services) {
|
|
2195
|
+
const logger = createLogger(`[${`endpoint:${def.method} ${def.path}`}]`);
|
|
2196
|
+
return async ({ params, body, query, headers, request, set }) => {
|
|
2197
|
+
const { traceId, requestId } = requestIds(headers, set);
|
|
2198
|
+
const ctx = {
|
|
2199
|
+
body,
|
|
2200
|
+
db: def.database ? def.database.getDb() : resolveEndpointDb(def.service, services),
|
|
2201
|
+
headers: headers ?? {},
|
|
2202
|
+
logger,
|
|
2203
|
+
params: params ?? {},
|
|
2204
|
+
query: query ?? {},
|
|
2205
|
+
request: request instanceof Request ? request : new Request(`http://localhost${def.path}`, {
|
|
2206
|
+
headers: new Headers(headers ?? {}),
|
|
2207
|
+
method: def.method
|
|
2208
|
+
}),
|
|
2209
|
+
requestId,
|
|
2210
|
+
set,
|
|
2211
|
+
traceId
|
|
2212
|
+
};
|
|
2213
|
+
try {
|
|
2214
|
+
return await def.handler(ctx);
|
|
2215
|
+
} catch (err) {
|
|
2216
|
+
const response = toErrorResponse(!(err instanceof ActionExecutionError || err instanceof ValidationError) && err !== null && typeof err === "object" && "status" in err && typeof err.status === "number" && Number.isInteger(err.status) && err.status >= 400 && err.status < 500 ? new ActionExecutionError("HTTP_ERROR", "message" in err && typeof err.message === "string" ? err.message : "Endpoint error", err.status, void 0, { cause: err }) : err, {
|
|
2217
|
+
logger: ctx.logger,
|
|
2218
|
+
requestId
|
|
2219
|
+
});
|
|
2220
|
+
set.status = response.status;
|
|
2221
|
+
return response;
|
|
2222
|
+
}
|
|
2223
|
+
};
|
|
2224
|
+
}
|
|
2225
|
+
/** OpenAPI `paths` fragment for declared endpoints (raw HTML included). */
|
|
2226
|
+
function endpointPaths(defs) {
|
|
2227
|
+
const paths = {};
|
|
2228
|
+
for (const def of defs) {
|
|
2229
|
+
const openApiPath = toOpenApiPath(def.path);
|
|
2230
|
+
if (!paths[openApiPath]) paths[openApiPath] = {};
|
|
2231
|
+
const params = pathParamNames(def.path).map((name) => ({
|
|
2232
|
+
in: "path",
|
|
2233
|
+
name,
|
|
2234
|
+
required: true,
|
|
2235
|
+
schema: { type: "string" }
|
|
2236
|
+
}));
|
|
2237
|
+
paths[openApiPath][def.method.toLowerCase()] = {
|
|
2238
|
+
...def.summary ? { summary: def.summary } : {},
|
|
2239
|
+
...def.description ? { description: def.description } : {},
|
|
2240
|
+
...def.tags ? { tags: def.tags } : {},
|
|
2241
|
+
...def.plugin ? { "x-brick-plugin": def.plugin } : {},
|
|
2242
|
+
...params.length > 0 ? { parameters: params } : {},
|
|
2243
|
+
responses: { 200: { description: "Successful response" } }
|
|
2244
|
+
};
|
|
2245
|
+
}
|
|
2246
|
+
return paths;
|
|
2247
|
+
}
|
|
2248
|
+
// src/events/id.ts
|
|
2249
|
+
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
2250
|
+
function newEventId(now = Date.now()) {
|
|
2251
|
+
let time = "";
|
|
2252
|
+
let remaining = now;
|
|
2253
|
+
for (let index = 0; index < 10; index++) {
|
|
2254
|
+
time = ALPHABET[remaining % 32] + time;
|
|
2255
|
+
remaining = Math.floor(remaining / 32);
|
|
2256
|
+
}
|
|
2257
|
+
let random = "";
|
|
2258
|
+
for (const byte of crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))) random += ALPHABET[byte % 32];
|
|
2259
|
+
return `evt_${time}${random}`;
|
|
2260
|
+
}
|
|
2261
|
+
/**
|
|
2262
|
+
* A delivery's id: `<event id>:<listener>`, which is why a listener name cannot
|
|
2263
|
+
* contain `:`.
|
|
2264
|
+
*/
|
|
2265
|
+
const deliveryId = (eventId, listener) => `${eventId}:${listener}`;
|
|
2266
|
+
// src/events/outbox.ts
|
|
2267
|
+
const OUTBOX = Symbol.for("brick.outbox");
|
|
2268
|
+
const OUTBOX_STATUSES = [
|
|
2269
|
+
"pending",
|
|
2270
|
+
"claimed",
|
|
2271
|
+
"delivered",
|
|
2272
|
+
"dead"
|
|
2273
|
+
];
|
|
2274
|
+
function sqliteOutbox(name) {
|
|
2275
|
+
const timestampMs = (column) => integer(column, { mode: "timestamp_ms" });
|
|
2276
|
+
return sqliteTable(name, {
|
|
2277
|
+
seq: integer("seq").primaryKey({ autoIncrement: true }),
|
|
2278
|
+
id: text("id").notNull().unique(),
|
|
2279
|
+
eventId: text("event_id").notNull(),
|
|
2280
|
+
listener: text("listener").notNull(),
|
|
2281
|
+
name: text("name").notNull(),
|
|
2282
|
+
payload: text("payload", { mode: "json" }).notNull(),
|
|
2283
|
+
traceId: text("trace_id"),
|
|
2284
|
+
source: text("source"),
|
|
2285
|
+
occurredAt: timestampMs("occurred_at").notNull(),
|
|
2286
|
+
status: text("status").$type().notNull(),
|
|
2287
|
+
attempts: integer("attempts").notNull().default(0),
|
|
2288
|
+
lastError: text("last_error"),
|
|
2289
|
+
availableAt: timestampMs("available_at").notNull(),
|
|
2290
|
+
claimedAt: timestampMs("claimed_at"),
|
|
2291
|
+
deliveredAt: timestampMs("delivered_at")
|
|
2292
|
+
}, (table) => [index(`${name}_due`).on(table.status, table.availableAt), index(`${name}_event`).on(table.eventId)]);
|
|
2293
|
+
}
|
|
2294
|
+
function postgresOutbox(name) {
|
|
2295
|
+
const at = (column) => timestamp(column, { withTimezone: true });
|
|
2296
|
+
return pgTable(name, {
|
|
2297
|
+
seq: bigserial("seq", { mode: "number" }).primaryKey(),
|
|
2298
|
+
id: text$1("id").notNull().unique(),
|
|
2299
|
+
eventId: text$1("event_id").notNull(),
|
|
2300
|
+
listener: text$1("listener").notNull(),
|
|
2301
|
+
name: text$1("name").notNull(),
|
|
2302
|
+
payload: jsonb("payload").notNull(),
|
|
2303
|
+
traceId: text$1("trace_id"),
|
|
2304
|
+
source: text$1("source"),
|
|
2305
|
+
occurredAt: at("occurred_at").notNull(),
|
|
2306
|
+
status: text$1("status").$type().notNull(),
|
|
2307
|
+
attempts: integer$1("attempts").notNull().default(0),
|
|
2308
|
+
lastError: text$1("last_error"),
|
|
2309
|
+
availableAt: at("available_at").notNull(),
|
|
2310
|
+
claimedAt: at("claimed_at"),
|
|
2311
|
+
deliveredAt: at("delivered_at")
|
|
2312
|
+
}, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
|
|
2313
|
+
}
|
|
2314
|
+
function outboxTable(engine, options = {}) {
|
|
2315
|
+
const name = options.name ?? "brick_outbox";
|
|
2316
|
+
const table = engine === "sqlite" ? sqliteOutbox(name) : postgresOutbox(name);
|
|
2317
|
+
Object.defineProperty(table, OUTBOX, { value: { engine } });
|
|
2318
|
+
return table;
|
|
2319
|
+
}
|
|
2320
|
+
/**
|
|
2321
|
+
* Whether a value is an outbox table made by `outboxTable`.
|
|
2322
|
+
*
|
|
2323
|
+
* @param value - Anything.
|
|
2324
|
+
* @returns `true` for an outbox table, narrowing its type.
|
|
2325
|
+
*/
|
|
2326
|
+
function isOutboxTable(value) {
|
|
2327
|
+
return typeof value === "object" && value !== null && OUTBOX in value;
|
|
2328
|
+
}
|
|
2329
|
+
/** The rows that record an event: one per listener, due now. */
|
|
2330
|
+
function outboxRows(event, listeners) {
|
|
2331
|
+
return listeners.map((listener) => ({
|
|
2332
|
+
id: deliveryId(event.id, listener),
|
|
2333
|
+
eventId: event.id,
|
|
2334
|
+
listener,
|
|
2335
|
+
name: event.name,
|
|
2336
|
+
payload: event.payload,
|
|
2337
|
+
traceId: event.traceId ?? null,
|
|
2338
|
+
source: event.source ?? null,
|
|
2339
|
+
occurredAt: event.occurredAt,
|
|
2340
|
+
status: "pending",
|
|
2341
|
+
attempts: 0,
|
|
2342
|
+
availableAt: event.occurredAt
|
|
2343
|
+
}));
|
|
2344
|
+
}
|
|
2345
|
+
/** The delivery a row of `outboxRows` is. */
|
|
2346
|
+
function deliveryOf(row) {
|
|
2347
|
+
return {
|
|
2348
|
+
id: row.eventId,
|
|
2349
|
+
name: row.name,
|
|
2350
|
+
payload: row.payload,
|
|
2351
|
+
occurredAt: row.occurredAt.toISOString(),
|
|
2352
|
+
...row.traceId ? { traceId: row.traceId } : {},
|
|
2353
|
+
...row.source ? { source: row.source } : {},
|
|
2354
|
+
listener: row.listener,
|
|
2355
|
+
deliveryId: row.id,
|
|
2356
|
+
attempt: row.attempts
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
function outboxEngine(table) {
|
|
2360
|
+
return table[OUTBOX].engine;
|
|
2361
|
+
}
|
|
2362
|
+
// src/events/transaction.ts
|
|
2363
|
+
const sqliteQueues = /* @__PURE__ */ new WeakMap();
|
|
2364
|
+
const active = new AsyncLocalStorage();
|
|
2365
|
+
function joined(db) {
|
|
2366
|
+
const open = active.getStore();
|
|
2367
|
+
return open?.open && open.handles.has(db) ? open : void 0;
|
|
2368
|
+
}
|
|
2369
|
+
function isSqliteDatabase(db) {
|
|
2370
|
+
return typeof db?.$client?.prepare === "function" && typeof db?.$client?.run === "function";
|
|
2371
|
+
}
|
|
2372
|
+
function rollbackQuietly(db, statement = "ROLLBACK") {
|
|
2373
|
+
try {
|
|
2374
|
+
db.$client.run(statement);
|
|
2375
|
+
} catch {
|
|
2376
|
+
return;
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
async function nested(db, open, fn) {
|
|
2380
|
+
const commits = open.commits.length;
|
|
2381
|
+
try {
|
|
2382
|
+
if (!isSqliteDatabase(db)) return await db.transaction((tx) => {
|
|
2383
|
+
open.handles.add(tx);
|
|
2384
|
+
return fn(tx);
|
|
2385
|
+
});
|
|
2386
|
+
const name = `brick_${++open.savepoints}`;
|
|
2387
|
+
db.$client.run(`SAVEPOINT ${name}`);
|
|
2388
|
+
try {
|
|
2389
|
+
const result = await fn(db);
|
|
2390
|
+
db.$client.run(`RELEASE ${name}`);
|
|
2391
|
+
return result;
|
|
2392
|
+
} catch (error) {
|
|
2393
|
+
rollbackQuietly(db, `ROLLBACK TO ${name}`);
|
|
2394
|
+
rollbackQuietly(db, `RELEASE ${name}`);
|
|
2395
|
+
throw error;
|
|
2396
|
+
}
|
|
2397
|
+
} catch (error) {
|
|
2398
|
+
open.commits.length = commits;
|
|
2399
|
+
throw error;
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
/**
|
|
2403
|
+
* Run `fn` in a database transaction: everything it writes through the `tx` it is
|
|
2404
|
+
* given is committed together when it returns, or undone if it throws.
|
|
2405
|
+
*
|
|
2406
|
+
* Postgres uses a real transaction on one connection. SQLite has one connection
|
|
2407
|
+
* and a synchronous driver, which Drizzle's own `transaction` cannot use with an
|
|
2408
|
+
* async callback (it would commit before the callback finished). So transactions
|
|
2409
|
+
* on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
|
|
2410
|
+
* A write made elsewhere in the process during that time, outside this helper,
|
|
2411
|
+
* would join the transaction; use Postgres where that matters.
|
|
2412
|
+
*
|
|
2413
|
+
* A call made inside `fn` with the `tx` it was given (on SQLite, the database
|
|
2414
|
+
* itself) joins the open transaction as a savepoint instead of waiting for it: a
|
|
2415
|
+
* nested failure undoes only the nested work, and the outer transaction decides
|
|
2416
|
+
* the commit. Nested calls must run one at a time.
|
|
2417
|
+
*
|
|
2418
|
+
* @param db - A Drizzle database, from `service.getDb()`.
|
|
2419
|
+
* @param fn - Receives the transaction handle to run queries on.
|
|
2420
|
+
* @returns What `fn` returned.
|
|
2421
|
+
* @throws What `fn` threw, after rolling back.
|
|
2422
|
+
*/
|
|
2423
|
+
async function runInTransaction(db, fn) {
|
|
2424
|
+
const outer = joined(db);
|
|
2425
|
+
if (outer) return nested(db, outer, fn);
|
|
2426
|
+
const open = {
|
|
2427
|
+
handles: /* @__PURE__ */ new Set(),
|
|
2428
|
+
commits: [],
|
|
2429
|
+
open: true,
|
|
2430
|
+
savepoints: 0
|
|
2431
|
+
};
|
|
2432
|
+
let result;
|
|
2433
|
+
try {
|
|
2434
|
+
result = await active.run(open, () => begin(db, open, fn));
|
|
2435
|
+
} finally {
|
|
2436
|
+
open.open = false;
|
|
2437
|
+
}
|
|
2438
|
+
for (const commit of open.commits) await commit();
|
|
2439
|
+
return result;
|
|
2440
|
+
}
|
|
2441
|
+
async function begin(db, open, fn) {
|
|
2442
|
+
if (!isSqliteDatabase(db)) return db.transaction((tx) => {
|
|
2443
|
+
open.handles.add(tx);
|
|
2444
|
+
return fn(tx);
|
|
2445
|
+
});
|
|
2446
|
+
open.handles.add(db);
|
|
2447
|
+
const previous = sqliteQueues.get(db) ?? Promise.resolve();
|
|
2448
|
+
let release;
|
|
2449
|
+
const turn = new Promise((resolve) => {
|
|
2450
|
+
release = resolve;
|
|
2451
|
+
});
|
|
2452
|
+
sqliteQueues.set(db, previous.then(() => turn));
|
|
2453
|
+
await previous;
|
|
2454
|
+
try {
|
|
2455
|
+
db.$client.run("BEGIN IMMEDIATE");
|
|
2456
|
+
try {
|
|
2457
|
+
const result = await fn(db);
|
|
2458
|
+
db.$client.run("COMMIT");
|
|
2459
|
+
return result;
|
|
2460
|
+
} catch (error) {
|
|
2461
|
+
rollbackQuietly(db);
|
|
2462
|
+
throw error;
|
|
2463
|
+
}
|
|
2464
|
+
} finally {
|
|
2465
|
+
release();
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
|
|
2469
|
+
function inTransaction(db) {
|
|
2470
|
+
return joined(db) !== void 0;
|
|
2471
|
+
}
|
|
2472
|
+
/**
|
|
2473
|
+
* Run `fn` once the transaction that `db` belongs to has committed, or now when
|
|
2474
|
+
* `db` is not in one opened by `runInTransaction`. It never runs when that
|
|
2475
|
+
* transaction, or the savepoint it was queued in, rolls back. An error it throws
|
|
2476
|
+
* reaches the caller of the outermost `runInTransaction`, after the commit.
|
|
2477
|
+
*
|
|
2478
|
+
* @param db - The handle the work ran on: a `tx`, or a database.
|
|
2479
|
+
* @param fn - The side effect, such as clearing a cache.
|
|
2480
|
+
*/
|
|
2481
|
+
async function onTransactionCommit(db, fn) {
|
|
2482
|
+
const open = joined(db);
|
|
2483
|
+
if (open) open.commits.push(fn);
|
|
2484
|
+
else await fn();
|
|
2485
|
+
}
|
|
2486
|
+
// src/events/dispatcher.ts
|
|
2487
|
+
function resolveDispatchOptions(options) {
|
|
2488
|
+
return {
|
|
2489
|
+
timer: options.timer ?? true,
|
|
2490
|
+
intervalMs: options.intervalMs ?? 1e3,
|
|
2491
|
+
batchSize: options.batchSize ?? 50,
|
|
2492
|
+
maxAttempts: options.maxAttempts ?? 8,
|
|
2493
|
+
claimTimeoutMs: options.claimTimeoutMs ?? 6e4,
|
|
2494
|
+
maxBackoffMs: options.maxBackoffMs ?? 3e5,
|
|
2495
|
+
retainDeliveredMs: options.retainDeliveredMs ?? 864e5
|
|
2496
|
+
};
|
|
2497
|
+
}
|
|
2498
|
+
const PURGE_INTERVAL_MS = 6e4;
|
|
2499
|
+
/** Listeners whose `retry` threw, logged once each. */
|
|
2500
|
+
const brokenRetry = /* @__PURE__ */ new WeakSet();
|
|
2501
|
+
/** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry", and is logged once. */
|
|
2502
|
+
function decideRetry(name, listener, error) {
|
|
2503
|
+
if (!listener.retry) return "retry";
|
|
2504
|
+
try {
|
|
2505
|
+
return listener.retry(error instanceof ActionExecutionError && listener.errors?.[error.code] ? {
|
|
2506
|
+
code: error.code,
|
|
2507
|
+
message: error.message,
|
|
2508
|
+
details: error.details
|
|
2509
|
+
} : {
|
|
2510
|
+
code: "UNKNOWN",
|
|
2511
|
+
message: error instanceof Error ? error.message : String(error),
|
|
2512
|
+
cause: error
|
|
2513
|
+
});
|
|
2514
|
+
} catch (thrown) {
|
|
2515
|
+
if (!brokenRetry.has(listener)) {
|
|
2516
|
+
brokenRetry.add(listener);
|
|
2517
|
+
console.error(`[Brick-TS events] Listener '${name}': its retry() threw, so the failure is retried. Later throws are not logged.`, thrown);
|
|
2518
|
+
}
|
|
2519
|
+
return "retry";
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
function backoffMs(attempt, maxBackoffMs) {
|
|
2523
|
+
return Math.min(1e3 * 2 ** Math.max(0, attempt - 1), maxBackoffMs);
|
|
2524
|
+
}
|
|
2525
|
+
/**
|
|
2526
|
+
* Delivers the events recorded in one outbox table to the app's listeners.
|
|
2527
|
+
*
|
|
2528
|
+
* It claims a batch of due rows, runs each listener, and marks the row delivered.
|
|
2529
|
+
* A listener that throws is retried later with a growing delay, and parked as
|
|
2530
|
+
* dead after its attempts run out. Several dispatchers can share a table: on
|
|
2531
|
+
* Postgres they claim with `FOR UPDATE SKIP LOCKED`, and a claim that is not
|
|
2532
|
+
* finished within `claimTimeoutMs` (the process died) is taken by another.
|
|
2533
|
+
* Delivery is at least once, so a listener should tolerate running twice for the
|
|
2534
|
+
* same `deliveryId`.
|
|
2535
|
+
*/
|
|
2536
|
+
var Dispatcher = class {
|
|
2537
|
+
db;
|
|
2538
|
+
table;
|
|
2539
|
+
listeners;
|
|
2540
|
+
engine;
|
|
2541
|
+
options;
|
|
2542
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
2543
|
+
timer;
|
|
2544
|
+
tickQueue;
|
|
2545
|
+
lastPurge = 0;
|
|
2546
|
+
constructor(db, table, listeners, options = {}) {
|
|
2547
|
+
this.db = db;
|
|
2548
|
+
this.table = table;
|
|
2549
|
+
this.listeners = listeners;
|
|
2550
|
+
this.engine = outboxEngine(table);
|
|
2551
|
+
this.options = resolveDispatchOptions(options);
|
|
2552
|
+
}
|
|
2553
|
+
/** Start looking for due deliveries on a timer. Does nothing if it already is. */
|
|
2554
|
+
start() {
|
|
2555
|
+
if (this.timer || !this.options.timer) return;
|
|
2556
|
+
this.timer = setInterval(() => void this.tick(), this.options.intervalMs);
|
|
2557
|
+
this.timer.unref?.();
|
|
2558
|
+
this.tick();
|
|
2559
|
+
}
|
|
2560
|
+
/** Stop the timer and wait for the deliveries that are running to finish. */
|
|
2561
|
+
async stop() {
|
|
2562
|
+
if (this.timer) clearInterval(this.timer);
|
|
2563
|
+
this.timer = void 0;
|
|
2564
|
+
await this.tickQueue;
|
|
2565
|
+
await Promise.allSettled(this.inFlight);
|
|
2566
|
+
}
|
|
2567
|
+
/** Look for work soon, without waiting for the timer. Safe to call often. */
|
|
2568
|
+
notify() {
|
|
2569
|
+
if (!this.timer) return;
|
|
2570
|
+
setTimeout(() => void this.tick(), 0).unref?.();
|
|
2571
|
+
}
|
|
2572
|
+
/** Claim what is due and run it, once. @returns How many deliveries it started. */
|
|
2573
|
+
tick() {
|
|
2574
|
+
this.tickQueue = (this.tickQueue ?? Promise.resolve(0)).then(() => this.claimAndRun(), () => this.claimAndRun());
|
|
2575
|
+
return this.tickQueue;
|
|
2576
|
+
}
|
|
2577
|
+
/**
|
|
2578
|
+
* Deliver everything that is due now and wait until those deliveries are done.
|
|
2579
|
+
* Deliveries that fail and are rescheduled are not waited for again.
|
|
2580
|
+
*
|
|
2581
|
+
* @returns How many deliveries it ran.
|
|
2582
|
+
*/
|
|
2583
|
+
async drain() {
|
|
2584
|
+
let total = 0;
|
|
2585
|
+
for (;;) {
|
|
2586
|
+
const started = await this.tick();
|
|
2587
|
+
await Promise.allSettled(this.inFlight);
|
|
2588
|
+
if (started === 0) return total;
|
|
2589
|
+
total += started;
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
async counts() {
|
|
2593
|
+
const t = this.table;
|
|
2594
|
+
const rows = await this.db.select({
|
|
2595
|
+
status: t.status,
|
|
2596
|
+
count: sql`count(*)`
|
|
2597
|
+
}).from(t).groupBy(t.status);
|
|
2598
|
+
const counts = Object.fromEntries(OUTBOX_STATUSES.map((status) => [status, 0]));
|
|
2599
|
+
for (const row of rows) counts[row.status] = Number(row.count);
|
|
2600
|
+
return counts;
|
|
2601
|
+
}
|
|
2602
|
+
/**
|
|
2603
|
+
* Put parked deliveries back in line, with their attempts reset.
|
|
2604
|
+
*
|
|
2605
|
+
* @param deliveryId - One delivery to retry. Omit it to retry every dead one.
|
|
2606
|
+
* @returns How many deliveries were put back.
|
|
2607
|
+
*/
|
|
2608
|
+
async retryDead(deliveryId) {
|
|
2609
|
+
const t = this.table;
|
|
2610
|
+
const rows = await this.db.update(t).set({
|
|
2611
|
+
status: "pending",
|
|
2612
|
+
attempts: 0,
|
|
2613
|
+
availableAt: /* @__PURE__ */ new Date()
|
|
2614
|
+
}).where(deliveryId ? and(eq(t.status, "dead"), eq(t.id, deliveryId)) : eq(t.status, "dead")).returning({ id: t.id });
|
|
2615
|
+
if (rows.length) this.notify();
|
|
2616
|
+
return rows.length;
|
|
2617
|
+
}
|
|
2618
|
+
async claimAndRun() {
|
|
2619
|
+
try {
|
|
2620
|
+
const room = this.options.batchSize - this.inFlight.size;
|
|
2621
|
+
if (room <= 0) return 0;
|
|
2622
|
+
const rows = await this.claim(room);
|
|
2623
|
+
for (const row of rows) {
|
|
2624
|
+
const run = this.deliver(row).finally(() => {
|
|
2625
|
+
this.inFlight.delete(run);
|
|
2626
|
+
});
|
|
2627
|
+
this.inFlight.add(run);
|
|
2628
|
+
}
|
|
2629
|
+
await this.purgeDelivered();
|
|
2630
|
+
return rows.length;
|
|
2631
|
+
} catch (error) {
|
|
2632
|
+
this.logError(error);
|
|
2633
|
+
return 0;
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
async claim(limit) {
|
|
2637
|
+
const t = this.table;
|
|
2638
|
+
const now = /* @__PURE__ */ new Date();
|
|
2639
|
+
const stale = new Date(now.getTime() - this.options.claimTimeoutMs);
|
|
2640
|
+
const due = or(and(eq(t.status, "pending"), lte(t.availableAt, now)), and(eq(t.status, "claimed"), lt(t.claimedAt, stale)));
|
|
2641
|
+
const claimIn = async (tx) => {
|
|
2642
|
+
let select = tx.select().from(t).where(due).orderBy(asc(t.seq)).limit(limit);
|
|
2643
|
+
if (this.engine === "postgres") select = select.for("update", { skipLocked: true });
|
|
2644
|
+
const picked = await select;
|
|
2645
|
+
if (!picked.length) return [];
|
|
2646
|
+
await tx.update(t).set({
|
|
2647
|
+
status: "claimed",
|
|
2648
|
+
claimedAt: now,
|
|
2649
|
+
attempts: sql`${t.attempts} + 1`
|
|
2650
|
+
}).where(inArray(t.seq, picked.map((row) => row.seq)));
|
|
2651
|
+
return picked.map((row) => ({
|
|
2652
|
+
...row,
|
|
2653
|
+
attempts: row.attempts + 1
|
|
2654
|
+
}));
|
|
2655
|
+
};
|
|
2656
|
+
return this.engine === "postgres" ? this.db.transaction(claimIn) : runInTransaction(this.db, claimIn);
|
|
2657
|
+
}
|
|
2658
|
+
async deliver(row) {
|
|
2659
|
+
const listener = this.listeners(row.listener);
|
|
2660
|
+
if (!listener) {
|
|
2661
|
+
await this.park(row, `No listener named '${row.listener}' is registered`);
|
|
2662
|
+
return;
|
|
2663
|
+
}
|
|
2664
|
+
try {
|
|
2665
|
+
await listener.run(deliveryOf(row));
|
|
2666
|
+
} catch (error) {
|
|
2667
|
+
await this.fail(row, error, listener.maxAttempts ?? this.options.maxAttempts, decideRetry(row.listener, listener, error));
|
|
2668
|
+
return;
|
|
2669
|
+
}
|
|
2670
|
+
await this.markDelivered(row);
|
|
2671
|
+
}
|
|
2672
|
+
async markDelivered(row) {
|
|
2673
|
+
const t = this.table;
|
|
2674
|
+
try {
|
|
2675
|
+
if (this.options.retainDeliveredMs === 0) await this.db.delete(t).where(eq(t.seq, row.seq));
|
|
2676
|
+
else await this.db.update(t).set({
|
|
2677
|
+
status: "delivered",
|
|
2678
|
+
deliveredAt: /* @__PURE__ */ new Date(),
|
|
2679
|
+
lastError: null
|
|
2680
|
+
}).where(eq(t.seq, row.seq));
|
|
2681
|
+
} catch (error) {
|
|
2682
|
+
this.logError(error);
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
async fail(row, error, maxAttempts, decision) {
|
|
2686
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2687
|
+
if (decision === "dead" || row.attempts >= maxAttempts) {
|
|
2688
|
+
await this.park(row, message);
|
|
2689
|
+
return;
|
|
2690
|
+
}
|
|
2691
|
+
const t = this.table;
|
|
2692
|
+
try {
|
|
2693
|
+
await this.db.update(t).set({
|
|
2694
|
+
status: "pending",
|
|
2695
|
+
lastError: message,
|
|
2696
|
+
claimedAt: null,
|
|
2697
|
+
availableAt: new Date(Date.now() + backoffMs(row.attempts, this.options.maxBackoffMs))
|
|
2698
|
+
}).where(eq(t.seq, row.seq));
|
|
2699
|
+
} catch (writeError) {
|
|
2700
|
+
this.logError(writeError);
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
async park(row, message) {
|
|
2704
|
+
const t = this.table;
|
|
2705
|
+
try {
|
|
2706
|
+
await this.db.update(t).set({
|
|
2707
|
+
status: "dead",
|
|
2708
|
+
lastError: message,
|
|
2709
|
+
claimedAt: null
|
|
2710
|
+
}).where(eq(t.seq, row.seq));
|
|
2711
|
+
} catch (error) {
|
|
2712
|
+
this.logError(error);
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
logError(error) {
|
|
2716
|
+
console.error("[Brick-TS events]", error);
|
|
2717
|
+
}
|
|
2718
|
+
async purgeDelivered() {
|
|
2719
|
+
const keep = this.options.retainDeliveredMs;
|
|
2720
|
+
const now = Date.now();
|
|
2721
|
+
if (keep === 0 || now - this.lastPurge < PURGE_INTERVAL_MS) return;
|
|
2722
|
+
this.lastPurge = now;
|
|
2723
|
+
const t = this.table;
|
|
2724
|
+
await this.db.delete(t).where(and(eq(t.status, "delivered"), lt(t.deliveredAt, new Date(now - keep))));
|
|
2725
|
+
}
|
|
2726
|
+
};
|
|
2727
|
+
// src/events/catalog.ts
|
|
2728
|
+
function isEventRef(value) {
|
|
2729
|
+
return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.service === "string" && typeof value.schema === "object";
|
|
2730
|
+
}
|
|
2731
|
+
/** Build `service.events` from its catalog. */
|
|
2732
|
+
function eventRefs(service, catalog) {
|
|
2733
|
+
const refs = Object.create(null);
|
|
2734
|
+
for (const [key, schema] of Object.entries(catalog ?? {})) {
|
|
2735
|
+
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`);
|
|
2736
|
+
if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
|
|
2737
|
+
refs[key] = Object.freeze({
|
|
2738
|
+
name: `${service}.${key}`,
|
|
2739
|
+
service,
|
|
2740
|
+
schema
|
|
2741
|
+
});
|
|
2742
|
+
}
|
|
2743
|
+
return Object.freeze(refs);
|
|
2744
|
+
}
|
|
2745
|
+
/** @throws When the payload does not match the event's schema. */
|
|
2746
|
+
function checkPayload(ref, payload) {
|
|
2747
|
+
const result = validateWithSchema(ref.schema, payload);
|
|
2748
|
+
if (!result.success) throw new Error(`Event "${ref.name}" payload does not match its schema: ${result.errors.map((error) => `${error.path || "/"} ${error.message}`).join("; ")}`);
|
|
2749
|
+
}
|
|
2750
|
+
/** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
|
|
2751
|
+
const CRUD_EVENT_OPERATIONS = [
|
|
2752
|
+
"create",
|
|
2753
|
+
"update",
|
|
2754
|
+
"delete"
|
|
2755
|
+
];
|
|
2756
|
+
/** The event a CRUD write records: `<resource>.<operation>`. */
|
|
2757
|
+
const crudEventName = (resource, operation) => `${resource}.${operation}`;
|
|
2758
|
+
/** The `source` of a resource's events: `<service>.<resource>`. */
|
|
2759
|
+
const crudEventSource = (service, resource) => `${service}.${resource}`;
|
|
2760
|
+
/** Whether `name` is the CRUD event of one of `resources`. */
|
|
2761
|
+
function isCrudEvent(name, resources) {
|
|
2762
|
+
const dot = name.indexOf(".");
|
|
2763
|
+
return dot > 0 && CRUD_EVENT_OPERATIONS.includes(name.slice(dot + 1)) && resources.includes(name.slice(0, dot));
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* Check an event against the catalog of the service recording it. Without a
|
|
2767
|
+
* catalog any name goes. With one, the name must be `<service>.<event>` from it
|
|
2768
|
+
* (the payload is checked against its schema) or a CRUD event of one of the
|
|
2769
|
+
* service's resources (`<resource>.create|update|delete`).
|
|
2770
|
+
*
|
|
2771
|
+
* @throws When the name is not declared or the payload does not match.
|
|
2772
|
+
*/
|
|
2773
|
+
function checkEvent(service, name, payload) {
|
|
2774
|
+
const prefix = `${service.name}.`;
|
|
2775
|
+
const ref = name.startsWith(prefix) ? service.events[name.slice(prefix.length)] : void 0;
|
|
2776
|
+
if (ref) return checkPayload(ref, payload);
|
|
2777
|
+
if (!service.hasCatalog) return;
|
|
2778
|
+
if (isCrudEvent(name, service.listResources().map((r) => r.name))) return;
|
|
2779
|
+
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"})`);
|
|
2780
|
+
}
|
|
2781
|
+
// src/events/listener.ts
|
|
2782
|
+
function defineListener(config) {
|
|
2783
|
+
const on = (Array.isArray(config.on) ? config.on : [config.on]).map((item) => isEventRef(item) ? item.name : item);
|
|
2784
|
+
validateListener({
|
|
2785
|
+
...config,
|
|
2786
|
+
on
|
|
2787
|
+
});
|
|
2788
|
+
const helpers = buildErrorHelpers(config.errors);
|
|
2789
|
+
return Object.freeze({
|
|
2790
|
+
name: config.name,
|
|
2791
|
+
on: Object.freeze(on),
|
|
2792
|
+
...config.run !== void 0 ? { run: ((delivery) => config.run(delivery, { error: helpers })) } : {},
|
|
2793
|
+
...config.errors ? { errors: config.errors } : {},
|
|
2794
|
+
...config.retry ? { retry: config.retry } : {},
|
|
2795
|
+
...config.workflow !== void 0 ? { workflow: config.workflow } : {},
|
|
2796
|
+
...config.maxAttempts !== void 0 ? { maxAttempts: config.maxAttempts } : {}
|
|
2797
|
+
});
|
|
2798
|
+
}
|
|
2799
|
+
/**
|
|
2800
|
+
* @throws When the name is empty or contains `:`, `on` is empty, `maxAttempts`
|
|
2801
|
+
* is not a positive integer, or the listener has both or neither of `run` and
|
|
2802
|
+
* `workflow`.
|
|
2803
|
+
*/
|
|
2804
|
+
function validateListener(listener) {
|
|
2805
|
+
const { name, on, maxAttempts, run, workflow } = listener;
|
|
2806
|
+
if (typeof name !== "string" || !name) throw new Error("An event listener needs a name");
|
|
2807
|
+
if (name.includes(":")) throw new Error(`Event listener name '${name}' must not contain ':'`);
|
|
2808
|
+
if (!Array.isArray(on) || !on.length || on.some((pattern) => !pattern || typeof pattern !== "string")) throw new Error(`Event listener '${name}' listens for nothing`);
|
|
2809
|
+
if (maxAttempts !== void 0 && (!Number.isInteger(maxAttempts) || maxAttempts < 1)) throw new Error(`Event listener '${name}': maxAttempts must be a positive integer`);
|
|
2810
|
+
if (run !== void 0 && workflow !== void 0) throw new Error(`Event listener '${name}' has both run and workflow; give it one`);
|
|
2811
|
+
if (run === void 0 && workflow === void 0) throw new Error(`Event listener '${name}' needs a run handler or a workflow`);
|
|
2812
|
+
if (run !== void 0 && typeof run !== "function") throw new Error(`Event listener '${name}': run must be a function`);
|
|
2813
|
+
if (workflow !== void 0 && typeof workflow !== "function") throw new Error(`Event listener '${name}': workflow must be a function marked "use workflow"`);
|
|
2814
|
+
}
|
|
2815
|
+
/** The deps a plugin's listener runs with, set by the plugin install; `undefined` for the app's own. */
|
|
2816
|
+
const listenerDeps = (listener) => listener[PLUGIN_DEPS];
|
|
2817
|
+
// src/events/workflows.ts
|
|
2818
|
+
/** The workflow bundle `buildWorkflows()` writes and the runtime reads: its directory under the project root, and its files. */
|
|
2819
|
+
const WORKFLOW_BUNDLE = {
|
|
2820
|
+
dir: ".well-known/workflow/v1",
|
|
2821
|
+
flow: "flow.mjs",
|
|
2822
|
+
steps: "__step_registrations.mjs",
|
|
2823
|
+
webhook: "webhook.mjs",
|
|
2824
|
+
manifest: "manifest.json"
|
|
2825
|
+
};
|
|
2826
|
+
/** From the Workflow SDK: the queue a workflow run goes to (`getQueueTopicPrefix("workflow")` in `@workflow/world`), and the header a world names it in. */
|
|
2827
|
+
const WORKFLOW_QUEUE = {
|
|
2828
|
+
prefix: "__wkf_workflow_",
|
|
2829
|
+
header: "x-vqs-queue-name"
|
|
2830
|
+
};
|
|
2831
|
+
const STOPPED = "The events were stopped, so workflows can no longer run";
|
|
2832
|
+
const NOT_BUILT = "brick dev and brick start build it; in a test or script, call buildWorkflows() from @brickkit/cli/workflows first.";
|
|
2833
|
+
/** Where the SDK builds the URL of a webhook: the route `handleWebhook` serves. */
|
|
2834
|
+
const WEBHOOK_ROUTE = `/${WORKFLOW_BUNDLE.dir}/webhook/*`;
|
|
2835
|
+
/** Where the transform and the bundle register steps by id. The SDK's own generated code uses it. */
|
|
2836
|
+
const STEP_REGISTRY = Symbol.for("@workflow/core//registeredSteps");
|
|
2837
|
+
/**
|
|
2838
|
+
* Where the workflow bundle is read from, and the project it is built from.
|
|
2839
|
+
*
|
|
2840
|
+
* @param options - The `events.workflows` option.
|
|
2841
|
+
* @returns Absolute `root` and `dir`. The bundle cannot live elsewhere: the
|
|
2842
|
+
* builder finds the SDK from where it writes, and skips only this directory when it
|
|
2843
|
+
* looks for workflows.
|
|
2844
|
+
*/
|
|
2845
|
+
function resolveWorkflowPaths(options = {}) {
|
|
2846
|
+
const root = resolve(options.root ?? process.cwd());
|
|
2847
|
+
return {
|
|
2848
|
+
root,
|
|
2849
|
+
dir: join(root, WORKFLOW_BUNDLE.dir)
|
|
2850
|
+
};
|
|
2851
|
+
}
|
|
2852
|
+
/**
|
|
2853
|
+
* Runs workflow listeners: wires the world into the Workflow SDK, serves the
|
|
2854
|
+
* built bundle from this process, and starts one run for each delivery.
|
|
2855
|
+
*
|
|
2856
|
+
* Nothing is loaded until it is needed, so an app without workflow listeners
|
|
2857
|
+
* never imports the SDK.
|
|
2858
|
+
*/
|
|
2859
|
+
var WorkflowRuntime = class {
|
|
2860
|
+
world;
|
|
2861
|
+
listeners;
|
|
2862
|
+
deps;
|
|
2863
|
+
root;
|
|
2864
|
+
dir;
|
|
2865
|
+
ready;
|
|
2866
|
+
connected;
|
|
2867
|
+
closed = false;
|
|
2868
|
+
constructor(world, options, listeners, deps = {}) {
|
|
2869
|
+
this.world = world;
|
|
2870
|
+
this.listeners = listeners;
|
|
2871
|
+
this.deps = deps;
|
|
2872
|
+
({root: this.root, dir: this.dir} = resolveWorkflowPaths(options));
|
|
2873
|
+
}
|
|
2874
|
+
/** Begin loading the runtime now rather than at the first delivery. */
|
|
2875
|
+
warmUp() {
|
|
2876
|
+
this.ensure().catch((error) => console.error(`[Brick-TS] The workflow runtime did not start: ${error instanceof Error ? error.message : String(error)}`));
|
|
2877
|
+
}
|
|
2878
|
+
/**
|
|
2879
|
+
* Start the run for a delivery.
|
|
2880
|
+
*
|
|
2881
|
+
* The run is named after the delivery id, so a delivery that is tried again
|
|
2882
|
+
* finds the run it already started instead of starting another.
|
|
2883
|
+
*
|
|
2884
|
+
* @param listener - The workflow listener the delivery is for.
|
|
2885
|
+
* @param delivery - The delivery.
|
|
2886
|
+
*/
|
|
2887
|
+
async startRun(listener, delivery) {
|
|
2888
|
+
const sdk = await this.ensure();
|
|
2889
|
+
const { attempt: _attempt, ...event } = delivery;
|
|
2890
|
+
await sdk.start(listener.workflow, [event], {
|
|
2891
|
+
world: this.world,
|
|
2892
|
+
runKey: delivery.deliveryId,
|
|
2893
|
+
runKeyTime: Date.parse(delivery.occurredAt)
|
|
2894
|
+
});
|
|
2895
|
+
}
|
|
2896
|
+
/**
|
|
2897
|
+
* Answer a request to a webhook a workflow created with `createWebhook`, by
|
|
2898
|
+
* resuming the workflow that waits on it. Needs the world but not the queue
|
|
2899
|
+
* consumer, so a process that only records events (`dispatch: false`) serves
|
|
2900
|
+
* webhooks too.
|
|
2901
|
+
*
|
|
2902
|
+
* @param request - The request to `/.well-known/workflow/v1/webhook/<token>`.
|
|
2903
|
+
* @returns The response the bundle's webhook handler gives.
|
|
2904
|
+
*/
|
|
2905
|
+
async handleWebhook(request) {
|
|
2906
|
+
await this.connect();
|
|
2907
|
+
const file = join(this.dir, WORKFLOW_BUNDLE.webhook);
|
|
2908
|
+
if (!existsSync(file)) throw new Error(`No webhook bundle at ${file}. ${NOT_BUILT}`);
|
|
2909
|
+
const handler = (await import(pathToFileURL(file).href))[request.method];
|
|
2910
|
+
if (typeof handler !== "function") return new Response(null, { status: 405 });
|
|
2911
|
+
return handler(request);
|
|
2912
|
+
}
|
|
2913
|
+
/** Stop the world. The runtime cannot be started again afterwards. */
|
|
2914
|
+
async close() {
|
|
2915
|
+
this.closed = true;
|
|
2916
|
+
await this.ready?.catch(() => {});
|
|
2917
|
+
await this.connected?.catch(() => {});
|
|
2918
|
+
await this.world.close?.();
|
|
2919
|
+
}
|
|
2920
|
+
ensure() {
|
|
2921
|
+
if (this.closed) return Promise.reject(/* @__PURE__ */ new Error(STOPPED));
|
|
2922
|
+
this.ready ??= this.initialize().catch((error) => {
|
|
2923
|
+
this.ready = void 0;
|
|
2924
|
+
throw error;
|
|
2925
|
+
});
|
|
2926
|
+
return this.ready;
|
|
2927
|
+
}
|
|
2928
|
+
/** Load the SDK and give it the world: all a webhook needs. */
|
|
2929
|
+
connect() {
|
|
2930
|
+
if (this.closed) return Promise.reject(/* @__PURE__ */ new Error(STOPPED));
|
|
2931
|
+
this.connected ??= this.loadSdk().then((sdk) => {
|
|
2932
|
+
sdk.setWorld(this.world);
|
|
2933
|
+
return sdk;
|
|
2934
|
+
}).catch((error) => {
|
|
2935
|
+
this.connected = void 0;
|
|
2936
|
+
throw error;
|
|
2937
|
+
});
|
|
2938
|
+
return this.connected;
|
|
2939
|
+
}
|
|
2940
|
+
async initialize() {
|
|
2941
|
+
if (typeof this.world.createRunId !== "function") throw new Error("This world cannot name a run after its key, so an event delivered twice would start two runs. Use the world from @brickkit/redis-world or @brickkit/bullmq-world.");
|
|
2942
|
+
const sdk = await this.connect();
|
|
2943
|
+
const flow = join(this.dir, WORKFLOW_BUNDLE.flow);
|
|
2944
|
+
if (!existsSync(flow)) throw new Error(`No workflow bundle at ${flow}. ${NOT_BUILT}`);
|
|
2945
|
+
const manifest = this.readManifest();
|
|
2946
|
+
const depsOf = this.checkListeners(manifest);
|
|
2947
|
+
const bundle = await this.loadBundle(flow);
|
|
2948
|
+
if (typeof bundle.POST !== "function") throw new Error(`${flow} does not export a POST handler`);
|
|
2949
|
+
const post = bundle.POST;
|
|
2950
|
+
this.world.registerHandler?.(WORKFLOW_QUEUE.prefix, (request) => {
|
|
2951
|
+
const queue = request.headers.get(WORKFLOW_QUEUE.header) ?? "";
|
|
2952
|
+
return runWithDeps(depsOf.get(queue.slice(WORKFLOW_QUEUE.prefix.length)) ?? this.deps, () => post(request));
|
|
2953
|
+
});
|
|
2954
|
+
await this.world.start?.();
|
|
2955
|
+
return sdk;
|
|
2956
|
+
}
|
|
2957
|
+
async loadSdk() {
|
|
2958
|
+
const from = createRequire(join(this.root, "package.json"));
|
|
2959
|
+
const load = async (specifier) => {
|
|
2960
|
+
let path;
|
|
2961
|
+
try {
|
|
2962
|
+
path = from.resolve(specifier);
|
|
2963
|
+
} catch {
|
|
2964
|
+
throw new Error(`The Workflow SDK is not installed in ${this.root} (could not resolve '${specifier}'). Add it with: bun add workflow`);
|
|
2965
|
+
}
|
|
2966
|
+
return import(pathToFileURL(path).href);
|
|
2967
|
+
};
|
|
2968
|
+
const [api, runtime] = await Promise.all([load("workflow/api"), load("workflow/runtime")]);
|
|
2969
|
+
return {
|
|
2970
|
+
start: api.start,
|
|
2971
|
+
setWorld: runtime.setWorld
|
|
2972
|
+
};
|
|
2973
|
+
}
|
|
2974
|
+
/**
|
|
2975
|
+
* The bundle holds its own copy of every step and registers them all when it
|
|
2976
|
+
* loads, replacing the ones the app registered. A copy has its own module state:
|
|
2977
|
+
* a step would find no database connection, no config, none of what the app set
|
|
2978
|
+
* up. So the app's steps are put back, and the bundle's copies serve only the
|
|
2979
|
+
* steps the app never loaded.
|
|
2980
|
+
*/
|
|
2981
|
+
async loadBundle(flow) {
|
|
2982
|
+
const registry = () => globalThis[STEP_REGISTRY];
|
|
2983
|
+
const app = new Map(registry());
|
|
2984
|
+
const bundle = await import(pathToFileURL(flow).href);
|
|
2985
|
+
const registered = registry();
|
|
2986
|
+
if (registered) for (const [id, step] of app) registered.set(id, step);
|
|
2987
|
+
return bundle;
|
|
2988
|
+
}
|
|
2989
|
+
readManifest() {
|
|
2990
|
+
const path = join(this.dir, WORKFLOW_BUNDLE.manifest);
|
|
2991
|
+
if (!existsSync(path)) return void 0;
|
|
2992
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
2993
|
+
}
|
|
2994
|
+
/**
|
|
2995
|
+
* A listener's workflow must carry the id the transform gives it, and the bundle
|
|
2996
|
+
* must know that id: a function that was never transformed, or a bundle built
|
|
2997
|
+
* before the workflow existed, would fail on its first delivery with a less
|
|
2998
|
+
* helpful message.
|
|
2999
|
+
*
|
|
3000
|
+
* @returns The deps each workflow's steps run with, by workflow id.
|
|
3001
|
+
* @throws When one workflow is run by listeners with different deps (an app
|
|
3002
|
+
* and a plugin, or two plugin installs): its steps could see only one set.
|
|
3003
|
+
*/
|
|
3004
|
+
checkListeners(manifest) {
|
|
3005
|
+
const depsOf = /* @__PURE__ */ new Map();
|
|
3006
|
+
const known = /* @__PURE__ */ new Set();
|
|
3007
|
+
for (const file of Object.values(manifest?.workflows ?? {})) for (const entry of Object.values(file)) if (entry.workflowId) known.add(entry.workflowId);
|
|
3008
|
+
for (const listener of this.listeners) {
|
|
3009
|
+
const id = listener.workflow?.workflowId;
|
|
3010
|
+
if (typeof id !== "string") throw new Error(`The workflow of listener '${listener.name}' was not transformed. Run the app with brick dev or brick start, or call registerWorkflowTransform() from @brickkit/cli/workflows before importing it.`);
|
|
3011
|
+
if (manifest && !known.has(id)) throw new Error(`The workflow bundle does not contain '${id}' (listener '${listener.name}'). Rebuild it with brick dev or brick start.`);
|
|
3012
|
+
const deps = listenerDeps(listener) ?? this.deps;
|
|
3013
|
+
if ((depsOf.get(id) ?? deps) !== deps) throw new Error(`Workflow '${id}' is run by listeners with different deps (listener '${listener.name}'); give each app or plugin install its own workflow.`);
|
|
3014
|
+
depsOf.set(id, deps);
|
|
3015
|
+
}
|
|
3016
|
+
return depsOf;
|
|
3017
|
+
}
|
|
3018
|
+
};
|
|
3019
|
+
// src/events/hub.ts
|
|
3020
|
+
function matchesEvent(pattern, name) {
|
|
3021
|
+
if (pattern === "*") return true;
|
|
3022
|
+
if (pattern.endsWith("*")) return name.startsWith(pattern.slice(0, -1));
|
|
3023
|
+
return pattern === name;
|
|
3024
|
+
}
|
|
3025
|
+
/** The service of each database that records events, so `emitEvent(ctx, ...)` can find it from `ctx.db`. */
|
|
3026
|
+
const recordingServices = /* @__PURE__ */ new WeakMap();
|
|
3027
|
+
const startedHubs = globalThis[Symbol.for(GLOBAL_SYMBOL.eventsStarted)] ??= /* @__PURE__ */ new Set();
|
|
3028
|
+
/**
|
|
3029
|
+
* Stop every events hub started in this process, by any copy of `@brickkit/core`,
|
|
3030
|
+
* and wait for their deliveries. A hub that fails to stop does not cut the wait
|
|
3031
|
+
* for the others: the first failure is thrown once every hub is done.
|
|
3032
|
+
*/
|
|
3033
|
+
async function stopAllEvents() {
|
|
3034
|
+
const failed = (await Promise.allSettled([...startedHubs].map((hub) => hub.stop()))).find((result) => result.status === "rejected");
|
|
3035
|
+
if (failed) throw failed.reason;
|
|
3036
|
+
}
|
|
3037
|
+
/**
|
|
3038
|
+
* The events of one app: who listens, where events are recorded, and the
|
|
3039
|
+
* dispatchers that deliver them. `brick({ events })` makes one and puts it on
|
|
3040
|
+
* `app.events`.
|
|
3041
|
+
*/
|
|
3042
|
+
var EventsHub = class {
|
|
3043
|
+
deps;
|
|
3044
|
+
byName = /* @__PURE__ */ new Map();
|
|
3045
|
+
dispatchers = /* @__PURE__ */ new Map();
|
|
3046
|
+
deliverables = /* @__PURE__ */ new Map();
|
|
3047
|
+
dispatchOptions;
|
|
3048
|
+
runtime;
|
|
3049
|
+
recorderNames = [];
|
|
3050
|
+
started = false;
|
|
3051
|
+
stopping;
|
|
3052
|
+
/**
|
|
3053
|
+
* @param options - The `events` option.
|
|
3054
|
+
* @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
|
|
3055
|
+
* listeners and workflow steps.
|
|
3056
|
+
*/
|
|
3057
|
+
constructor(options, deps = {}) {
|
|
3058
|
+
this.deps = deps;
|
|
3059
|
+
for (const listener of options.listeners ?? []) {
|
|
3060
|
+
validateListener(listener);
|
|
3061
|
+
if (this.byName.has(listener.name)) throw new DuplicateNameError(`Duplicate event listener '${listener.name}'`);
|
|
3062
|
+
this.byName.set(listener.name, listener);
|
|
3063
|
+
}
|
|
3064
|
+
const workflowListeners = [...this.byName.values()].filter((listener) => listener.workflow);
|
|
3065
|
+
if (workflowListeners.length) {
|
|
3066
|
+
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.`);
|
|
3067
|
+
this.runtime = new WorkflowRuntime(options.world, options.workflows, workflowListeners, deps);
|
|
3068
|
+
}
|
|
3069
|
+
this.dispatchOptions = options.dispatch === false ? false : options.dispatch === true || options.dispatch === void 0 ? {} : options.dispatch;
|
|
3070
|
+
}
|
|
3071
|
+
/**
|
|
3072
|
+
* Give each service whose database holds an outbox table a recorder, and a
|
|
3073
|
+
* dispatcher for that table. Call it before the first request: a service has no
|
|
3074
|
+
* recorder until then.
|
|
3075
|
+
*
|
|
3076
|
+
* @param services - The app's services.
|
|
3077
|
+
* @returns The hub, for chaining.
|
|
3078
|
+
*/
|
|
3079
|
+
attach(services) {
|
|
3080
|
+
for (const service of services.map(portOf)) {
|
|
3081
|
+
const table = service.getOutbox();
|
|
3082
|
+
if (!table) continue;
|
|
3083
|
+
this.recorderNames.push(service.name);
|
|
3084
|
+
service.setRecorder(this.bind(table, (name, payload) => service.checkEvent(name, payload)));
|
|
3085
|
+
const db = service.getDb();
|
|
3086
|
+
if (db && typeof db === "object") recordingServices.set(db, service);
|
|
3087
|
+
if (!this.dispatchers.has(table)) this.dispatchers.set(table, new Dispatcher(db, table, (name) => this.deliverable(name), this.dispatchOptions || {}));
|
|
3088
|
+
}
|
|
3089
|
+
if (this.recorderNames.length === 0 && this.byName.size > 0) console.warn("[Brick-TS] events are configured, but no service database has an outbox table. Add outboxTable() to a database's tables so its writes can record events.");
|
|
3090
|
+
return this;
|
|
3091
|
+
}
|
|
3092
|
+
matching(name) {
|
|
3093
|
+
const found = [];
|
|
3094
|
+
for (const listener of this.byName.values()) if (listener.on.some((pattern) => matchesEvent(pattern, name))) found.push(listener);
|
|
3095
|
+
return found;
|
|
3096
|
+
}
|
|
3097
|
+
describe() {
|
|
3098
|
+
return {
|
|
3099
|
+
listeners: [...this.byName.values()].map((listener) => ({
|
|
3100
|
+
name: listener.name,
|
|
3101
|
+
on: [...listener.on],
|
|
3102
|
+
kind: listener.workflow ? "workflow" : "handler"
|
|
3103
|
+
})),
|
|
3104
|
+
dispatch: this.dispatchOptions !== false,
|
|
3105
|
+
recorders: [...this.recorderNames]
|
|
3106
|
+
};
|
|
3107
|
+
}
|
|
3108
|
+
/**
|
|
3109
|
+
* Where the workflow bundle is read from, the project it is built from, and
|
|
3110
|
+
* the world the workflows run on. Only set when a listener runs a workflow.
|
|
3111
|
+
* The CLI builds the bundle there before events start, and shows the world's
|
|
3112
|
+
* runs in the dev dashboard.
|
|
3113
|
+
*/
|
|
3114
|
+
get workflows() {
|
|
3115
|
+
return this.runtime && {
|
|
3116
|
+
root: this.runtime.root,
|
|
3117
|
+
dir: this.runtime.dir,
|
|
3118
|
+
world: this.runtime.world
|
|
3119
|
+
};
|
|
3120
|
+
}
|
|
3121
|
+
/**
|
|
3122
|
+
* Resume the workflow that waits on a webhook. The server mounts this on the
|
|
3123
|
+
* route the Workflow SDK puts in webhook URLs.
|
|
3124
|
+
*/
|
|
3125
|
+
webhook(request) {
|
|
3126
|
+
if (!this.runtime) throw new Error("No listener of this app runs a workflow");
|
|
3127
|
+
return this.runtime.handleWebhook(request);
|
|
3128
|
+
}
|
|
3129
|
+
/**
|
|
3130
|
+
* Start delivering recorded events from this process, and start the world that
|
|
3131
|
+
* runs workflow listeners. Does nothing if this process only records events
|
|
3132
|
+
* (`dispatch: false`), already started, or a stop is still waiting.
|
|
3133
|
+
*/
|
|
3134
|
+
start() {
|
|
3135
|
+
if (this.dispatchOptions === false || this.started || this.stopping) return;
|
|
3136
|
+
this.started = true;
|
|
3137
|
+
startedHubs.add(this);
|
|
3138
|
+
this.runtime?.warmUp();
|
|
3139
|
+
for (const dispatcher of this.dispatchers.values()) dispatcher.start();
|
|
3140
|
+
}
|
|
3141
|
+
/**
|
|
3142
|
+
* Stop delivering, wait for the deliveries that are running, and close the
|
|
3143
|
+
* world. A world cannot be started again, so workflow listeners stop for good.
|
|
3144
|
+
* A stop that arrives while another runs waits for that one.
|
|
3145
|
+
*/
|
|
3146
|
+
stop() {
|
|
3147
|
+
return this.stopping ??= this.shutDown().finally(() => {
|
|
3148
|
+
this.stopping = void 0;
|
|
3149
|
+
startedHubs.delete(this);
|
|
3150
|
+
});
|
|
3151
|
+
}
|
|
3152
|
+
async shutDown() {
|
|
3153
|
+
this.started = false;
|
|
3154
|
+
await Promise.all([...this.dispatchers.values()].map((dispatcher) => dispatcher.stop()));
|
|
3155
|
+
await this.runtime?.close();
|
|
3156
|
+
}
|
|
3157
|
+
/**
|
|
3158
|
+
* Deliver everything that is due now and wait for it. For tests and for
|
|
3159
|
+
* workers that drive delivery themselves.
|
|
3160
|
+
*
|
|
3161
|
+
* @returns How many deliveries ran.
|
|
3162
|
+
*/
|
|
3163
|
+
async drain() {
|
|
3164
|
+
let total = 0;
|
|
3165
|
+
for (const dispatcher of this.dispatchers.values()) total += await dispatcher.drain();
|
|
3166
|
+
return total;
|
|
3167
|
+
}
|
|
3168
|
+
/** How many rows are in each state, across the app's outbox tables. */
|
|
3169
|
+
async counts() {
|
|
3170
|
+
const total = Object.fromEntries(OUTBOX_STATUSES.map((status) => [status, 0]));
|
|
3171
|
+
for (const dispatcher of this.dispatchers.values()) {
|
|
3172
|
+
const counts = await dispatcher.counts();
|
|
3173
|
+
for (const status of OUTBOX_STATUSES) total[status] += counts[status];
|
|
3174
|
+
}
|
|
3175
|
+
return total;
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Put parked deliveries back in line.
|
|
3179
|
+
*
|
|
3180
|
+
* @param deliveryId - One delivery. Omit it to retry every dead one.
|
|
3181
|
+
* @returns How many deliveries were put back.
|
|
3182
|
+
*/
|
|
3183
|
+
async retryDead(deliveryId) {
|
|
3184
|
+
let total = 0;
|
|
3185
|
+
for (const dispatcher of this.dispatchers.values()) total += await dispatcher.retryDead(deliveryId);
|
|
3186
|
+
return total;
|
|
3187
|
+
}
|
|
3188
|
+
deliverable(name) {
|
|
3189
|
+
const listener = this.byName.get(name);
|
|
3190
|
+
if (!listener) return void 0;
|
|
3191
|
+
let found = this.deliverables.get(name);
|
|
3192
|
+
if (!found) {
|
|
3193
|
+
const { run, workflow, maxAttempts, errors, retry } = listener;
|
|
3194
|
+
const deps = listenerDeps(listener) ?? this.deps;
|
|
3195
|
+
found = {
|
|
3196
|
+
...errors ? { errors } : {},
|
|
3197
|
+
...retry ? { retry } : {},
|
|
3198
|
+
...maxAttempts !== void 0 ? { maxAttempts } : {},
|
|
3199
|
+
run: workflow ? (delivery) => this.runtime.startRun(listener, delivery) : (delivery) => runWithDeps(deps, () => run(delivery))
|
|
3200
|
+
};
|
|
3201
|
+
this.deliverables.set(name, found);
|
|
3202
|
+
}
|
|
3203
|
+
return found;
|
|
3204
|
+
}
|
|
3205
|
+
bind(table, check) {
|
|
3206
|
+
const startAndNotify = () => {
|
|
3207
|
+
this.start();
|
|
3208
|
+
this.dispatchers.get(table)?.notify();
|
|
3209
|
+
};
|
|
3210
|
+
const insert = async (tx, context, name, payload) => {
|
|
3211
|
+
check(name, payload);
|
|
3212
|
+
const listeners = this.matching(name);
|
|
3213
|
+
if (!listeners.length) return false;
|
|
3214
|
+
await tx.insert(table).values(outboxRows({
|
|
3215
|
+
id: newEventId(),
|
|
3216
|
+
name,
|
|
3217
|
+
payload,
|
|
3218
|
+
occurredAt: /* @__PURE__ */ new Date(),
|
|
3219
|
+
...context
|
|
3220
|
+
}, listeners.map((listener) => listener.name)));
|
|
3221
|
+
return true;
|
|
3222
|
+
};
|
|
3223
|
+
return {
|
|
3224
|
+
wants: (name) => this.matching(name).length > 0,
|
|
3225
|
+
transaction: async (db, context, fn) => {
|
|
3226
|
+
let recorded = false;
|
|
3227
|
+
const result = await runInTransaction(db, async (tx) => {
|
|
3228
|
+
const record = async (name, payload) => {
|
|
3229
|
+
if (await insert(tx, context, name, payload)) recorded = true;
|
|
3230
|
+
};
|
|
3231
|
+
return fn(tx, record);
|
|
3232
|
+
});
|
|
3233
|
+
if (recorded) startAndNotify();
|
|
3234
|
+
return result;
|
|
3235
|
+
},
|
|
3236
|
+
record: async (tx, context, name, payload) => {
|
|
3237
|
+
await insert(tx, context, name, payload);
|
|
3238
|
+
}
|
|
3239
|
+
};
|
|
3240
|
+
}
|
|
3241
|
+
};
|
|
3242
|
+
// src/cors.ts
|
|
3243
|
+
/** The origin a browser saw, so TLS-terminating proxies still pass the same-origin check. */
|
|
3244
|
+
function publicOrigin(request) {
|
|
3245
|
+
const forwarded = (name) => request.headers.get(name)?.split(",")[0]?.trim() || void 0;
|
|
3246
|
+
const url = new URL(request.url);
|
|
3247
|
+
const proto = forwarded("x-forwarded-proto");
|
|
3248
|
+
return `${proto ? `${proto}:` : url.protocol}//${forwarded("x-forwarded-host") ?? url.host}`;
|
|
3249
|
+
}
|
|
3250
|
+
const METHODS = "GET, POST, PUT, PATCH, DELETE";
|
|
3251
|
+
/**
|
|
3252
|
+
* A request hook that adds CORS headers for allowed origins and answers
|
|
3253
|
+
* preflights. An origin that doesn't match gets no `Access-Control-Allow-Origin`,
|
|
3254
|
+
* so the browser blocks it; origins are compared exactly and never reflected
|
|
3255
|
+
* unless the rule allows them.
|
|
3256
|
+
*/
|
|
3257
|
+
function corsHook(cors) {
|
|
3258
|
+
const { origin = true, credentials = false } = typeof cors === "object" && !Array.isArray(cors) ? cors : { origin: cors };
|
|
3259
|
+
const list = typeof origin === "string" ? [origin] : Array.isArray(origin) ? origin : void 0;
|
|
3260
|
+
if (list?.includes("*")) throw new Error("Brick: cors origin \"*\" is not supported. List the origins, or pass a predicate.");
|
|
3261
|
+
const allows = (from, request) => origin === true ? from === publicOrigin(request) : typeof origin === "function" ? origin(from, request) === true : list.includes(from);
|
|
3262
|
+
return ({ request, set }) => {
|
|
3263
|
+
const from = request.headers.get("origin");
|
|
3264
|
+
if (from === null) return;
|
|
3265
|
+
const headers = { vary: "Origin" };
|
|
3266
|
+
if (allows(from, request)) {
|
|
3267
|
+
headers["access-control-allow-origin"] = from;
|
|
3268
|
+
if (credentials) headers["access-control-allow-credentials"] = "true";
|
|
3269
|
+
}
|
|
3270
|
+
if (!(request.method === "OPTIONS" && request.headers.has("access-control-request-method"))) {
|
|
3271
|
+
Object.assign(set.headers, headers);
|
|
3272
|
+
return;
|
|
3273
|
+
}
|
|
3274
|
+
if (headers["access-control-allow-origin"]) {
|
|
3275
|
+
headers["access-control-allow-methods"] = METHODS;
|
|
3276
|
+
const requested = request.headers.get("access-control-request-headers");
|
|
3277
|
+
if (requested) headers["access-control-allow-headers"] = requested;
|
|
3278
|
+
}
|
|
3279
|
+
return new Response(null, {
|
|
3280
|
+
status: 204,
|
|
3281
|
+
headers
|
|
3282
|
+
});
|
|
3283
|
+
};
|
|
3284
|
+
}
|
|
3285
|
+
// src/socket.ts
|
|
3286
|
+
var SocketDenied = class extends Error {};
|
|
3287
|
+
/** Validates and serializes one output message, rechecking what survives JSON. */
|
|
3288
|
+
function outputFrame(output, event, data) {
|
|
3289
|
+
const schema = Object.hasOwn(output, event) ? output[event] : void 0;
|
|
3290
|
+
if (!schema || !getCompiledCheck(schema).Check(data)) throw new Error("Invalid socket output");
|
|
3291
|
+
const frame = encodeFrame(event, data);
|
|
3292
|
+
if (byteLength(frame) > 65536) throw new Error("Socket output too large");
|
|
3293
|
+
if (!getCompiledCheck(schema).Check(JSON.parse(frame).data)) throw new Error("Socket output is not JSON-compatible");
|
|
3294
|
+
return frame;
|
|
3295
|
+
}
|
|
3296
|
+
/** Delivers within this process. The default broker of every app. */
|
|
3297
|
+
function localBroker() {
|
|
3298
|
+
const topics = /* @__PURE__ */ new Map();
|
|
3299
|
+
const epoch = Date.now();
|
|
3300
|
+
let counter = 0;
|
|
3301
|
+
/** Rooms dropped from `kept` once idle, at counter values up to this. */
|
|
3302
|
+
let swept = 0;
|
|
3303
|
+
const kept = /* @__PURE__ */ new Map();
|
|
3304
|
+
const prune = (names) => {
|
|
3305
|
+
for (const topic of names) {
|
|
3306
|
+
const room = kept.get(topic);
|
|
3307
|
+
if (!room) continue;
|
|
3308
|
+
const oldest = Date.now() - room.maxAgeMs;
|
|
3309
|
+
while (room.entries[0] && room.entries[0].at < oldest) room.trimmed = room.entries.shift().n;
|
|
3310
|
+
if (!room.entries.length) {
|
|
3311
|
+
kept.delete(topic);
|
|
3312
|
+
swept = counter;
|
|
3313
|
+
}
|
|
3314
|
+
}
|
|
3315
|
+
};
|
|
3316
|
+
return {
|
|
3317
|
+
publish(message, replay) {
|
|
3318
|
+
if (message.type === "emit" && replay) {
|
|
3319
|
+
const n = ++counter;
|
|
3320
|
+
message = {
|
|
3321
|
+
...message,
|
|
3322
|
+
seq: `${epoch}-${n}`
|
|
3323
|
+
};
|
|
3324
|
+
const room = kept.get(message.topic) ?? {
|
|
3325
|
+
entries: [],
|
|
3326
|
+
trimmed: 0,
|
|
3327
|
+
maxAgeMs: replay.maxAgeMs
|
|
3328
|
+
};
|
|
3329
|
+
kept.set(message.topic, room);
|
|
3330
|
+
room.entries.push({
|
|
3331
|
+
n,
|
|
3332
|
+
at: Date.now(),
|
|
3333
|
+
message
|
|
3334
|
+
});
|
|
3335
|
+
if (room.entries.length > replay.keep) room.trimmed = room.entries.shift().n;
|
|
3336
|
+
if (n % 1e3 === 0) prune([...kept.keys()]);
|
|
3337
|
+
}
|
|
3338
|
+
for (const deliver of topics.get(message.topic) ?? []) deliver(message);
|
|
3339
|
+
},
|
|
3340
|
+
head: () => `${epoch}-${counter}`,
|
|
3341
|
+
history(topic, since) {
|
|
3342
|
+
const [from, n] = since.split("-").map(Number);
|
|
3343
|
+
if (from !== epoch || n > counter) return void 0;
|
|
3344
|
+
prune([topic]);
|
|
3345
|
+
const room = kept.get(topic);
|
|
3346
|
+
if (!room) return n >= swept ? [] : void 0;
|
|
3347
|
+
if (n < room.trimmed) return void 0;
|
|
3348
|
+
return room.entries.filter((entry) => entry.n > n).map((entry) => entry.message);
|
|
3349
|
+
},
|
|
3350
|
+
subscribe(topic, deliver) {
|
|
3351
|
+
const listeners = topics.get(topic) ?? /* @__PURE__ */ new Set();
|
|
3352
|
+
listeners.add(deliver);
|
|
3353
|
+
topics.set(topic, listeners);
|
|
3354
|
+
return () => {
|
|
3355
|
+
listeners.delete(deliver);
|
|
3356
|
+
if (!listeners.size) topics.delete(topic);
|
|
3357
|
+
};
|
|
3358
|
+
}
|
|
3359
|
+
};
|
|
3360
|
+
}
|
|
3361
|
+
function defineServiceSocket(service, config, resolve) {
|
|
3362
|
+
if (!config.name || config.name.split(".").some((part) => !/^[a-zA-Z_][\w-]*$/.test(part))) throw new Error("Invalid socket name");
|
|
3363
|
+
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");
|
|
3364
|
+
const input = Object.freeze({ ...config.input });
|
|
3365
|
+
const output = Object.freeze({ ...config.output });
|
|
3366
|
+
const handlers = { ...config.handlers };
|
|
3367
|
+
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");
|
|
3368
|
+
if ([...Object.keys(input), ...Object.keys(output)].some(isControlEvent)) throw new Error("Socket event names starting with $ are reserved");
|
|
3369
|
+
const maxRooms = config.maxRooms ?? 100;
|
|
3370
|
+
if (!Number.isInteger(maxRooms) || maxRooms < 1) throw new Error("Socket maxRooms must be a positive integer");
|
|
3371
|
+
const replay = config.replay && { ...config.replay };
|
|
3372
|
+
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");
|
|
3373
|
+
for (const schema of [...Object.values(input), ...Object.values(output)]) {
|
|
3374
|
+
serializeSocketSchema(schema);
|
|
3375
|
+
getCompiledCheck(schema);
|
|
3376
|
+
}
|
|
3377
|
+
const typed = (socket) => socket;
|
|
3378
|
+
const error = buildErrorHelpers(config.errors);
|
|
3379
|
+
const context = async (request) => {
|
|
3380
|
+
const ctx = await resolve(request);
|
|
3381
|
+
if (config.authorize && !await config.authorize({ ctx })) throw new SocketDenied();
|
|
3382
|
+
return ctx;
|
|
3383
|
+
};
|
|
3384
|
+
const topicPrefix = `${service}.${config.name}:`;
|
|
3385
|
+
const topic = (room) => {
|
|
3386
|
+
if (!isSocketRoom(room)) throw new Error(`Invalid socket room: ${room}`);
|
|
3387
|
+
return topicPrefix + room;
|
|
3388
|
+
};
|
|
3389
|
+
const brokers = /* @__PURE__ */ new Set();
|
|
3390
|
+
const publish = (messages, after) => {
|
|
3391
|
+
const send = () => {
|
|
3392
|
+
for (const broker of brokers) for (const message of messages) broker.publish(message, replay);
|
|
3393
|
+
};
|
|
3394
|
+
if (after === void 0) return send();
|
|
3395
|
+
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");
|
|
3396
|
+
onTransactionCommit(after, send);
|
|
3397
|
+
};
|
|
3398
|
+
return {
|
|
3399
|
+
schema: {
|
|
3400
|
+
name: config.name,
|
|
3401
|
+
path: config.path,
|
|
3402
|
+
description: config.description,
|
|
3403
|
+
input: Object.keys(input),
|
|
3404
|
+
output: Object.keys(output),
|
|
3405
|
+
hasAuthorize: !!config.authorize
|
|
3406
|
+
},
|
|
3407
|
+
input,
|
|
3408
|
+
output,
|
|
3409
|
+
...config.errors ? { errors: { ...config.errors } } : {},
|
|
3410
|
+
allowedOrigins: config.allowedOrigins ? [...config.allowedOrigins] : void 0,
|
|
3411
|
+
allowMissingOrigin: config.allowMissingOrigin,
|
|
3412
|
+
maxRooms,
|
|
3413
|
+
replay,
|
|
3414
|
+
brokers,
|
|
3415
|
+
topicPrefix,
|
|
3416
|
+
topic,
|
|
3417
|
+
handle: {
|
|
3418
|
+
name: config.name,
|
|
3419
|
+
emit(rooms, ...[event, payload, options]) {
|
|
3420
|
+
const unique = [...new Set(typeof rooms === "string" ? [rooms] : rooms)];
|
|
3421
|
+
const topics = unique.map(topic);
|
|
3422
|
+
const frame = outputFrame(output, event, payload);
|
|
3423
|
+
if (replay && unique.some((room) => byteLength(frame) + replayHeadroom(room) > 65536)) throw new Error("Socket output too large");
|
|
3424
|
+
publish(topics.map((topic) => ({
|
|
3425
|
+
type: "emit",
|
|
3426
|
+
topic,
|
|
3427
|
+
frame
|
|
3428
|
+
})), options?.after);
|
|
3429
|
+
},
|
|
3430
|
+
kick(room, options = {}) {
|
|
3431
|
+
publish([{
|
|
3432
|
+
type: "kick",
|
|
3433
|
+
topic: topic(room),
|
|
3434
|
+
...options.also !== void 0 ? { also: topic(options.also) } : {},
|
|
3435
|
+
...options.reason !== void 0 ? { reason: String(options.reason) } : {}
|
|
3436
|
+
}], void 0);
|
|
3437
|
+
}
|
|
3438
|
+
},
|
|
3439
|
+
async connect(request) {
|
|
3440
|
+
const initial = await context(request);
|
|
3441
|
+
const rooms = [...new Set(config.rooms ? await config.rooms({ ctx: initial }) : [])];
|
|
3442
|
+
rooms.forEach(topic);
|
|
3443
|
+
if (rooms.length > maxRooms) throw new Error("Too many socket rooms");
|
|
3444
|
+
return {
|
|
3445
|
+
rooms,
|
|
3446
|
+
async open(socket) {
|
|
3447
|
+
await config.open?.({
|
|
3448
|
+
ctx: initial,
|
|
3449
|
+
socket: typed(socket)
|
|
3450
|
+
});
|
|
3451
|
+
},
|
|
3452
|
+
async message(event, data, socket) {
|
|
3453
|
+
const schema = Object.hasOwn(input, event) ? input[event] : void 0;
|
|
3454
|
+
if (!schema || !getCompiledCheck(schema).Check(data)) throw new SocketDenied();
|
|
3455
|
+
const ctx = await context(request);
|
|
3456
|
+
if (!socket.isOpen) return;
|
|
3457
|
+
const handler = handlers[event];
|
|
3458
|
+
await handler({
|
|
3459
|
+
input: data,
|
|
3460
|
+
ctx,
|
|
3461
|
+
socket: typed(socket),
|
|
3462
|
+
error
|
|
3463
|
+
});
|
|
3464
|
+
},
|
|
3465
|
+
async join(room) {
|
|
3466
|
+
const ctx = await context(request);
|
|
3467
|
+
return !!config.join && await config.join({
|
|
3468
|
+
ctx,
|
|
3469
|
+
room
|
|
3470
|
+
});
|
|
3471
|
+
},
|
|
3472
|
+
async close(socket, code, reason) {
|
|
3473
|
+
await config.close?.({
|
|
3474
|
+
ctx: initial,
|
|
3475
|
+
socket: typed(socket),
|
|
3476
|
+
code,
|
|
3477
|
+
reason
|
|
3478
|
+
});
|
|
3479
|
+
}
|
|
3480
|
+
};
|
|
3481
|
+
}
|
|
3482
|
+
};
|
|
3483
|
+
}
|
|
3484
|
+
/** `${prefix}/${service}/${socket}`; an explicit path is relative to the service. */
|
|
3485
|
+
function socketPath(prefix, service, socket) {
|
|
3486
|
+
return joinRoute(ownerPath(prefix, service), socket.schema.path ?? `/${kebabCase(socket.schema.name)}`);
|
|
3487
|
+
}
|
|
3488
|
+
const protocols = (request) => (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((protocol) => protocol.trim()).filter(Boolean);
|
|
3489
|
+
/** Moves a `brick.token.<token>` subprotocol into `Authorization: Bearer` for the context resolver. */
|
|
3490
|
+
function tokenRequest(request) {
|
|
3491
|
+
const offered = protocols(request);
|
|
3492
|
+
const token = offered.find((protocol) => protocol.startsWith(SOCKET_TOKEN_PROTOCOL))?.slice(SOCKET_TOKEN_PROTOCOL.length);
|
|
3493
|
+
if (!token) return {
|
|
3494
|
+
token: false,
|
|
3495
|
+
request
|
|
3496
|
+
};
|
|
3497
|
+
const headers = new Headers(request.headers);
|
|
3498
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
3499
|
+
const rest = offered.filter((protocol) => !protocol.startsWith(SOCKET_TOKEN_PROTOCOL));
|
|
3500
|
+
if (rest.length) headers.set("sec-websocket-protocol", rest.join(", "));
|
|
3501
|
+
else headers.delete("sec-websocket-protocol");
|
|
3502
|
+
return {
|
|
3503
|
+
token: true,
|
|
3504
|
+
request: new Request(request.url, {
|
|
3505
|
+
method: request.method,
|
|
3506
|
+
headers
|
|
3507
|
+
})
|
|
3508
|
+
};
|
|
3509
|
+
}
|
|
3510
|
+
/** Each connection owns its queue and service session. */
|
|
3511
|
+
function mountSockets(app, sockets, broker, secret) {
|
|
3512
|
+
if (secret === "") throw new Error("Brick: sockets.secret can't be empty");
|
|
3513
|
+
const key = secret ?? randomBytes(32);
|
|
3514
|
+
const signature = (topic, seq) => createHmac("sha256", key).update(`${topic}\n${seq}`).digest("base64url").slice(0, 22);
|
|
3515
|
+
const sign = (topic, seq) => signSeq(seq, signature(topic, seq));
|
|
3516
|
+
const verify = (topic, signed) => {
|
|
3517
|
+
const [seq, sig] = splitSeq(signed);
|
|
3518
|
+
return timingSafeEqual(Buffer.from(sig), Buffer.from(signature(topic, seq))) ? seq : void 0;
|
|
3519
|
+
};
|
|
3520
|
+
if (sockets.some(({ definition }) => definition.replay) && !(broker.head && broker.history)) throw new Error("Brick: the socket broker does not support replay");
|
|
3521
|
+
for (const { definition } of sockets) definition.brokers.add(broker);
|
|
3522
|
+
app.onStop(async () => {
|
|
3523
|
+
for (const { definition } of sockets) definition.brokers.delete(broker);
|
|
3524
|
+
await broker.close?.();
|
|
3525
|
+
});
|
|
3526
|
+
if (!sockets.length) return;
|
|
3527
|
+
app.use(websocket({
|
|
3528
|
+
maxPayloadLength: SOCKET_MAX_BYTES,
|
|
3529
|
+
backpressureLimit: SOCKET_BUFFER_BYTES,
|
|
3530
|
+
closeOnBackpressureLimit: true
|
|
3531
|
+
}));
|
|
3532
|
+
for (const { service, path, definition } of sockets) {
|
|
3533
|
+
const logger = createLogger(`[Brick socket ${service}.${definition.schema.name}]`);
|
|
3534
|
+
const sessions = /* @__PURE__ */ new WeakMap();
|
|
3535
|
+
const connections = /* @__PURE__ */ new WeakMap();
|
|
3536
|
+
const roomOf = (topic) => topic.slice(definition.topicPrefix.length);
|
|
3537
|
+
const holders = /* @__PURE__ */ new Map();
|
|
3538
|
+
const control = (ws, event, data) => {
|
|
3539
|
+
if (ws.readyState === 1) ws.send(encodeFrame(event, data));
|
|
3540
|
+
};
|
|
3541
|
+
/** Joins a room; resolves once the broker delivers its messages here. `live: false` holds the room without receiving yet. */
|
|
3542
|
+
const enter = async (connection, topic, live = true) => {
|
|
3543
|
+
if (connection.rooms.has(topic)) return;
|
|
3544
|
+
connection.rooms.add(topic);
|
|
3545
|
+
if (live) connection.ws.subscribe(topic);
|
|
3546
|
+
let holder = holders.get(topic);
|
|
3547
|
+
if (!holder) {
|
|
3548
|
+
holder = {
|
|
3549
|
+
connections: /* @__PURE__ */ new Set(),
|
|
3550
|
+
unsubscribe: () => {}
|
|
3551
|
+
};
|
|
3552
|
+
holders.set(topic, holder);
|
|
3553
|
+
holder.unsubscribe = broker.subscribe(topic, deliver);
|
|
3554
|
+
}
|
|
3555
|
+
holder.connections.add(connection);
|
|
3556
|
+
await broker.ready?.(topic).catch(() => {});
|
|
3557
|
+
};
|
|
3558
|
+
const exit = (connection, topic) => {
|
|
3559
|
+
if (!connection.rooms.delete(topic)) return;
|
|
3560
|
+
connection.requested.delete(topic);
|
|
3561
|
+
if (connection.ws.readyState === 1) connection.ws.unsubscribe(topic);
|
|
3562
|
+
const holder = holders.get(topic);
|
|
3563
|
+
if (!holder?.connections.delete(connection) || holder.connections.size) return;
|
|
3564
|
+
holders.delete(topic);
|
|
3565
|
+
holder.unsubscribe();
|
|
3566
|
+
};
|
|
3567
|
+
const frameOf = (message) => message.seq === void 0 ? message.frame : replayFrame(message.frame, roomOf(message.topic), sign(message.topic, message.seq));
|
|
3568
|
+
const deliver = (message) => {
|
|
3569
|
+
if (message.type === "emit") {
|
|
3570
|
+
app.server?.publish(message.topic, frameOf(message));
|
|
3571
|
+
return;
|
|
3572
|
+
}
|
|
3573
|
+
for (const connection of holders.get(message.topic)?.connections ?? []) {
|
|
3574
|
+
if (message.also && !connection.ws.isSubscribed(message.also)) continue;
|
|
3575
|
+
exit(connection, message.topic);
|
|
3576
|
+
control(connection.ws, SOCKET_CONTROL.left, {
|
|
3577
|
+
room: roomOf(message.topic),
|
|
3578
|
+
...message.reason !== void 0 ? { reason: message.reason } : {}
|
|
3579
|
+
});
|
|
3580
|
+
}
|
|
3581
|
+
};
|
|
3582
|
+
/** `$join` and `$leave`, acknowledged with the same event. */
|
|
3583
|
+
const room = async (connection, event, data) => {
|
|
3584
|
+
const { room: name, since } = data && typeof data === "object" ? data : {};
|
|
3585
|
+
if (!isSocketRoom(name) || since !== void 0 && !isSocketSeq(since)) throw new SocketDenied();
|
|
3586
|
+
const topic = definition.topic(name);
|
|
3587
|
+
if (event === SOCKET_CONTROL.leave) {
|
|
3588
|
+
if (connection.requested.has(topic)) exit(connection, topic);
|
|
3589
|
+
control(connection.ws, SOCKET_CONTROL.leave, { room: name });
|
|
3590
|
+
return;
|
|
3591
|
+
}
|
|
3592
|
+
const isOpen = () => !connection.closed && connection.ws.readyState === 1;
|
|
3593
|
+
const ok = connection.rooms.has(topic) || connection.rooms.size < definition.maxRooms && await connection.session.join(name);
|
|
3594
|
+
if (!isOpen()) return;
|
|
3595
|
+
const replay = definition.replay;
|
|
3596
|
+
let seq;
|
|
3597
|
+
if (ok && !connection.rooms.has(topic)) {
|
|
3598
|
+
const entered = enter(connection, topic, !replay);
|
|
3599
|
+
connection.requested.add(topic);
|
|
3600
|
+
await entered;
|
|
3601
|
+
if (replay && connection.rooms.has(topic)) {
|
|
3602
|
+
const start = since === void 0 ? await broker.head(topic) : verify(topic, since);
|
|
3603
|
+
const missed = start === void 0 ? void 0 : await broker.history(topic, start, replay);
|
|
3604
|
+
const restart = missed ? void 0 : await broker.head(topic);
|
|
3605
|
+
if (!isOpen()) return;
|
|
3606
|
+
if (connection.rooms.has(topic)) {
|
|
3607
|
+
connection.ws.subscribe(topic);
|
|
3608
|
+
if (since === void 0) seq = sign(topic, start);
|
|
3609
|
+
for (const message of missed ?? []) if (message.type === "emit") connection.ws.send(frameOf(message));
|
|
3610
|
+
if (restart !== void 0) control(connection.ws, SOCKET_CONTROL.gap, {
|
|
3611
|
+
room: name,
|
|
3612
|
+
seq: sign(topic, restart)
|
|
3613
|
+
});
|
|
3614
|
+
}
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3617
|
+
control(connection.ws, SOCKET_CONTROL.join, {
|
|
3618
|
+
room: name,
|
|
3619
|
+
ok: ok && connection.rooms.has(topic),
|
|
3620
|
+
...seq !== void 0 ? { seq } : {}
|
|
3621
|
+
});
|
|
3622
|
+
};
|
|
3623
|
+
const raisable = {
|
|
3624
|
+
...STANDARD_ERRORS,
|
|
3625
|
+
...definition.errors
|
|
3626
|
+
};
|
|
3627
|
+
const fail = (ws, error) => {
|
|
3628
|
+
if (!(error instanceof SocketDenied)) logger.error({
|
|
3629
|
+
error,
|
|
3630
|
+
service,
|
|
3631
|
+
socket: definition.schema.name
|
|
3632
|
+
});
|
|
3633
|
+
if (ws.readyState !== 1) return;
|
|
3634
|
+
ws.close(error instanceof SocketDenied ? SOCKET_CLOSE.policy : SOCKET_CLOSE.serverError, error instanceof SocketDenied ? "Message refused" : "Socket handler failed");
|
|
3635
|
+
};
|
|
3636
|
+
app.ws(path, {
|
|
3637
|
+
async beforeHandle({ request }) {
|
|
3638
|
+
if (sessions.has(request)) return;
|
|
3639
|
+
const { token, request: resolved } = tokenRequest(request);
|
|
3640
|
+
const origin = request.headers.get("origin");
|
|
3641
|
+
if (origin ? !(definition.allowedOrigins ?? [publicOrigin(request)]).includes(origin) : !(definition.allowMissingOrigin ?? token)) return new Response("Socket origin refused", { status: 403 });
|
|
3642
|
+
try {
|
|
3643
|
+
sessions.set(request, await definition.connect(resolved));
|
|
3644
|
+
} catch (error) {
|
|
3645
|
+
if (!(error instanceof SocketDenied)) logger.error({
|
|
3646
|
+
error,
|
|
3647
|
+
service,
|
|
3648
|
+
socket: definition.schema.name
|
|
3649
|
+
});
|
|
3650
|
+
return new Response("Socket connection refused", { status: error instanceof SocketDenied ? 403 : 500 });
|
|
3651
|
+
}
|
|
3652
|
+
},
|
|
3653
|
+
upgrade: ({ request }) => protocols(request).includes("brick.v1") ? { "Sec-WebSocket-Protocol": SOCKET_PROTOCOL } : void 0,
|
|
3654
|
+
async open(ws) {
|
|
3655
|
+
const session = sessions.get(ws.request);
|
|
3656
|
+
if (!session) {
|
|
3657
|
+
ws.close(SOCKET_CLOSE.serverError, "Missing socket session");
|
|
3658
|
+
return;
|
|
3659
|
+
}
|
|
3660
|
+
const sender = {
|
|
3661
|
+
get isOpen() {
|
|
3662
|
+
return !state.closed && ws.readyState === 1;
|
|
3663
|
+
},
|
|
3664
|
+
close() {
|
|
3665
|
+
ws.close(SOCKET_CLOSE.normal, "");
|
|
3666
|
+
},
|
|
3667
|
+
send(event, data) {
|
|
3668
|
+
if (!sender.isOpen) throw new Error("Socket is closed");
|
|
3669
|
+
if (ws.send(outputFrame(definition.output, event, data)) === 0) {
|
|
3670
|
+
ws.close(SOCKET_CLOSE.tryAgainLater, "Socket buffer full");
|
|
3671
|
+
throw new Error("Socket buffer full");
|
|
3672
|
+
}
|
|
3673
|
+
}
|
|
3674
|
+
};
|
|
3675
|
+
const state = {
|
|
3676
|
+
ws,
|
|
3677
|
+
session,
|
|
3678
|
+
sender,
|
|
3679
|
+
tail: Promise.resolve(),
|
|
3680
|
+
pending: 0,
|
|
3681
|
+
bytes: 0,
|
|
3682
|
+
closed: false,
|
|
3683
|
+
rooms: /* @__PURE__ */ new Set(),
|
|
3684
|
+
requested: /* @__PURE__ */ new Set()
|
|
3685
|
+
};
|
|
3686
|
+
connections.set(ws.request, state);
|
|
3687
|
+
try {
|
|
3688
|
+
await Promise.all(session.rooms.map((room) => enter(state, definition.topic(room))));
|
|
3689
|
+
await session.open(sender);
|
|
3690
|
+
} catch (error) {
|
|
3691
|
+
fail(ws, error);
|
|
3692
|
+
}
|
|
3693
|
+
},
|
|
3694
|
+
message(ws, value) {
|
|
3695
|
+
const state = connections.get(ws.request);
|
|
3696
|
+
if (!state || state.closed || ws.readyState !== 1) return;
|
|
3697
|
+
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
|
3698
|
+
ws.close(SOCKET_CLOSE.unsupportedData, "Only JSON text is supported");
|
|
3699
|
+
return;
|
|
3700
|
+
}
|
|
3701
|
+
if (typeof value === "string") {
|
|
3702
|
+
ws.close(SOCKET_CLOSE.invalidPayload, "Expected JSON envelope");
|
|
3703
|
+
return;
|
|
3704
|
+
}
|
|
3705
|
+
if (!isSocketEnvelope(value)) {
|
|
3706
|
+
ws.close(SOCKET_CLOSE.policy, "Invalid socket envelope");
|
|
3707
|
+
return;
|
|
3708
|
+
}
|
|
3709
|
+
const size = byteLength(JSON.stringify(value));
|
|
3710
|
+
if (size > 65536) {
|
|
3711
|
+
ws.close(SOCKET_CLOSE.tooLarge, "Message too large");
|
|
3712
|
+
return;
|
|
3713
|
+
}
|
|
3714
|
+
if (state.pending >= 32 || state.bytes + size > 1048576) {
|
|
3715
|
+
ws.close(SOCKET_CLOSE.tryAgainLater, "Socket queue full");
|
|
3716
|
+
return;
|
|
3717
|
+
}
|
|
3718
|
+
state.pending++;
|
|
3719
|
+
state.bytes += size;
|
|
3720
|
+
state.tail = state.tail.then(async () => {
|
|
3721
|
+
if (state.closed || ws.readyState !== 1) return;
|
|
3722
|
+
if (value.event === SOCKET_CONTROL.join || value.event === SOCKET_CONTROL.leave) await room(state, value.event, value.data);
|
|
3723
|
+
else await state.session.message(value.event, value.data, state.sender);
|
|
3724
|
+
}).catch((error) => {
|
|
3725
|
+
if (error instanceof ActionExecutionError && !state.closed && value.event !== SOCKET_CONTROL.join && value.event !== SOCKET_CONTROL.leave && Object.hasOwn(raisable, error.code)) try {
|
|
3726
|
+
const frame = encodeFrame(SOCKET_CONTROL.error, {
|
|
3727
|
+
event: value.event,
|
|
3728
|
+
...error.toJSON()
|
|
3729
|
+
});
|
|
3730
|
+
if (byteLength(frame) > 65536) throw new Error("Socket error too large", { cause: error });
|
|
3731
|
+
if (ws.readyState === 1) ws.send(frame);
|
|
3732
|
+
return;
|
|
3733
|
+
} catch (unsent) {
|
|
3734
|
+
return fail(ws, unsent);
|
|
3735
|
+
}
|
|
3736
|
+
fail(ws, error);
|
|
3737
|
+
}).finally(() => {
|
|
3738
|
+
state.pending--;
|
|
3739
|
+
state.bytes -= size;
|
|
3740
|
+
});
|
|
3741
|
+
},
|
|
3742
|
+
async close(ws, code = 1006, reason = "") {
|
|
3743
|
+
const state = connections.get(ws.request);
|
|
3744
|
+
sessions.delete(ws.request);
|
|
3745
|
+
if (!state || state.closed) return;
|
|
3746
|
+
state.closed = true;
|
|
3747
|
+
for (const topic of state.rooms) exit(state, topic);
|
|
3748
|
+
try {
|
|
3749
|
+
await state.session.close(state.sender, code, reason);
|
|
3750
|
+
} catch (error) {
|
|
3751
|
+
logger.error({
|
|
3752
|
+
error,
|
|
3753
|
+
service,
|
|
3754
|
+
socket: definition.schema.name,
|
|
3755
|
+
phase: "cleanup"
|
|
3756
|
+
});
|
|
3757
|
+
}
|
|
3758
|
+
connections.delete(ws.request);
|
|
3759
|
+
}
|
|
3760
|
+
});
|
|
3761
|
+
}
|
|
3762
|
+
}
|
|
3763
|
+
// src/server.ts
|
|
3764
|
+
/**
|
|
3765
|
+
* Create the HTTP application: an Elysia app that serves every service's
|
|
3766
|
+
* actions (and the tools that opt in with `http: true`) as routes, with
|
|
3767
|
+
* `/_health`, an OpenAPI document at `/openapi.json`, Scalar at `/docs`,
|
|
3768
|
+
* Swagger UI at `/swagger`, and the shape of the services at `/_brick/services`.
|
|
3769
|
+
*
|
|
3770
|
+
* Services come from the global registry unless `services` is given. The app
|
|
3771
|
+
* does not listen by itself: export it from your entry file, where `brick dev`,
|
|
3772
|
+
* `brick start`, and the Vite plugin load it, or call `app.listen(port)` in your
|
|
3773
|
+
* own server bootstrap.
|
|
3774
|
+
*
|
|
3775
|
+
* @param options - `prefix` for action routes (default `/api`), `services`,
|
|
3776
|
+
* `title`, `version`, and `description` for the OpenAPI document, `docs` and the
|
|
3777
|
+
* paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
|
|
3778
|
+
* `telemetry`, `documentation`, `dashboard`, and `deps`. See `CreateServerOptions`.
|
|
3779
|
+
* @returns The app, with `definition` (its services, prefix, and routes),
|
|
3780
|
+
* `endpoint()` to add raw routes, and `listEndpoints()` to list them.
|
|
3781
|
+
* @throws When a required secret is missing, `documentation` or `dashboard`
|
|
3782
|
+
* is invalid, or `deps` misses a dep a service declares or has one none declares.
|
|
3783
|
+
* @example
|
|
3784
|
+
* import { brick } from "@brickkit/core";
|
|
3785
|
+
* import { pagesService } from "./services/pages";
|
|
3786
|
+
*
|
|
3787
|
+
* export default brick({
|
|
3788
|
+
* services: [pagesService],
|
|
3789
|
+
* title: "Pages API",
|
|
3790
|
+
* telemetry: true,
|
|
3791
|
+
* });
|
|
3792
|
+
*/
|
|
3793
|
+
function brick(options = {}) {
|
|
3794
|
+
const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
|
|
3795
|
+
const title = options.title ?? OPENAPI_DEFAULTS.title;
|
|
3796
|
+
const version = options.version ?? OPENAPI_DEFAULTS.version;
|
|
3797
|
+
const enableDocs = options.docs ?? true;
|
|
3798
|
+
const openApiPath = options.openApiPath ?? OPENAPI_DEFAULTS.path;
|
|
3799
|
+
const docsPath = options.docsPath ?? "/docs";
|
|
3800
|
+
const swaggerPath = options.swaggerPath ?? "/swagger";
|
|
3801
|
+
const dashboard = normalizeDashboard(options.dashboard);
|
|
3802
|
+
const telemetry = options.telemetry === true || dashboard !== void 0;
|
|
3803
|
+
const app = new Elysia();
|
|
3804
|
+
if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
|
|
3805
|
+
const services = options.services ?? getGlobalRegistry().list();
|
|
3806
|
+
const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
|
|
3807
|
+
if (options.cors) app.onRequest(corsHook(options.cors));
|
|
3808
|
+
for (const handler of plugins.middleware) app.onRequest(handler);
|
|
3809
|
+
const registeredRoutes = /* @__PURE__ */ new Map();
|
|
3810
|
+
const builtIn = (path, handler) => {
|
|
3811
|
+
app.get(path, handler);
|
|
3812
|
+
registeredRoutes.set(routeKey("GET", path), false);
|
|
3813
|
+
};
|
|
3814
|
+
builtIn("/_health", () => ({
|
|
3815
|
+
status: "ok",
|
|
3816
|
+
uptime: process.uptime(),
|
|
3817
|
+
timestamp: Date.now()
|
|
3818
|
+
}));
|
|
3819
|
+
const requestLogging = options.requestLogging ?? true;
|
|
3820
|
+
if (requestLogging !== false) app.use(requestLoggingPlugin(requestLogging === true ? {} : requestLogging));
|
|
3821
|
+
const reference = options.reference ?? false;
|
|
3822
|
+
const referenceOptions = typeof reference === "object" ? reference : {};
|
|
3823
|
+
const referencePath = reference === true ? "/reference" : referenceOptions.path;
|
|
3824
|
+
if (referencePath !== void 0) builtIn(referencePath, htmlResponse(scalarDocsHTML(referenceOptions.specUrl ?? openApiPath, referenceOptions.title ?? title)));
|
|
3825
|
+
const byName = /* @__PURE__ */ new Map();
|
|
3826
|
+
for (const service of services) {
|
|
3827
|
+
if ((byName.get(service.name) ?? service) !== service) throw new DuplicateNameError(`Brick: duplicate service "${service.name}" in brick()`);
|
|
3828
|
+
byName.set(service.name, service);
|
|
3829
|
+
}
|
|
3830
|
+
bindDeps(services, options.deps);
|
|
3831
|
+
const eventsOptions = plugins.listeners.length ? {
|
|
3832
|
+
...options.events,
|
|
3833
|
+
listeners: [...options.events?.listeners ?? [], ...plugins.listeners]
|
|
3834
|
+
} : options.events;
|
|
3835
|
+
const events = eventsOptions ? new EventsHub(eventsOptions, options.deps).attach(services) : void 0;
|
|
3836
|
+
if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
|
|
3837
|
+
if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
|
|
3838
|
+
for (const service of services) service.build();
|
|
3839
|
+
const endpointDefs = [];
|
|
3840
|
+
let endpointRevision = 0;
|
|
3841
|
+
const buildSpec = () => {
|
|
3842
|
+
const spec = generateOpenApiSpec({
|
|
3843
|
+
title,
|
|
3844
|
+
version,
|
|
3845
|
+
description: options.description,
|
|
3846
|
+
prefix,
|
|
3847
|
+
services
|
|
3848
|
+
});
|
|
3849
|
+
const paths = { ...spec.paths };
|
|
3850
|
+
for (const [path, operations] of Object.entries(endpointPaths(endpointDefs))) paths[path] = {
|
|
3851
|
+
...paths[path],
|
|
3852
|
+
...operations
|
|
3853
|
+
};
|
|
3854
|
+
return {
|
|
3855
|
+
...spec,
|
|
3856
|
+
paths
|
|
3857
|
+
};
|
|
3858
|
+
};
|
|
3859
|
+
if (enableDocs) {
|
|
3860
|
+
builtIn(openApiPath, cachedJsonRoute(buildSpec, () => [getGlobalRegistry(), getGlobalRegistry().revision + endpointRevision]));
|
|
3861
|
+
builtIn(docsPath, htmlResponse(scalarDocsHTML(openApiPath, title)));
|
|
3862
|
+
builtIn(swaggerPath, htmlResponse(swaggerDocsHTML(openApiPath, title)));
|
|
3863
|
+
}
|
|
3864
|
+
builtIn("/_brick/services", (context) => architecture(context));
|
|
3865
|
+
const sockets = services.flatMap((service) => service.listSockets().map((definition) => ({
|
|
3866
|
+
service: service.name,
|
|
3867
|
+
path: socketPath(prefix, service.name, definition),
|
|
3868
|
+
definition
|
|
3869
|
+
})));
|
|
3870
|
+
const socketRoutes = /* @__PURE__ */ new Set();
|
|
3871
|
+
for (const socket of sockets) {
|
|
3872
|
+
const key = routeKey("GET", socket.path);
|
|
3873
|
+
if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new DuplicateNameError(`Brick: duplicate socket route '${socket.path}'`);
|
|
3874
|
+
socketRoutes.add(key);
|
|
3875
|
+
}
|
|
3876
|
+
const mountRoute = (method, path, handler, plugin = false) => {
|
|
3877
|
+
const key = routeKey(method, path);
|
|
3878
|
+
if (socketRoutes.has(key)) throw new DuplicateNameError(`Brick: route '${method} ${path}' conflicts with a socket`);
|
|
3879
|
+
if (registeredRoutes.has(key)) {
|
|
3880
|
+
if (plugin || registeredRoutes.get(key)) throw new DuplicateNameError(`Brick: duplicate plugin route '${method} ${path}'`);
|
|
3881
|
+
return false;
|
|
3882
|
+
}
|
|
3883
|
+
app.route(method, path, handler);
|
|
3884
|
+
registeredRoutes.set(key, plugin);
|
|
3885
|
+
return true;
|
|
3886
|
+
};
|
|
3887
|
+
const mountEndpoint = (def, plugin = false) => {
|
|
3888
|
+
const handler = createEndpointHandler(def, services);
|
|
3889
|
+
mountRoute(def.method, def.path, telemetry ? (context) => traceHttpRequest(context, def.method, def.path, () => handler(context)) : handler, plugin);
|
|
3890
|
+
endpointDefs.push(def);
|
|
3891
|
+
endpointRevision++;
|
|
3892
|
+
};
|
|
3893
|
+
for (const service of services) for (const def of getPluginEndpoints(service, prefix)) mountEndpoint(def, true);
|
|
3894
|
+
for (const def of options.endpoints ?? []) mountEndpoint(def);
|
|
3895
|
+
const brickApp = app;
|
|
3896
|
+
brickApp.endpoint = (def) => {
|
|
3897
|
+
mountEndpoint(def);
|
|
3898
|
+
};
|
|
3899
|
+
brickApp.listEndpoints = () => [...endpointDefs];
|
|
3900
|
+
brickApp.openApiDocument = buildSpec;
|
|
3901
|
+
brickApp.referenceDocuments = async () => {
|
|
3902
|
+
const documents = enableDocs ? [{
|
|
3903
|
+
title,
|
|
3904
|
+
document: buildSpec()
|
|
3905
|
+
}] : [];
|
|
3906
|
+
for (const extra of referenceOptions.documents ?? []) try {
|
|
3907
|
+
const document = typeof extra.document === "function" ? await extra.document() : extra.document;
|
|
3908
|
+
documents.push({
|
|
3909
|
+
title: extra.title,
|
|
3910
|
+
document
|
|
3911
|
+
});
|
|
3912
|
+
} catch (error) {
|
|
3913
|
+
console.warn(`[Brick-TS] Skipping the "${extra.title}" API document: ${error instanceof Error ? error.message : String(error)}`);
|
|
3914
|
+
}
|
|
3915
|
+
return documents;
|
|
3916
|
+
};
|
|
3917
|
+
const compilation = options.compilation ?? compileBrickApplication({
|
|
3918
|
+
services,
|
|
3919
|
+
prefix,
|
|
3920
|
+
mode: options.compiler === false ? "generic" : "specialized"
|
|
3921
|
+
});
|
|
3922
|
+
if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
|
|
3923
|
+
const mountedRoutes = [];
|
|
3924
|
+
for (const route of compilation.routes) {
|
|
3925
|
+
const invoke = (context) => {
|
|
3926
|
+
const result = telemetry ? withSpan(`${SPAN.actionPrefix}${route.ir.service}.${route.ir.action}`, {
|
|
3927
|
+
[ATTR.service]: route.ir.service,
|
|
3928
|
+
[ATTR.action]: route.ir.action
|
|
3929
|
+
}, () => route.handler(context)) : route.handler(context);
|
|
3930
|
+
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
3931
|
+
};
|
|
3932
|
+
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin))) mountedRoutes.push(route.ir);
|
|
3933
|
+
}
|
|
3934
|
+
mountSockets(app, sockets, options.sockets?.broker ?? localBroker(), options.sockets?.secret);
|
|
3935
|
+
const definition = Object.freeze({
|
|
3936
|
+
services: Object.freeze([...services]),
|
|
3937
|
+
prefix,
|
|
3938
|
+
routes: Object.freeze(mountedRoutes),
|
|
3939
|
+
sockets: Object.freeze(sockets.map(({ service, path, definition }) => ({
|
|
3940
|
+
...definition.schema,
|
|
3941
|
+
service,
|
|
3942
|
+
path
|
|
3943
|
+
}))),
|
|
3944
|
+
telemetry,
|
|
3945
|
+
documentation: normalizeDocumentation(options.documentation),
|
|
3946
|
+
dashboard,
|
|
3947
|
+
...events ? { events: events.describe() } : {},
|
|
3948
|
+
plugins: Object.freeze(plugins.plugins)
|
|
3949
|
+
});
|
|
3950
|
+
Object.defineProperty(brickApp, "definition", { value: definition });
|
|
3951
|
+
Object.defineProperty(brickApp, "events", { value: events });
|
|
3952
|
+
const lifecycle = pluginLifecycle(plugins.lifecycles);
|
|
3953
|
+
const listen = app.listen.bind(app);
|
|
3954
|
+
const stop = app.stop.bind(app);
|
|
3955
|
+
Object.defineProperty(brickApp, "start", { value: lifecycle.start });
|
|
3956
|
+
brickApp.listen = ((...args) => {
|
|
3957
|
+
lifecycle.start().catch((error) => {
|
|
3958
|
+
console.error("[Brick-TS] A plugin failed to start:", error);
|
|
3959
|
+
return stop(true);
|
|
3960
|
+
});
|
|
3961
|
+
return listen(...args);
|
|
3962
|
+
});
|
|
3963
|
+
brickApp.stop = (async (closeActiveConnections) => {
|
|
3964
|
+
try {
|
|
3965
|
+
await stop(closeActiveConnections);
|
|
3966
|
+
} finally {
|
|
3967
|
+
await lifecycle.stop();
|
|
3968
|
+
}
|
|
3969
|
+
});
|
|
3970
|
+
Object.defineProperty(brickApp, "serve", { value: async ({ port }) => {
|
|
3971
|
+
await lifecycle.start();
|
|
3972
|
+
listen(port);
|
|
3973
|
+
events?.start();
|
|
3974
|
+
return brickApp;
|
|
3975
|
+
} });
|
|
3976
|
+
Object.defineProperty(brickApp, "shutdown", { value: async (closeActiveConnections) => {
|
|
3977
|
+
await events?.stop();
|
|
3978
|
+
await brickApp.stop(closeActiveConnections);
|
|
3979
|
+
} });
|
|
3980
|
+
const architecture = cachedJsonRoute(() => getGlobalRegistry().exportArchitecture(definition), () => {
|
|
3981
|
+
const registry = getGlobalRegistry();
|
|
3982
|
+
return [registry, registry.revision];
|
|
3983
|
+
});
|
|
3984
|
+
return brickApp;
|
|
3985
|
+
}
|
|
3986
|
+
function normalizeDocumentation(documentation) {
|
|
3987
|
+
if (documentation === void 0) return void 0;
|
|
3988
|
+
const options = typeof documentation === "string" ? { dir: documentation } : documentation;
|
|
3989
|
+
if (typeof options.dir !== "string" || options.dir === "") throw new Error("Brick: documentation needs a folder, such as './docs'.");
|
|
3990
|
+
return Object.freeze({
|
|
3991
|
+
dir: options.dir,
|
|
3992
|
+
...options.components ? { components: options.components } : {}
|
|
3993
|
+
});
|
|
3994
|
+
}
|
|
3995
|
+
function jsonActionResult(value) {
|
|
3996
|
+
return value === null ? new Response("null", { headers: { "content-type": "application/json" } }) : value;
|
|
3997
|
+
}
|
|
3998
|
+
function htmlResponse(html) {
|
|
3999
|
+
return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
4000
|
+
}
|
|
4001
|
+
/** Reuse serialized JSON, without sharing a mutable response body between requests. */
|
|
4002
|
+
function cachedJsonRoute(build, revision) {
|
|
4003
|
+
let [owner, version] = revision();
|
|
4004
|
+
let json = JSON.stringify(build());
|
|
4005
|
+
return ({ set }) => {
|
|
4006
|
+
const [currentOwner, currentVersion] = revision();
|
|
4007
|
+
if (currentOwner !== owner || currentVersion !== version) {
|
|
4008
|
+
json = JSON.stringify(build());
|
|
4009
|
+
owner = currentOwner;
|
|
4010
|
+
version = currentVersion;
|
|
4011
|
+
}
|
|
4012
|
+
set.headers["content-type"] = "application/json;charset=utf-8";
|
|
4013
|
+
return json;
|
|
4014
|
+
};
|
|
4015
|
+
}
|
|
4016
|
+
export { validateName as $, generateOpenApiSpec as A, createActionHandler as B, SecretRef as C, overrideSecret as D, listSecrets as E, bindCompiledApplication as F, useDeps as G, definitionSite as H, compileBrickApplication as I, getPluginEndpoints as J, defineResourcePlugin as K, loadCompiledBrickApp as L, setActionAccess as M, getGlobalRegistry as N, resetSecrets as O, resetGlobalRegistry as P, segmentClaimant as Q, isBrickApp as R, requestLoggingPlugin as S, envSource as T, INTERNALS as U, claimName as V, port as W, installPlugin as X, hasPlugin as Y, isInstallingPlugin as Z, isOutboxTable as _, WORKFLOW_BUNDLE as a, baseContext as at, registerReferenceRoute as b, checkEvent as c, t as ct, crudEventSource as d, withCallSpan as dt, portOf as et, eventRefs as f, PLUGIN_COMMIT as ft, runInTransaction as g, onTransactionCommit as h, stopAllEvents as i, deny as it, getActionAccess as j, resolveSecrets as k, checkPayload as l, validateWithSchema as lt, Dispatcher as m, defineServiceSocket as n, defineAction as nt, resolveWorkflowPaths as o, pickContextEnvelope as ot, isCrudEvent as p, PLUGIN_KIND as pt, defineServicePlugin as q, recordingServices as r, errorsOf as rt, defineListener as s, Type as st, brick as t, buildErrorHelpers as tt, crudEventName as u, traceRoute as ut, outboxTable as v, defineSecret as w, scalarDocsHTML as x, referencePlugin as y, requireBrickApp as z };
|
|
4017
|
+
|
|
4018
|
+
//# sourceMappingURL=server.js.map
|