@brickkit/core 0.12.0 → 0.13.1
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 +54 -13
- package/dist/chunks/client.js +382 -91
- package/dist/chunks/client.js.map +1 -1
- package/dist/chunks/server.d.ts +444 -0
- package/dist/chunks/server.js +1138 -1744
- package/dist/chunks/server.js.map +1 -1
- package/dist/chunks/types.d.ts +434 -630
- package/dist/client.d.ts +3 -3
- package/dist/client.js +1 -1
- package/dist/index.d.ts +766 -5
- package/dist/index.js +532 -302
- package/dist/index.js.map +1 -1
- package/dist/tanstack-query.js.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -3
- package/dist/testing.js.map +1 -1
- package/dist/workflow.d.ts +74 -2
- package/package.json +2 -1
- package/dist/chunks/index.d.ts +0 -1106
- package/dist/chunks/workflow.d.ts +0 -74
package/dist/index.js
CHANGED
|
@@ -1,82 +1,374 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { a as isBrickTransportError,
|
|
1
|
+
import { $ as validateName, A as generateOpenApiSpec, B as createActionHandler, C as SecretRef, D as overrideSecret, E as listSecrets, F as bindCompiledApplication, G as useDeps, H as definitionSite, I as compileBrickApplication, J as getPluginEndpoints, K as defineResourcePlugin, L as loadCompiledBrickApp, M as setActionAccess, N as getGlobalRegistry, O as resetSecrets, P as resetGlobalRegistry, Q as segmentClaimant, R as isBrickApp, S as requestLoggingPlugin, T as envSource, U as INTERNALS, V as claimName, W as port, X as installPlugin, Y as hasPlugin, Z as isInstallingPlugin, _ as isOutboxTable, a as WORKFLOW_BUNDLE, at as baseContext, b as registerReferenceRoute, c as checkEvent, ct as t, d as crudEventSource, dt as withCallSpan, et as portOf, f as eventRefs, ft as PLUGIN_COMMIT, g as runInTransaction, h as onTransactionCommit, i as stopAllEvents, it as deny, j as getActionAccess, k as resolveSecrets, l as checkPayload, lt as validateWithSchema, m as Dispatcher, n as defineServiceSocket, nt as defineAction, o as resolveWorkflowPaths, ot as pickContextEnvelope, p as isCrudEvent, pt as PLUGIN_KIND, q as defineServicePlugin, r as recordingServices, rt as errorsOf, s as defineListener, st as Type, t as brick, tt as buildErrorHelpers, u as crudEventName, ut as traceRoute, v as outboxTable, w as defineSecret, x as scalarDocsHTML, y as referencePlugin, z as requireBrickApp } from "./chunks/server.js";
|
|
2
|
+
import { G as DuplicateNameError, H as GLOBAL_SYMBOL, K as ValidationError, S as actionMeta, U as SPAN, V as ATTR, W as ActionExecutionError, a as isBrickTransportError, d as getActionRoute, f as getPluginActionRoute, i as isBrickServerError, j as compareSocketSeq, l as actionOwners, n as BrickTransportError, r as createBrickClient, s as serializeSocketSchema, t as BrickServerError, x as kebabCase } from "./chunks/client.js";
|
|
3
3
|
import { defineError, stepErrors, stepFailure } from "./workflow.js";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { dirname, isAbsolute, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { Value } from "@sinclair/typebox/value";
|
|
8
8
|
import { Table, and, and as and$1, asc, desc, eq, eq as eq$1, getTableColumns, getTableColumns as getTableColumns$1, getTableName, getTableName as getTableName$1, gt, gte, ilike, inArray, inArray as inArray$1, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql, sql as sql$1 } from "drizzle-orm";
|
|
9
|
-
import { blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
10
|
-
import { getTableConfig, isPgEnum, pgSchema } from "drizzle-orm/pg-core";
|
|
11
|
-
import
|
|
12
|
-
import { drizzle } from "drizzle-orm/postgres-js";
|
|
9
|
+
import { blob, foreignKey, index, integer, integer as integer$1, primaryKey, real, real as real$1, sqliteTable, sqliteTable as sqliteTable$1, text, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
10
|
+
import { boolean, doublePrecision, getTableConfig, integer as integer$2, isPgEnum, jsonb, pgSchema, pgTable, text as text$2, timestamp } from "drizzle-orm/pg-core";
|
|
11
|
+
import { mkdirSync, readFileSync } from "node:fs";
|
|
13
12
|
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
|
14
13
|
import { migrate as migrate$1 } from "drizzle-orm/bun-sqlite/migrator";
|
|
14
|
+
import postgres from "postgres";
|
|
15
|
+
import { drizzle } from "drizzle-orm/postgres-js";
|
|
15
16
|
// \0rolldown/runtime.js
|
|
16
17
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
17
|
-
// src/
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
18
|
+
// src/plugin-hooks.ts
|
|
19
|
+
/** Where `hooks.*` stores a plugin's hooks on its host; `@brickkit/crud` runs them. */
|
|
20
|
+
const HOST_HOOKS = Symbol.for("brickkit.plugin.hooks");
|
|
21
|
+
const HOOK_NAMES = Object.keys({
|
|
22
|
+
beforeCreate: true,
|
|
23
|
+
afterCreate: true,
|
|
24
|
+
beforeUpdate: true,
|
|
25
|
+
afterUpdate: true,
|
|
26
|
+
beforeDelete: true,
|
|
27
|
+
afterDelete: true,
|
|
28
|
+
afterCommit: true
|
|
29
|
+
});
|
|
30
|
+
/** The plugin hooks installed on a service or resource, by hook name. */
|
|
31
|
+
function getHostHooks(host) {
|
|
32
|
+
return host[HOST_HOOKS];
|
|
33
|
+
}
|
|
34
|
+
/** Add hooks to a host, after those already there. */
|
|
35
|
+
function addHostHooks(host, added) {
|
|
36
|
+
const store = host[HOST_HOOKS] ??= {};
|
|
37
|
+
for (const name of HOOK_NAMES) if (added[name]) (store[name] ??= []).push(...added[name]);
|
|
38
|
+
}
|
|
39
|
+
// src/plugin-tables.ts
|
|
40
|
+
const OWNER = Symbol.for("brickkit.plugin.owner");
|
|
41
|
+
function setPluginOwner(table, plugin) {
|
|
42
|
+
Object.defineProperty(table, OWNER, { value: plugin });
|
|
43
|
+
}
|
|
44
|
+
/** The plugin that owns a table, for tables a `definePlugin` contributed. */
|
|
45
|
+
function pluginOwner(table) {
|
|
46
|
+
return table && typeof table === "object" ? table[OWNER] : void 0;
|
|
47
|
+
}
|
|
48
|
+
const sqliteBuilders = {
|
|
49
|
+
/** A table. Its name gets the plugin's prefix (`page_comments`). */
|
|
50
|
+
table: (name, columns) => sqliteTable$1(name, columns),
|
|
51
|
+
text: (name) => text$1(name),
|
|
52
|
+
integer: (name) => integer$1(name, { mode: "number" }),
|
|
53
|
+
real: (name) => real$1(name),
|
|
54
|
+
boolean: (name) => integer$1(name, { mode: "boolean" }),
|
|
55
|
+
/** A `Date`, stored as epoch milliseconds or `timestamptz`. */
|
|
56
|
+
timestamp: (name) => integer$1(name, { mode: "timestamp_ms" }),
|
|
57
|
+
json: (name) => text$1(name, { mode: "json" })
|
|
58
|
+
};
|
|
59
|
+
function builders(engine, tableName) {
|
|
60
|
+
if (engine === "postgres") return {
|
|
61
|
+
engine,
|
|
62
|
+
table: (name, columns) => pgTable(tableName(name), columns),
|
|
63
|
+
text: (name) => text$2(name),
|
|
64
|
+
integer: (name) => integer$2(name),
|
|
65
|
+
real: (name) => doublePrecision(name),
|
|
66
|
+
boolean: (name) => boolean(name),
|
|
67
|
+
timestamp: (name) => timestamp(name, {
|
|
68
|
+
mode: "date",
|
|
69
|
+
withTimezone: true
|
|
70
|
+
}),
|
|
71
|
+
json: (name) => jsonb(name)
|
|
72
|
+
};
|
|
73
|
+
return {
|
|
74
|
+
...sqliteBuilders,
|
|
75
|
+
engine,
|
|
76
|
+
table: (name, columns) => sqliteTable$1(tableName(name), columns)
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
// src/version.ts
|
|
80
|
+
let runningVersion;
|
|
81
|
+
/** The version of this @brickkit/core, read from its package.json; `""` when unknown. */
|
|
82
|
+
function brickVersion() {
|
|
83
|
+
if (runningVersion !== void 0) return runningVersion;
|
|
84
|
+
for (const relative of ["../package.json", "../../package.json"]) try {
|
|
85
|
+
const json = JSON.parse(readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8"));
|
|
86
|
+
if (json.name === "@brickkit/core") return runningVersion = json.version;
|
|
87
|
+
} catch {}
|
|
88
|
+
return runningVersion = "";
|
|
89
|
+
}
|
|
90
|
+
function parseVersion(version) {
|
|
91
|
+
const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[-+]/)[0].split(".").map(Number);
|
|
92
|
+
return [
|
|
93
|
+
major,
|
|
94
|
+
minor,
|
|
95
|
+
patch
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
function compare(a, b) {
|
|
99
|
+
return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,
|
|
103
|
+
* `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.
|
|
104
|
+
*/
|
|
105
|
+
function satisfiesRange(version, range) {
|
|
106
|
+
const current = parseVersion(version);
|
|
107
|
+
return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
|
|
108
|
+
const match = /^(\^|~|>=|<=|>|<|=)?v?([\dx*]+(?:\.[\dx*]+){0,2})?/i.exec(comparator);
|
|
109
|
+
const operator = match?.[1] ?? "";
|
|
110
|
+
const parts = (match?.[2] ?? "*").split(".");
|
|
111
|
+
const wild = parts.findIndex((part) => /^[x*]$/i.test(part));
|
|
112
|
+
const given = wild === -1 ? parts.length : wild;
|
|
113
|
+
const low = parseVersion(parts.slice(0, given).join(".") || "0");
|
|
114
|
+
if (given === 0) return true;
|
|
115
|
+
const cmp = compare(current, low);
|
|
116
|
+
if (operator === ">=") return cmp >= 0;
|
|
117
|
+
if (operator === ">") return cmp > 0;
|
|
118
|
+
if (operator === "<") return cmp < 0;
|
|
119
|
+
if (operator === "<=") return cmp <= 0;
|
|
120
|
+
let high;
|
|
121
|
+
if (operator === "^") high = low[0] > 0 || given === 1 ? [
|
|
122
|
+
low[0] + 1,
|
|
123
|
+
0,
|
|
124
|
+
0
|
|
125
|
+
] : low[1] > 0 || given === 2 ? [
|
|
126
|
+
0,
|
|
127
|
+
low[1] + 1,
|
|
128
|
+
0
|
|
129
|
+
] : [
|
|
130
|
+
0,
|
|
131
|
+
0,
|
|
132
|
+
low[2] + 1
|
|
133
|
+
];
|
|
134
|
+
else if (operator === "~" || given < 3) high = given === 1 ? [
|
|
135
|
+
low[0] + 1,
|
|
136
|
+
0,
|
|
137
|
+
0
|
|
138
|
+
] : [
|
|
139
|
+
low[0],
|
|
140
|
+
low[1] + 1,
|
|
141
|
+
0
|
|
142
|
+
];
|
|
143
|
+
else return cmp === 0;
|
|
144
|
+
return cmp >= 0 && compare(current, high) < 0;
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
// src/define-plugin.ts
|
|
148
|
+
let installCount = 0;
|
|
149
|
+
const toWords = (name) => (name.split("/").pop() ?? name).replace(/^brick-/, "").replace(/-plugin$/, "").split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
150
|
+
const snake = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
151
|
+
/**
|
|
152
|
+
* Define a plugin: a manifest Brick checks, plus the capabilities the plugin
|
|
153
|
+
* brings. Install its instances with `resource.use()`, `service.use()` or
|
|
154
|
+
* `brick({ plugins })`; scope comes from where it is installed.
|
|
155
|
+
*
|
|
156
|
+
* @param manifest - `name`, `brick` (semver range), `requires`, `options`
|
|
157
|
+
* (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`
|
|
158
|
+
* parts, and a `dashboard` extension.
|
|
159
|
+
* @returns A factory: `comments({ maxLength: 500 })` validates the options and
|
|
160
|
+
* the Brick version and returns an instance to install.
|
|
161
|
+
* @throws From the factory, when the running Brick is outside `brick` or an
|
|
162
|
+
* option is invalid; when installed, when a required plugin is missing or the
|
|
163
|
+
* host does not suit the plugin.
|
|
164
|
+
* @example
|
|
165
|
+
* export const audit = definePlugin({
|
|
166
|
+
* name: "@acme/brick-audit",
|
|
167
|
+
* brick: "^0.12.0",
|
|
168
|
+
* requires: ["@brickkit/crud"],
|
|
169
|
+
* options: t.Object({ table: t.String({ default: "audit" }) }),
|
|
170
|
+
* tables: ({ table, text, timestamp }) => ({
|
|
171
|
+
* log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
|
|
172
|
+
* }),
|
|
173
|
+
* resource: ({ tables, hooks }) => {
|
|
174
|
+
* hooks.afterCreate(({ row, tx }) =>
|
|
175
|
+
* tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
|
|
176
|
+
* return {};
|
|
177
|
+
* },
|
|
178
|
+
* });
|
|
179
|
+
*
|
|
180
|
+
* page.use(audit());
|
|
181
|
+
*/
|
|
182
|
+
function definePlugin(manifest) {
|
|
183
|
+
const { name } = manifest;
|
|
184
|
+
validateName(name);
|
|
185
|
+
if (!manifest.resource && !manifest.service && !manifest.app) throw new Error(`Plugin "${name}" needs a resource, service or app part to install`);
|
|
186
|
+
for (const key of Object.keys(manifest.events ?? {})) if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key)) throw new Error(`Event "${key}" of plugin "${name}" must be a plain name such as added`);
|
|
187
|
+
const site = definitionSite()?.replace(/:\d+$/, "");
|
|
188
|
+
const dashboard = manifest.dashboard === void 0 ? void 0 : manifest.dashboard.startsWith("file:") ? fileURLToPath(manifest.dashboard) : isAbsolute(manifest.dashboard) || !site ? resolve(manifest.dashboard) : resolve(dirname(site), manifest.dashboard);
|
|
189
|
+
const info = Object.freeze({
|
|
190
|
+
name,
|
|
191
|
+
description: manifest.description,
|
|
192
|
+
brick: manifest.brick,
|
|
193
|
+
requires: Object.freeze([...manifest.requires ?? []]),
|
|
194
|
+
options: manifest.options,
|
|
195
|
+
secrets: Object.freeze(Object.values(manifest.secrets ?? {}).map((secret) => secret.name)),
|
|
196
|
+
deps: Object.freeze(Object.keys(manifest.deps ?? {})),
|
|
197
|
+
capabilities: Object.freeze([
|
|
198
|
+
"tables",
|
|
199
|
+
"events",
|
|
200
|
+
"resource",
|
|
201
|
+
"service",
|
|
202
|
+
"app",
|
|
203
|
+
"dashboard"
|
|
204
|
+
].filter((key) => manifest[key] !== void 0))
|
|
205
|
+
});
|
|
206
|
+
const words = toWords(name);
|
|
207
|
+
const eventSpace = words.map((word, index) => index ? word[0].toUpperCase() + word.slice(1) : word).join("");
|
|
208
|
+
const tableSpace = snake(words.join("_"));
|
|
209
|
+
if (!eventSpace) throw new Error(`Plugin "${name}" needs letters or digits in its name`);
|
|
210
|
+
const factory = (input = {}, install = {}) => {
|
|
211
|
+
const version = brickVersion();
|
|
212
|
+
if (manifest.brick && version && !satisfiesRange(version, manifest.brick)) throw new Error(`${name} supports Brick ${manifest.brick}; this app runs ${version}`);
|
|
213
|
+
const options = checkOptions(name, manifest.options, input);
|
|
214
|
+
const deps = checkDeps(name, eventSpace, manifest.deps, install.deps);
|
|
215
|
+
const secrets = manifest.secrets ?? {};
|
|
216
|
+
const internals = {
|
|
217
|
+
manifest,
|
|
218
|
+
options,
|
|
219
|
+
deps,
|
|
220
|
+
install,
|
|
221
|
+
dashboard,
|
|
222
|
+
installs: []
|
|
223
|
+
};
|
|
224
|
+
const setup = (context) => {
|
|
225
|
+
const { service, resource } = context;
|
|
226
|
+
const host = resource ?? service;
|
|
227
|
+
const where = resource ? `resource "${resource.name}"` : `service "${service.name}"`;
|
|
228
|
+
const part = resource ? manifest.resource : manifest.service;
|
|
229
|
+
if (!part) throw new Error(`${name} cannot be installed on a ${resource ? "resource" : "service"}; ${manifest.resource ? "use resource.use()" : manifest.service ? "use service.use()" : "add it to brick({ plugins })"}`);
|
|
230
|
+
for (const required of manifest.requires ?? []) if (!hasPlugin(service, host, required)) throw new Error(`${name} requires ${required}, installed on ${where} before it`);
|
|
231
|
+
let tables = {};
|
|
232
|
+
if (manifest.tables) {
|
|
233
|
+
const database = service.getDatabaseHandle?.();
|
|
234
|
+
if (!database) throw new Error(`${name} owns tables, so service "${service.name}" needs a database`);
|
|
235
|
+
const prefix = install.prefix ?? `${snake(resource?.name ?? service.name)}_`;
|
|
236
|
+
tables = manifest.tables(builders(database.engine, (table) => install.prefix !== void 0 || table === tableSpace ? `${prefix}${table}` : `${prefix}${tableSpace}_${table}`));
|
|
237
|
+
const taken = new Set([...service.tables.values(), ...Object.values(database.tables)].map((table) => getTableName$1(table)));
|
|
238
|
+
for (const table of Object.values(tables)) {
|
|
239
|
+
const tableName = getTableName$1(table);
|
|
240
|
+
if (taken.has(tableName)) throw new Error(`${name} table "${tableName}" clashes with a table service "${service.name}" already has; install it with another prefix`);
|
|
241
|
+
taken.add(tableName);
|
|
242
|
+
setPluginOwner(table, name);
|
|
243
|
+
portOf(service).registerTable(table);
|
|
244
|
+
}
|
|
33
245
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
246
|
+
const catalog = service.events;
|
|
247
|
+
const events = {};
|
|
248
|
+
for (const [key, schema] of Object.entries(manifest.events ?? {})) {
|
|
249
|
+
const existing = catalog[`${eventSpace}.${key}`];
|
|
250
|
+
if (existing && existing.plugin !== name) throw new Error(`${name} event "${eventSpace}.${key}" is already in the catalog of service "${service.name}"`);
|
|
251
|
+
events[key] = existing ?? Object.freeze({
|
|
252
|
+
name: `${service.name}.${eventSpace}.${key}`,
|
|
253
|
+
service: service.name,
|
|
254
|
+
schema,
|
|
255
|
+
plugin: name
|
|
256
|
+
});
|
|
43
257
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
258
|
+
const added = {};
|
|
259
|
+
const hooks = Object.fromEntries(HOOK_NAMES.map((hook) => [hook, (fn) => {
|
|
260
|
+
if (typeof fn !== "function") throw new Error(`${name}: hooks.${hook} needs a function`);
|
|
261
|
+
(added[hook] ??= []).push((args) => fn({
|
|
262
|
+
...args,
|
|
263
|
+
ctx: {
|
|
264
|
+
...args.ctx,
|
|
265
|
+
deps
|
|
266
|
+
}
|
|
267
|
+
}));
|
|
268
|
+
}]));
|
|
269
|
+
const routes = {
|
|
270
|
+
action: (config) => context.routes.action(config),
|
|
271
|
+
endpoint: (config) => context.routes.endpoint({
|
|
272
|
+
...config,
|
|
273
|
+
handler: (args) => config.handler({
|
|
274
|
+
...args,
|
|
275
|
+
ctx: {
|
|
276
|
+
...args.ctx,
|
|
277
|
+
deps
|
|
278
|
+
}
|
|
279
|
+
})
|
|
280
|
+
}),
|
|
281
|
+
claim: (segment) => context.routes.claim(segment)
|
|
282
|
+
};
|
|
283
|
+
const before = /* @__PURE__ */ new Set([
|
|
284
|
+
...service.listActions(),
|
|
285
|
+
...service.listTools(),
|
|
286
|
+
...service.listSockets()
|
|
287
|
+
]);
|
|
288
|
+
const started = bindings;
|
|
289
|
+
const api = part({
|
|
290
|
+
options,
|
|
291
|
+
secrets,
|
|
292
|
+
tables,
|
|
293
|
+
events,
|
|
294
|
+
deps,
|
|
295
|
+
service,
|
|
296
|
+
resource,
|
|
297
|
+
routes,
|
|
298
|
+
hooks
|
|
299
|
+
});
|
|
300
|
+
for (const action of [...service.listActions(), ...service.listTools()]) if (!before.has(action)) bindPluginDeps(name, action, deps, started);
|
|
301
|
+
for (const socket of service.listSockets()) if (!before.has(socket)) socket.deps ??= deps;
|
|
302
|
+
context[PLUGIN_COMMIT]?.(() => {
|
|
303
|
+
const database = service.getDatabaseHandle?.();
|
|
304
|
+
for (const table of Object.values(tables)) database?.addTable?.(getTableName$1(table), table);
|
|
305
|
+
if (Object.keys(events).length) portOf(service).addEvents(Object.fromEntries(Object.entries(events).map(([key, ref]) => [`${eventSpace}.${key}`, ref])));
|
|
306
|
+
addHostHooks(host, added);
|
|
307
|
+
internals.installs.push({
|
|
308
|
+
scope: resource ? "resource" : "service",
|
|
309
|
+
service: service.name,
|
|
310
|
+
resource: resource?.name
|
|
311
|
+
});
|
|
312
|
+
internals.order ??= ++installCount;
|
|
313
|
+
});
|
|
314
|
+
return resource ? api ?? {} : api;
|
|
315
|
+
};
|
|
316
|
+
return Object.freeze({
|
|
317
|
+
[PLUGIN_KIND]: "plugin",
|
|
318
|
+
name,
|
|
319
|
+
info,
|
|
320
|
+
setup,
|
|
321
|
+
[INTERNALS]: internals
|
|
322
|
+
});
|
|
323
|
+
};
|
|
324
|
+
return Object.assign(factory, { info });
|
|
325
|
+
}
|
|
326
|
+
/** Counts bindings, so a setup can tell a nested install's from an earlier one's. */
|
|
327
|
+
let bindings = 0;
|
|
328
|
+
/**
|
|
329
|
+
* Run an action with the plugin's deps as `ctx.deps`: context resolution
|
|
330
|
+
* reads them from its metadata. A nested definePlugin binds its own actions
|
|
331
|
+
* first, so they keep its deps.
|
|
332
|
+
*
|
|
333
|
+
* @throws When the action is already bound to another install's deps: one
|
|
334
|
+
* action object shared by two installs could only run with one of them.
|
|
335
|
+
*/
|
|
336
|
+
function bindPluginDeps(plugin, action, deps, started) {
|
|
337
|
+
const meta = actionMeta(action);
|
|
338
|
+
if (meta.deps) {
|
|
339
|
+
if (meta.deps.values === deps || meta.deps.at > started) return;
|
|
340
|
+
throw new Error(`${plugin}: action "${action.name}" is already bound to the deps of another install; create the action inside the setup so each install gets its own`);
|
|
48
341
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if (
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
${
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
}`;
|
|
342
|
+
meta.deps = {
|
|
343
|
+
values: deps,
|
|
344
|
+
at: ++bindings
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
/** Check the deps passed at install against the ports the plugin declares. */
|
|
348
|
+
function checkDeps(plugin, camelName, ports, given = {}) {
|
|
349
|
+
if (given === null || typeof given !== "object" || Array.isArray(given)) throw new Error(`${plugin}: deps must be an object`);
|
|
350
|
+
const declared = Object.keys(ports ?? {});
|
|
351
|
+
const provided = given;
|
|
352
|
+
const extra = Object.keys(provided).filter((key) => !declared.includes(key));
|
|
353
|
+
if (extra.length) throw new Error(`${plugin} does not declare ${extra.map((key) => `deps.${key}`).join(", ")}; ${declared.length ? `it takes ${declared.join(", ")}` : "it takes no deps"}`);
|
|
354
|
+
const missing = declared.filter((key) => provided[key] === void 0);
|
|
355
|
+
if (missing.length) throw new Error(`${plugin} needs ${missing.map((key) => `deps.${key}`).join(", ")}; pass it when installing: ${camelName}(options, { deps: { ${missing.join(", ")} } })`);
|
|
356
|
+
return Object.freeze(Object.fromEntries(declared.map((key) => [key, provided[key]])));
|
|
357
|
+
}
|
|
358
|
+
function checkOptions(plugin, schema, input) {
|
|
359
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error(`${plugin}: options must be an object`);
|
|
360
|
+
if (!schema) {
|
|
361
|
+
if (Object.keys(input).length) throw new Error(`${plugin} takes no options`);
|
|
362
|
+
return {};
|
|
363
|
+
}
|
|
364
|
+
const value = Value.Default(schema, structuredClone(input));
|
|
365
|
+
const result = validateWithSchema(schema, value);
|
|
366
|
+
if (!result.success) {
|
|
367
|
+
const [first] = result.errors;
|
|
368
|
+
const option = first.path.replace(/^\//, "").replaceAll("/", ".");
|
|
369
|
+
throw new Error(`${plugin}: option ${option ? `"${option}"` : ""} ${first.message}`.replace(/\s+/g, " "));
|
|
370
|
+
}
|
|
371
|
+
return value;
|
|
80
372
|
}
|
|
81
373
|
// src/tool.ts
|
|
82
374
|
function defineTool(config) {
|
|
@@ -124,9 +416,8 @@ function createSQLiteDatabase(config = {}) {
|
|
|
124
416
|
// src/db/postgres.ts
|
|
125
417
|
/**
|
|
126
418
|
* Creates a PostgreSQL Drizzle instance using postgres-js.
|
|
127
|
-
* Static imports (
|
|
128
|
-
*
|
|
129
|
-
* `sqlite.ts` since it only exists under Bun.
|
|
419
|
+
* Static imports so bundlers (Nitro/Rollup) trace and ship the driver.
|
|
420
|
+
* `bun:sqlite` stays lazy in `sqlite.ts` since it only exists under Bun.
|
|
130
421
|
*/
|
|
131
422
|
function createPostgresDatabase(config = {}) {
|
|
132
423
|
const connectionUrl = config.url ?? config.connectionString ?? (typeof process !== "undefined" ? process.env?.DATABASE_URL : void 0);
|
|
@@ -172,6 +463,7 @@ function defineDatabase(options = {}) {
|
|
|
172
463
|
"database",
|
|
173
464
|
"ssl",
|
|
174
465
|
"max",
|
|
466
|
+
"prepare",
|
|
175
467
|
"schemaName"
|
|
176
468
|
] : [
|
|
177
469
|
"path",
|
|
@@ -243,18 +535,24 @@ function defineDatabase(options = {}) {
|
|
|
243
535
|
}
|
|
244
536
|
};
|
|
245
537
|
}
|
|
246
|
-
// src/db/
|
|
538
|
+
// src/db/column.ts
|
|
247
539
|
/**
|
|
248
|
-
*
|
|
249
|
-
*
|
|
250
|
-
*
|
|
540
|
+
* A JSON value as its column stores it: an ISO string becomes a Date for a date
|
|
541
|
+
* column, an integer string a BigInt for a bigint column. Other values pass
|
|
542
|
+
* through.
|
|
543
|
+
*
|
|
544
|
+
* @returns `undefined` when the string can't be a value of the column.
|
|
251
545
|
*/
|
|
252
|
-
function
|
|
253
|
-
|
|
254
|
-
if (
|
|
255
|
-
|
|
256
|
-
|
|
546
|
+
function columnValue(column, value) {
|
|
547
|
+
if (typeof value !== "string") return value;
|
|
548
|
+
if (column.dataType === "date") {
|
|
549
|
+
const date = new Date(value);
|
|
550
|
+
return Number.isNaN(date.getTime()) ? void 0 : date;
|
|
551
|
+
}
|
|
552
|
+
if (column.dataType === "bigint") return /^-?\d+$/.test(value) ? BigInt(value) : void 0;
|
|
553
|
+
return value;
|
|
257
554
|
}
|
|
555
|
+
// src/db/index.ts
|
|
258
556
|
/**
|
|
259
557
|
* Apply the migrations in a folder that have not run yet, in order, and record
|
|
260
558
|
* them in the database's `__drizzle_migrations` table. The folder is the one
|
|
@@ -345,10 +643,13 @@ function generateSQLiteIndexDdl(table, opts = {}) {
|
|
|
345
643
|
/**
|
|
346
644
|
* Ensures secondary indexes exist for a resource table.
|
|
347
645
|
* SQLite: B-tree indexes for owner scope + sort + composite hot path.
|
|
348
|
-
* Postgres: same B-trees plus pg_trgm GIN indexes for substring search
|
|
349
|
-
*
|
|
646
|
+
* Postgres: same B-trees plus pg_trgm GIN indexes for substring search,
|
|
647
|
+
* created one after another (each GIN index needs the extension).
|
|
648
|
+
* Best-effort: a failed statement warns and the rest still run (e.g. a
|
|
649
|
+
* read-only replica, or no right to create pg_trgm); queries still work, only
|
|
650
|
+
* slower. On SQLite every statement has run when it returns.
|
|
350
651
|
*/
|
|
351
|
-
function ensureResourceIndexes(db, table, opts = {}) {
|
|
652
|
+
async function ensureResourceIndexes(db, table, opts = {}) {
|
|
352
653
|
if (!db) return;
|
|
353
654
|
const isPostgres = typeof db.execute === "function" && !db.$client?.run;
|
|
354
655
|
const stmts = generateSQLiteIndexDdl(table, opts);
|
|
@@ -365,15 +666,14 @@ function ensureResourceIndexes(db, table, opts = {}) {
|
|
|
365
666
|
}
|
|
366
667
|
}
|
|
367
668
|
if (stmts.length === 0) return;
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
for (const s of stmts) run(s);
|
|
669
|
+
if (isPostgres) stmts.unshift(`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);
|
|
670
|
+
for (const stmt of stmts) try {
|
|
671
|
+
if (db.$client?.run) db.$client.run(stmt);
|
|
672
|
+
else if (isPostgres) await db.execute(sql$1.raw(stmt));
|
|
673
|
+
else db.run?.(stmt);
|
|
674
|
+
} catch (error) {
|
|
675
|
+
console.warn(`[Brick-TS DB] Skipped an index: ${stmt} (${error instanceof Error ? error.message : String(error)})`);
|
|
676
|
+
}
|
|
377
677
|
}
|
|
378
678
|
/**
|
|
379
679
|
* SQLite FTS5 search layer for resource list (?search=).
|
|
@@ -420,7 +720,9 @@ function ensureSQLiteFts(db, table, searchCols) {
|
|
|
420
720
|
run(`CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ad`)} AFTER DELETE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE "id" = old.${quoteIdent(idCol)}; END;`);
|
|
421
721
|
run(`CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_au`)} AFTER UPDATE ON ${quoteIdent(tableName)} BEGIN DELETE FROM ${quoteIdent(fts)} WHERE "id" = old.${quoteIdent(idCol)}; INSERT INTO ${quoteIdent(fts)}("id", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals}); END;`);
|
|
422
722
|
run(`INSERT INTO ${quoteIdent(fts)}("id", ${colList}) SELECT ${quoteIdent(idCol)}, ${colList} FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(idCol)} NOT IN (SELECT "id" FROM ${quoteIdent(fts)});`);
|
|
423
|
-
} catch {
|
|
723
|
+
} catch (error) {
|
|
724
|
+
console.warn(`[Brick-TS DB] Skipped full-text search for ${getTableName$1(table)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
725
|
+
}
|
|
424
726
|
}
|
|
425
727
|
/**
|
|
426
728
|
* Builds an FTS5 MATCH condition for a resource search term.
|
|
@@ -530,16 +832,6 @@ async function createMissingPostgresTables(db, tables) {
|
|
|
530
832
|
});
|
|
531
833
|
}
|
|
532
834
|
// src/resource.ts
|
|
533
|
-
/** Resource actions can't take a CRUD route segment. */
|
|
534
|
-
const CRUD_SEGMENTS = /* @__PURE__ */ new Set([
|
|
535
|
-
"query",
|
|
536
|
-
"count",
|
|
537
|
-
"exists",
|
|
538
|
-
"find-one",
|
|
539
|
-
"bulk-create",
|
|
540
|
-
"bulk-update",
|
|
541
|
-
"bulk-delete"
|
|
542
|
-
]);
|
|
543
835
|
/**
|
|
544
836
|
* Load the row a record action (or command) works on, through its `access`.
|
|
545
837
|
*
|
|
@@ -549,7 +841,7 @@ const CRUD_SEGMENTS = /* @__PURE__ */ new Set([
|
|
|
549
841
|
async function loadRecord(resource, args) {
|
|
550
842
|
if (!args.access) throw new Error(`Resource '${resource.name}' has no access rule for loading records: set \`access\` on the record action`);
|
|
551
843
|
const db = args.db ?? args.ctx?.db;
|
|
552
|
-
const id =
|
|
844
|
+
const id = columnValue(resource.id, args.id);
|
|
553
845
|
if (id === void 0) return void 0;
|
|
554
846
|
if (!db) throw new Error("Record actions require a configured database");
|
|
555
847
|
const scope = args.access === "public" ? void 0 : await args.access.scope({ ctx: args.ctx });
|
|
@@ -561,16 +853,10 @@ function checkRecordAccess(resource, info) {
|
|
|
561
853
|
const name = `${resource.name}.${info.name}`;
|
|
562
854
|
if (info.access === void 0) throw new Error(`Record action '${name}' needs \`access\` ("public" or { scope })`);
|
|
563
855
|
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
if (typeof id !== "string") return id;
|
|
567
|
-
if (column.dataType === "date") {
|
|
568
|
-
const date = new Date(id);
|
|
569
|
-
return Number.isNaN(date.getTime()) ? void 0 : date;
|
|
570
|
-
}
|
|
571
|
-
if (column.dataType === "bigint") return /^-?\d+$/.test(id) ? BigInt(id) : void 0;
|
|
572
|
-
return id;
|
|
856
|
+
function notFound(resource, id, error) {
|
|
857
|
+
error.NOT_FOUND(`${resource.name} '${String(id)}' not found`);
|
|
573
858
|
}
|
|
859
|
+
/** The schema of a resource's `:id`. */
|
|
574
860
|
function idSchema(column) {
|
|
575
861
|
return column.dataType === "number" ? Type.Number() : Type.String();
|
|
576
862
|
}
|
|
@@ -579,8 +865,10 @@ function defineResourceAction(service, resource, config, command) {
|
|
|
579
865
|
if (!config.name || /[./]/.test(config.name)) throw new Error(`Invalid resource action name '${config.name}'`);
|
|
580
866
|
const name = `${resource.name}.${config.name}`;
|
|
581
867
|
const segment = kebabCase(config.name);
|
|
582
|
-
|
|
583
|
-
if (
|
|
868
|
+
const claimant = segmentClaimant(service, resource, segment);
|
|
869
|
+
if (claimant) throw new DuplicateNameError(`Brick: duplicate name "${name}" in service "${service.name}": "${segment}" is a ${claimant} route`);
|
|
870
|
+
const existing = service.getAction(name);
|
|
871
|
+
if (existing && actionMeta(existing).route) throw new DuplicateNameError(`Brick: duplicate name "${name}" in service "${service.name}"`);
|
|
584
872
|
if (!record && access !== void 0) throw new Error(`Only record actions take \`access\` ('${name}')`);
|
|
585
873
|
if (record && config.path !== void 0 && !/\/:id(\/|$)/.test(config.path)) throw new Error(`Record action '${name}' needs ':id' in its path`);
|
|
586
874
|
let input = config.input;
|
|
@@ -607,7 +895,7 @@ function defineResourceAction(service, resource, config, command) {
|
|
|
607
895
|
ctx,
|
|
608
896
|
access
|
|
609
897
|
}) : void 0;
|
|
610
|
-
if (record && row === void 0)
|
|
898
|
+
if (record && row === void 0) notFound(resource, input.id, error);
|
|
611
899
|
return execute({
|
|
612
900
|
input,
|
|
613
901
|
ctx,
|
|
@@ -622,10 +910,7 @@ function defineResourceAction(service, resource, config, command) {
|
|
|
622
910
|
record,
|
|
623
911
|
...access === void 0 ? {} : { access }
|
|
624
912
|
};
|
|
625
|
-
|
|
626
|
-
resource: resource.name,
|
|
627
|
-
resourceAction: info
|
|
628
|
-
});
|
|
913
|
+
actionMeta(action).resourceAction = info;
|
|
629
914
|
service.action(action);
|
|
630
915
|
return action;
|
|
631
916
|
}
|
|
@@ -672,7 +957,7 @@ function defineCommand(service, resource, name, config) {
|
|
|
672
957
|
const error = commandErrors(config.errors);
|
|
673
958
|
const decide = (row, input) => config.decide(row, input, { error });
|
|
674
959
|
const events = service.events;
|
|
675
|
-
const run = async ({ input, ctx }) => {
|
|
960
|
+
const run = async ({ input, ctx, error: helpers }) => {
|
|
676
961
|
const db = ctx.db;
|
|
677
962
|
if (!db) throw new Error(`${where} requires a configured database`);
|
|
678
963
|
const recorder = service.recorder;
|
|
@@ -683,7 +968,7 @@ function defineCommand(service, resource, name, config) {
|
|
|
683
968
|
db: tx,
|
|
684
969
|
access: config.access
|
|
685
970
|
});
|
|
686
|
-
if (row === void 0)
|
|
971
|
+
if (row === void 0) notFound(resource, input.id, helpers);
|
|
687
972
|
const id = row[resource.idField];
|
|
688
973
|
for (const child of loaded) row[child.name] = await tx.select().from(child.table).where(eq$1(child.parent, id));
|
|
689
974
|
const decision = decide(row, input);
|
|
@@ -692,7 +977,7 @@ function defineCommand(service, resource, name, config) {
|
|
|
692
977
|
const emits = Object.entries(emit ?? {}).filter(([, payload]) => payload !== void 0).map(([key, payload]) => {
|
|
693
978
|
const ref = Object.hasOwn(events, key) ? events[key] : void 0;
|
|
694
979
|
if (!ref) throw new Error(`${where} emits '${key}', which is not in the event catalog of service '${service.name}'`);
|
|
695
|
-
|
|
980
|
+
checkPayload(ref, payload);
|
|
696
981
|
return [ref.name, payload];
|
|
697
982
|
});
|
|
698
983
|
if (emits.length && !record) throw new Error(`${where} emits events, but service '${service.name}' records none: give its database an outbox table and the app \`events\``);
|
|
@@ -720,7 +1005,7 @@ function defineCommand(service, resource, name, config) {
|
|
|
720
1005
|
};
|
|
721
1006
|
return recorder ? recorder.transaction(db, {
|
|
722
1007
|
traceId: ctx.traceId,
|
|
723
|
-
source:
|
|
1008
|
+
source: crudEventSource(service.name, resource.name)
|
|
724
1009
|
}, body) : runInTransaction(db, (tx) => body(tx));
|
|
725
1010
|
};
|
|
726
1011
|
const action = defineResourceAction(service, resource, {
|
|
@@ -735,17 +1020,13 @@ function defineCommand(service, resource, name, config) {
|
|
|
735
1020
|
...config.authorize ? { authorize: config.authorize } : {},
|
|
736
1021
|
execute: () => void 0
|
|
737
1022
|
}, run);
|
|
738
|
-
Object.assign(action, {
|
|
739
|
-
decide,
|
|
740
|
-
command: true
|
|
741
|
-
});
|
|
1023
|
+
Object.assign(action, { decide });
|
|
742
1024
|
return action;
|
|
743
1025
|
}
|
|
744
|
-
/** Declares a plugin host
|
|
1026
|
+
/** Declares a resource: a plugin host over a table, with its own `action()` and `command()`. */
|
|
745
1027
|
function defineResource(service, config) {
|
|
746
1028
|
const columns = getTableColumns$1(config.table);
|
|
747
|
-
const
|
|
748
|
-
const id = config.id ?? (primary.length === 1 ? primary[0]?.[1] : void 0);
|
|
1029
|
+
const id = config.id ?? primaryColumn(config.table)?.[1];
|
|
749
1030
|
const entry = Object.entries(columns).find(([, column]) => column === id);
|
|
750
1031
|
if (!entry || !id) throw new Error(`Resource '${config.name}' requires an id column belonging to its table`);
|
|
751
1032
|
if (!config.name || config.name.includes("/") || [
|
|
@@ -753,7 +1034,7 @@ function defineResource(service, config) {
|
|
|
753
1034
|
"constructor",
|
|
754
1035
|
"prototype"
|
|
755
1036
|
].includes(config.name)) throw new Error(`Invalid resource name '${config.name}'`);
|
|
756
|
-
service.registerTable(config.table);
|
|
1037
|
+
portOf(service).registerTable(config.table);
|
|
757
1038
|
const resource = {
|
|
758
1039
|
name: config.name,
|
|
759
1040
|
serviceName: service.name,
|
|
@@ -776,64 +1057,7 @@ function defineResource(service, config) {
|
|
|
776
1057
|
};
|
|
777
1058
|
return resource;
|
|
778
1059
|
}
|
|
779
|
-
// src/events/catalog.ts
|
|
780
|
-
function isEventRef(value) {
|
|
781
|
-
return typeof value === "object" && value !== null && typeof value.name === "string" && typeof value.service === "string" && typeof value.schema === "object";
|
|
782
|
-
}
|
|
783
|
-
/** Build `service.events` from its catalog. */
|
|
784
|
-
function eventRefs(service, catalog) {
|
|
785
|
-
const refs = Object.create(null);
|
|
786
|
-
for (const [key, schema] of Object.entries(catalog ?? {})) {
|
|
787
|
-
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`);
|
|
788
|
-
if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
|
|
789
|
-
refs[key] = Object.freeze({
|
|
790
|
-
name: `${service}.${key}`,
|
|
791
|
-
service,
|
|
792
|
-
schema
|
|
793
|
-
});
|
|
794
|
-
}
|
|
795
|
-
return Object.freeze(refs);
|
|
796
|
-
}
|
|
797
|
-
const CRUD_EVENT = /^(create|update|delete)$/;
|
|
798
|
-
/**
|
|
799
|
-
* Check an event against the catalog of the service recording it. Without a
|
|
800
|
-
* catalog any name goes. With one, the name must be `<service>.<event>` from it
|
|
801
|
-
* (the payload is checked against its schema) or a CRUD event of one of the
|
|
802
|
-
* service's resources (`<resource>.create|update|delete`).
|
|
803
|
-
*
|
|
804
|
-
* @throws When the name is not declared or the payload does not match.
|
|
805
|
-
*/
|
|
806
|
-
function checkEvent(service, name, payload) {
|
|
807
|
-
const prefix = `${service.name}.`;
|
|
808
|
-
const ref = name.startsWith(prefix) ? service.events[name.slice(prefix.length)] : void 0;
|
|
809
|
-
if (ref) {
|
|
810
|
-
const result = validateWithSchema(ref.schema, payload);
|
|
811
|
-
if (!result.success) throw new Error(`Event "${name}" payload does not match its schema: ${result.errors.map((error) => `${error.path || "/"} ${error.message}`).join("; ")}`);
|
|
812
|
-
return;
|
|
813
|
-
}
|
|
814
|
-
if (!service.hasCatalog) return;
|
|
815
|
-
const dot = name.indexOf(".");
|
|
816
|
-
if (dot > 0 && CRUD_EVENT.test(name.slice(dot + 1)) && service.listResources().some((r) => r.name === name.slice(0, dot))) return;
|
|
817
|
-
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"})`);
|
|
818
|
-
}
|
|
819
|
-
// src/context.ts
|
|
820
|
-
function pickContextEnvelope(context) {
|
|
821
|
-
if (!context) return {};
|
|
822
|
-
const envelope = {};
|
|
823
|
-
if (context.caller !== void 0) envelope.caller = context.caller;
|
|
824
|
-
if (context.user !== void 0) envelope.user = context.user;
|
|
825
|
-
if (context.traceId !== void 0) envelope.traceId = context.traceId;
|
|
826
|
-
if (context.requestId !== void 0) envelope.requestId = context.requestId;
|
|
827
|
-
if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
|
|
828
|
-
return envelope;
|
|
829
|
-
}
|
|
830
1060
|
// src/service.ts
|
|
831
|
-
const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
|
|
832
|
-
const DEFAULT_REQUEST = new Request("http://localhost");
|
|
833
|
-
const EMPTY_SERVICES = Object.freeze({});
|
|
834
|
-
const EMPTY_METADATA = Object.freeze({});
|
|
835
|
-
const EMPTY_DEPS = Object.freeze({});
|
|
836
|
-
let _ctxSeq = 0;
|
|
837
1061
|
const RESOLVED_SYMBOL = Symbol("resolved");
|
|
838
1062
|
/** The deps a resolved context was resolved with, to restore them when a plugin's copy comes back. */
|
|
839
1063
|
const OWN_DEPS = Symbol("ownDeps");
|
|
@@ -850,16 +1074,23 @@ var ServiceImpl = class {
|
|
|
850
1074
|
sites = /* @__PURE__ */ new Map();
|
|
851
1075
|
database;
|
|
852
1076
|
_isBuilt = false;
|
|
853
|
-
|
|
854
|
-
events
|
|
1077
|
+
_events;
|
|
1078
|
+
/** What a write needs to record events. Set by `brick({ events })`. */
|
|
1079
|
+
recorder;
|
|
1080
|
+
/** The values of this service's `deps`. Set by `brick({ deps })`. */
|
|
1081
|
+
deps;
|
|
855
1082
|
constructor(name, options = {}) {
|
|
856
1083
|
this.name = name;
|
|
857
1084
|
this.options = options;
|
|
858
|
-
this.
|
|
859
|
-
for (const key of Object.keys(this.
|
|
1085
|
+
this._events = eventRefs(name, options.events);
|
|
1086
|
+
for (const key of Object.keys(this._events)) this.claim("event", key);
|
|
860
1087
|
if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
|
|
861
1088
|
this.database = options.database;
|
|
862
1089
|
}
|
|
1090
|
+
/** The declared events: `service.events.<name>`. */
|
|
1091
|
+
get events() {
|
|
1092
|
+
return this._events;
|
|
1093
|
+
}
|
|
863
1094
|
use(plugin) {
|
|
864
1095
|
return installPlugin(this, void 0, plugin);
|
|
865
1096
|
}
|
|
@@ -869,6 +1100,43 @@ var ServiceImpl = class {
|
|
|
869
1100
|
get isBuilt() {
|
|
870
1101
|
return this._isBuilt;
|
|
871
1102
|
}
|
|
1103
|
+
/** Every definition change passes here, so cached architecture and OpenAPI are rebuilt. */
|
|
1104
|
+
touch() {
|
|
1105
|
+
getGlobalRegistry().touch();
|
|
1106
|
+
}
|
|
1107
|
+
snapshot() {
|
|
1108
|
+
const maps = [
|
|
1109
|
+
this.actions,
|
|
1110
|
+
this.tools,
|
|
1111
|
+
this.tables,
|
|
1112
|
+
this.sockets,
|
|
1113
|
+
this.resources,
|
|
1114
|
+
this.preparations,
|
|
1115
|
+
this.sites
|
|
1116
|
+
];
|
|
1117
|
+
const saved = maps.map((map) => new Map(map));
|
|
1118
|
+
const events = this._events;
|
|
1119
|
+
const properties = new Map([...this.resources.values()].map((item) => [item, Object.getOwnPropertyDescriptors(item)]));
|
|
1120
|
+
return () => {
|
|
1121
|
+
maps.forEach((map, index) => {
|
|
1122
|
+
map.clear();
|
|
1123
|
+
for (const [key, value] of saved[index]) map.set(key, value);
|
|
1124
|
+
});
|
|
1125
|
+
this._events = events;
|
|
1126
|
+
for (const [item, own] of properties) {
|
|
1127
|
+
for (const key of Reflect.ownKeys(item)) if (!Object.hasOwn(own, key)) Reflect.deleteProperty(item, key);
|
|
1128
|
+
Object.defineProperties(item, own);
|
|
1129
|
+
}
|
|
1130
|
+
this.touch();
|
|
1131
|
+
};
|
|
1132
|
+
}
|
|
1133
|
+
addEvents(refs) {
|
|
1134
|
+
this._events = Object.freeze({
|
|
1135
|
+
...this._events,
|
|
1136
|
+
...refs
|
|
1137
|
+
});
|
|
1138
|
+
this.touch();
|
|
1139
|
+
}
|
|
872
1140
|
/**
|
|
873
1141
|
* Closes declarations after plugins have registered their actions and preparations.
|
|
874
1142
|
*/
|
|
@@ -876,7 +1144,7 @@ var ServiceImpl = class {
|
|
|
876
1144
|
if (isInstallingPlugin(this)) throw new Error("Cannot build a service during plugin setup");
|
|
877
1145
|
if (this._isBuilt) return this;
|
|
878
1146
|
for (const action of this.actions.values()) {
|
|
879
|
-
const info = action.resourceAction;
|
|
1147
|
+
const info = actionMeta(action).resourceAction;
|
|
880
1148
|
const resource = info?.record && this.resources.get(info.resource);
|
|
881
1149
|
if (resource) checkRecordAccess(resource, info);
|
|
882
1150
|
}
|
|
@@ -890,7 +1158,7 @@ var ServiceImpl = class {
|
|
|
890
1158
|
if (this._isBuilt) throw new Error("Preparations must be registered before service build");
|
|
891
1159
|
if (this.preparations.has(contribution.name)) throw new Error(`Duplicate preparation '${contribution.name}'`);
|
|
892
1160
|
this.preparations.set(contribution.name, contribution);
|
|
893
|
-
|
|
1161
|
+
this.touch();
|
|
894
1162
|
}
|
|
895
1163
|
listPreparations() {
|
|
896
1164
|
return [...this.preparations.values()];
|
|
@@ -899,23 +1167,18 @@ var ServiceImpl = class {
|
|
|
899
1167
|
for (const contribution of this.preparations.values()) contribution.prepare();
|
|
900
1168
|
}
|
|
901
1169
|
registerTable(table) {
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
this.tables.set(tableName, table);
|
|
905
|
-
} catch {
|
|
906
|
-
const fallbackName = table._?.name ?? `table_${this.tables.size + 1}`;
|
|
907
|
-
this.tables.set(fallbackName, table);
|
|
908
|
-
}
|
|
1170
|
+
this.tables.set(getTableName(table), table);
|
|
1171
|
+
this.touch();
|
|
909
1172
|
return this;
|
|
910
1173
|
}
|
|
911
|
-
resource
|
|
1174
|
+
resource(config) {
|
|
912
1175
|
if (this._isBuilt) throw new Error("Resources must be registered before service build");
|
|
913
1176
|
this.claim("resource", config.name);
|
|
914
1177
|
const resourceInstance = defineResource(this, config);
|
|
915
1178
|
this.resources.set(resourceInstance.name, resourceInstance);
|
|
916
|
-
|
|
1179
|
+
this.touch();
|
|
917
1180
|
return resourceInstance;
|
|
918
|
-
}
|
|
1181
|
+
}
|
|
919
1182
|
getResource(name) {
|
|
920
1183
|
return this.resources.get(name);
|
|
921
1184
|
}
|
|
@@ -923,29 +1186,25 @@ var ServiceImpl = class {
|
|
|
923
1186
|
return Array.from(this.resources.values());
|
|
924
1187
|
}
|
|
925
1188
|
action(actionOrConfig) {
|
|
926
|
-
let actionInstance;
|
|
927
1189
|
const isActionFunction = typeof actionOrConfig === "function" && "config" in actionOrConfig;
|
|
928
|
-
|
|
929
|
-
else actionInstance = defineAction(actionOrConfig);
|
|
930
|
-
if (isInstallingPlugin(this) && this.actions.has(actionInstance.name) && this.actions.get(actionInstance.name) !== actionInstance) throw new Error(`Duplicate plugin action: ${actionInstance.name}`);
|
|
1190
|
+
const actionInstance = isActionFunction ? actionOrConfig : defineAction(actionOrConfig);
|
|
931
1191
|
if (this.actions.get(actionInstance.name) !== actionInstance) this.claim("action", actionInstance.name);
|
|
932
1192
|
if (isTool(actionInstance)) actionInstance.config.http = true;
|
|
933
1193
|
actionInstance.serviceName = this.name;
|
|
934
|
-
actionInstance.service = this;
|
|
1194
|
+
actionMeta(actionInstance).service = this;
|
|
935
1195
|
this.actions.set(actionInstance.name, actionInstance);
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
return actionInstance;
|
|
1196
|
+
this.touch();
|
|
1197
|
+
return isActionFunction ? this : actionInstance;
|
|
939
1198
|
}
|
|
940
1199
|
tool(toolOrConfig) {
|
|
941
1200
|
const existing = isTool(toolOrConfig);
|
|
942
1201
|
const tool = existing ? toolOrConfig : defineTool(toolOrConfig);
|
|
943
1202
|
this.claim("tool", tool.name);
|
|
944
1203
|
tool.serviceName = this.name;
|
|
945
|
-
tool.service = this;
|
|
1204
|
+
actionMeta(tool).service = this;
|
|
946
1205
|
this.tools.set(tool.name, tool);
|
|
947
1206
|
if (tool.config.http) this.action(tool);
|
|
948
|
-
|
|
1207
|
+
this.touch();
|
|
949
1208
|
return existing ? this : tool;
|
|
950
1209
|
}
|
|
951
1210
|
getTool(name) {
|
|
@@ -954,16 +1213,9 @@ var ServiceImpl = class {
|
|
|
954
1213
|
socket(config) {
|
|
955
1214
|
if (this._isBuilt) throw new Error("Sockets must be declared before service build");
|
|
956
1215
|
this.claim("socket", config.name);
|
|
957
|
-
const socket = defineServiceSocket(this.name, config,
|
|
958
|
-
const ctx = await resolveServiceContext(this, { request });
|
|
959
|
-
const deps = socket[PLUGIN_DEPS];
|
|
960
|
-
return deps ? {
|
|
961
|
-
...ctx,
|
|
962
|
-
deps
|
|
963
|
-
} : ctx;
|
|
964
|
-
});
|
|
1216
|
+
const socket = defineServiceSocket(this.name, config, (request) => resolveServiceContext(this, { request }, socket.deps));
|
|
965
1217
|
this.sockets.set(config.name, socket);
|
|
966
|
-
|
|
1218
|
+
this.touch();
|
|
967
1219
|
return socket.handle;
|
|
968
1220
|
}
|
|
969
1221
|
listSockets() {
|
|
@@ -985,15 +1237,12 @@ var ServiceImpl = class {
|
|
|
985
1237
|
getDatabaseHandle() {
|
|
986
1238
|
return this.database;
|
|
987
1239
|
}
|
|
988
|
-
/** What a write needs to record events. Set by `brick({ events })`. */
|
|
989
|
-
recorder;
|
|
990
1240
|
getOutbox() {
|
|
991
1241
|
return Object.values(this.database?.tables ?? {}).find(isOutboxTable);
|
|
992
1242
|
}
|
|
993
1243
|
setRecorder(recorder) {
|
|
994
1244
|
this.recorder = recorder;
|
|
995
1245
|
}
|
|
996
|
-
/** Whether the service declares an event catalog. */
|
|
997
1246
|
get hasCatalog() {
|
|
998
1247
|
return this.options.events !== void 0;
|
|
999
1248
|
}
|
|
@@ -1001,23 +1250,21 @@ var ServiceImpl = class {
|
|
|
1001
1250
|
checkEvent(name, payload) {
|
|
1002
1251
|
checkEvent(this, name, payload);
|
|
1003
1252
|
}
|
|
1004
|
-
/** The values of this service's `deps`. Set by `brick({ deps })`. */
|
|
1005
|
-
deps;
|
|
1006
1253
|
setDeps(deps) {
|
|
1007
1254
|
this.deps = deps;
|
|
1008
1255
|
}
|
|
1009
1256
|
setDb(database) {
|
|
1010
1257
|
if (!isDatabaseHandle(database)) throw new Error("Use defineDatabase() to set a service database");
|
|
1011
1258
|
this.database = database;
|
|
1012
|
-
|
|
1259
|
+
this.touch();
|
|
1013
1260
|
}
|
|
1014
1261
|
/**
|
|
1015
1262
|
* Resolves the complete service execution context once per incoming request.
|
|
1016
1263
|
* Merges framework BaseContext with the service's custom context hook.
|
|
1017
1264
|
* Always rebuilds context for this service to prevent caller context from overriding.
|
|
1018
1265
|
*/
|
|
1019
|
-
resolveContext(callCtx) {
|
|
1020
|
-
return resolveServiceContext(this, callCtx);
|
|
1266
|
+
resolveContext(callCtx, pluginDeps) {
|
|
1267
|
+
return resolveServiceContext(this, callCtx, pluginDeps);
|
|
1021
1268
|
}
|
|
1022
1269
|
introspect() {
|
|
1023
1270
|
const databaseConfig = this.database ? {
|
|
@@ -1039,8 +1286,7 @@ var ServiceImpl = class {
|
|
|
1039
1286
|
return {
|
|
1040
1287
|
name: act.name,
|
|
1041
1288
|
serviceName: this.name,
|
|
1042
|
-
...act
|
|
1043
|
-
...act.resource ? { resource: act.resource } : {},
|
|
1289
|
+
...actionOwners(act),
|
|
1044
1290
|
description: act.config.description,
|
|
1045
1291
|
inputSchema: act.config.input,
|
|
1046
1292
|
outputSchema: act.config.output,
|
|
@@ -1070,40 +1316,41 @@ function pluginTables(tables) {
|
|
|
1070
1316
|
});
|
|
1071
1317
|
return owners.length ? { plugins: Object.fromEntries(owners) } : {};
|
|
1072
1318
|
}
|
|
1073
|
-
|
|
1319
|
+
/**
|
|
1320
|
+
* The context of a call to one of the service's actions or sockets. The one
|
|
1321
|
+
* rule for which deps it sees: those of the plugin install that created the
|
|
1322
|
+
* action or socket (`pluginDeps`), else the service's own. The service's
|
|
1323
|
+
* `context` hook always sees the service's own.
|
|
1324
|
+
*/
|
|
1325
|
+
async function resolveServiceContext(service, callCtx, pluginDeps) {
|
|
1074
1326
|
if (callCtx?.[RESOLVED_SYMBOL] === service) {
|
|
1075
|
-
const
|
|
1076
|
-
return callCtx.deps ===
|
|
1327
|
+
const deps = pluginDeps ?? callCtx[OWN_DEPS];
|
|
1328
|
+
return callCtx.deps === deps ? callCtx : {
|
|
1077
1329
|
...callCtx,
|
|
1078
|
-
deps
|
|
1330
|
+
deps
|
|
1079
1331
|
};
|
|
1080
1332
|
}
|
|
1081
|
-
const
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1333
|
+
const framework = baseContext({
|
|
1334
|
+
request: callCtx?.request,
|
|
1335
|
+
db: service.getDb(),
|
|
1336
|
+
logger: callCtx?.logger,
|
|
1337
|
+
traceId: callCtx?.traceId,
|
|
1338
|
+
requestId: callCtx?.requestId,
|
|
1339
|
+
services: callCtx?.services,
|
|
1340
|
+
metadata: callCtx?.metadata,
|
|
1341
|
+
deps: service.deps ?? (callCtx?.[RESOLVED_SYMBOL] ? void 0 : callCtx?.deps)
|
|
1342
|
+
});
|
|
1090
1343
|
const fullBaseCtx = {
|
|
1091
|
-
|
|
1092
|
-
db,
|
|
1093
|
-
logger,
|
|
1094
|
-
traceId,
|
|
1095
|
-
requestId,
|
|
1096
|
-
services,
|
|
1097
|
-
metadata,
|
|
1344
|
+
...framework,
|
|
1098
1345
|
...pickContextEnvelope(callCtx)
|
|
1099
1346
|
};
|
|
1100
1347
|
const resolvedExtra = service.options.context ? await service.options.context(fullBaseCtx) : {};
|
|
1101
1348
|
return {
|
|
1102
1349
|
...fullBaseCtx,
|
|
1103
1350
|
...resolvedExtra,
|
|
1104
|
-
deps,
|
|
1351
|
+
deps: pluginDeps ?? framework.deps,
|
|
1105
1352
|
[RESOLVED_SYMBOL]: service,
|
|
1106
|
-
[OWN_DEPS]: deps
|
|
1353
|
+
[OWN_DEPS]: framework.deps
|
|
1107
1354
|
};
|
|
1108
1355
|
}
|
|
1109
1356
|
/**
|
|
@@ -1153,6 +1400,8 @@ function reconnectDelay(failures) {
|
|
|
1153
1400
|
const ceiling = Math.min(3e4, 500 * 2 ** failures);
|
|
1154
1401
|
return ceiling / 2 + Math.random() * (ceiling / 2);
|
|
1155
1402
|
}
|
|
1403
|
+
/** How long a call waits for Redis to connect before going on without it. */
|
|
1404
|
+
const REDIS_WAIT_MS = 1e3;
|
|
1156
1405
|
/** One Redis connection that reconnects by itself and reports each fresh connection. */
|
|
1157
1406
|
function connection(url, connected) {
|
|
1158
1407
|
let redis;
|
|
@@ -1185,7 +1434,6 @@ function connection(url, connected) {
|
|
|
1185
1434
|
}, () => lost(client));
|
|
1186
1435
|
};
|
|
1187
1436
|
return {
|
|
1188
|
-
/** The connected client, starting a connection when there is none. */
|
|
1189
1437
|
get() {
|
|
1190
1438
|
start();
|
|
1191
1439
|
return redis?.connected ? redis : void 0;
|
|
@@ -1195,8 +1443,11 @@ function connection(url, connected) {
|
|
|
1195
1443
|
if (redis?.connected) return Promise.resolve();
|
|
1196
1444
|
start();
|
|
1197
1445
|
return new Promise((resolve) => {
|
|
1198
|
-
|
|
1199
|
-
|
|
1446
|
+
const timeout = setTimeout(resolve, ms);
|
|
1447
|
+
waiters.push(() => {
|
|
1448
|
+
clearTimeout(timeout);
|
|
1449
|
+
resolve();
|
|
1450
|
+
});
|
|
1200
1451
|
});
|
|
1201
1452
|
},
|
|
1202
1453
|
close() {
|
|
@@ -1222,6 +1473,12 @@ function redisBroker(options = {}) {
|
|
|
1222
1473
|
const listeners = /* @__PURE__ */ new Map();
|
|
1223
1474
|
const pending = /* @__PURE__ */ new Map();
|
|
1224
1475
|
const stream = (topic) => `brick:socket:stream:${topic}`;
|
|
1476
|
+
const warned = /* @__PURE__ */ new Set();
|
|
1477
|
+
const warn = (what) => (error) => {
|
|
1478
|
+
if (warned.has(what)) return;
|
|
1479
|
+
warned.add(what);
|
|
1480
|
+
console.warn(`[Brick-TS] Redis socket broker: ${what} failed; later failures of it are not logged.`, error);
|
|
1481
|
+
};
|
|
1225
1482
|
const queue = [];
|
|
1226
1483
|
const send = (work) => {
|
|
1227
1484
|
const redis = publisher.get();
|
|
@@ -1239,7 +1496,7 @@ function redisBroker(options = {}) {
|
|
|
1239
1496
|
for (const deliver of listeners.get(name) ?? []) deliver(message);
|
|
1240
1497
|
};
|
|
1241
1498
|
const subscribe = (redis, name) => {
|
|
1242
|
-
const done = redis.subscribe(name, receive).catch(()
|
|
1499
|
+
const done = redis.subscribe(name, receive).catch(warn("SUBSCRIBE"));
|
|
1243
1500
|
pending.set(name, done);
|
|
1244
1501
|
done.then(() => {
|
|
1245
1502
|
if (pending.get(name) === done) pending.delete(name);
|
|
@@ -1254,7 +1511,7 @@ function redisBroker(options = {}) {
|
|
|
1254
1511
|
return {
|
|
1255
1512
|
publish(message, replay) {
|
|
1256
1513
|
const name = channel(message.topic);
|
|
1257
|
-
if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(()
|
|
1514
|
+
if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(warn("PUBLISH")));
|
|
1258
1515
|
const key = stream(message.topic);
|
|
1259
1516
|
send((redis) => {
|
|
1260
1517
|
redis.send("XADD", [
|
|
@@ -1266,17 +1523,17 @@ function redisBroker(options = {}) {
|
|
|
1266
1523
|
"m",
|
|
1267
1524
|
message.frame
|
|
1268
1525
|
]).then((seq) => {
|
|
1269
|
-
redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(()
|
|
1526
|
+
redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(warn("PEXPIRE"));
|
|
1270
1527
|
return redis.publish(name, JSON.stringify({
|
|
1271
1528
|
...message,
|
|
1272
1529
|
seq
|
|
1273
1530
|
}));
|
|
1274
|
-
}).catch(()
|
|
1531
|
+
}).catch(warn("XADD/PUBLISH"));
|
|
1275
1532
|
});
|
|
1276
1533
|
},
|
|
1277
1534
|
async head() {
|
|
1278
1535
|
try {
|
|
1279
|
-
await publisher.opened(
|
|
1536
|
+
await publisher.opened(REDIS_WAIT_MS);
|
|
1280
1537
|
const [seconds, micros] = await publisher.get().send("TIME", []);
|
|
1281
1538
|
return `${Number(seconds) * 1e3 + Math.floor(Number(micros) / 1e3) - 1}-0`;
|
|
1282
1539
|
} catch {
|
|
@@ -1286,7 +1543,7 @@ function redisBroker(options = {}) {
|
|
|
1286
1543
|
async history(topic, since, replay) {
|
|
1287
1544
|
let raw;
|
|
1288
1545
|
try {
|
|
1289
|
-
await publisher.opened(
|
|
1546
|
+
await publisher.opened(REDIS_WAIT_MS);
|
|
1290
1547
|
raw = await publisher.get().send("XRANGE", [
|
|
1291
1548
|
stream(topic),
|
|
1292
1549
|
"-",
|
|
@@ -1320,12 +1577,12 @@ function redisBroker(options = {}) {
|
|
|
1320
1577
|
if (local.size || listeners.get(name) !== local) return;
|
|
1321
1578
|
listeners.delete(name);
|
|
1322
1579
|
pending.delete(name);
|
|
1323
|
-
subscriber.get()?.unsubscribe(name).catch(()
|
|
1580
|
+
subscriber.get()?.unsubscribe(name).catch(warn("UNSUBSCRIBE"));
|
|
1324
1581
|
};
|
|
1325
1582
|
},
|
|
1326
1583
|
async ready(topic) {
|
|
1327
1584
|
const name = channel(topic);
|
|
1328
|
-
if (!pending.has(name)) await subscriber.opened(
|
|
1585
|
+
if (!pending.has(name)) await subscriber.opened(REDIS_WAIT_MS);
|
|
1329
1586
|
await pending.get(name);
|
|
1330
1587
|
},
|
|
1331
1588
|
close() {
|
|
@@ -1385,9 +1642,9 @@ async function callAction(serviceName, actionName, find, payload, callCtx, optio
|
|
|
1385
1642
|
const action = find(service);
|
|
1386
1643
|
if (!action) throw new Error(`[Brick-TS RPC] Action '${actionName}' does not exist on service '${serviceName}'.`);
|
|
1387
1644
|
const envelopeCtx = createRpcEnvelope(options.from, options.context, callCtx);
|
|
1388
|
-
return withCallSpan(
|
|
1389
|
-
|
|
1390
|
-
|
|
1645
|
+
return withCallSpan(`${SPAN.rpcPrefix}${serviceName}.${actionName}`, {
|
|
1646
|
+
[ATTR.service]: serviceName,
|
|
1647
|
+
[ATTR.action]: actionName
|
|
1391
1648
|
}, () => action.execute({
|
|
1392
1649
|
input: payload,
|
|
1393
1650
|
ctx: envelopeCtx
|
|
@@ -1409,39 +1666,12 @@ function createRpcEnvelope(from, defaultContext, callContext) {
|
|
|
1409
1666
|
if (from !== void 0) envelope.caller = from;
|
|
1410
1667
|
return envelope;
|
|
1411
1668
|
}
|
|
1412
|
-
// src/events/listener.ts
|
|
1413
|
-
function defineListener(config) {
|
|
1414
|
-
if (typeof config.name !== "string" || !config.name) throw new Error("An event listener needs a name");
|
|
1415
|
-
if (config.name.includes(":")) throw new Error(`Event listener name '${config.name}' must not contain ':'`);
|
|
1416
|
-
const on = (Array.isArray(config.on) ? config.on : [config.on]).map((item) => isEventRef(item) ? item.name : item);
|
|
1417
|
-
if (!on.length || on.some((pattern) => !pattern || typeof pattern !== "string")) throw new Error(`Event listener '${config.name}' listens for nothing`);
|
|
1418
|
-
if (config.maxAttempts !== void 0 && (!Number.isInteger(config.maxAttempts) || config.maxAttempts < 1)) throw new Error(`Event listener '${config.name}': maxAttempts must be a positive integer`);
|
|
1419
|
-
const { name, run, workflow } = config;
|
|
1420
|
-
if (run !== void 0 && workflow !== void 0) throw new Error(`Event listener '${name}' has both run and workflow; give it one`);
|
|
1421
|
-
if (run === void 0 && workflow === void 0) throw new Error(`Event listener '${name}' needs a run handler or a workflow`);
|
|
1422
|
-
if (run !== void 0 && typeof run !== "function") throw new Error(`Event listener '${name}': run must be a function`);
|
|
1423
|
-
if (workflow !== void 0 && typeof workflow !== "function") throw new Error(`Event listener '${name}': workflow must be a function marked "use workflow"`);
|
|
1424
|
-
const helpers = buildErrorHelpers(config.errors);
|
|
1425
|
-
return Object.freeze({
|
|
1426
|
-
name: config.name,
|
|
1427
|
-
on: Object.freeze(on),
|
|
1428
|
-
...config.run !== void 0 ? { run: ((delivery) => config.run(delivery, { error: helpers })) } : {},
|
|
1429
|
-
...config.errors ? { errors: config.errors } : {},
|
|
1430
|
-
...config.retry ? { retry: config.retry } : {},
|
|
1431
|
-
...config.workflow !== void 0 ? { workflow: config.workflow } : {},
|
|
1432
|
-
...config.maxAttempts !== void 0 ? { maxAttempts: config.maxAttempts } : {}
|
|
1433
|
-
});
|
|
1434
|
-
}
|
|
1435
1669
|
// src/events/emit.ts
|
|
1436
1670
|
async function emitEvent(ctx, event, payload, options = {}) {
|
|
1437
1671
|
const name = typeof event === "string" ? event : event.name;
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
hasCatalog: true,
|
|
1442
|
-
listResources: () => []
|
|
1443
|
-
}, name, payload);
|
|
1444
|
-
const events = ctx.db && typeof ctx.db === "object" ? recorders.get(ctx.db) : void 0;
|
|
1672
|
+
const service = ctx.db && typeof ctx.db === "object" ? recordingServices.get(ctx.db) : void 0;
|
|
1673
|
+
if (typeof event !== "string" && event.service !== service?.name) checkPayload(event, payload);
|
|
1674
|
+
const events = service?.recorder;
|
|
1445
1675
|
if (!events) throw new Error(`Cannot emit '${name}': ctx.db is not the database of a service with an outbox table (the app needs events, and ctx.db must be the service's own database, not a transaction)`);
|
|
1446
1676
|
const context = {
|
|
1447
1677
|
traceId: ctx.traceId,
|
|
@@ -1465,7 +1695,7 @@ function createMcpRegistry(options) {
|
|
|
1465
1695
|
const tools = /* @__PURE__ */ new Map();
|
|
1466
1696
|
for (const tool of [...options.tools ?? [], ...(options.services ?? []).flatMap((service) => service.listTools())]) {
|
|
1467
1697
|
const existing = tools.get(tool.name);
|
|
1468
|
-
if (existing && existing !== tool) throw new
|
|
1698
|
+
if (existing && existing !== tool) throw new DuplicateNameError(`Duplicate MCP tool: ${tool.name}`);
|
|
1469
1699
|
tools.set(tool.name, tool);
|
|
1470
1700
|
}
|
|
1471
1701
|
return tools;
|
|
@@ -1586,6 +1816,6 @@ function createMcpHandler(options) {
|
|
|
1586
1816
|
}
|
|
1587
1817
|
};
|
|
1588
1818
|
}
|
|
1589
|
-
export {
|
|
1819
|
+
export { ATTR, ActionExecutionError, BrickServerError, BrickTransportError, Dispatcher, DuplicateNameError, GLOBAL_SYMBOL, SPAN, SecretRef, Table, Type, UnknownToolError, ValidationError, WORKFLOW_BUNDLE, actionOwners, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, columnValue, compileBrickApplication, createActionHandler, createBrickClient, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, crudEventName, crudEventSource, defineAction, defineDatabase, defineError, defineListener, definePlugin, defineResource, defineResourcePlugin, defineSecret, defineService, defineServicePlugin, defineTool, deny, desc, drizzleSchema, emitEvent, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, errorsOf, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getActionRoute, getGlobalRegistry, getHostHooks, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, idSchema, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isCrudEvent, isDatabaseHandle, isNotNull, isNull, isTool, kebabCase, like, listSecrets, loadCompiledBrickApp, loadRecord, lt, lte, migrateDatabase, ne, not, notInArray, onTransactionCommit, or, outboxTable, overrideSecret, port, primaryKey, real, redisBroker, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveSecrets, resolveWorkflowPaths, runInTransaction, scalarDocsHTML, serializeSocketSchema, setActionAccess, sql, sqliteTable, stepErrors, stepFailure, stopAllEvents, syncSchema, t, text, traceRoute, uniqueIndex, useDeps, useService, validateWithSchema };
|
|
1590
1820
|
|
|
1591
1821
|
//# sourceMappingURL=index.js.map
|