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