@brickkit/effect 0.0.0-stage → 0.16.0-beta.7

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/index.js ADDED
@@ -0,0 +1,2501 @@
1
+ import { $ as getGlobalRegistry, $t as listSecrets, A as runInTransaction, An as traceRoute, At as invalid, B as claimSegment, Bn as signDashboardMcp, Bt as frameworkStorage, C as scheduleTable, Cn as createLogger, Ct as reject, D as localBroker, Dn as recordWebhook, Dt as createAction, E as defineServiceSocket, En as Telemetry, Et as RESET_STAGES, F as isCrudEvent, Fn as dashboardKey, Ft as redact, G as getPluginEndpoints, Gn as BrickError, Gt as LOCAL_FILES_ROUTE, H as defineResourcePlugin, Hn as GLOBAL_SYMBOL, Ht as redis, I as OPENAPI_DEFAULTS, In as dashboardMcpCaller, It as sensitivePointer, J as validatePath, Jn as ValidationError, Jt as StorageError, K as hasPlugin, Kn as DuplicateNameError, Kt as s3, L as generateOpenApiSpec, Ln as dashboardUser, Lt as carryClientRequest, M as crudEventSource, Mn as DASHBOARD_IDENTITY_HEADER, Mt as stagesOf, N as defineEvents, Nn as DASHBOARD_KEY_ENV, Nt as Sensitive, O as splitSeq, On as spanStore, Ot as deny, P as encodePayload, Pn as dashboardIdentity, Pt as hasSensitive, Q as PLUGIN_KIND, Qt as envSource, R as requestLoggingPlugin, Rn as markDashboardArrival, Rt as clientAddress, S as outboxTable, Sn as baseContext, St as kindOf, T as SocketDenied, Tn as SpanStore, Tt as HTTP_METHODS, U as defineServicePlugin, Un as SPAN, Ut as requireStorage, V as copyControls, Vn as ATTR, Vt as memory, W as getPluginActionRoute, Wn as actionMeta, Wt as storageKey, X as setInternals, Xn as toErrorResponse, Xt as SecretRef, Y as internalsOf, Yn as normalizeFailures, Yt as StorageUnavailableError, Z as PLUGIN_COMMIT, Zn as toWireError, Zt as defineSecret, _ as idSchema, _n as isAuditTable, _t as decodeCursor, a as WORKFLOW_TABLE, an as depsOverride, at as isObjectSchema, b as stopAllEvents, bn as recordInline, bt as invalid$1, c as workflowEngine, cn as useDeps, ct as setActionAccess, d as createMcpHandler, dn as UploadedFiles, dt as SORTABLE_TYPES, en as overrideSecret, et as resetGlobalRegistry, f as createMcpRegistry, fn as fileFields, ft as UNFILTERABLE_TYPES, g as defineResource, gn as inlineAuditOptions, gt as databaseValue, h as normalizeDashboard, hn as bindAuditTarget, ht as columnValue, i as DurableDeferred, in as definitionSite, it as getActionRoute, j as crudEventName, jn as traceScheduleRun, jt as runStages, k as onTransactionCommit, kn as telemetryLayer, kt as errorHelpers, l as INTERNALS, ln as withOverride, lt as setActionAudit, m as DASHBOARD_MCP_TOOLS, mn as auditTableOf, mt as columnSchema, n as Activity, nn as resolveSecrets, nt as DEFAULT_PREFIX, o as Workflow, on as freezeAsBuiltDeps, ot as kebabCase, p as DASHBOARD_MCP_ROUTE, pn as auditTable, pt as checkJsonSchema, q as installPlugin, qn as STANDARD_ERRORS, qt as scopeFiles, r as DurableClock, rn as claimName, rt as actionOwners, s as WorkflowEngine, sn as ownDeps, st as getActionAccess, t as brick, tn as resetSecrets, tt as exportArchitecture, u as UnknownToolError, un as UploadedFile, ut as ORDERED_TYPES, v as loadRecord, vn as isInlineAudit, vt as encodeCursor, w as defineSchedule, wn as defaultLogger, wt as withoutNull, x as defineListener, xn as actorOf, xt as jsonValue, y as Events, yn as recordAudit, yt as idSchema$1, z as scalarDocsHTML, zn as signDashboardIdentity, zt as defineStorage } from "./server-BK0CrkGH.js";
2
+ import { Cause, Context, Effect, Exit, Layer, Option, Redacted, Result, Schema, SchemaIssue } from "effect";
3
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
4
+ import { Param, SQL, Table, and, asc, between, defineRelations, desc, eq, getTableColumns, getTableName, gt, gte, inArray, is, isNotNull, isNull, lt, lte, ne, notInArray, or, sql } from "drizzle-orm";
5
+ import { PgDialect, PgTable, boolean, doublePrecision, getTableConfig, integer, isPgEnum, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
6
+ import { SQLiteDialect, SQLiteTable, integer as integer$1, real, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
7
+ import { dirname, isAbsolute, resolve } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { mkdirSync, readFileSync } from "node:fs";
10
+ import { SqlClient } from "effect/sql/SqlClient";
11
+ import { SqlError, UnknownError } from "effect/sql/SqlError";
12
+ // src/db.ts
13
+ /**
14
+ * Whether a value is a database handle made by `defineDatabase`.
15
+ *
16
+ * @param value - Anything.
17
+ * @returns `true` for a handle, narrowing its type.
18
+ */
19
+ function isDatabaseHandle(value) {
20
+ return typeof value === "object" && value !== null && "kind" in value && value.kind === "brick-database";
21
+ }
22
+ const driverError = (cause, driver) => new SqlError({ reason: new UnknownError({
23
+ cause,
24
+ message: `Brick: could not load the database driver; install ${driver}`
25
+ }) });
26
+ /**
27
+ * Open a SQLite database over drizzle's Effect driver, until the scope closes:
28
+ * the file's folders are made, `PRAGMA foreign_keys` is set, and the journal is
29
+ * the write-ahead log, unless `foreignKeys` or `wal` say otherwise. Needs
30
+ * `@effect/sql-sqlite-bun`, loaded here and nowhere else.
31
+ *
32
+ * @param config - The `filename` (default `":memory:"`), `tables`, `foreignKeys` and `wal`.
33
+ * @returns The drizzle database, whose queries are Effects.
34
+ * @example
35
+ * const db = yield* createSQLiteDatabase({ filename: "./data/app.db", tables: { pages } });
36
+ * const rows = yield* db.select().from(pages);
37
+ */
38
+ function createSQLiteDatabase(config = {}) {
39
+ const filename = config.filename ?? ":memory:";
40
+ return Effect.gen(function* () {
41
+ const [client, drizzle] = yield* Effect.tryPromise({
42
+ try: () => Promise.all([import("@effect/sql-sqlite-bun/SqliteClient"), import("drizzle-orm/effect-sqlite-bun")]),
43
+ catch: (cause) => driverError(cause, "@effect/sql-sqlite-bun")
44
+ });
45
+ if (filename !== ":memory:" && !filename.startsWith("file:")) yield* Effect.try({
46
+ try: () => mkdirSync(dirname(filename), { recursive: true }),
47
+ catch: (cause) => new SqlError({ reason: new UnknownError({
48
+ cause,
49
+ message: `Brick: could not create the folder of the SQLite file ${filename}`
50
+ }) })
51
+ });
52
+ const context = yield* Layer.build(client.layer({
53
+ filename,
54
+ disableWAL: config.wal === false
55
+ }));
56
+ if (config.foreignKeys !== false) yield* Context.get(context, SqlClient).unsafe("PRAGMA foreign_keys = ON");
57
+ return yield* drizzle.makeWithDefaults({ relations: defineRelations(config.tables ?? {}) }).pipe(Effect.provide(context));
58
+ });
59
+ }
60
+ /**
61
+ * Open a Postgres database over drizzle's Effect driver, until the scope
62
+ * closes. Needs `@effect/sql-pg`, loaded here and nowhere else.
63
+ *
64
+ * @param config - The `url`, `tables`, and the connection's `ssl`, pool size (`max`, `min`, `idleTimeout`) and `prepare`.
65
+ * @returns The drizzle database, whose queries are Effects.
66
+ * @example
67
+ * const db = yield* createPostgresDatabase({ url: process.env.DATABASE_URL!, ssl: true, max: 10 });
68
+ */
69
+ function createPostgresDatabase(config) {
70
+ return Effect.gen(function* () {
71
+ const [client, drizzle] = yield* Effect.tryPromise({
72
+ try: () => Promise.all([import("@effect/sql-pg/PgClient"), import("drizzle-orm/effect-postgres")]),
73
+ catch: (cause) => driverError(cause, "@effect/sql-pg")
74
+ });
75
+ const context = yield* Layer.build(client.layer({
76
+ url: Redacted.make(config.url),
77
+ ...config.ssl !== void 0 && { ssl: config.ssl },
78
+ ...config.max !== void 0 && { maxConnections: config.max },
79
+ ...config.min !== void 0 && { minConnections: config.min },
80
+ ...config.idleTimeout !== void 0 && { idleTimeout: config.idleTimeout },
81
+ ...config.prepare !== void 0 && { prepare: config.prepare }
82
+ }));
83
+ return yield* drizzle.makeWithDefaults({ relations: defineRelations(config.tables ?? {}) }).pipe(Effect.provide(context));
84
+ });
85
+ }
86
+ let databases = 0;
87
+ function defineDatabase(config) {
88
+ const Database = Context.Service(`@brickkit/effect/Database/${++databases}`);
89
+ const { tables } = config;
90
+ const open = "sqlite" in config ? createSQLiteDatabase({
91
+ filename: config.sqlite,
92
+ tables,
93
+ foreignKeys: config.foreignKeys,
94
+ wal: config.wal
95
+ }) : createPostgresDatabase({
96
+ url: config.postgres,
97
+ tables,
98
+ ssl: config.ssl,
99
+ max: config.max,
100
+ min: config.min,
101
+ idleTimeout: config.idleTimeout,
102
+ prepare: config.prepare
103
+ });
104
+ const connection = "sqlite" in config ? {
105
+ engine: "sqlite",
106
+ filename: config.sqlite,
107
+ foreignKeys: config.foreignKeys,
108
+ wal: config.wal
109
+ } : {
110
+ engine: "postgres",
111
+ url: config.postgres,
112
+ ssl: config.ssl,
113
+ max: config.max,
114
+ min: config.min,
115
+ idleTimeout: config.idleTimeout,
116
+ prepare: config.prepare
117
+ };
118
+ return Object.defineProperty({
119
+ kind: "brick-database",
120
+ name: config.name,
121
+ tables,
122
+ engine: connection.engine,
123
+ Database,
124
+ layer: Layer.effect(Database)(open)
125
+ }, "connection", { value: connection });
126
+ }
127
+ // src/db-schema.ts
128
+ const warn = (message) => Effect.sync(() => console.warn(`[Brick DB] ${message}`));
129
+ const reason = (error) => error instanceof Error ? error.message : String(error);
130
+ /** Runs one raw statement on a drizzle database, whatever its engine. */
131
+ const run = (db, statement) => typeof db.execute === "function" ? db.execute(sql.raw(statement)) : db.run(sql.raw(statement));
132
+ /**
133
+ * Apply the migrations in a folder that have not run yet, in order, and record
134
+ * them in the database's `__drizzle_migrations` table. The folder is the one
135
+ * `drizzle-kit generate` writes for drizzle 1.0: a folder per migration, each
136
+ * holding a `migration.sql`. A folder with a `meta/_journal.json` was written by
137
+ * an older drizzle-kit and is refused: run `drizzle-kit up` on it first.
138
+ *
139
+ * @param database - A handle from `defineDatabase`.
140
+ * @param migrationsFolder - The folder of migrations.
141
+ * @example
142
+ * yield* migrateDatabase(database, "./drizzle/pages");
143
+ */
144
+ const migrateDatabase = (database, migrationsFolder) => Effect.gen(function* () {
145
+ const db = yield* database.Database;
146
+ const { migrate } = database.engine === "postgres" ? yield* Effect.promise(() => import("drizzle-orm/effect-postgres/migrator")) : yield* Effect.promise(() => import("drizzle-orm/effect-sqlite-bun/migrator"));
147
+ yield* Effect.flatten(Effect.try({
148
+ try: () => migrate(db, { migrationsFolder }),
149
+ catch: (cause) => cause
150
+ }));
151
+ });
152
+ const sqliteDialect = new SQLiteDialect();
153
+ /**
154
+ * Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition
155
+ * directly from a Drizzle table schema.
156
+ */
157
+ function generateSQLiteTableDdl(table) {
158
+ const tableName = getTableName(table);
159
+ const columns = getTableColumns(table);
160
+ const colDefs = [];
161
+ for (const [, col] of Object.entries(columns)) {
162
+ let def = `"${col.name}" ${col.getSQLType().toUpperCase()}`;
163
+ if (col.primary) def += " PRIMARY KEY";
164
+ if (col.notNull) def += " NOT NULL";
165
+ if (col.isUnique) def += " UNIQUE";
166
+ if (col.hasDefault) {
167
+ if (typeof col.default === "string") def += ` DEFAULT '${col.default.replace(/'/g, "''")}'`;
168
+ else if (typeof col.default === "boolean") def += ` DEFAULT ${col.default ? 1 : 0}`;
169
+ else if (typeof col.default === "number") def += ` DEFAULT ${col.default}`;
170
+ else if (is(col.default, SQL)) def += ` DEFAULT (${sqliteDialect.sqlToQuery(col.default).sql})`;
171
+ else if (col.default !== void 0) {
172
+ const stored = col.mapToDriverValue(col.default);
173
+ def += typeof stored === "number" || typeof stored === "bigint" ? ` DEFAULT ${stored}` : ` DEFAULT '${String(stored).replace(/'/g, "''")}'`;
174
+ }
175
+ }
176
+ colDefs.push(def);
177
+ }
178
+ return `CREATE TABLE IF NOT EXISTS "${tableName}" (\n ${colDefs.join(",\n ")}\n);`;
179
+ }
180
+ /** The database name of the column a table field is known by, or `undefined` when it has none. */
181
+ function columnNameOf(table, field) {
182
+ const columns = getTableColumns(table);
183
+ if (columns[field]) return columns[field].name ?? field;
184
+ for (const col of Object.values(columns)) if (col.name === field) return col.name;
185
+ }
186
+ /**
187
+ * Generates idempotent secondary index DDL for a Drizzle table.
188
+ * Covers owner scoping, sort columns, and exact-match filters.
189
+ * UNIQUE columns already carry an implicit index, so they are skipped here.
190
+ * FTS and trigram indexes are handled separately by the search layer.
191
+ */
192
+ function generateSQLiteIndexDdl(table, opts = {}) {
193
+ const tableName = getTableName(table);
194
+ const stmts = [];
195
+ const seen = /* @__PURE__ */ new Set();
196
+ const push = (name, cols) => {
197
+ const clean = cols.filter(Boolean);
198
+ if (clean.length === 0) return;
199
+ const key = `${name}(${clean.join(",")})`;
200
+ if (seen.has(key)) return;
201
+ seen.add(key);
202
+ const colList = clean.map((c) => `"${c}"`).join(", ");
203
+ stmts.push(`CREATE INDEX IF NOT EXISTS "${name}" ON "${tableName}" (${colList});`);
204
+ };
205
+ let ownerCol;
206
+ if (opts.ownerField) {
207
+ const oc = columnNameOf(table, opts.ownerField);
208
+ if (oc) {
209
+ ownerCol = oc;
210
+ push(`idx_${tableName}_${oc}`, [oc]);
211
+ }
212
+ }
213
+ const sortCols = [];
214
+ for (const f of opts.sortFields ?? ["updated_at", "created_at"]) {
215
+ const c = columnNameOf(table, f);
216
+ if (c) {
217
+ sortCols.push(c);
218
+ push(`idx_${tableName}_${c}`, [c]);
219
+ }
220
+ }
221
+ if (ownerCol && sortCols.length > 0) push(`idx_${tableName}_${ownerCol}_${sortCols[0]}`, [ownerCol, sortCols[0]]);
222
+ return stmts;
223
+ }
224
+ /**
225
+ * Ensures secondary indexes exist for a resource table.
226
+ * SQLite: B-tree indexes for owner scope + sort + composite hot path.
227
+ * Postgres: the same B-trees plus pg_trgm GIN indexes for substring search,
228
+ * created one after another (each GIN index needs the extension).
229
+ * Best-effort: a failed statement warns and the rest still run (a read-only
230
+ * replica, or no right to create pg_trgm); queries still work, only slower.
231
+ *
232
+ * @param db - A drizzle database, such as `ctx.db`.
233
+ * @param table - The resource's table.
234
+ * @param opts - The `ownerField`, `sortFields` and (Postgres) `searchFields` of the resource.
235
+ */
236
+ function ensureResourceIndexes(db, table, opts = {}) {
237
+ return Effect.gen(function* () {
238
+ if (!db) return;
239
+ const isPostgres = is(table, PgTable);
240
+ const stmts = generateSQLiteIndexDdl(table, opts);
241
+ if (isPostgres && opts.searchFields && opts.searchFields.length > 0) {
242
+ const tableName = getTableName(table);
243
+ for (const f of opts.searchFields) {
244
+ const c = columnNameOf(table, f);
245
+ if (c) stmts.push(`CREATE INDEX IF NOT EXISTS "idx_${tableName}_${c}_trgm" ON "${tableName}" USING gin ("${c}" gin_trgm_ops);`);
246
+ }
247
+ }
248
+ if (stmts.length === 0) return;
249
+ if (isPostgres) stmts.unshift(`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);
250
+ for (const stmt of stmts) yield* run(db, stmt).pipe(Effect.catchCause((cause) => warn(`Skipped an index: ${stmt} (${reason(cause)})`)));
251
+ });
252
+ }
253
+ const quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
254
+ /**
255
+ * Creates the FTS5 sidecar table + sync triggers + backfills existing rows.
256
+ * Idempotent; safe to call on every resource registration.
257
+ * No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.
258
+ * Best-effort: a failure warns, and search without FTS still works.
259
+ *
260
+ * @param db - A drizzle SQLite database, such as `ctx.db`.
261
+ * @param table - The resource's table.
262
+ * @param searchCols - The fields to search.
263
+ */
264
+ function ensureSQLiteFts(db, table, searchCols) {
265
+ return Effect.gen(function* () {
266
+ if (!db || searchCols.length === 0 || !is(table, SQLiteTable)) return;
267
+ const tableName = getTableName(table);
268
+ const columns = getTableColumns(table);
269
+ const dbCols = searchCols.map((field) => columnNameOf(table, field)).filter((c) => !!c);
270
+ if (dbCols.length === 0) return;
271
+ const idCol = columnNameOf(table, "id") ?? Object.values(columns).find((c) => c.primary)?.name ?? "id";
272
+ const fts = `${tableName}_fts`;
273
+ const ftsCols = [`"id" UNINDEXED`, ...dbCols.map(quoteIdent)].join(", ");
274
+ const colList = dbCols.map(quoteIdent).join(", ");
275
+ const newVals = dbCols.map((c) => `new.${quoteIdent(c)}`).join(", ");
276
+ const insert = `INSERT INTO ${quoteIdent(fts)}("id", ${colList}) VALUES (new.${quoteIdent(idCol)}, ${newVals});`;
277
+ const removeOld = `DELETE FROM ${quoteIdent(fts)} WHERE "id" = old.${quoteIdent(idCol)};`;
278
+ yield* Effect.forEach([
279
+ `CREATE VIRTUAL TABLE IF NOT EXISTS ${quoteIdent(fts)} USING fts5(${ftsCols}, tokenize='porter');`,
280
+ `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ai`)} AFTER INSERT ON ${quoteIdent(tableName)} BEGIN ${insert} END;`,
281
+ `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_ad`)} AFTER DELETE ON ${quoteIdent(tableName)} BEGIN ${removeOld} END;`,
282
+ `CREATE TRIGGER IF NOT EXISTS ${quoteIdent(`${fts}_au`)} AFTER UPDATE ON ${quoteIdent(tableName)} BEGIN ${removeOld} ${insert} END;`,
283
+ `INSERT INTO ${quoteIdent(fts)}("id", ${colList}) SELECT ${quoteIdent(idCol)}, ${colList} FROM ${quoteIdent(tableName)} WHERE ${quoteIdent(idCol)} NOT IN (SELECT "id" FROM ${quoteIdent(fts)});`
284
+ ], (statement) => run(db, statement), { discard: true }).pipe(Effect.catchCause((cause) => warn(`Skipped full-text search for ${tableName}: ${reason(cause)}`)));
285
+ });
286
+ }
287
+ /**
288
+ * Builds an FTS5 MATCH condition for a resource search term.
289
+ * Returns null when the term has no usable tokens; the caller falls back to LIKE.
290
+ */
291
+ function buildFtsMatchQuery(search) {
292
+ const escaped = search.split(/\s+/).map((s) => s.trim()).filter(Boolean).slice(0, 10).map((term) => term.replace(/"/g, "").trim()).filter(Boolean).map((clean) => `"${clean}"*`);
293
+ return escaped.length === 0 ? null : escaped.join(" AND ");
294
+ }
295
+ const quote = (name) => `"${name.replace(/"/g, "\"\"")}"`;
296
+ const qualified = (schema, name) => schema && schema !== "public" ? `${quote(schema)}.${quote(name)}` : quote(name);
297
+ const literal = (value) => `'${value.replace(/'/g, "''")}'`;
298
+ const dialect = new PgDialect();
299
+ /** An SQL fragment as text, its parameters written in. */
300
+ function render(fragment) {
301
+ const { sql: text, params } = dialect.sqlToQuery(fragment);
302
+ return text.replace(/\$(\d+)/g, (_, n) => {
303
+ const value = params[Number(n) - 1];
304
+ return typeof value === "number" || typeof value === "boolean" ? String(value) : literal(String(value));
305
+ });
306
+ }
307
+ /** The SQL type of a Postgres column: enums by their qualified name, arrays with their brackets. */
308
+ function pgType(col) {
309
+ return (isPgEnum(col.enum) ? qualified(col.enum.schema, col.enum.enumName) : col.getSQLType()) + "[]".repeat(col.dimensions ?? 0);
310
+ }
311
+ /** A column's default as SQL, or `undefined` when it has none to write (a `$defaultFn` runs in the app). */
312
+ function pgDefault(col) {
313
+ const value = col.default;
314
+ if (value === void 0) return void 0;
315
+ if (is(value, SQL)) return render(value);
316
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
317
+ if (typeof value === "bigint") return value.toString();
318
+ if (typeof value === "string") return literal(value);
319
+ if (value instanceof Date) return literal(value.toISOString());
320
+ if (Array.isArray(value) && col.dimensions) return value.length === 0 ? `'{}'` : `ARRAY[${value.map((item) => typeof item === "string" ? literal(item) : String(item)).join(", ")}]::${pgType(col)}`;
321
+ return `${literal(JSON.stringify(value))}::${col.getSQLType()}`;
322
+ }
323
+ function pgColumnDdl(col) {
324
+ let def = `${quote(col.name)} ${pgType(col)}`;
325
+ if (col.generated) {
326
+ const as = typeof col.generated.as === "function" ? col.generated.as() : col.generated.as;
327
+ def += ` GENERATED ALWAYS AS (${is(as, SQL) ? render(as) : String(as)}) STORED`;
328
+ } else if (col.generatedIdentity) def += ` GENERATED ${col.generatedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY`;
329
+ else {
330
+ const fallback = pgDefault(col);
331
+ if (fallback !== void 0) def += ` DEFAULT ${fallback}`;
332
+ }
333
+ if (col.notNull) def += " NOT NULL";
334
+ if (col.isUnique) def += ` UNIQUE${col.uniqueType === "not distinct" ? " NULLS NOT DISTINCT" : ""}`;
335
+ return def;
336
+ }
337
+ /** The statements that make a Postgres table: its enums and schema come before, its foreign keys and indexes after. */
338
+ function pgTableDdl(table) {
339
+ const config = getTableConfig(table);
340
+ const columns = config.columns;
341
+ const target = qualified(config.schema, config.name);
342
+ const parts = columns.map(pgColumnDdl);
343
+ const primary = columns.filter((col) => col.primary);
344
+ if (primary.length) parts.push(`PRIMARY KEY (${primary.map((c) => quote(c.name)).join(", ")})`);
345
+ for (const key of config.primaryKeys) parts.push(`CONSTRAINT ${quote(key.getName())} PRIMARY KEY (${key.columns.map((c) => quote(c.name)).join(", ")})`);
346
+ for (const unique of config.uniqueConstraints) parts.push(`CONSTRAINT ${quote(unique.getName() ?? "")} UNIQUE${unique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""} (${unique.columns.map((c) => quote(c.name)).join(", ")})`);
347
+ return {
348
+ create: `CREATE TABLE ${target} (\n ${parts.join(",\n ")}\n)`,
349
+ foreignKeys: config.foreignKeys.map((key) => {
350
+ const { columns: from, foreignColumns: to, foreignTable } = key.reference();
351
+ const foreign = getTableConfig(foreignTable);
352
+ const action = (verb, value) => value && value !== "no action" ? ` ON ${verb} ${value.toUpperCase()}` : "";
353
+ return `ALTER TABLE ${target} ADD CONSTRAINT ${quote(key.getName())} FOREIGN KEY (${from.map((c) => quote(c.name)).join(", ")}) REFERENCES ${qualified(foreign.schema, foreign.name)} (${to.map((c) => quote(c.name)).join(", ")})${action("DELETE", key.onDelete)}${action("UPDATE", key.onUpdate)}`;
354
+ }),
355
+ indexes: config.indexes.map(({ config: index }) => {
356
+ const on = index.columns.map((col) => is(col, SQL) ? `(${render(col)})` : quote(col.name)).join(", ");
357
+ return `CREATE ${index.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${quote(index.name ?? "")} ON ${index.only ? "ONLY " : ""}${target} USING ${index.method ?? "btree"} (${on})${index.where ? ` WHERE ${render(index.where)}` : ""}`;
358
+ })
359
+ };
360
+ }
361
+ const createMissingPostgresTables = (db, tables) => Effect.gen(function* () {
362
+ const names = (result) => new Set(result.rows.map((row) => row.name));
363
+ const present = names(yield* db.execute(sql`select table_schema || '.' || table_name as name from information_schema.tables`));
364
+ const missing = tables.filter((table) => {
365
+ const { schema = "public", name } = getTableConfig(table);
366
+ return !present.has(`${schema}.${name}`);
367
+ });
368
+ if (missing.length === 0) return;
369
+ const enums = /* @__PURE__ */ new Map();
370
+ const schemas = /* @__PURE__ */ new Set();
371
+ for (const table of missing) {
372
+ const { schema, columns } = getTableConfig(table);
373
+ if (schema && schema !== "public") schemas.add(schema);
374
+ for (const col of columns) if (isPgEnum(col.enum)) enums.set(qualified(col.enum.schema, col.enum.enumName), col.enum);
375
+ }
376
+ const existing = names(yield* db.execute(sql`select n.nspname || '.' || t.typname as name from pg_type t join pg_namespace n on n.oid = t.typnamespace where t.typtype = 'e'`));
377
+ const statements = [...schemas].map((schema) => `CREATE SCHEMA IF NOT EXISTS ${quote(schema)}`);
378
+ for (const [name, pgEnum] of enums) if (!existing.has(`${pgEnum.schema ?? "public"}.${pgEnum.enumName}`)) statements.push(`CREATE TYPE ${name} AS ENUM (${pgEnum.enumValues.map(literal).join(", ")})`);
379
+ const made = missing.map(pgTableDdl);
380
+ statements.push(...made.map((table) => table.create), ...made.flatMap((table) => table.foreignKeys), ...made.flatMap((table) => table.indexes));
381
+ yield* db.transaction((tx) => Effect.forEach(statements, (statement) => run(tx, statement), { discard: true }));
382
+ });
383
+ function syncSchema(source, db) {
384
+ return Effect.gen(function* () {
385
+ const handle = isDatabaseHandle(source) ? source : void 0;
386
+ const target = handle ? yield* handle.Database : db;
387
+ const tables = (Array.isArray(source) ? source : Object.values(handle ? handle.tables : source)).filter((value) => is(value, Table));
388
+ if (!target || tables.length === 0) return;
389
+ if (is(tables[0], PgTable)) {
390
+ yield* createMissingPostgresTables(target, tables);
391
+ return;
392
+ }
393
+ for (const table of tables) yield* run(target, generateSQLiteTableDdl(table)).pipe(Effect.catchCause((cause) => warn(`Failed to create table: ${reason(cause)}`)));
394
+ });
395
+ }
396
+ // src/standalone.ts
397
+ const BOUND = Symbol.for("brickkit.effect.action.service");
398
+ /**
399
+ * An action no service owns yet: it runs with a bare `ctx` until
400
+ * `service.action(action)` (or `service.tool`) gives it the service's database,
401
+ * context, identity and deps. Its stages are built when it is first called.
402
+ */
403
+ function standaloneAction(config) {
404
+ const bound = {};
405
+ const host = {
406
+ get name() {
407
+ return bound.service?.name ?? "";
408
+ },
409
+ get hasIdentity() {
410
+ return bound.service?.hasIdentity ?? false;
411
+ },
412
+ get storage() {
413
+ return bound.service?.storage;
414
+ },
415
+ get database() {
416
+ return bound.service?.database;
417
+ },
418
+ resolveContext: (call) => bound.service ? bound.service.resolveContext(call) : Effect.succeed({
419
+ ...baseContext(call),
420
+ user: call?.user ?? null
421
+ })
422
+ };
423
+ const action = createAction(host, config, true);
424
+ Object.defineProperties(action, {
425
+ serviceName: {
426
+ get: () => host.name,
427
+ enumerable: true
428
+ },
429
+ [BOUND]: { value: bound }
430
+ });
431
+ return action;
432
+ }
433
+ /** Whether `standaloneAction` made it, so a service has to take it. */
434
+ const isStandalone = (action) => BOUND in action;
435
+ /**
436
+ * Gives a standalone action the service it runs under.
437
+ *
438
+ * @throws When another service has it, or the service cannot run it (a rate limit per `"actor"` without an `identity`).
439
+ */
440
+ function bindAction(action, service, kind = "Action") {
441
+ const bound = action[BOUND];
442
+ if (bound.service && bound.service !== service) throw new Error(`${kind} '${action.name}' is already registered on service '${bound.service.name}'`);
443
+ stagesOf(action.config, service);
444
+ bound.service = service;
445
+ action[RESET_STAGES]();
446
+ }
447
+ function defineAction(config) {
448
+ return standaloneAction(config);
449
+ }
450
+ // src/webhook.ts
451
+ /** Whether an action was declared with `service.webhook`. */
452
+ function isWebhook(action) {
453
+ return action.webhook !== void 0;
454
+ }
455
+ const DEFAULT_MAX_BODY_BYTES = 1048576;
456
+ const IN_FLIGHT_CLAIM_MS = 3e5;
457
+ const HANDLED = "handled";
458
+ const eventIdFrom = (value) => Number.isSafeInteger(value) ? String(value) : typeof value === "string" && value ? value : void 0;
459
+ const refuse = (code, message, status) => new BrickError({
460
+ code,
461
+ message,
462
+ status
463
+ });
464
+ function fieldsOf(params) {
465
+ const grouped = /* @__PURE__ */ new Map();
466
+ for (const [name, value] of params) grouped.set(name, [...grouped.get(name) ?? [], value]);
467
+ return Object.fromEntries([...grouped].map(([name, values]) => [name, values.length > 1 ? values : values[0]]));
468
+ }
469
+ /** The body, or `undefined` once it passes `limit`. */
470
+ async function readBody(request, limit) {
471
+ if (Number(request.headers.get("content-length")) > limit) return void 0;
472
+ const chunks = [];
473
+ let size = 0;
474
+ if (request.body) {
475
+ const reader = request.body.getReader();
476
+ for (;;) {
477
+ const { done, value } = await reader.read();
478
+ if (done) break;
479
+ size += value.byteLength;
480
+ if (size > limit) {
481
+ reader.cancel().catch(() => {});
482
+ return;
483
+ }
484
+ chunks.push(value);
485
+ }
486
+ }
487
+ return new Uint8Array(Buffer.concat(chunks));
488
+ }
489
+ /** The payload of a delivery before its schema checks it, and how it arrived. */
490
+ function payloadOf(name, request, rawBody) {
491
+ const text = new TextDecoder().decode(rawBody);
492
+ const form = request.method === "GET" ? new URL(request.url).searchParams : /^application\/x-www-form-urlencoded/i.test(request.headers.get("content-type") ?? "") ? new URLSearchParams(text) : void 0;
493
+ if (form) return Effect.succeed({
494
+ input: fieldsOf(form),
495
+ wire: "query"
496
+ });
497
+ if (!text) return Effect.succeed({
498
+ input: void 0,
499
+ wire: "json"
500
+ });
501
+ try {
502
+ return Effect.succeed({
503
+ input: JSON.parse(text),
504
+ wire: "json"
505
+ });
506
+ } catch {
507
+ return Effect.fail(invalid(name, "input", [{
508
+ path: "",
509
+ message: "Body is not valid JSON"
510
+ }]));
511
+ }
512
+ }
513
+ /**
514
+ * Throws on a declaration a webhook cannot run with.
515
+ */
516
+ function check(service, config, hasReplay) {
517
+ const where = `Service "${service}": webhook '${config?.name}'`;
518
+ if (typeof config?.verify !== "function") throw new Error(`${where} needs verify: a verifier such as hmacSignature({ secret, header }), standardWebhooks({ secret }) or twilioSignature({ authToken, url }), or your own (request) => Effect<boolean>. A webhook cannot run without one.`);
519
+ if (!Schema.isSchema(config.input)) throw new Error(`${where} needs input: the schema of the payload, such as Schema.Struct({ ... }).`);
520
+ if (config.method !== void 0 && !["POST", "GET"].includes(config.method)) throw new Error(`${where}: method must be "POST" or "GET".`);
521
+ if (config.method === "GET" && config.verify.signsBody) throw new Error(`${where}: method "GET" has no body, and this verifier signs the body, so it would accept one signature for every query. Use twilioSignature (it signs the URL) or a verifier of your own, or method "POST".`);
522
+ for (const option of ["authorize", "output"]) if (config[option] !== void 0) throw new Error(`${where}: ${option} is not an option of a webhook, and would be ignored. verify is the check.`);
523
+ if (!Number.isSafeInteger(config.maxBodyBytes ?? 1) || (config.maxBodyBytes ?? 1) < 1) throw new Error(`${where}: maxBodyBytes must be a positive integer.`);
524
+ const ttlMs = config.replay?.ttlMs;
525
+ if (ttlMs !== void 0 && (!Number.isSafeInteger(ttlMs) || ttlMs < 1)) throw new Error(`${where}: replay.ttlMs must be a positive integer.`);
526
+ if (hasReplay && !config.eventId && !config.verify.suppliesEventId) throw new Error(`${where} has no event id to tell deliveries apart by, so a delivery sent twice would run twice. Add eventId: ({ input }) => Effect.succeed(input.id), reading an id from a field of the signed payload (an id from a header the signature does not cover only removes accidental duplicates: anyone who captured a delivery can resend it with another id), use a verifier that supplies one (standardWebhooks), or set replay: false to run every delivery.`);
527
+ }
528
+ /**
529
+ * Declare a webhook on a service: a route a provider calls. The delivery's raw
530
+ * body is verified before anything else runs, then parsed and checked against
531
+ * `input`, then claimed by its event id so a repeat is not run twice, then the
532
+ * service's context, rate limits and `execute` run. Answers 401 for a refused
533
+ * delivery, 413 over `maxBodyBytes`, 400 for a bad payload or no event id,
534
+ * 409 while another delivery of the event is being handled, and 503 when the
535
+ * storage cannot say.
536
+ */
537
+ function createWebhook(host, config) {
538
+ const hasReplay = config.replay !== false;
539
+ check(host.name, config, hasReplay);
540
+ const { verify, eventId: eventIdOf, replay, maxBodyBytes = DEFAULT_MAX_BODY_BYTES, ...declared } = config;
541
+ const ttlMs = replay === false ? void 0 : replay?.ttlMs ?? 6048e5;
542
+ const actionConfig = {
543
+ ...declared,
544
+ method: config.method ?? "POST"
545
+ };
546
+ const base = createAction(host, actionConfig);
547
+ const stages = stagesOf(actionConfig, host);
548
+ const inputAt = stages.findIndex((stage) => stage.name === "input");
549
+ const beforeClaim = stages.slice(0, inputAt + 1);
550
+ const rest = stages.slice(inputAt + 1);
551
+ const error = errorHelpers(config.errors);
552
+ const { name } = config;
553
+ const verified = (request, call) => verify(request).pipe(Effect.catchCause((cause) => Effect.sync(() => {
554
+ if (!Cause.hasInterruptsOnly(cause)) (call.logger ?? defaultLogger).warn("A webhook verifier threw, so its delivery was refused", {
555
+ service: host.name,
556
+ webhook: name,
557
+ error: Cause.squash(cause)?.constructor?.name ?? "unknown",
558
+ requestId: call.requestId
559
+ });
560
+ return false;
561
+ })));
562
+ const claim = (request, given, callContext, delivery) => ({
563
+ name: "replay",
564
+ run: (call, next) => Effect.gen(function* () {
565
+ delivery.outcome = "failed";
566
+ const eventId = given ?? eventIdFrom(yield* eventIdOf?.({
567
+ input: call.input,
568
+ headers: request.headers,
569
+ url: request.url,
570
+ method: request.method
571
+ }) ?? Effect.succeed(void 0));
572
+ delivery.eventId = eventId;
573
+ if (ttlMs === void 0) return yield* next({
574
+ ...call,
575
+ eventId
576
+ });
577
+ const storage = yield* requireStorage(host, `Webhook '${name}' of service "${host.name}", which remembers the events it has handled,`);
578
+ if (!eventId) {
579
+ delivery.outcome = "no_event_id";
580
+ return yield* refuse("BAD_REQUEST", "The delivery has no event id", 400);
581
+ }
582
+ const key = storageKey("webhook", [
583
+ host.name,
584
+ name,
585
+ eventId
586
+ ]);
587
+ const mine = `pending:${crypto.randomUUID()}`;
588
+ const release = storage.compareAndDelete(key, mine).pipe(Effect.ignore);
589
+ const claimed = yield* storage.putIfAbsent(key, mine, IN_FLIGHT_CLAIM_MS).pipe(Effect.catchTag("StorageUnavailableError", (cause) => Effect.andThen(release, Effect.suspend(() => {
590
+ delivery.outcome = "unavailable";
591
+ return Effect.fail(new BrickError({
592
+ code: "SERVICE_UNAVAILABLE",
593
+ message: "Webhook storage is unavailable; retry later",
594
+ status: 503,
595
+ details: cause.message
596
+ }));
597
+ }))));
598
+ if (!claimed.stored) {
599
+ if (claimed.value === HANDLED) {
600
+ delivery.outcome = "duplicate";
601
+ return { duplicate: true };
602
+ }
603
+ delivery.outcome = "in_flight";
604
+ return yield* refuse("CONFLICT", "Another delivery of this event is being handled; retry later", 409);
605
+ }
606
+ const renew = Effect.forever(Effect.sleep(IN_FLIGHT_CLAIM_MS / 3).pipe(Effect.andThen(storage.put(key, mine, IN_FLIGHT_CLAIM_MS)), Effect.ignore));
607
+ const result = yield* next({
608
+ ...call,
609
+ eventId
610
+ }).pipe(Effect.raceFirst(renew), Effect.onError(() => release));
611
+ if (result instanceof Response && result.status >= 400) yield* release;
612
+ else yield* storage.put(key, HANDLED, ttlMs).pipe(Effect.catchCause((cause) => Effect.sync(() => (callContext.logger ?? defaultLogger).warn("Webhook handled, but its id was not recorded; a retry may run it again", { requestId: callContext.requestId }, Cause.pretty(cause)))));
613
+ return result;
614
+ })
615
+ });
616
+ const deliver = (request, callContext) => {
617
+ const delivery = {
618
+ outcome: "failed",
619
+ eventId: void 0
620
+ };
621
+ return Effect.gen(function* () {
622
+ const rawBody = yield* Effect.promise(() => readBody(request, maxBodyBytes));
623
+ if (!rawBody) {
624
+ delivery.outcome = "too_large";
625
+ return yield* refuse("PAYLOAD_TOO_LARGE", `Request body exceeds ${maxBodyBytes} bytes`, 413);
626
+ }
627
+ const verdict = yield* verified({
628
+ rawBody,
629
+ headers: request.headers,
630
+ url: request.url,
631
+ method: request.method
632
+ }, callContext);
633
+ const given = eventIdFrom(typeof verdict === "object" ? verdict.eventId : void 0);
634
+ if (verdict !== true && !given) {
635
+ delivery.outcome = "refused";
636
+ return yield* refuse("UNAUTHORIZED", "Webhook verification failed", 401);
637
+ }
638
+ delivery.eventId = given;
639
+ delivery.outcome = "invalid";
640
+ const { input, wire } = yield* payloadOf(name, request, rawBody);
641
+ const result = yield* runStages([
642
+ ...beforeClaim,
643
+ claim(request, given, callContext, delivery),
644
+ {
645
+ name: "context",
646
+ run: (call, next) => Effect.flatMap(host.resolveContext(callContext), (ctx) => next({
647
+ ...call,
648
+ ctx
649
+ }))
650
+ },
651
+ ...rest
652
+ ], {
653
+ input: input === void 0 && isObjectSchema(config.input) ? {} : input,
654
+ ctx: void 0,
655
+ error,
656
+ wire
657
+ });
658
+ if (delivery.outcome === "failed") delivery.outcome = result instanceof Response && result.status >= 400 ? "failed" : "processed";
659
+ return result === void 0 ? { ok: true } : result;
660
+ }).pipe(normalizeFailures({
661
+ logger: callContext.logger ?? defaultLogger,
662
+ requestId: callContext.requestId
663
+ }), Effect.ensuring(Effect.suspend(() => recordWebhook(name, delivery.eventId, delivery.outcome))));
664
+ };
665
+ return {
666
+ ...base,
667
+ webhook: {
668
+ maxBodyBytes,
669
+ replay: ttlMs === void 0 ? false : { ttlMs }
670
+ },
671
+ deliver
672
+ };
673
+ }
674
+ // src/rpc.ts
675
+ function useService(service, options = {}) {
676
+ return serviceRef(service.name, options, []);
677
+ }
678
+ function serviceRef(serviceName, options, path) {
679
+ return new Proxy(function() {}, {
680
+ get(_, key) {
681
+ if (typeof key !== "string" || key === "then") return void 0;
682
+ return serviceRef(serviceName, options, [...path, key]);
683
+ },
684
+ apply(_, __, [payload, callCtx]) {
685
+ const name = path.join(".");
686
+ return Effect.suspend(() => {
687
+ const service = getGlobalRegistry().get(serviceName);
688
+ if (!service) return Effect.die(/* @__PURE__ */ new Error(`[Brick RPC] Service '${serviceName}' is not registered in the local runtime.`));
689
+ const clientPath = [serviceName, ...path].join(".");
690
+ const action = service.getAction(name) ?? service.listActions().find((item) => (getPluginActionRoute(item) || void 0)?.clientPath?.join(".") === clientPath);
691
+ return action ? action.execute({
692
+ input: payload,
693
+ ctx: createRpcEnvelope(options.from, options.context, callCtx)
694
+ }) : Effect.die(/* @__PURE__ */ new Error(`[Brick RPC] Action '${name}' does not exist on service '${serviceName}'.`));
695
+ });
696
+ }
697
+ });
698
+ }
699
+ /** What of a call context crosses to the target: who the user is, the trace ids and the client. Never the caller's `db`, `deps` or request. */
700
+ const envelopeOf = (context) => {
701
+ if (!context) return {};
702
+ const envelope = {};
703
+ for (const key of [
704
+ "caller",
705
+ "user",
706
+ "traceId",
707
+ "requestId",
708
+ "dashboard"
709
+ ]) if (context[key] !== void 0) envelope[key] = context[key];
710
+ carryClientRequest(envelope, context);
711
+ return envelope;
712
+ };
713
+ /**
714
+ * The trusted context of a call through `useService`. When `from` is given it
715
+ * always sets `caller`; any `caller` in `defaultContext` or `callContext` is
716
+ * ignored. Without `from`, a `caller` passed in still goes through; otherwise
717
+ * `caller` stays unset (never the target service).
718
+ */
719
+ function createRpcEnvelope(from, defaultContext, callContext) {
720
+ const envelope = {
721
+ ...envelopeOf(defaultContext),
722
+ ...envelopeOf(callContext)
723
+ };
724
+ if (from !== void 0) envelope.caller = from;
725
+ return envelope;
726
+ }
727
+ // src/webhook-verifiers.ts
728
+ function valuesOf(secret) {
729
+ const values = (Array.isArray(secret) ? secret : [secret]).map((item) => typeof item === "string" ? item : Redacted.isRedacted(item) ? Redacted.value(item) : item.require());
730
+ if (!values.length || values.some((value) => !value.trim())) throw new Error("A webhook secret is empty");
731
+ return values;
732
+ }
733
+ function same(a, b) {
734
+ const x = Buffer.from(a);
735
+ const y = Buffer.from(b);
736
+ return x.length === y.length && timingSafeEqual(x, y);
737
+ }
738
+ const hasBody = (method) => method === "POST";
739
+ function matchesAnyWithoutShortCircuit(given, candidates) {
740
+ let found = false;
741
+ for (const candidate of candidates) found = same(given, candidate) || found;
742
+ return found;
743
+ }
744
+ /**
745
+ * Verifies an HMAC of the raw body, compared in constant time with a header.
746
+ * It signs the body alone and checks no timestamp. Give the webhook an
747
+ * `eventId`: it stops a replayed capture only when it comes from the signed body.
748
+ *
749
+ * @example
750
+ * verify: hmacSignature({ secret: hookSecret, header: "x-hub-signature-256", prefix: "sha256=" })
751
+ */
752
+ function hmacSignature(options) {
753
+ const { header, prefix = "", algorithm = "sha256", encoding = "hex" } = options;
754
+ const verify = ({ rawBody, headers, method }) => Effect.sync(() => {
755
+ if (!hasBody(method)) return false;
756
+ const value = headers.get(header);
757
+ if (value === null || !value.startsWith(prefix)) return false;
758
+ const given = value.slice(prefix.length);
759
+ const expected = valuesOf(options.secret).map((secret) => createHmac(algorithm, secret).update(rawBody).digest(encoding));
760
+ return matchesAnyWithoutShortCircuit(encoding === "hex" ? given.toLowerCase() : given, expected);
761
+ });
762
+ return Object.assign(verify, { signsBody: true });
763
+ }
764
+ function keyOf(secret) {
765
+ const encoded = secret.trim().replace(/^whsec_/, "");
766
+ const key = /^[A-Za-z0-9+/]+={0,2}$/.test(encoded) ? Buffer.from(encoded, "base64") : Buffer.alloc(0);
767
+ if (!key.length) throw new Error("A Standard Webhooks secret is not base64, or is empty");
768
+ return key;
769
+ }
770
+ /**
771
+ * Verifies the Standard Webhooks scheme (standardwebhooks.com): a base64
772
+ * HMAC-SHA256 of `id.timestamp.body` in `webhook-signature`, as `v1,<signature>`
773
+ * entries separated by spaces, with the timestamp in `webhook-timestamp`.
774
+ * Svix's `svix-id`, `svix-timestamp` and `svix-signature` are read the same way.
775
+ * The id header is the event id, so the webhook needs no `eventId`.
776
+ *
777
+ * @example
778
+ * verify: standardWebhooks({ secret: billingSecret })
779
+ */
780
+ function standardWebhooks(options) {
781
+ const toleranceMs = options.toleranceMs ?? 3e5;
782
+ const verify = ({ rawBody, headers, method }) => Effect.sync(() => {
783
+ if (!hasBody(method)) return false;
784
+ const header = (name) => headers.get(`webhook-${name}`) ?? headers.get(`svix-${name}`);
785
+ const id = header("id");
786
+ const timestamp = header("timestamp");
787
+ const signatures = header("signature");
788
+ if (!id || !timestamp || !signatures || !/^\d{1,15}$/.test(timestamp)) return false;
789
+ if (Math.abs(Date.now() - Number(timestamp) * 1e3) > toleranceMs) return false;
790
+ const signed = Buffer.concat([Buffer.from(`${id}.${timestamp}.`), rawBody]);
791
+ const expected = valuesOf(options.secret).map((secret) => createHmac("sha256", keyOf(secret)).update(signed).digest("base64"));
792
+ let ok = false;
793
+ for (const entry of signatures.split(" ")) {
794
+ const [version, signature] = entry.split(",");
795
+ if (version === "v1" && signature) ok = matchesAnyWithoutShortCircuit(signature, expected) || ok;
796
+ }
797
+ return ok ? { eventId: id } : false;
798
+ });
799
+ return Object.assign(verify, {
800
+ suppliesEventId: true,
801
+ signsBody: true
802
+ });
803
+ }
804
+ /**
805
+ * Verifies Twilio's `X-Twilio-Signature`: a base64 HMAC-SHA1, keyed with the
806
+ * auth token, of the URL followed by the form parameters sorted by name, each
807
+ * as name and value. For a JSON body, Twilio signs the URL alone and puts the
808
+ * body's SHA-256 (hex) in its `bodySHA256` query parameter, which is checked
809
+ * against the body. For a GET, it signs the URL alone, and a request whose
810
+ * query is not the signed URL's is refused. It supplies no event id: give the
811
+ * webhook an `eventId`.
812
+ *
813
+ * @example
814
+ * verify: twilioSignature({ authToken, url: "https://api.example.com/api/telephony/voice-status" })
815
+ */
816
+ function twilioSignature(options) {
817
+ return (request) => Effect.gen(function* () {
818
+ const given = request.headers.get("x-twilio-signature");
819
+ if (!given) return false;
820
+ const url = typeof options.url === "string" ? options.url : yield* options.url(request);
821
+ return yield* Effect.sync(() => {
822
+ if (request.method !== "POST" && new URL(url).search !== new URL(request.url).search) return false;
823
+ let signed = url;
824
+ const claimed = new URL(url).searchParams.get("bodySHA256");
825
+ if (request.headers.get("content-type")?.includes("json") || request.method === "POST" && claimed !== null) {
826
+ const actual = createHash("sha256").update(request.rawBody).digest("hex");
827
+ if (!claimed || !same(claimed.toLowerCase(), actual)) return false;
828
+ } else if (request.method === "POST") {
829
+ const form = new URLSearchParams(Buffer.from(request.rawBody).toString());
830
+ for (const name of [...new Set(form.keys())].sort()) for (const value of [...new Set(form.getAll(name))].sort()) signed += name + value;
831
+ }
832
+ return matchesAnyWithoutShortCircuit(given, valuesOf(options.authToken).map((token) => createHmac("sha1", token).update(signed).digest("base64")));
833
+ });
834
+ });
835
+ }
836
+ // src/tool.ts
837
+ function defineTool(config) {
838
+ if (config.input && !isObjectSchema(config.input)) throw new Error(`Tool '${config.name}' input must be an object schema`);
839
+ if (config.input && fileFields(config.input).length) throw new Error(`Tool '${config.name}' input has file fields; MCP carries JSON only, so take uploads in an action`);
840
+ const tool = standaloneAction(config);
841
+ Object.defineProperty(tool, "kind", { value: "tool" });
842
+ return tool;
843
+ }
844
+ /**
845
+ * Whether a value was made with `defineTool`, as opposed to `service.action`.
846
+ *
847
+ * @returns `true` for a tool, narrowing its type.
848
+ */
849
+ function isTool(value) {
850
+ return typeof value === "object" && value !== null && value.kind === "tool";
851
+ }
852
+ // src/service.ts
853
+ /**
854
+ * Declare a service. Its name is its segment of every action route
855
+ * (`/api/<name>/<action>`).
856
+ *
857
+ * @example
858
+ * const pages = defineService("pages", {
859
+ * database,
860
+ * identity: ({ request }) => readUser(request),
861
+ * });
862
+ * export const getPage = pages.action({
863
+ * name: "get",
864
+ * method: "GET",
865
+ * input: Schema.Struct({ id: Schema.String }),
866
+ * output: Page,
867
+ * execute: ({ input, ctx, error }) =>
868
+ * Effect.gen(function* () {
869
+ * const [page] = yield* ctx.db.select().from(tables.pages).where(eq(tables.pages.id, input.id));
870
+ * return page ?? (yield* error.NOT_FOUND());
871
+ * }),
872
+ * });
873
+ */
874
+ function defineService(name, options = {}) {
875
+ const actions = /* @__PURE__ */ new Map();
876
+ const sockets = /* @__PURE__ */ new Map();
877
+ const tools = /* @__PURE__ */ new Map();
878
+ const resources = /* @__PURE__ */ new Map();
879
+ const resolved = /* @__PURE__ */ new WeakSet();
880
+ const { database, context, identity } = options;
881
+ const deps = ownDeps(name, options.deps);
882
+ const touch = () => getGlobalRegistry().touch();
883
+ let events = defineEvents(name, options.events ?? {});
884
+ const auditTable = auditTableOf(database);
885
+ if (auditTable && !identity) throw new Error(`Service "${name}": its database holds an audit table, but the service declares no identity, so the log would not say who. Add identity: ({ request }) => Effect.succeed(user && { id: user.id }) to defineService("${name}", { ... }).`);
886
+ const resolveContext = (call) => call && resolved.has(call) ? Effect.succeed(call) : Effect.gen(function* () {
887
+ const db = database && (yield* database.Database);
888
+ const own = withOverride(deps, depsOverride(call));
889
+ const ctx = {
890
+ ...baseContext(call),
891
+ ...database && { db },
892
+ deps: own,
893
+ user: call?.user ?? null
894
+ };
895
+ carryClientRequest(ctx, call);
896
+ if (context) Object.assign(ctx, yield* context(ctx));
897
+ if (identity) ctx.user = (yield* identity(ctx)) ?? null;
898
+ ctx.deps = scopeFiles(own, ctx, name);
899
+ resolved.add(ctx);
900
+ if (auditTable) bindAuditTarget(ctx, name, auditTable);
901
+ return ctx;
902
+ });
903
+ const sites = /* @__PURE__ */ new Map();
904
+ const place = (action, site) => {
905
+ const previous = actions.get(action.name);
906
+ if (previous === action) return;
907
+ if (previous && isWebhook(previous) !== isWebhook(action)) throw new DuplicateNameError(`Brick: duplicate action "${action.name}" in service "${name}": it is defined both as a webhook and as an action. Give one of them another name: an action of the same name would answer in place of the webhook, without its check.`);
908
+ claimName(sites, `action "${action.name}" in service "${name}"`, action.name, site);
909
+ };
910
+ const register = (config, create) => {
911
+ const site = definitionSite();
912
+ const action = create(service, config);
913
+ place(action, site);
914
+ actions.set(config.name, action);
915
+ touch();
916
+ return action;
917
+ };
918
+ const service = {
919
+ name,
920
+ database,
921
+ deps,
922
+ storage: options.storage,
923
+ hasContext: context !== void 0,
924
+ hasIdentity: identity !== void 0,
925
+ get events() {
926
+ return events;
927
+ },
928
+ hasCatalog: options.events !== void 0,
929
+ action(config) {
930
+ const existing = typeof config.run === "function";
931
+ const site = definitionSite();
932
+ const action = existing ? config : createAction(service, config);
933
+ if (isStandalone(action)) bindAction(action, service, isTool(action) ? "Tool" : "Action");
934
+ place(action, site);
935
+ actions.set(config.name, action);
936
+ touch();
937
+ return existing ? service : action;
938
+ },
939
+ webhook: (config) => register(config, createWebhook),
940
+ getAction: (actionName) => actions.get(actionName),
941
+ listActions: () => [...actions.values()],
942
+ socket(config) {
943
+ if (sockets.has(config.name)) throw new DuplicateNameError(`Brick: duplicate socket "${config.name}" in service "${name}"`);
944
+ const socket = defineServiceSocket(name, config, (request) => resolveContext({ request }));
945
+ sockets.set(config.name, socket);
946
+ touch();
947
+ return socket.handle;
948
+ },
949
+ listSockets: () => [...sockets.values()],
950
+ tool(config) {
951
+ const existing = isTool(config);
952
+ const tool = existing ? config : defineTool(config);
953
+ const previous = tools.get(tool.name);
954
+ if (previous && previous !== tool) throw new DuplicateNameError(`Brick: duplicate tool "${tool.name}" in service "${name}"`);
955
+ bindAction(tool, service, "Tool");
956
+ if (tool.config.http) service.action(tool);
957
+ tools.set(tool.name, tool);
958
+ touch();
959
+ return existing ? service : tool;
960
+ },
961
+ getTool: (toolName) => tools.get(toolName),
962
+ listTools: () => [...tools.values()],
963
+ resource(config) {
964
+ if (resources.has(config.name)) throw new DuplicateNameError(`Brick: duplicate resource "${config.name}" in service "${name}"`);
965
+ const resource = defineResource(service, config);
966
+ resources.set(config.name, resource);
967
+ touch();
968
+ return resource;
969
+ },
970
+ getResource: (resourceName) => resources.get(resourceName),
971
+ listResources: () => [...resources.values()],
972
+ use: (plugin) => installPlugin(service, void 0, plugin),
973
+ resolveContext
974
+ };
975
+ setInternals(service, {
976
+ addEvents(refs) {
977
+ events = Object.freeze({
978
+ ...events,
979
+ ...refs
980
+ });
981
+ },
982
+ snapshot() {
983
+ const savedEvents = events;
984
+ const maps = [
985
+ actions,
986
+ sockets,
987
+ tools,
988
+ resources,
989
+ sites
990
+ ];
991
+ const saved = maps.map((map) => new Map(map));
992
+ const tables = database && new Set(Object.keys(database.tables));
993
+ const properties = new Map([...resources.values()].map((item) => [item, Object.getOwnPropertyDescriptors(item)]));
994
+ return () => {
995
+ events = savedEvents;
996
+ maps.forEach((map, index) => {
997
+ map.clear();
998
+ for (const [key, value] of saved[index]) map.set(key, value);
999
+ });
1000
+ for (const key of Object.keys(database?.tables ?? {})) if (!tables.has(key)) delete database.tables[key];
1001
+ for (const [item, own] of properties) {
1002
+ for (const key of Reflect.ownKeys(item)) if (!Object.hasOwn(own, key)) Reflect.deleteProperty(item, key);
1003
+ Object.defineProperties(item, own);
1004
+ }
1005
+ touch();
1006
+ };
1007
+ }
1008
+ });
1009
+ getGlobalRegistry().register(service);
1010
+ return service;
1011
+ }
1012
+ // src/socket-redis.ts
1013
+ /** Orders two sequences, signed or not. */
1014
+ function compareSocketSeq(a, b) {
1015
+ const [a1, a2] = splitSeq(a)[0].split("-").map(BigInt);
1016
+ const [b1, b2] = splitSeq(b)[0].split("-").map(BigInt);
1017
+ if (a1 !== b1) return a1 > b1 ? 1 : -1;
1018
+ return a2 === b2 ? 0 : a2 > b2 ? 1 : -1;
1019
+ }
1020
+ /** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */
1021
+ function reconnectDelay(failures) {
1022
+ const ceiling = Math.min(3e4, 500 * 2 ** failures);
1023
+ return ceiling / 2 + Math.random() * (ceiling / 2);
1024
+ }
1025
+ /** How long a call waits for Redis to connect before going on without it. */
1026
+ const REDIS_WAIT_MS = 1e3;
1027
+ /** One Redis connection that reconnects by itself and reports each fresh connection. */
1028
+ function connection(url, connected) {
1029
+ let redis;
1030
+ let timer;
1031
+ let closed = false;
1032
+ let failures = 0;
1033
+ let failure;
1034
+ const waiters = [];
1035
+ const lost = (client, delay) => {
1036
+ if (redis !== client) return;
1037
+ redis = void 0;
1038
+ if (closed || timer) return;
1039
+ timer = setTimeout(() => {
1040
+ timer = void 0;
1041
+ start();
1042
+ }, delay ?? reconnectDelay(failures++));
1043
+ timer.unref();
1044
+ };
1045
+ const start = () => {
1046
+ if (closed || redis || timer) return;
1047
+ const client = new Bun.RedisClient(url, {
1048
+ autoReconnect: false,
1049
+ enableOfflineQueue: false
1050
+ });
1051
+ redis = client;
1052
+ client.onclose = () => lost(client);
1053
+ client.connect().then(() => {
1054
+ if (redis !== client) return;
1055
+ failures = 0;
1056
+ failure = void 0;
1057
+ connected(client);
1058
+ for (const wake of waiters.splice(0)) wake();
1059
+ }, (error) => {
1060
+ failure = error;
1061
+ lost(client);
1062
+ });
1063
+ };
1064
+ return {
1065
+ get() {
1066
+ start();
1067
+ return redis?.connected ? redis : void 0;
1068
+ },
1069
+ failure: () => failure,
1070
+ /** Resolves after the next connection is made and announced, or after `ms`. */
1071
+ opened(ms) {
1072
+ if (redis?.connected) return Promise.resolve();
1073
+ start();
1074
+ return new Promise((resolve) => {
1075
+ const wake = () => {
1076
+ clearTimeout(timeout);
1077
+ resolve();
1078
+ };
1079
+ const timeout = setTimeout(() => {
1080
+ const at = waiters.indexOf(wake);
1081
+ if (at >= 0) waiters.splice(at, 1);
1082
+ resolve();
1083
+ }, ms);
1084
+ waiters.push(wake);
1085
+ });
1086
+ },
1087
+ /** Drops `client` and dials a fresh one after `delay`, as if it had closed. */
1088
+ reset(client, delay) {
1089
+ lost(client, delay);
1090
+ client.close();
1091
+ },
1092
+ close() {
1093
+ closed = true;
1094
+ clearTimeout(timer);
1095
+ for (const wake of waiters.splice(0)) wake();
1096
+ const client = redis;
1097
+ redis = void 0;
1098
+ client?.close();
1099
+ }
1100
+ };
1101
+ }
1102
+ /**
1103
+ * Fans socket emits and kicks out across processes through Redis pub/sub, one
1104
+ * channel per room topic. An emit is a PUBLISH only: every process, the emitting
1105
+ * one included, delivers it once to its own connections. Uses Bun's built-in
1106
+ * Redis client and two connections, one to publish and one to subscribe.
1107
+ */
1108
+ function redisBroker(options = {}) {
1109
+ const limit = options.queue ?? 1e3;
1110
+ if (!Number.isInteger(limit) || limit < 0) throw new Error("redisBroker queue must be a nonnegative integer");
1111
+ const channel = (topic) => `brick:socket:${topic}`;
1112
+ const listeners = /* @__PURE__ */ new Map();
1113
+ const pending = /* @__PURE__ */ new Map();
1114
+ const stream = (topic) => `brick:socket:stream:${topic}`;
1115
+ const warned = /* @__PURE__ */ new Set();
1116
+ const warn = (what) => (error) => {
1117
+ if (warned.has(what)) return;
1118
+ warned.add(what);
1119
+ console.warn(`[Brick-TS] Redis socket broker: ${what} failed; later failures of it are not logged.`, error);
1120
+ };
1121
+ const queue = [];
1122
+ const send = (work) => {
1123
+ const redis = publisher.get();
1124
+ if (redis) return work(redis);
1125
+ queue.push(work);
1126
+ if (queue.length > limit) queue.shift();
1127
+ };
1128
+ const receive = (payload, name) => {
1129
+ let message;
1130
+ try {
1131
+ message = JSON.parse(payload);
1132
+ } catch {
1133
+ return;
1134
+ }
1135
+ for (const deliver of listeners.get(name) ?? []) deliver(message);
1136
+ };
1137
+ let subscribeFailures = 0;
1138
+ const subscribe = (redis, name) => {
1139
+ const done = redis.subscribe(name, receive).then(() => void (subscribeFailures = 0)).catch((error) => {
1140
+ warn("SUBSCRIBE")(error);
1141
+ subscriber.reset(redis, reconnectDelay(subscribeFailures++));
1142
+ });
1143
+ pending.set(name, done);
1144
+ done.then(() => {
1145
+ if (pending.get(name) === done) pending.delete(name);
1146
+ });
1147
+ };
1148
+ const publisher = connection(options.url, (redis) => {
1149
+ for (const work of queue.splice(0)) work(redis);
1150
+ });
1151
+ const subscriber = connection(options.url, (redis) => {
1152
+ for (const name of listeners.keys()) subscribe(redis, name);
1153
+ });
1154
+ return {
1155
+ publish(message, replay) {
1156
+ const name = channel(message.topic);
1157
+ if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(warn("PUBLISH")));
1158
+ const key = stream(message.topic);
1159
+ send((redis) => {
1160
+ redis.send("XADD", [
1161
+ key,
1162
+ "MAXLEN",
1163
+ "~",
1164
+ String(replay.keep),
1165
+ "*",
1166
+ "m",
1167
+ message.frame
1168
+ ]).then((seq) => {
1169
+ redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(warn("PEXPIRE"));
1170
+ return redis.publish(name, JSON.stringify({
1171
+ ...message,
1172
+ seq
1173
+ }));
1174
+ }).catch(warn("XADD/PUBLISH"));
1175
+ });
1176
+ },
1177
+ async head() {
1178
+ try {
1179
+ await publisher.opened(REDIS_WAIT_MS);
1180
+ const [seconds, micros] = await publisher.get().send("TIME", []);
1181
+ return `${Number(seconds) * 1e3 + Math.floor(Number(micros) / 1e3) - 1}-0`;
1182
+ } catch {
1183
+ return `${Date.now() - 1}-0`;
1184
+ }
1185
+ },
1186
+ async history(topic, since, replay) {
1187
+ let raw;
1188
+ try {
1189
+ await publisher.opened(REDIS_WAIT_MS);
1190
+ raw = await publisher.get().send("XRANGE", [
1191
+ stream(topic),
1192
+ "-",
1193
+ "+"
1194
+ ]);
1195
+ } catch {
1196
+ return;
1197
+ }
1198
+ const ms = (seq) => Number(seq.split("-")[0]);
1199
+ const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);
1200
+ if (after.length === raw.length && (raw.length >= replay.keep || (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)) return void 0;
1201
+ return after.map(([seq, fields]) => ({
1202
+ type: "emit",
1203
+ topic,
1204
+ frame: fields[fields.indexOf("m") + 1],
1205
+ seq
1206
+ }));
1207
+ },
1208
+ subscribe(topic, deliver) {
1209
+ const name = channel(topic);
1210
+ let local = listeners.get(name);
1211
+ if (!local) {
1212
+ local = /* @__PURE__ */ new Set();
1213
+ listeners.set(name, local);
1214
+ const redis = subscriber.get();
1215
+ if (redis) subscribe(redis, name);
1216
+ }
1217
+ local.add(deliver);
1218
+ return () => {
1219
+ local.delete(deliver);
1220
+ if (local.size || listeners.get(name) !== local) return;
1221
+ listeners.delete(name);
1222
+ pending.delete(name);
1223
+ subscriber.get()?.unsubscribe(name).catch(warn("UNSUBSCRIBE"));
1224
+ };
1225
+ },
1226
+ async ready(topic) {
1227
+ const name = channel(topic);
1228
+ if (!pending.has(name)) await subscriber.opened(REDIS_WAIT_MS);
1229
+ await pending.get(name);
1230
+ },
1231
+ close() {
1232
+ publisher.close();
1233
+ subscriber.close();
1234
+ }
1235
+ };
1236
+ }
1237
+ // src/events/emit.ts
1238
+ function emitEvent(ctx, event, payload, options = {}) {
1239
+ return Effect.gen(function* () {
1240
+ const name = typeof event === "string" ? event : event.name;
1241
+ const hub = Option.getOrUndefined(yield* Effect.serviceOption(Events));
1242
+ if (!hub?.records(ctx.db)) return yield* Effect.die(/* @__PURE__ */ new Error(`Cannot emit '${name}': ${hub ? "ctx.db is not the database of a service with an outbox table" : "the app has no events"}`));
1243
+ const json = typeof event === "string" ? payload : yield* encodePayload(event, payload);
1244
+ yield* hub.transaction(ctx.db, {
1245
+ traceId: ctx.traceId,
1246
+ source: options.source
1247
+ }, (_tx, record) => record(name, json, { encoded: typeof event !== "string" }));
1248
+ }).pipe(Effect.catch((error) => Effect.die(error)));
1249
+ }
1250
+ // src/plugin-hooks.ts
1251
+ /** Where `hooks.*` stores a plugin's hooks on its host; `crud` runs them. */
1252
+ const HOST_HOOKS = Symbol.for("brickkit.effect.plugin.hooks");
1253
+ const HOOK_NAMES = Object.keys({
1254
+ beforeCreate: true,
1255
+ afterCreate: true,
1256
+ beforeUpdate: true,
1257
+ afterUpdate: true,
1258
+ beforeDelete: true,
1259
+ afterDelete: true,
1260
+ afterCommit: true
1261
+ });
1262
+ /** The plugin hooks installed on a service or resource, by hook name. */
1263
+ function getHostHooks(host) {
1264
+ return host[HOST_HOOKS];
1265
+ }
1266
+ /** Add hooks to a host, after those already there. */
1267
+ function addHostHooks(host, added) {
1268
+ const store = host[HOST_HOOKS] ??= {};
1269
+ for (const name of HOOK_NAMES) if (added[name]) (store[name] ??= []).push(...added[name]);
1270
+ }
1271
+ // src/crud/statement.ts
1272
+ /** Prepared statements kept per database, the oldest dropped past this many. */
1273
+ const CACHE_LIMIT = 128;
1274
+ /**
1275
+ * Builds one call's statement. When it can be cached, bound values become
1276
+ * placeholders, and the statement is prepared once per key: `identity` plus
1277
+ * the query part and the shape recorded while building it. As in core, the
1278
+ * cache saves building the SQL again, and is kept per database object.
1279
+ */
1280
+ function statements() {
1281
+ const prepared = /* @__PURE__ */ new WeakMap();
1282
+ const prepare = (db, key, build) => {
1283
+ let cache = prepared.get(db);
1284
+ if (!cache) {
1285
+ cache = /* @__PURE__ */ new Map();
1286
+ prepared.set(db, cache);
1287
+ }
1288
+ let statement = cache.get(key);
1289
+ if (!statement) {
1290
+ statement = build().prepare();
1291
+ if (cache.size >= CACHE_LIMIT) cache.delete(cache.keys().next().value);
1292
+ cache.set(key, statement);
1293
+ }
1294
+ return statement;
1295
+ };
1296
+ return (cacheable, identity) => {
1297
+ const params = {};
1298
+ const shape = [];
1299
+ let parameter = 0;
1300
+ const key = (part) => JSON.stringify([
1301
+ ...identity,
1302
+ part,
1303
+ shape
1304
+ ]);
1305
+ return {
1306
+ shape,
1307
+ bind(value, column) {
1308
+ if (!cacheable) return column ? new Param(value, column) : value;
1309
+ const name = `p${parameter++}`;
1310
+ params[name] = value;
1311
+ const placeholder = sql.placeholder(name);
1312
+ return column ? new Param(placeholder, column) : placeholder;
1313
+ },
1314
+ run(db, part, build) {
1315
+ return Effect.suspend(() => cacheable ? prepare(db, key(part), build).execute(params) : build());
1316
+ }
1317
+ };
1318
+ };
1319
+ }
1320
+ // src/crud/where.ts
1321
+ const like = (column, pattern, bind) => sql`${column} LIKE ${bind(pattern)} ESCAPE '\\'`;
1322
+ const escape = (value) => String(value).replace(/[\\%_]/g, "\\$&");
1323
+ /** Every filter operator: the `FilterOperator` type, validation and SQL all come from here. */
1324
+ const OPERATORS = {
1325
+ eq: {
1326
+ operand: "one",
1327
+ build: (c, v, bind) => eq(c, bind(v))
1328
+ },
1329
+ ne: {
1330
+ operand: "one",
1331
+ build: (c, v, bind) => ne(c, bind(v))
1332
+ },
1333
+ in: {
1334
+ operand: "list",
1335
+ build: (c, v, bind) => inArray(c, v.map(bind))
1336
+ },
1337
+ notIn: {
1338
+ operand: "list",
1339
+ build: (c, v, bind) => notInArray(c, v.map(bind))
1340
+ },
1341
+ gt: {
1342
+ operand: "one",
1343
+ ordered: true,
1344
+ build: (c, v, bind) => gt(c, bind(v))
1345
+ },
1346
+ gte: {
1347
+ operand: "one",
1348
+ ordered: true,
1349
+ build: (c, v, bind) => gte(c, bind(v))
1350
+ },
1351
+ lt: {
1352
+ operand: "one",
1353
+ ordered: true,
1354
+ build: (c, v, bind) => lt(c, bind(v))
1355
+ },
1356
+ lte: {
1357
+ operand: "one",
1358
+ ordered: true,
1359
+ build: (c, v, bind) => lte(c, bind(v))
1360
+ },
1361
+ between: {
1362
+ operand: "pair",
1363
+ ordered: true,
1364
+ build: (c, v, bind) => between(c, bind(v[0]), bind(v[1]))
1365
+ },
1366
+ contains: {
1367
+ operand: "one",
1368
+ text: true,
1369
+ build: (c, v, bind) => like(c, `%${escape(v)}%`, bind)
1370
+ },
1371
+ startsWith: {
1372
+ operand: "one",
1373
+ text: true,
1374
+ build: (c, v, bind) => like(c, `${escape(v)}%`, bind)
1375
+ },
1376
+ endsWith: {
1377
+ operand: "one",
1378
+ text: true,
1379
+ build: (c, v, bind) => like(c, `%${escape(v)}`, bind)
1380
+ },
1381
+ isNull: {
1382
+ operand: "none",
1383
+ build: (c) => isNull(c)
1384
+ },
1385
+ isNotNull: {
1386
+ operand: "none",
1387
+ build: (c) => isNotNull(c)
1388
+ }
1389
+ };
1390
+ const operator = (name) => Object.hasOwn(OPERATORS, name) ? OPERATORS[name] : void 0;
1391
+ function checkFilters(key, column, operators) {
1392
+ for (const name of operators) {
1393
+ const op = operator(name);
1394
+ if (!op) throw new Error(`Unknown filter operator '${name}'`);
1395
+ if (op.text && kindOf(column) !== "string") throw new Error(`Text filter '${name}' requires a string column '${key}'`);
1396
+ if (op.ordered && !ORDERED_TYPES.has(kindOf(column))) throw new Error(`Ordered filter '${name}' is unsupported for '${key}'`);
1397
+ if (op.operand !== "none" && UNFILTERABLE_TYPES.has(kindOf(column))) throw new Error(`Filter '${name}' is unsupported for '${key}'`);
1398
+ }
1399
+ }
1400
+ /** The filter AST of a resource: a leaf per allowed field and operator, combined with `and` and `or`. */
1401
+ function whereSchema(resourceName, fields, schemas) {
1402
+ const leaves = [];
1403
+ for (const [field, policy] of Object.entries(fields)) {
1404
+ const operators = policy.filter ?? [];
1405
+ if (!operators.length) continue;
1406
+ if (field === "and" || field === "or") throw new Error(`CRUD filter field '${field}' on '${resourceName}' collides with the '${field}' branch`);
1407
+ const value = withoutNull(schemas[field]);
1408
+ const operands = {
1409
+ none: {},
1410
+ one: { value },
1411
+ list: { value: Schema.Array(value).check(Schema.isMinLength(1), Schema.isMaxLength(1e3)) },
1412
+ pair: { value: Schema.Tuple([value, value]) }
1413
+ };
1414
+ for (const op of operators) leaves.push(Schema.Struct({
1415
+ field: Schema.Literal(field),
1416
+ op: Schema.Literal(op),
1417
+ ...operands[OPERATORS[op].operand]
1418
+ }));
1419
+ }
1420
+ if (!leaves.length) return Schema.Never;
1421
+ const branch = (key) => Schema.Struct({ [key]: Schema.Array(Schema.suspend(() => where)).check(Schema.isMinLength(1), Schema.isMaxLength(50)) });
1422
+ const where = Schema.Union([
1423
+ ...leaves,
1424
+ branch("and"),
1425
+ branch("or")
1426
+ ]).annotate({ identifier: `Where:${resourceName}` });
1427
+ return where;
1428
+ }
1429
+ /**
1430
+ * Whether the raw `where` of an input nests `and` and `or` past the bound. It
1431
+ * walks iteratively, so it can run before the input is decoded: decoding
1432
+ * recurses, and a deep enough filter would overflow the stack.
1433
+ */
1434
+ function whereDepthExceeded(input) {
1435
+ const root = input && typeof input === "object" ? input.where : void 0;
1436
+ if (!root || typeof root !== "object") return false;
1437
+ const stack = [{
1438
+ node: root,
1439
+ depth: 0
1440
+ }];
1441
+ while (stack.length > 0) {
1442
+ const { node, depth } = stack.pop();
1443
+ if (depth > 20) return true;
1444
+ if (!node || typeof node !== "object") continue;
1445
+ const record = node;
1446
+ for (const key of ["and", "or"]) {
1447
+ const children = record[key];
1448
+ if (Array.isArray(children)) for (const child of children) stack.push({
1449
+ node: child,
1450
+ depth: depth + 1
1451
+ });
1452
+ }
1453
+ }
1454
+ return false;
1455
+ }
1456
+ /** The SQL for a validated `where`, its values bound and its shape recorded on `query`. */
1457
+ function condition(node, columns, query) {
1458
+ if (node.and) {
1459
+ query.shape.push("and", node.and.length);
1460
+ return and(...node.and.map((n) => condition(n, columns, query)));
1461
+ }
1462
+ if (node.or) {
1463
+ query.shape.push("or", node.or.length);
1464
+ return or(...node.or.map((n) => condition(n, columns, query)));
1465
+ }
1466
+ const column = columns[node.field];
1467
+ query.shape.push(node.field, node.op);
1468
+ const op = operator(node.op);
1469
+ if (!op) return invalid$1("Unknown filter operator");
1470
+ if (op.operand === "list") query.shape.push(node.value.length);
1471
+ return op.build(column, node.value, (value) => query.bind(databaseValue(column, value), column));
1472
+ }
1473
+ // src/crud/perform.ts
1474
+ /** Each bulk operation runs its single-row operation once per item. */
1475
+ const bulkOperations = {
1476
+ bulkCreate: "create",
1477
+ bulkUpdate: "update",
1478
+ bulkDelete: "delete"
1479
+ };
1480
+ /** The hooks that make a write open its own transaction. */
1481
+ const writeHooks = {
1482
+ create: ["beforeCreate", "afterCreate"],
1483
+ update: ["beforeUpdate", "afterUpdate"],
1484
+ delete: ["beforeDelete", "afterDelete"]
1485
+ };
1486
+ /** Whether an error, or what it wraps, is a unique or primary key violation. */
1487
+ function uniqueViolation(error, depth = 0) {
1488
+ if (depth > 6 || !error || typeof error !== "object") return false;
1489
+ if (Cause.isCause(error)) {
1490
+ const found = Cause.findError(error);
1491
+ return Result.isSuccess(found) && uniqueViolation(found.success, depth + 1);
1492
+ }
1493
+ const { _tag, code, cause, reason } = error;
1494
+ return _tag === "UniqueViolation" || [
1495
+ "23505",
1496
+ "SQLITE_CONSTRAINT_UNIQUE",
1497
+ "SQLITE_CONSTRAINT_PRIMARYKEY"
1498
+ ].includes(String(code)) || uniqueViolation(reason, depth + 1) || uniqueViolation(cause, depth + 1);
1499
+ }
1500
+ const fail = errorHelpers();
1501
+ const attempt = (build) => Effect.try({
1502
+ try: build,
1503
+ catch: (error) => error
1504
+ });
1505
+ function operations(model) {
1506
+ const { access, resource, fields, columns, readable } = model;
1507
+ /** The `crud` hooks, then those of plugins on the resource, then on the service. */
1508
+ const hooksOf = () => {
1509
+ const hosted = model.hostHooks();
1510
+ if (!hosted.length) return model.hooks;
1511
+ const merged = {};
1512
+ for (const name of HOOK_NAMES) {
1513
+ const chain = [model.hooks[name], ...hosted.flatMap(({ hooks, resource: host }) => (hooks[name] ?? []).map((hook) => (args) => hook(host ? {
1514
+ ...args,
1515
+ resource: host
1516
+ } : args)))].filter((hook) => hook !== void 0);
1517
+ if (!chain.length) continue;
1518
+ merged[name] = name === "afterCommit" ? (args) => Effect.forEach(chain, (hook) => Effect.exit(Effect.suspend(() => hook(args)))).pipe(Effect.flatMap((exits) => {
1519
+ const failed = exits.find(Exit.isFailure);
1520
+ return failed ? Effect.failCause(failed.cause) : Effect.void;
1521
+ })) : (args) => Effect.forEach(chain, (hook) => hook(args), { discard: true });
1522
+ }
1523
+ return merged;
1524
+ };
1525
+ const idColumn = resource.id;
1526
+ const eventRow = (row) => Object.fromEntries(readable.map((field) => [field, jsonValue(row[field])]));
1527
+ const eventId = (row) => jsonValue(row[resource.idField]);
1528
+ /** The events hub when this write is to record an event: events on, an outbox on the database, and a listener that wants it. */
1529
+ const recorderFor = (db, operation) => Effect.map(Effect.serviceOption(Events), (hub) => model.events && Option.isSome(hub) && hub.value.records(db) && hub.value.wants(crudEventName(resource.name, operation)) ? hub.value : void 0);
1530
+ const eventContext = (ctx) => ({
1531
+ traceId: ctx.traceId,
1532
+ source: crudEventSource(model.service.name, resource.name),
1533
+ service: model.service
1534
+ });
1535
+ const cursorColumns = new Set(readable.filter((key) => !fields[key].scrub).map((key) => columns[key]));
1536
+ const statement = statements();
1537
+ /**
1538
+ * Whether a call's statement is prepared and kept per database, as in core:
1539
+ * SQLite, a read, over the app's own database handle, and no scope (its SQL
1540
+ * changes per call). A write builds its statement each time: it runs in a
1541
+ * transaction, whose handle is new for every call.
1542
+ */
1543
+ const cacheable = (operation, scope, outer) => [
1544
+ "list",
1545
+ "findOne",
1546
+ "get",
1547
+ "count",
1548
+ "exists"
1549
+ ].includes(operation) && !scope && !outer && model.engine === "sqlite";
1550
+ /** A call's statement parts: the scope, the filters and, for one row, its id. */
1551
+ const begin = (operation, input, scope, outer) => {
1552
+ const asked = operation === "create" ? {} : input;
1553
+ const derived = asked.include ?? [];
1554
+ const selected = [...asked.select ?? readable, ...derived];
1555
+ const query = statement(cacheable(operation, scope, outer), [
1556
+ operation,
1557
+ selected,
1558
+ asked.orderBy
1559
+ ]);
1560
+ return {
1561
+ operation,
1562
+ input,
1563
+ scope,
1564
+ derived,
1565
+ selected,
1566
+ query,
1567
+ where: and(scope, asked.where ? condition(asked.where, columns, query) : void 0, [
1568
+ "get",
1569
+ "update",
1570
+ "delete"
1571
+ ].includes(operation) ? eq(idColumn, query.bind(columnValue(idColumn, input.id) ?? (() => {
1572
+ throw reject("NOT_FOUND", "Resource not found");
1573
+ })(), idColumn)) : void 0)
1574
+ };
1575
+ };
1576
+ /** The select behind list, findOne and get, with its cursor and limits. */
1577
+ const rowsQuery = ({ operation, input, where, selected, derived, query }) => {
1578
+ const paging = operation === "list" && input.cursor !== void 0;
1579
+ if (paging) query.shape.push("paging");
1580
+ const sorts = input.orderBy ?? [];
1581
+ const sortKey = (column) => paging && column.columnType === "PgTimestamp" && (column.precision ?? 6) > 3 ? sql`date_trunc('milliseconds', ${column})` : sql`${column}`;
1582
+ const keyset = sorts.map((sort) => ({
1583
+ column: columns[sort.field],
1584
+ key: sortKey(columns[sort.field]),
1585
+ desc: sort.direction === "desc"
1586
+ }));
1587
+ if (paging) {
1588
+ if (input.offset) invalid$1("Use cursor or offset, not both");
1589
+ if (!keyset.some((key) => key.column === idColumn)) keyset.push({
1590
+ column: idColumn,
1591
+ key: sql`${idColumn}`,
1592
+ desc: false
1593
+ });
1594
+ if (keyset.some((key) => !key.column.notNull)) invalid$1("Cursor pagination needs sort fields that are not null");
1595
+ if (keyset.some((key) => !cursorColumns.has(key.column))) invalid$1("Cursor pagination needs sort fields and an ID that are readable and not scrubbed");
1596
+ }
1597
+ const cursorSpec = sorts.map((sort) => `${sort.field}:${sort.direction}`).join(",");
1598
+ let after;
1599
+ if (paging && input.cursor !== null) {
1600
+ const values = decodeCursor(input.cursor, cursorSpec, keyset);
1601
+ query.shape.push("after");
1602
+ for (let index = keyset.length - 1; index >= 0; index--) {
1603
+ const { column, key, desc: down } = keyset[index];
1604
+ const value = () => query.bind(databaseValue(column, values[index]), column);
1605
+ const past = down ? lt(key, value()) : gt(key, value());
1606
+ after = after ? or(past, and(eq(key, value()), after)) : past;
1607
+ }
1608
+ }
1609
+ const selectedProjection = Object.fromEntries(selected.filter((key) => !fields[key].resolve).map((key) => [key, columns[key]]));
1610
+ const projection = {
1611
+ ...derived.length ? columns : Object.keys(selectedProjection).length ? selectedProjection : { __brickSentinel: idColumn },
1612
+ ...paging ? Object.fromEntries(keyset.map((key, index) => [`__brickKey${index}`, key.column])) : {}
1613
+ };
1614
+ const limit = operation === "list" ? input.limit ?? model.defaultLimit : 1;
1615
+ const ordering = keyset.map((key) => key.desc ? desc(key.key) : asc(key.key));
1616
+ const offset = input.offset ?? 0;
1617
+ const boundLimit = query.bind(paging ? limit + 1 : limit);
1618
+ const boundOffset = query.bind(offset);
1619
+ return {
1620
+ paging,
1621
+ limit,
1622
+ offset,
1623
+ next: (last) => encodeCursor(cursorSpec, keyset.map((_, index) => last[`__brickKey${index}`])),
1624
+ build: (db) => db.select(projection).from(resource.table).where(after ? and(where, after) : where).orderBy(...ordering).limit(boundLimit).offset(boundOffset)
1625
+ };
1626
+ };
1627
+ const resolveRows = (call, rows) => Effect.gen(function* () {
1628
+ if (!rows.length) return rows;
1629
+ const resolved = rows.map((row) => ({ ...row }));
1630
+ for (const key of call.derived) {
1631
+ const values = yield* fields[key].resolve({
1632
+ rows,
1633
+ ctx: call.ctx
1634
+ });
1635
+ if (values.length !== rows.length) return yield* Effect.die(/* @__PURE__ */ new Error(`Derived CRUD field '${key}' returned an incorrect number of values`));
1636
+ for (let index = 0; index < rows.length; index++) resolved[index][key] = values[index];
1637
+ }
1638
+ return resolved;
1639
+ });
1640
+ const scrub = (call, row) => Effect.gen(function* () {
1641
+ const result = {};
1642
+ for (const key of call.selected) {
1643
+ const value = jsonValue(row[key]);
1644
+ const scrubbed = fields[key].scrub;
1645
+ result[key] = scrubbed ? yield* scrubbed({
1646
+ value,
1647
+ ctx: call.ctx
1648
+ }) : value;
1649
+ }
1650
+ return result;
1651
+ });
1652
+ const count = (call, part) => Effect.map(call.query.run(call.db, part, () => call.db.select({ count: sql`count(*)`.mapWith(Number) }).from(resource.table).where(call.where)), (rows) => rows[0].count);
1653
+ const read = (call) => Effect.gen(function* () {
1654
+ const { operation, input, db } = call;
1655
+ const rowsOf = yield* attempt(() => rowsQuery(call));
1656
+ const fetched = yield* call.query.run(db, "rows", () => rowsOf.build(db));
1657
+ const more = rowsOf.paging && fetched.length > rowsOf.limit;
1658
+ const rows = yield* resolveRows(call, more ? fetched.slice(0, rowsOf.limit) : fetched);
1659
+ if (operation === "get") {
1660
+ if (!rows[0]) return yield* fail.NOT_FOUND("Resource not found");
1661
+ return yield* scrub(call, rows[0]);
1662
+ }
1663
+ if (operation === "findOne") return rows[0] ? yield* scrub(call, rows[0]) : null;
1664
+ const result = {
1665
+ items: yield* Effect.forEach(rows, (row) => scrub(call, row)),
1666
+ limit: rowsOf.limit,
1667
+ offset: rowsOf.offset
1668
+ };
1669
+ if (rowsOf.paging) {
1670
+ const last = rows.at(-1);
1671
+ result.nextCursor = more && last ? rowsOf.next(last) : null;
1672
+ }
1673
+ if (input.includeTotal) result.total = yield* count(call, "total");
1674
+ return result;
1675
+ });
1676
+ const run = (name, args) => hooksOf()[name]?.(args) ?? Effect.void;
1677
+ /**
1678
+ * Runs a write in the bulk call's transaction, in the event recorder's, or
1679
+ * in one opened for its hooks or its audit row.
1680
+ */
1681
+ const transaction = (call, fn) => Effect.gen(function* () {
1682
+ if (call.outer) return yield* fn(call.outer.tx, call.outer.record);
1683
+ const operation = call.operation;
1684
+ const hub = yield* recorderFor(call.db, operation);
1685
+ if (hub) return yield* hub.transaction(call.db, eventContext(call.ctx), fn);
1686
+ const current = hooksOf();
1687
+ return yield* writeHooks[operation].some((name) => current[name]) || isInlineAudit(call.ctx) ? runInTransaction(call.db, (tx) => fn(tx)) : fn(call.db);
1688
+ });
1689
+ /** The audit row of a write, in the write's transaction, when the running action records itself inline. */
1690
+ const recordAudit = (call, tx, operation, id) => isInlineAudit(call.ctx) ? recordInline(call.ctx, tx, {
1691
+ action: `${resource.name}.${operation}`,
1692
+ resource: resource.name,
1693
+ recordId: id
1694
+ }) : Effect.void;
1695
+ /** Runs `afterCommit` once the write is committed: after the outermost transaction's commit, if one is open. */
1696
+ const committed = (call, args) => {
1697
+ const { afterCommit } = hooksOf();
1698
+ if (!afterCommit) return Effect.void;
1699
+ const hook = afterCommit({
1700
+ ...args,
1701
+ id: "row" in args ? args.row[resource.idField] : call.input.id,
1702
+ ctx: call.ctx
1703
+ }).pipe(Effect.catchCause((cause) => Effect.sync(() => call.ctx.logger?.error?.(`${resource.name} afterCommit hook failed`, Cause.pretty(cause)))));
1704
+ const client = call.ctx.db?.$client;
1705
+ return client?.afterCommit ? client.afterCommit(hook) : hook;
1706
+ };
1707
+ const remove = (call) => Effect.gen(function* () {
1708
+ const { input, ctx, error, where } = call;
1709
+ yield* transaction(call, (tx, record) => Effect.gen(function* () {
1710
+ const args = {
1711
+ id: input.id,
1712
+ ctx,
1713
+ error,
1714
+ tx,
1715
+ resource
1716
+ };
1717
+ yield* run("beforeDelete", args);
1718
+ const rows = yield* tx.delete(resource.table).where(where).returning(record ? columns : { id: idColumn });
1719
+ if (!rows.length) return yield* fail.NOT_FOUND("Resource not found");
1720
+ if (record) yield* record(crudEventName(resource.name, "delete"), {
1721
+ id: eventId(rows[0]),
1722
+ row: eventRow(rows[0])
1723
+ });
1724
+ yield* run("afterDelete", args);
1725
+ yield* recordAudit(call, tx, "delete", input.id);
1726
+ }));
1727
+ yield* committed(call, { operation: "delete" });
1728
+ return { success: true };
1729
+ });
1730
+ /** The row an update is about to change, locked where the database can, from inside the call's scope. */
1731
+ const lockedRow = (tx, where) => {
1732
+ const select = tx.select(columns).from(resource.table).where(where).limit(1);
1733
+ return typeof select.for === "function" ? select.for("update") : select;
1734
+ };
1735
+ const write = (call) => Effect.gen(function* () {
1736
+ const { input, ctx, error, where } = call;
1737
+ const operation = call.operation;
1738
+ if (operation === "create" && call.scope) return yield* fail.FORBIDDEN("Row-scoped creation requires an explicit create policy");
1739
+ const rows = yield* transaction(call, (tx, record) => Effect.gen(function* () {
1740
+ const data = { ...operation === "create" ? input : input.data };
1741
+ const args = {
1742
+ ctx,
1743
+ error,
1744
+ tx,
1745
+ resource
1746
+ };
1747
+ if (operation === "create") yield* run("beforeCreate", {
1748
+ ...args,
1749
+ data
1750
+ });
1751
+ else yield* run("beforeUpdate", {
1752
+ ...args,
1753
+ id: input.id,
1754
+ data
1755
+ });
1756
+ for (const field of Object.keys(data)) if (!Object.hasOwn(columns, field)) return yield* Effect.die(/* @__PURE__ */ new Error(`Write hook supplied unknown field '${field}'`));
1757
+ if (operation === "update" && !Object.keys(data).length) return yield* attempt(() => invalid$1("Update requires at least one field"));
1758
+ const stored = yield* attempt(() => Object.fromEntries(Object.keys(data).sort((a, b) => a < b ? -1 : 1).map((field) => [field, databaseValue(columns[field], data[field])])));
1759
+ const before = record && operation === "update" ? (yield* lockedRow(tx, where))[0] : void 0;
1760
+ const written = yield* (operation === "create" ? tx.insert(resource.table).values(stored).returning(columns) : tx.update(resource.table).set(stored).where(where).returning(columns)).pipe(Effect.catch((cause) => uniqueViolation(cause) ? fail.CONFLICT("Resource already exists") : Effect.fail(cause)));
1761
+ if (!written[0]) return yield* fail.NOT_FOUND("Resource not found");
1762
+ if (record) yield* record(crudEventName(resource.name, operation), operation === "create" ? {
1763
+ id: eventId(written[0]),
1764
+ row: eventRow(written[0])
1765
+ } : {
1766
+ id: eventId(written[0]),
1767
+ before: eventRow(before ?? {}),
1768
+ after: eventRow(written[0])
1769
+ });
1770
+ if (operation === "create") yield* run("afterCreate", {
1771
+ ...args,
1772
+ row: written[0]
1773
+ });
1774
+ else yield* run("afterUpdate", {
1775
+ ...args,
1776
+ id: input.id,
1777
+ row: written[0]
1778
+ });
1779
+ yield* recordAudit(call, tx, operation, written[0][resource.idField]);
1780
+ return written;
1781
+ }));
1782
+ yield* committed(call, {
1783
+ operation,
1784
+ row: rows[0]
1785
+ });
1786
+ return yield* scrub(call, (yield* resolveRows(call, rows))[0]);
1787
+ });
1788
+ /** Whether a call may go ahead: `access`' `authorize`, which is absent when nothing allows it. */
1789
+ const authorize = (operation, input, ctx) => access === "public" ? Effect.succeed(true) : access.authorize?.({
1790
+ operation,
1791
+ input,
1792
+ ctx
1793
+ }) ?? Effect.succeed(false);
1794
+ const perform = (operation, input, ctx, error, outer) => Effect.gen(function* () {
1795
+ if (outer && !(yield* authorize(operation, input, ctx))) return yield* deny(`${resource.name}.${operation}`, ctx.user);
1796
+ const db = outer?.tx ?? ctx.db;
1797
+ if (!db) return yield* Effect.die(/* @__PURE__ */ new Error("CRUD requires a configured database"));
1798
+ const scope = access === "public" ? void 0 : access.scope ? yield* access.scope({
1799
+ operation,
1800
+ ctx
1801
+ }) : void 0;
1802
+ const call = {
1803
+ ...yield* attempt(() => begin(operation, input, scope, outer)),
1804
+ db,
1805
+ ctx,
1806
+ error,
1807
+ outer
1808
+ };
1809
+ switch (operation) {
1810
+ case "list":
1811
+ case "findOne":
1812
+ case "get": return yield* read(call);
1813
+ case "count": return { count: yield* count(call, "count") };
1814
+ case "exists": return { exists: (yield* call.query.run(db, "exists", () => db.select({ id: idColumn }).from(resource.table).where(call.where).limit(1))).length > 0 };
1815
+ case "delete": return yield* remove(call);
1816
+ default: return yield* write(call);
1817
+ }
1818
+ });
1819
+ /** One transaction for the whole batch: every item goes through the single-row path (authorize, scope, hooks) or nothing is kept. */
1820
+ const performBulk = (operation, input, ctx, error) => Effect.gen(function* () {
1821
+ const single = bulkOperations[operation];
1822
+ const items = single === "delete" ? input.ids.map((id) => ({ id })) : input.items;
1823
+ if (!ctx.db) return yield* Effect.die(/* @__PURE__ */ new Error("CRUD requires a configured database"));
1824
+ const body = (tx, record) => Effect.forEach(items, (item, index) => perform(single, item, ctx, error, {
1825
+ tx,
1826
+ record
1827
+ }).pipe(Effect.mapError((cause) => cause instanceof BrickError ? new BrickError({
1828
+ code: cause.code,
1829
+ message: `Item ${index}: ${cause.message}`,
1830
+ status: cause.status,
1831
+ details: {
1832
+ index,
1833
+ code: cause.code,
1834
+ message: cause.message
1835
+ }
1836
+ }) : cause)));
1837
+ const hub = yield* recorderFor(ctx.db, single);
1838
+ const results = yield* hub ? hub.transaction(ctx.db, eventContext(ctx), body) : runInTransaction(ctx.db, (tx) => body(tx));
1839
+ return single === "delete" ? { count: results.length } : { items: results };
1840
+ });
1841
+ return {
1842
+ perform,
1843
+ performBulk,
1844
+ authorize
1845
+ };
1846
+ }
1847
+ // src/crud/index.ts
1848
+ const methods = {
1849
+ list: {
1850
+ method: "POST",
1851
+ path: "/query"
1852
+ },
1853
+ get: {
1854
+ method: "GET",
1855
+ path: "/:id"
1856
+ },
1857
+ create: {
1858
+ method: "POST",
1859
+ path: "/"
1860
+ },
1861
+ update: {
1862
+ method: "PATCH",
1863
+ path: "/:id"
1864
+ },
1865
+ delete: {
1866
+ method: "DELETE",
1867
+ path: "/:id"
1868
+ },
1869
+ findOne: {
1870
+ method: "POST",
1871
+ path: "/find-one"
1872
+ },
1873
+ count: {
1874
+ method: "POST",
1875
+ path: "/count"
1876
+ },
1877
+ exists: {
1878
+ method: "POST",
1879
+ path: "/exists"
1880
+ },
1881
+ bulkCreate: {
1882
+ method: "POST",
1883
+ path: "/bulk-create"
1884
+ },
1885
+ bulkUpdate: {
1886
+ method: "POST",
1887
+ path: "/bulk-update"
1888
+ },
1889
+ bulkDelete: {
1890
+ method: "POST",
1891
+ path: "/bulk-delete"
1892
+ }
1893
+ };
1894
+ const CRUD_PLUGIN = "@brickkit/crud";
1895
+ const writes = /* @__PURE__ */ new Set([
1896
+ "create",
1897
+ "update",
1898
+ "delete",
1899
+ "bulkCreate",
1900
+ "bulkUpdate",
1901
+ "bulkDelete"
1902
+ ]);
1903
+ const literals = (keys) => keys.length ? Schema.Literals(keys) : Schema.Never;
1904
+ const optional = (schema) => Schema.optional(schema);
1905
+ const struct = (fields) => Schema.Struct(fields);
1906
+ /**
1907
+ * Give a table its CRUD actions on a service: `list`, `get`, `create`,
1908
+ * `update`, `delete`, `findOne`, `count` and `exists`, with validated input and
1909
+ * output, filters and sorting, paging, and access rules. The actions are named
1910
+ * `<name>.<operation>` and routed under `/<service>/<name>`:
1911
+ * `POST /query`, `GET /:id`, `POST /`, `PATCH /:id`, `DELETE /:id`,
1912
+ * `POST /find-one`, `/count` and `/exists`, and `POST /bulk-create`,
1913
+ * `/bulk-update` and `/bulk-delete` when `operations` turns them on.
1914
+ *
1915
+ * It denies by default: `access` is required. A column is hidden from reads,
1916
+ * writes and filters until its `fields` entry allows it.
1917
+ *
1918
+ * @param service - A service with a database.
1919
+ * @param options - `fields` (per column: `read`, `create`, `update`, `filter`
1920
+ * operators, `sort`, and `schema`, `scrub` and `resolve`), `access` (`"public"`,
1921
+ * or `{ authorize, scope }`), `operations` to switch some off, `hooks` around
1922
+ * writes, and `defaultLimit`, `maxLimit` and `maxBatchSize`.
1923
+ * @returns The actions, which run in-process with `action.run`.
1924
+ * @throws When a field is unknown, a filter does not fit its column, or the
1925
+ * resource has no id column.
1926
+ * @example
1927
+ * export const page = crud(pages, {
1928
+ * name: "page",
1929
+ * table: tables.pages,
1930
+ * access: "public",
1931
+ * fields: {
1932
+ * id: { read: true, filter: ["eq", "in"] },
1933
+ * title: { read: true, create: true, update: true, sort: true },
1934
+ * },
1935
+ * });
1936
+ * const created = yield* page.create.run({ title: "Hello" });
1937
+ */
1938
+ function crud(service, options) {
1939
+ const { name, table, access } = options;
1940
+ if (!name || name.includes("/") || name.includes(".")) throw new Error(`Invalid resource name '${name}'`);
1941
+ if (options.operations === false) return {};
1942
+ const columns = getTableColumns(table);
1943
+ const idColumn = options.id ?? Object.values(columns).find((column) => column.primary && Object.values(columns).filter((other) => other.primary).length === 1);
1944
+ const idField = Object.entries(columns).find(([, column]) => column === idColumn)?.[0];
1945
+ if (!idColumn || !idField) throw new Error(`Resource '${name}' requires an id column belonging to its table`);
1946
+ const fields = options.fields;
1947
+ const schemas = {};
1948
+ const readable = Object.keys(fields).filter((key) => fields[key].read && !fields[key].resolve);
1949
+ const includable = Object.keys(fields).filter((key) => fields[key].resolve);
1950
+ for (const [key, policy] of Object.entries(fields)) {
1951
+ if (policy.resolve) {
1952
+ if (!policy.read || !policy.schema || policy.create || policy.update || policy.sort || policy.filter?.length) throw new Error(`Derived CRUD field '${key}' requires read/schema and cannot enable writes, filters or sorting`);
1953
+ if (Object.hasOwn(columns, key)) throw new Error(`Derived CRUD field '${key}' cannot replace a table column`);
1954
+ schemas[key] = policy.schema;
1955
+ checkJsonSchema(policy.schema);
1956
+ continue;
1957
+ }
1958
+ if (!Object.hasOwn(columns, key)) throw new Error(`Unknown CRUD field '${key}' on '${name}'`);
1959
+ const column = columns[key];
1960
+ schemas[key] = policy.schema ?? columnSchema(column);
1961
+ checkJsonSchema(schemas[key]);
1962
+ if (column === idColumn && policy.update) throw new Error("CRUD primary key cannot be updated");
1963
+ checkFilters(key, column, policy.filter ?? []);
1964
+ if (policy.sort && !SORTABLE_TYPES.has(kindOf(column))) throw new Error(`Sorting is unsupported for '${key}'`);
1965
+ }
1966
+ for (const [key, policy] of Object.entries(fields)) {
1967
+ if (!hasSensitive(schemas[key])) continue;
1968
+ if (policy.resolve) throw new Error(`Derived CRUD field '${key}' on '${name}' in service '${service.name}' cannot be Sensitive: a derived field is always read`);
1969
+ const option = policy.read ? "read: true" : policy.filter?.length ? "filter" : policy.sort ? "sort" : void 0;
1970
+ if (option) throw new Error(`CRUD field '${key}' on '${name}' in service '${service.name}' is Sensitive and cannot have \`${option}\`; drop it`);
1971
+ }
1972
+ const defaultLimit = options.defaultLimit ?? 20;
1973
+ const maxLimit = options.maxLimit ?? 100;
1974
+ if (!Number.isInteger(defaultLimit) || defaultLimit < 1 || !Number.isInteger(maxLimit) || maxLimit < defaultLimit) throw new Error("Invalid CRUD pagination limits");
1975
+ const maxBatchSize = options.maxBatchSize ?? 100;
1976
+ if (!Number.isInteger(maxBatchSize) || maxBatchSize < 1) throw new Error("Invalid CRUD maxBatchSize");
1977
+ const batch = (item, unique = false) => Schema.Array(item).check(Schema.isMinLength(1), Schema.isMaxLength(maxBatchSize), ...unique ? [Schema.isUnique()] : []);
1978
+ const where = whereSchema(name, fields, schemas);
1979
+ const selection = optional(Schema.Array(literals(readable)).check(Schema.isMinLength(1), Schema.isUnique()));
1980
+ const includes = optional(Schema.Array(literals(includable)).check(Schema.isUnique()));
1981
+ const queryProperties = {
1982
+ select: selection,
1983
+ include: includes,
1984
+ where: optional(where),
1985
+ orderBy: optional(Schema.Array(struct({
1986
+ field: literals(Object.keys(fields).filter((key) => fields[key].sort)),
1987
+ direction: Schema.Literals(["asc", "desc"])
1988
+ })).check(Schema.isMaxLength(20))),
1989
+ limit: optional(Schema.Int.check(Schema.isBetween({
1990
+ minimum: 1,
1991
+ maximum: maxLimit
1992
+ }))),
1993
+ offset: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
1994
+ includeTotal: optional(Schema.Boolean)
1995
+ };
1996
+ const rowSchema = struct(Object.fromEntries([...readable, ...includable].map((key) => [key, optional(fields[key].schema ?? (fields[key].scrub ? Schema.Unknown : schemas[key]))])));
1997
+ const writeSchema = (kind) => struct(Object.fromEntries(Object.entries(fields).filter(([, policy]) => policy[kind]).map(([key]) => [key, kind === "update" || columns[key].hasDefault || !columns[key].notNull ? optional(schemas[key]) : schemas[key]])));
1998
+ const createSchema = writeSchema("create");
1999
+ const updateSchema = writeSchema("update");
2000
+ const pathId = idSchema$1(idColumn, true);
2001
+ const bodyId = idSchema$1(idColumn, false);
2002
+ const inputs = {
2003
+ list: struct({
2004
+ ...queryProperties,
2005
+ cursor: optional(Schema.NullOr(Schema.String.check(Schema.isMaxLength(4096))))
2006
+ }),
2007
+ findOne: struct(queryProperties),
2008
+ get: struct({
2009
+ id: pathId,
2010
+ select: selection,
2011
+ include: includes
2012
+ }),
2013
+ create: createSchema,
2014
+ update: struct({
2015
+ id: pathId,
2016
+ data: updateSchema
2017
+ }),
2018
+ delete: struct({ id: pathId }),
2019
+ count: struct({ where: optional(where) }),
2020
+ exists: struct({ where: optional(where) }),
2021
+ bulkCreate: struct({ items: batch(createSchema) }),
2022
+ bulkUpdate: struct({ items: batch(struct({
2023
+ id: bodyId,
2024
+ data: updateSchema
2025
+ })) }),
2026
+ bulkDelete: struct({ ids: batch(bodyId, true) })
2027
+ };
2028
+ const outputs = {
2029
+ list: struct({
2030
+ items: Schema.Array(rowSchema),
2031
+ total: optional(Schema.Int),
2032
+ limit: Schema.Int,
2033
+ offset: Schema.Int,
2034
+ nextCursor: optional(Schema.NullOr(Schema.String))
2035
+ }),
2036
+ findOne: Schema.NullOr(rowSchema),
2037
+ get: rowSchema,
2038
+ create: rowSchema,
2039
+ update: rowSchema,
2040
+ delete: struct({ success: Schema.Literal(true) }),
2041
+ count: struct({ count: Schema.Int }),
2042
+ exists: struct({ exists: Schema.Boolean }),
2043
+ bulkCreate: struct({ items: Schema.Array(rowSchema) }),
2044
+ bulkUpdate: struct({ items: Schema.Array(rowSchema) }),
2045
+ bulkDelete: struct({ count: Schema.Int })
2046
+ };
2047
+ const resource = service.getResource(name) ?? service.resource({
2048
+ name,
2049
+ table,
2050
+ id: idColumn
2051
+ });
2052
+ const { perform, performBulk, authorize } = operations({
2053
+ service,
2054
+ events: options.events !== false,
2055
+ access,
2056
+ hooks: options.hooks ?? {},
2057
+ resource: {
2058
+ name,
2059
+ table,
2060
+ id: idColumn,
2061
+ idField
2062
+ },
2063
+ fields,
2064
+ columns,
2065
+ readable,
2066
+ defaultLimit,
2067
+ engine: service.database?.engine,
2068
+ hostHooks: () => [resource, service].flatMap((host) => {
2069
+ const hooks = getHostHooks(host);
2070
+ return hooks ? [{
2071
+ hooks,
2072
+ resource
2073
+ }] : [];
2074
+ })
2075
+ });
2076
+ const controls = copyControls(options.routes);
2077
+ for (const { path } of Object.values(methods)) if (/^\/[a-z-]+$/.test(path)) claimSegment(service, resource, path.slice(1), CRUD_PLUGIN);
2078
+ const api = {};
2079
+ const named = /* @__PURE__ */ new Set();
2080
+ const switches = options.operations || {};
2081
+ const enabled = Object.keys(methods).filter((operation) => operation in bulkOperations ? switches[operation] === true : switches[operation] !== false);
2082
+ if (isAuditTable(table) && enabled.some((operation) => writes.has(operation))) throw new Error(`CRUD resource '${name}' is over the audit table, so its writes would let callers forge or delete audit rows. Make it read-only: operations: { create: false, update: false, delete: false }`);
2083
+ for (const operation of enabled) {
2084
+ const bulk = operation in bulkOperations;
2085
+ const { method, path } = methods[operation];
2086
+ named.add(operation);
2087
+ const control = controls === false ? false : controls?.[operation];
2088
+ const mounted = control && control.path || path;
2089
+ validatePath(mounted);
2090
+ const scope = control && control.scope || "resource";
2091
+ const segment = mounted.split("/")[1];
2092
+ if (scope === "resource" && segment && !segment.startsWith(":")) claimSegment(service, resource, segment, CRUD_PLUGIN);
2093
+ const binding = {
2094
+ plugin: CRUD_PLUGIN,
2095
+ service: service.name,
2096
+ resource: name,
2097
+ path: mounted,
2098
+ method,
2099
+ scope,
2100
+ enabled: control !== false,
2101
+ clientPath: [
2102
+ service.name,
2103
+ name,
2104
+ operation
2105
+ ]
2106
+ };
2107
+ const action = service.action({
2108
+ name: `${name}.${operation}`,
2109
+ method,
2110
+ input: inputs[operation],
2111
+ output: outputs[operation],
2112
+ strict: true,
2113
+ audit: writes.has(operation) ? inlineAuditOptions({ resource: name }) : false,
2114
+ checkInput: (input) => whereDepthExceeded(input) ? [{
2115
+ path: "where",
2116
+ message: `Filter nesting exceeds 20 levels`
2117
+ }] : void 0,
2118
+ ...access !== "public" && { authorize: ({ input, ctx }) => bulk ? Effect.succeed(true) : authorize(operation, input, ctx) },
2119
+ execute: ({ input, ctx, error }) => bulk ? performBulk(operation, input, ctx, error) : perform(operation, input, ctx, error)
2120
+ });
2121
+ actionMeta(action).route = binding;
2122
+ const hasScope = typeof access === "object" && typeof access.scope === "function" && operation !== "create" && operation !== "bulkCreate";
2123
+ setActionAccess(action, {
2124
+ hasAuthorize: access !== "public",
2125
+ hasScope,
2126
+ policy: access === "public" ? "public" : hasScope ? "scoped" : "authorized"
2127
+ });
2128
+ api[operation] = action;
2129
+ }
2130
+ if (controls) {
2131
+ for (const key of Object.keys(controls)) if (!named.has(key)) throw new Error(`Plugin '${CRUD_PLUGIN}' has an override for an unknown route`);
2132
+ }
2133
+ return api;
2134
+ }
2135
+ // src/plugin-tables.ts
2136
+ const OWNER = Symbol.for("brickkit.effect.plugin.owner");
2137
+ function setPluginOwner(table, plugin) {
2138
+ Object.defineProperty(table, OWNER, { value: plugin });
2139
+ }
2140
+ /** The plugin that owns a table, for tables a `definePlugin` contributed. */
2141
+ function pluginOwner(table) {
2142
+ return table && typeof table === "object" ? table[OWNER] : void 0;
2143
+ }
2144
+ const sqliteBuilders = {
2145
+ /** A table. Its name gets the plugin's prefix (`page_comments`). */
2146
+ table: (name, columns) => sqliteTable(name, columns),
2147
+ text: (name) => text$1(name),
2148
+ integer: (name) => integer$1(name, { mode: "number" }),
2149
+ real: (name) => real(name),
2150
+ boolean: (name) => integer$1(name, { mode: "boolean" }),
2151
+ /** A `Date`, stored as epoch milliseconds or `timestamptz`. */
2152
+ timestamp: (name) => integer$1(name, { mode: "timestamp_ms" }),
2153
+ json: (name) => text$1(name, { mode: "json" })
2154
+ };
2155
+ function builders(engine, tableName) {
2156
+ if (engine === "postgres") return {
2157
+ engine,
2158
+ table: (name, columns) => pgTable(tableName(name), columns),
2159
+ text: (name) => text(name),
2160
+ integer: (name) => integer(name),
2161
+ real: (name) => doublePrecision(name),
2162
+ boolean: (name) => boolean(name),
2163
+ timestamp: (name) => timestamp(name, {
2164
+ mode: "date",
2165
+ withTimezone: true
2166
+ }),
2167
+ json: (name) => jsonb(name)
2168
+ };
2169
+ return {
2170
+ ...sqliteBuilders,
2171
+ engine,
2172
+ table: (name, columns) => sqliteTable(tableName(name), columns)
2173
+ };
2174
+ }
2175
+ // src/version.ts
2176
+ let runningVersion;
2177
+ /** The version of this @brickkit/effect, read from its package.json; `""` when unknown. */
2178
+ function brickVersion() {
2179
+ if (runningVersion !== void 0) return runningVersion;
2180
+ for (const relative of ["../package.json", "../../package.json"]) try {
2181
+ const json = JSON.parse(readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8"));
2182
+ if (json.name === "@brickkit/effect") return runningVersion = json.version;
2183
+ } catch {}
2184
+ return runningVersion = "";
2185
+ }
2186
+ function parseVersion(version) {
2187
+ const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[-+]/)[0].split(".").map(Number);
2188
+ return [
2189
+ major,
2190
+ minor,
2191
+ patch
2192
+ ];
2193
+ }
2194
+ const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
2195
+ /**
2196
+ * Whether `version` is in a semver `range`: `^0.11.0`, `~0.11.2`, `>=0.11 <0.13`,
2197
+ * `0.11.x`, `*`, and `||` between alternatives. Prerelease tags are ignored.
2198
+ */
2199
+ function satisfiesRange(version, range) {
2200
+ const current = parseVersion(version);
2201
+ return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
2202
+ const match = /^(\^|~|>=|<=|>|<|=)?v?([\dx*]+(?:\.[\dx*]+){0,2})?/i.exec(comparator);
2203
+ const operator = match?.[1] ?? "";
2204
+ const parts = (match?.[2] ?? "*").split(".");
2205
+ const wild = parts.findIndex((part) => /^[x*]$/i.test(part));
2206
+ const given = wild === -1 ? parts.length : wild;
2207
+ const low = parseVersion(parts.slice(0, given).join(".") || "0");
2208
+ if (given === 0) return true;
2209
+ const cmp = compare(current, low);
2210
+ if (operator === ">=") return cmp >= 0;
2211
+ const next = given === 1 ? [
2212
+ low[0] + 1,
2213
+ 0,
2214
+ 0
2215
+ ] : [
2216
+ low[0],
2217
+ low[1] + 1,
2218
+ 0
2219
+ ];
2220
+ if (operator === ">") return given < 3 ? compare(current, next) >= 0 : cmp > 0;
2221
+ if (operator === "<") return cmp < 0;
2222
+ if (operator === "<=") return given < 3 ? compare(current, next) < 0 : cmp <= 0;
2223
+ let high;
2224
+ if (operator === "^") high = low[0] > 0 || given === 1 ? [
2225
+ low[0] + 1,
2226
+ 0,
2227
+ 0
2228
+ ] : low[1] > 0 || given === 2 ? [
2229
+ 0,
2230
+ low[1] + 1,
2231
+ 0
2232
+ ] : [
2233
+ 0,
2234
+ 0,
2235
+ low[2] + 1
2236
+ ];
2237
+ else if (operator === "~" || given < 3) high = given === 1 ? [
2238
+ low[0] + 1,
2239
+ 0,
2240
+ 0
2241
+ ] : [
2242
+ low[0],
2243
+ low[1] + 1,
2244
+ 0
2245
+ ];
2246
+ else return cmp === 0;
2247
+ return cmp >= 0 && compare(current, high) < 0;
2248
+ }));
2249
+ }
2250
+ // src/define-plugin.ts
2251
+ let installCount = 0;
2252
+ const toWords = (name) => (name.split("/").pop() ?? name).replace(/^brick-/, "").replace(/-plugin$/, "").split(/[^a-zA-Z0-9]+/).filter(Boolean);
2253
+ const snake = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
2254
+ /**
2255
+ * Define a plugin: a manifest Brick checks, plus the capabilities the plugin
2256
+ * brings. Install its instances with `resource.use()`, `service.use()` or
2257
+ * `brick({ plugins })`; scope comes from where it is installed.
2258
+ *
2259
+ * @param manifest - `name`, `brick` (semver range), `requires`, `options`
2260
+ * (Schema), `secrets`, `deps`, `tables`, `events`, the `resource`, `service`
2261
+ * and `app` parts, and a `dashboard` extension.
2262
+ * @returns A factory: `comments({ maxLength: 500 })` validates the options and
2263
+ * the Brick version and returns an instance to install.
2264
+ * @throws From the factory, when the running Brick is outside `brick` or an
2265
+ * option is invalid; when installed, when a required plugin is missing or the
2266
+ * host does not suit the plugin.
2267
+ * @example
2268
+ * export const audit = definePlugin({
2269
+ * name: "@acme/brick-audit",
2270
+ * requires: ["@brickkit/crud"],
2271
+ * options: Schema.Struct({
2272
+ * table: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed("audit"))),
2273
+ * }),
2274
+ * tables: ({ table, text, timestamp }) => ({
2275
+ * log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
2276
+ * }),
2277
+ * resource: ({ tables, hooks }) => {
2278
+ * hooks.afterCreate(({ row, tx }) =>
2279
+ * tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
2280
+ * return {};
2281
+ * },
2282
+ * });
2283
+ *
2284
+ * page.use(audit());
2285
+ */
2286
+ function definePlugin(manifest) {
2287
+ const { name } = manifest;
2288
+ if (!name || name.trim() !== name) throw new Error("Plugin and route names must be nonempty and have no surrounding whitespace");
2289
+ if (!manifest.resource && !manifest.service && !manifest.app) throw new Error(`Plugin "${name}" needs a resource, service or app part to install`);
2290
+ for (const [key, schema] of Object.entries(manifest.events ?? {})) {
2291
+ 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`);
2292
+ if (!Schema.isSchema(schema)) throw new Error(`Event "${key}" of plugin "${name}" needs a payload schema, such as Schema.Struct({ ... })`);
2293
+ const at = sensitivePointer(schema);
2294
+ if (at) throw new Error(`Event "${key}" of plugin "${name}" marks '${at}' Sensitive, which event payloads do not support yet; carry an id and load the secret in the listener`);
2295
+ }
2296
+ const site = definitionSite()?.replace(/:\d+$/, "");
2297
+ 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);
2298
+ const words = toWords(name);
2299
+ const tableSpace = snake(words.join("_"));
2300
+ if (!tableSpace) throw new Error(`Plugin "${name}" needs letters or digits in its name`);
2301
+ const info = Object.freeze({
2302
+ name,
2303
+ description: manifest.description,
2304
+ brick: manifest.brick,
2305
+ requires: Object.freeze([...manifest.requires ?? []]),
2306
+ options: manifest.options,
2307
+ secrets: Object.freeze(Object.values(manifest.secrets ?? {}).map((secret) => secret.name)),
2308
+ deps: Object.freeze(Object.keys(manifest.deps ?? {})),
2309
+ capabilities: Object.freeze([
2310
+ "tables",
2311
+ "events",
2312
+ "resource",
2313
+ "service",
2314
+ "app",
2315
+ "dashboard"
2316
+ ].filter((key) => manifest[key] !== void 0))
2317
+ });
2318
+ const camelName = words.map((word, index) => index ? word[0].toUpperCase() + word.slice(1) : word).join("");
2319
+ const factory = (input = {}, install = {}) => {
2320
+ const version = brickVersion();
2321
+ if (manifest.brick && version && !satisfiesRange(version, manifest.brick)) throw new Error(`${name} supports Brick ${manifest.brick}; this app runs ${version}`);
2322
+ const options = checkOptions(name, manifest.options, input);
2323
+ const deps = checkDeps(name, camelName, manifest.deps, install.deps);
2324
+ const secrets = manifest.secrets ?? {};
2325
+ const internals = {
2326
+ manifest,
2327
+ options,
2328
+ deps,
2329
+ install,
2330
+ ...dashboard !== void 0 && { dashboard },
2331
+ installs: []
2332
+ };
2333
+ const setup = (context) => {
2334
+ const { service, resource } = context;
2335
+ const host = resource ?? service;
2336
+ const where = resource ? `resource "${resource.name}"` : `service "${service.name}"`;
2337
+ const part = resource ? manifest.resource : manifest.service;
2338
+ 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 })"}`);
2339
+ for (const required of manifest.requires ?? []) if (!hasPlugin(service, host, required)) throw new Error(`${name} requires ${required}, installed on ${where} before it`);
2340
+ let tables = {};
2341
+ if (manifest.tables) {
2342
+ const { database } = service;
2343
+ if (!database) throw new Error(`${name} owns tables, so service "${service.name}" needs a database`);
2344
+ const prefix = install.prefix ?? `${snake(resource?.name ?? service.name)}_`;
2345
+ tables = manifest.tables(builders(database.engine, (table) => install.prefix !== void 0 || table === tableSpace ? `${prefix}${table}` : `${prefix}${tableSpace}_${table}`));
2346
+ const taken = new Set([...service.listResources().map((item) => item.table), ...Object.values(database.tables)].map((table) => getTableName(table)));
2347
+ for (const table of Object.values(tables)) {
2348
+ const tableName = getTableName(table);
2349
+ if (taken.has(tableName)) throw new Error(`${name} table "${tableName}" clashes with a table service "${service.name}" already has; install it with another prefix`);
2350
+ taken.add(tableName);
2351
+ setPluginOwner(table, name);
2352
+ }
2353
+ }
2354
+ const catalog = service.events;
2355
+ const events = {};
2356
+ for (const [key, schema] of Object.entries(manifest.events ?? {})) {
2357
+ const existing = catalog[`${camelName}.${key}`];
2358
+ if (existing && existing.plugin !== name) throw new Error(`${name} event "${camelName}.${key}" is already in the catalog of service "${service.name}"`);
2359
+ events[key] = existing ?? Object.freeze({
2360
+ name: `${service.name}.${camelName}.${key}`,
2361
+ service: service.name,
2362
+ schema,
2363
+ plugin: name
2364
+ });
2365
+ }
2366
+ const added = {};
2367
+ const hooks = Object.fromEntries(HOOK_NAMES.map((hook) => [hook, (fn) => {
2368
+ if (typeof fn !== "function") throw new Error(`${name}: hooks.${hook} needs a function`);
2369
+ (added[hook] ??= []).push((args) => fn({
2370
+ ...args,
2371
+ ctx: {
2372
+ ...args.ctx,
2373
+ deps
2374
+ }
2375
+ }));
2376
+ }]));
2377
+ const routes = {
2378
+ action: (config) => context.routes.action(config),
2379
+ endpoint: (config) => context.routes.endpoint({
2380
+ ...config,
2381
+ handler: (args) => config.handler({
2382
+ ...args,
2383
+ ctx: {
2384
+ ...args.ctx,
2385
+ deps
2386
+ }
2387
+ })
2388
+ }),
2389
+ claim: (segment) => context.routes.claim(segment)
2390
+ };
2391
+ const before = /* @__PURE__ */ new Set([...service.listActions(), ...service.listTools()]);
2392
+ const started = bindings;
2393
+ const api = part({
2394
+ options,
2395
+ secrets,
2396
+ tables,
2397
+ events,
2398
+ deps,
2399
+ service,
2400
+ resource,
2401
+ routes,
2402
+ hooks
2403
+ });
2404
+ for (const action of [...service.listActions(), ...service.listTools()]) if (!before.has(action)) bindPluginDeps(name, action, deps, started);
2405
+ context[PLUGIN_COMMIT]?.(() => {
2406
+ for (const table of Object.values(tables)) service.database.tables[getTableName(table)] = table;
2407
+ if (Object.keys(events).length) internalsOf(service).addEvents(Object.fromEntries(Object.entries(events).map(([key, ref]) => [`${camelName}.${key}`, ref])));
2408
+ addHostHooks(host, added);
2409
+ internals.installs.push({
2410
+ scope: resource ? "resource" : "service",
2411
+ service: service.name,
2412
+ ...resource && { resource: resource.name }
2413
+ });
2414
+ internals.order ??= ++installCount;
2415
+ });
2416
+ return resource ? api ?? {} : api;
2417
+ };
2418
+ return Object.freeze({
2419
+ [PLUGIN_KIND]: "plugin",
2420
+ name,
2421
+ info,
2422
+ setup,
2423
+ [INTERNALS]: internals
2424
+ });
2425
+ };
2426
+ return Object.assign(factory, { info });
2427
+ }
2428
+ /** Counts bindings, so a setup can tell a nested install's from an earlier one's. */
2429
+ let bindings = 0;
2430
+ /**
2431
+ * Run an action with the plugin's deps as `ctx.deps`: the action reads them
2432
+ * from its metadata. A nested definePlugin binds its own actions first, so they
2433
+ * keep its deps.
2434
+ *
2435
+ * @throws When the action is already bound to another install's deps: one
2436
+ * action object shared by two installs could only run with one of them.
2437
+ */
2438
+ function bindPluginDeps(plugin, action, deps, started) {
2439
+ const meta = actionMeta(action);
2440
+ if (meta.deps) {
2441
+ if (meta.deps.values === deps || meta.deps.at > started) return;
2442
+ 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`);
2443
+ }
2444
+ meta.deps = {
2445
+ values: deps,
2446
+ at: ++bindings
2447
+ };
2448
+ }
2449
+ function checkDeps(plugin, camelName, declaredDeps, given = {}) {
2450
+ if (given === null || typeof given !== "object" || Array.isArray(given)) throw new Error(`${plugin}: deps must be an object`);
2451
+ const declared = Object.keys(declaredDeps ?? {});
2452
+ const provided = given;
2453
+ const extra = Object.keys(provided).filter((key) => !declared.includes(key));
2454
+ 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"}`);
2455
+ const missing = declared.filter((key) => provided[key] === void 0);
2456
+ if (missing.length) throw new Error(`${plugin} needs ${missing.map((key) => `deps.${key}`).join(", ")}; pass it when installing: ${camelName}(options, { deps: { ${missing.join(", ")} } })`);
2457
+ return freezeAsBuiltDeps(Object.fromEntries(declared.map((key) => [key, provided[key]])));
2458
+ }
2459
+ function checkOptions(plugin, schema, input) {
2460
+ if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error(`${plugin}: options must be an object`);
2461
+ if (!schema) {
2462
+ if (Object.keys(input).length) throw new Error(`${plugin} takes no options`);
2463
+ return {};
2464
+ }
2465
+ try {
2466
+ return Schema.decodeUnknownSync(schema)(input);
2467
+ } catch (error) {
2468
+ if (!Schema.isSchemaError(error)) throw error;
2469
+ const [first] = SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues;
2470
+ const option = (first?.path ?? []).map((item) => String(typeof item === "object" && item !== null && "key" in item ? item.key : item)).join(".");
2471
+ throw new Error(`${plugin}: option ${option ? `"${option}"` : ""} ${first?.message ?? "is invalid"}`.replace(/\s+/g, " "));
2472
+ }
2473
+ }
2474
+ // src/app-entry.ts
2475
+ /**
2476
+ * Whether a value is an app made by `brick()`. It checks for the methods and
2477
+ * `definition` a `BrickApp` has, so it also recognizes one built by another copy
2478
+ * of the package.
2479
+ *
2480
+ * @param app - Anything, such as the default export of an entry file.
2481
+ */
2482
+ function isBrickApp(app) {
2483
+ if (!app || typeof app !== "object") return false;
2484
+ const { fetch, listen, definition } = app;
2485
+ return typeof fetch === "function" && typeof listen === "function" && !!definition && typeof definition === "object" && Array.isArray(definition.services) && typeof definition.prefix === "string";
2486
+ }
2487
+ /**
2488
+ * Check that a module's default export is an app ready to be served, for tools
2489
+ * that load an entry file.
2490
+ *
2491
+ * @throws When it is not a `BrickApp`, or it already called `.listen()`: the
2492
+ * entry must only build the app, and leave listening to the server bootstrap.
2493
+ */
2494
+ function requireBrickApp(app) {
2495
+ if (!isBrickApp(app)) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
2496
+ if (app.server) throw new Error("Brick: the app entry must not call .listen(); use a separate server bootstrap.");
2497
+ return app;
2498
+ }
2499
+ export { ATTR, Activity, BrickError, DASHBOARD_IDENTITY_HEADER, DASHBOARD_KEY_ENV, DASHBOARD_MCP_ROUTE, DASHBOARD_MCP_TOOLS, DEFAULT_PREFIX, DuplicateNameError, DurableClock, DurableDeferred, Events, GLOBAL_SYMBOL, HOOK_NAMES, HTTP_METHODS, LOCAL_FILES_ROUTE, OPENAPI_DEFAULTS, SPAN, STANDARD_ERRORS, SecretRef, Sensitive, SocketDenied, SpanStore, StorageError, StorageUnavailableError, Telemetry, UnknownToolError, UploadedFile, UploadedFiles, ValidationError, WORKFLOW_TABLE, Workflow, WorkflowEngine, actionOwners, actorOf, addHostHooks, auditTable, brick, buildFtsMatchQuery, clientAddress, columnValue, createLogger, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, crud, crudEventName, crudEventSource, dashboardIdentity, dashboardKey, dashboardMcpCaller, dashboardUser, defineAction, defineDatabase, defineEvents, defineListener, definePlugin, defineResource, defineResourcePlugin, defineSchedule, defineSecret, defineService, defineServicePlugin, defineStorage, defineTool, emitEvent, ensureResourceIndexes, ensureSQLiteFts, envSource, exportArchitecture, frameworkStorage, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getActionRoute, getGlobalRegistry, getHostHooks, getPluginActionRoute, getPluginEndpoints, hasSensitive, hmacSignature, idSchema, isAuditTable, isBrickApp, isCrudEvent, isDatabaseHandle, isTool, isWebhook, kebabCase, listSecrets, loadRecord, localBroker, markDashboardArrival, memory, migrateDatabase, normalizeDashboard, onTransactionCommit, outboxTable, overrideSecret, pluginOwner, recordAudit, recordWebhook, redact, redis, redisBroker, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveSecrets, runInTransaction, runStages, s3, satisfiesRange, scalarDocsHTML, scheduleTable, setActionAccess, setActionAudit, signDashboardIdentity, signDashboardMcp, spanStore, stagesOf, standardWebhooks, stopAllEvents, storageKey, syncSchema, telemetryLayer, toErrorResponse, toWireError, traceRoute, traceScheduleRun, twilioSignature, useDeps, useService, workflowEngine };
2500
+
2501
+ //# sourceMappingURL=index.js.map