@brickkit/effect 0.16.0-beta.8 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- import { Cause, Clock, Context, Data, Deferred, Duration, Effect, Exit, Fiber, FiberMap, Layer, ManagedRuntime, Option, Result, Schedule, Schema, SchemaIssue, SchemaTransformation, Scope, Semaphore, Tracer } from "effect";
2
- import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
1
+ import { Cause, Clock, Context, Data, Deferred, Duration, Effect, Exit, Fiber, FiberMap, Layer, ManagedRuntime, Option, Result, Schedule, Schema, SchemaAST, SchemaIssue, SchemaTransformation, Scope, Semaphore, Tracer } from "effect";
2
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { formatWithOptions, inspect } from "node:util";
5
5
  import { FetchHttpClient, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
6
6
  import { OtlpSerialization, OtlpTracer } from "effect/observability";
7
7
  import { Statement } from "effect/sql";
8
8
  import { and, asc, eq, getTableColumns, inArray, isNull, like, lt, lte, or, sql } from "drizzle-orm";
9
- import { bigserial, index, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
9
+ import { bigint, bigserial, index, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
10
10
  import { index as index$1, integer as integer$1, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
11
11
  import { lstat, mkdir, readFile, realpath, rm } from "node:fs/promises";
12
12
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
@@ -45,6 +45,12 @@ const STANDARD_ERRORS = {
45
45
  message: "Internal Server Error"
46
46
  }
47
47
  };
48
+ /** What a request answers when its work was interrupted and nothing failed: nginx's 499. Not a server fault, so it is not logged as one or counted as a 5xx. */
49
+ const CLIENT_CLOSED_REQUEST = {
50
+ code: "CLIENT_CLOSED_REQUEST",
51
+ status: 499,
52
+ message: "Client Closed Request"
53
+ };
48
54
  /** A declared failure of an action: a `code`, an HTTP `status`, and optional `details`. */
49
55
  var BrickError = class extends Data.TaggedError("BrickError") {};
50
56
  /** The input (400) or output (500) of an action did not match its schema. */
@@ -55,18 +61,119 @@ var ValidationError = class extends Data.TaggedError("ValidationError") {
55
61
  var DuplicateNameError = class extends Error {
56
62
  name = "DuplicateNameError";
57
63
  };
58
- const isFailure = (value) => value instanceof BrickError || value instanceof ValidationError;
64
+ /**
65
+ * Whether `value` is an error of core's class `name`, or of a subclass: core's
66
+ * `instanceof`, without importing core (a second copy of core has its own
67
+ * classes). Core sets `name` in its constructors, which a minifier cannot
68
+ * rename, so that settles it for an `Error`. A class name does not survive
69
+ * minification, so the prototype chain is only the fallback for a subclass that
70
+ * sets its own `name`.
71
+ */
72
+ const inheritsFrom = (value, name) => {
73
+ if (value instanceof Error && value.name === name) return true;
74
+ for (let at = Object.getPrototypeOf(value); at; at = Object.getPrototypeOf(at)) if (Object.hasOwn(at, "constructor") && at.constructor?.name === name) return true;
75
+ return false;
76
+ };
77
+ const isHttpStatus = (status) => Number.isInteger(status) && status >= 400 && status < 600;
78
+ const isIssue = (item) => item !== null && typeof item === "object" && typeof item.path === "string" && typeof item.message === "string";
79
+ /** The `name` of the core error a failure stands for, as core answers the error's `name`. */
80
+ const names = /* @__PURE__ */ new WeakMap();
81
+ function named(failure, core) {
82
+ const { name } = core;
83
+ if (typeof name === "string") names.set(failure, name);
84
+ return failure;
85
+ }
86
+ /**
87
+ * The failure `value` stands for, or `undefined`. Besides this package's own
88
+ * errors it takes an error of `@brickkit/core`, which core answers with its code,
89
+ * status and details wherever it came from: an `ActionExecutionError` (or a
90
+ * subclass of it) with a string `code` and `message` and a 4xx or 5xx `status`,
91
+ * and a `ValidationError` with its `errors`. Core checks the class and nothing
92
+ * else, so any other value that carries a `status` (an Elysia or third-party
93
+ * error, a plain `Error`) is not one.
94
+ */
95
+ function asFailure(value) {
96
+ if (value instanceof BrickError || value instanceof ValidationError) return value;
97
+ if (value === null || typeof value !== "object") return void 0;
98
+ const { code, message, status, details, errors } = value;
99
+ if (typeof message !== "string" || !isHttpStatus(status)) return void 0;
100
+ if (inheritsFrom(value, "ActionExecutionError") && typeof code === "string") return named(new BrickError({
101
+ code,
102
+ message,
103
+ status,
104
+ details,
105
+ cause: value
106
+ }), value);
107
+ if (inheritsFrom(value, "ValidationError") && code === "VALIDATION_FAILED" && Array.isArray(errors) && errors.every(isIssue)) return named(new ValidationError({
108
+ cause: value,
109
+ message,
110
+ status,
111
+ errors: errors.map(({ path, message, type }) => ({
112
+ path,
113
+ message,
114
+ ...typeof type === "number" && { type }
115
+ }))
116
+ }), value);
117
+ }
118
+ /** The first failure in `cause`, typed or a defect, that `asFailure` recognises. */
119
+ function failureOfCause(cause) {
120
+ for (const reason of cause.reasons) {
121
+ const failure = asFailure(Cause.isFailReason(reason) ? reason.error : Cause.isDieReason(reason) ? reason.defect : void 0);
122
+ if (failure) return failure;
123
+ }
124
+ }
125
+ /** The 500s `toFailure` built: named `InternalServerError`, as core names its own. */
126
+ const built$1 = /* @__PURE__ */ new WeakSet();
127
+ /** The 5xx failures already logged, so they are logged once. */
128
+ const logged$1 = /* @__PURE__ */ new WeakSet();
129
+ /**
130
+ * A copy of `failure` with other `message` and `details`, which is the same
131
+ * failure as far as its name and its logging go. The copy leaves out the
132
+ * `cause`: it was logged with `failure`, and holds what the caller redacted.
133
+ */
134
+ function redactedCopy(failure, { message, details }) {
135
+ const copy = failure instanceof ValidationError ? new ValidationError({
136
+ message,
137
+ status: failure.status,
138
+ errors: failure.errors
139
+ }) : new BrickError({
140
+ code: failure.code,
141
+ status: failure.status,
142
+ message,
143
+ details
144
+ });
145
+ const name = names.get(failure);
146
+ if (name !== void 0) names.set(copy, name);
147
+ if (built$1.has(failure)) built$1.add(copy);
148
+ if (logged$1.has(failure)) logged$1.add(copy);
149
+ return copy;
150
+ }
151
+ /**
152
+ * `prefixed` stands for `failure` with a longer message. Core logs the error a nested action passes through
153
+ * once, when it is answered, and the one it built after an unexpected throw twice, so only the first
154
+ * carries its log over.
155
+ */
156
+ function prefixedFailure(failure, prefixed) {
157
+ if (logged$1.has(failure) && !built$1.has(failure)) logged$1.add(prefixed);
158
+ return prefixed;
159
+ }
160
+ /** Logs a recognised failure with status 500 or more, as core does, once. */
161
+ function logServerFailure(failure, cause, { logger, requestId }) {
162
+ if (failure.status < 500 || logged$1.has(failure)) return;
163
+ logged$1.add(failure);
164
+ logger.error("Server action error", { requestId }, Cause.pretty(cause));
165
+ }
59
166
  /** A failure as JSON. A failed output check (status 500) leaves out its `errors`, which describe internals. */
60
167
  function toWireError(error) {
61
168
  if (error instanceof ValidationError) return {
62
- name: "ValidationError",
169
+ name: names.get(error) ?? "ValidationError",
63
170
  code: error.code,
64
171
  message: error.message,
65
172
  status: error.status,
66
173
  ...error.status < 500 && { errors: [...error.errors] }
67
174
  };
68
175
  return {
69
- name: error.code === "INTERNAL_SERVER_ERROR" ? "InternalServerError" : "ActionExecutionError",
176
+ name: names.get(error) ?? (built$1.has(error) ? "InternalServerError" : "ActionExecutionError"),
70
177
  code: error.code,
71
178
  message: error.message,
72
179
  status: error.status,
@@ -74,31 +181,42 @@ function toWireError(error) {
74
181
  };
75
182
  }
76
183
  /**
77
- * The failure a cause stands for: a declared one is kept; anything else (an
78
- * unknown failure or a defect) is logged and becomes `INTERNAL_SERVER_ERROR`
184
+ * The failure a cause stands for: a declared one, or a core error (see
185
+ * `asFailure`), is kept; anything else (an unknown failure or a defect) is logged and becomes `INTERNAL_SERVER_ERROR`
79
186
  * (500), with the cause kept out of the result.
80
187
  */
81
188
  function toFailure(cause, { logger, requestId }) {
82
- const found = Cause.findError(cause);
83
- if (Result.isSuccess(found) && isFailure(found.success)) return found.success;
189
+ const known = failureOfCause(cause);
190
+ if (known) {
191
+ logServerFailure(known, cause, {
192
+ logger,
193
+ requestId
194
+ });
195
+ return known;
196
+ }
84
197
  logger.error("Unexpected action error", { requestId }, Cause.pretty(cause));
85
- return new BrickError({
198
+ const failure = new BrickError({
86
199
  ...STANDARD_ERRORS.INTERNAL_SERVER_ERROR,
87
- code: "INTERNAL_SERVER_ERROR"
200
+ code: "INTERNAL_SERVER_ERROR",
201
+ cause: Cause.squash(cause)
88
202
  });
203
+ built$1.add(failure);
204
+ logged$1.add(failure);
205
+ return failure;
89
206
  }
90
207
  /** Turns whatever fails in `self` into a declared failure, except interruption. */
91
208
  const normalizeFailures = (context) => (self) => Effect.catchCause(self, (cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.fail(toFailure(cause, context)));
92
209
  /**
93
210
  * The JSON body of a failed HTTP call. Declared failures and validation errors
94
- * keep their code, status and details; anything else is logged and answered as a
95
- * generic `INTERNAL_SERVER_ERROR` (500), so internals are never exposed.
211
+ * keep their code, status and details; a cause of interrupts alone is answered
212
+ * as `CLIENT_CLOSED_REQUEST` (499) and not logged; anything else is logged and
213
+ * answered as a generic `INTERNAL_SERVER_ERROR` (500), so internals are never exposed.
96
214
  */
97
215
  function toErrorResponse(cause, context) {
98
- const failure = toFailure(cause, context);
99
- if (failure.status >= 500 && failure.code !== "INTERNAL_SERVER_ERROR") context.logger.error("Server action error", { requestId: context.requestId }, Cause.pretty(cause));
216
+ const known = failureOfCause(cause);
217
+ if (known) logServerFailure(known, cause, context);
100
218
  return {
101
- ...toWireError(failure),
219
+ ...toWireError(known ?? (Cause.hasInterruptsOnly(cause) ? new BrickError(CLIENT_CLOSED_REQUEST) : toFailure(cause, context))),
102
220
  requestId: context.requestId ?? ""
103
221
  };
104
222
  }
@@ -339,7 +457,6 @@ const truncate = (text, limit = MAX_TEXT_LENGTH) => text.length > limit ? `${tex
339
457
  const toMs = (nanos) => Number(nanos) / 1e6;
340
458
  const nowNanos = () => BigInt(Math.round((performance.timeOrigin + performance.now()) * 1e6));
341
459
  const messageOf = (error) => error instanceof Error ? error.message : String(error);
342
- const isHandled = (error) => error instanceof BrickError || error instanceof ValidationError;
343
460
  /** A span of the app's tracer: records what the dashboard reads when it starts and ends, and hands it to the OTLP tracer when there is one. */
344
461
  var BrickSpan = class extends Tracer.NativeSpan {
345
462
  #sql;
@@ -409,8 +526,8 @@ var BrickSpan = class extends Tracer.NativeSpan {
409
526
  }
410
527
  #record(cause, endTime) {
411
528
  const found = Cause.findError(cause);
412
- const error = Result.isSuccess(found) ? found.success : void 0;
413
- if (isHandled(error)) {
529
+ const error = failureOfCause(cause);
530
+ if (error) {
414
531
  super.attribute(ATTR.errorCode, error.code);
415
532
  super.attribute(ATTR.errorStatus, error.status);
416
533
  super.attribute(ATTR.errorMessage, truncate(error.message));
@@ -2126,6 +2243,30 @@ function rateLimitStage(config, service) {
2126
2243
  })
2127
2244
  };
2128
2245
  }
2246
+ // src/omit-undefined.ts
2247
+ const isPlain = (value) => {
2248
+ if (typeof value !== "object" || value === null) return false;
2249
+ const proto = Object.getPrototypeOf(value);
2250
+ return proto === Object.prototype || proto === null;
2251
+ };
2252
+ /**
2253
+ * The value without the keys of plain objects that hold `undefined`, as
2254
+ * `JSON.stringify` and so core drop them. Schemas encode an `undefined` to
2255
+ * `null`, so a handler's `{ domain: row.domain ?? undefined }` would put
2256
+ * `"domain": null` on the wire. Array items, class instances, `Date` and the
2257
+ * rest are left as they are.
2258
+ */
2259
+ const omitUndefined = (value) => {
2260
+ if (Array.isArray(value)) return value.map(omitUndefined);
2261
+ if (!isPlain(value)) return value;
2262
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).map(([key, item]) => [key, omitUndefined(item)]));
2263
+ };
2264
+ /**
2265
+ * Runs `run` on the value without its undefined keys. A schema that requires
2266
+ * such a key (`Schema.UndefinedOr`) refuses that, so it then runs on the value
2267
+ * as it came, and the key encodes as `null`.
2268
+ */
2269
+ const omittingUndefined = (run) => (value) => run(omitUndefined(value)).pipe(Effect.catch(() => run(value)));
2129
2270
  // src/sensitive.ts
2130
2271
  const MARK = "brickSensitive";
2131
2272
  /**
@@ -2151,7 +2292,7 @@ const holdsMark = (ast, seen = /* @__PURE__ */ new Set()) => {
2151
2292
  if (isMarked(ast)) return true;
2152
2293
  return (ast._tag === "Objects" ? [...ast.propertySignatures.map(({ type }) => type), ...ast.indexSignatures.map(({ type }) => type)] : ast._tag === "Arrays" ? [...ast.elements, ...ast.rest] : ast._tag === "Union" ? ast.types : ast._tag === "Suspend" ? [ast.thunk()] : ast._tag === "Declaration" ? ast.typeParameters : []).some((child) => holdsMark(child, seen));
2153
2294
  };
2154
- function collect(ast, segments, optional, walk) {
2295
+ function collect$1(ast, segments, optional, walk) {
2155
2296
  if (isMarked(ast)) {
2156
2297
  walk.paths.push({
2157
2298
  segments,
@@ -2164,11 +2305,11 @@ function collect(ast, segments, optional, walk) {
2164
2305
  return;
2165
2306
  }
2166
2307
  if (ast._tag === "Union") {
2167
- for (const branch of ast.types) collect(branch, segments, optional, walk);
2308
+ for (const branch of ast.types) collect$1(branch, segments, optional, walk);
2168
2309
  return;
2169
2310
  }
2170
2311
  if (ast._tag === "Declaration") {
2171
- for (const part of ast.typeParameters) collect(part, segments, optional, walk);
2312
+ for (const part of ast.typeParameters) collect$1(part, segments, optional, walk);
2172
2313
  return;
2173
2314
  }
2174
2315
  if (ast._tag === "Objects") {
@@ -2180,9 +2321,9 @@ function collect(ast, segments, optional, walk) {
2180
2321
  segments: here,
2181
2322
  required: !absentable
2182
2323
  });
2183
- collect(type, here, absentable, walk);
2324
+ collect$1(type, here, absentable, walk);
2184
2325
  }
2185
- for (const { type } of ast.indexSignatures) collect(type, [...segments, declared.length ? { except: declared } : null], true, walk);
2326
+ for (const { type } of ast.indexSignatures) collect$1(type, [...segments, declared.length ? { except: declared } : null], true, walk);
2186
2327
  return;
2187
2328
  }
2188
2329
  if (ast._tag === "Arrays") {
@@ -2192,7 +2333,7 @@ function collect(ast, segments, optional, walk) {
2192
2333
  segments: [...segments, segment],
2193
2334
  required: true
2194
2335
  });
2195
- collect(item, [...segments, segment], false, walk);
2336
+ collect$1(item, [...segments, segment], false, walk);
2196
2337
  }
2197
2338
  }
2198
2339
  }
@@ -2204,7 +2345,7 @@ function analyze(ast) {
2204
2345
  paths: [],
2205
2346
  publics: []
2206
2347
  };
2207
- collect(ast, [], false, analysis);
2348
+ collect$1(ast, [], false, analysis);
2208
2349
  analyses.set(ast, analysis);
2209
2350
  }
2210
2351
  return analysis;
@@ -2482,11 +2623,9 @@ function sensitiveStage(config, owner) {
2482
2623
  logger: call.ctx.logger,
2483
2624
  requestId: call.ctx.requestId
2484
2625
  });
2485
- return Effect.fail(failure instanceof BrickError ? new BrickError({
2486
- code: failure.code,
2487
- status: failure.status,
2626
+ return Effect.fail(failure instanceof BrickError || failure instanceof ValidationError ? redactedCopy(failure, {
2488
2627
  message: redactText(set, failure.message),
2489
- details: redactDetails(set, failure.details)
2628
+ details: failure instanceof BrickError ? redactDetails(set, failure.details) : void 0
2490
2629
  }) : failure);
2491
2630
  }), Effect.provideService(Redactions, set));
2492
2631
  const paths = (call.wire ? wireOutputs : outputs)?.paths;
@@ -2508,6 +2647,184 @@ function sensitiveStage(config, owner) {
2508
2647
  })
2509
2648
  };
2510
2649
  }
2650
+ // src/validation-issues.ts
2651
+ const stock = SchemaIssue.makeFormatterStandardSchemaV1();
2652
+ /** The message Effect would give a leaf or a filter, for what has no core wording. */
2653
+ const stockMessage = (issue) => stock(issue).issues[0]?.message ?? "Expected a valid value";
2654
+ const hasCheck = (ast, expected) => ast.checks?.some((check) => check.annotations?.expected === expected) ?? false;
2655
+ const unit = (ast) => ast?._tag === "Number" && hasCheck(ast, "an integer") ? "integer" : "number";
2656
+ /** The message of a value of the wrong type, as core words it; `undefined` for a type core has no wording for. */
2657
+ function typeMessage(ast) {
2658
+ switch (ast._tag) {
2659
+ case "String": return "Expected string";
2660
+ case "Number": return `Expected ${unit(ast)}`;
2661
+ case "Boolean": return "Expected boolean";
2662
+ case "Arrays": return ast.rest.length === 0 ? "Expected tuple" : "Expected array";
2663
+ case "Objects": return "Expected object";
2664
+ case "Null": return "Expected null";
2665
+ case "Undefined": return "Expected undefined";
2666
+ case "Literal": return `Expected ${typeof ast.literal === "string" ? `'${ast.literal}'` : String(ast.literal)}`;
2667
+ case "Union": {
2668
+ const rest = ast.types.filter((type) => type._tag !== "Undefined");
2669
+ return rest.length === 1 && ast.types.length === 2 ? typeMessage(rest[0]) : "Expected union value";
2670
+ }
2671
+ default: return;
2672
+ }
2673
+ }
2674
+ const bound = (word, orEqual) => `${word}${orEqual ? " or equal to" : " than"}`;
2675
+ /** The message of a failed check, as core words it; `undefined` for a check core has no wording for. */
2676
+ function checkMessage(issue, parent) {
2677
+ const custom = SchemaIssue.defaultCheckHook(issue);
2678
+ if (custom !== void 0) return custom;
2679
+ const expected = issue.filter.annotations?.expected;
2680
+ if (typeof expected !== "string") return void 0;
2681
+ const kind = parent?._tag;
2682
+ let match = /^a value with a length of at (least|most) (\d+)$/.exec(expected);
2683
+ if (match) {
2684
+ const cmp = bound(match[1] === "least" ? "greater" : "less", true);
2685
+ if (kind === "String") return `Expected string length ${cmp} ${match[2]}`;
2686
+ if (kind === "Arrays") return `Expected array length to be ${cmp} ${match[2]}`;
2687
+ return;
2688
+ }
2689
+ if (kind === "Number") {
2690
+ match = /^a value (greater|less) than( or equal to)? (.+)$/.exec(expected);
2691
+ if (match) return `Expected ${unit(parent)} to be ${bound(match[1], Boolean(match[2]))} ${match[3]}`;
2692
+ match = /^a value that is a multiple of (.+)$/.exec(expected);
2693
+ if (match) return `Expected ${unit(parent)} to be a multiple of ${match[1]}`;
2694
+ if (expected === "an integer") return "Expected integer";
2695
+ }
2696
+ if (kind === "String") {
2697
+ match = /^a string matching the RegExp (.+)$/.exec(expected);
2698
+ if (match) return `Expected string to match '${match[1]}'`;
2699
+ if (expected === "a UUID") return "Expected string to match 'uuid' format";
2700
+ }
2701
+ if (kind === "Arrays" && expected === "an array with unique items") return "Expected array elements to be unique";
2702
+ }
2703
+ const notUndefined = (issue) => !(issue._tag === "InvalidType" && issue.ast._tag === "Undefined");
2704
+ const isMissing = (issue) => issue._tag === "Pointer" && issue.issue._tag === "MissingKey";
2705
+ const isExtra = (issue) => issue._tag === "Pointer" && issue.issue._tag === "UnexpectedKey";
2706
+ const onlyExtraKeys = (issue) => {
2707
+ switch (issue._tag) {
2708
+ case "UnexpectedKey": return true;
2709
+ case "Pointer":
2710
+ case "Filter":
2711
+ case "Encoding": return onlyExtraKeys(issue.issue);
2712
+ case "Composite": return issue.issues.length > 0 && issue.issues.every(onlyExtraKeys);
2713
+ default: return false;
2714
+ }
2715
+ };
2716
+ const expectedOf = (issue) => issue._tag === "Filter" ? issue.filter.annotations?.expected : void 0;
2717
+ const filtersOf = (checks) => checks.flatMap((check) => check._tag === "FilterGroup" ? filtersOf(check.checks) : [check]);
2718
+ const valueAt = (input, path) => path.reduce((value, key) => value?.[key], input);
2719
+ /**
2720
+ * The children of a Composite issue on a number or an array, in TypeBox's order.
2721
+ * TypeBox stops at a failed integer check; Effect also reports the bounds.
2722
+ * Effect skips an array's own checks once an item fails; TypeBox reports the
2723
+ * lengths first and uniqueness last.
2724
+ */
2725
+ function childrenOf(issue, path, input) {
2726
+ const { ast } = issue;
2727
+ if (ast._tag === "Number") {
2728
+ const integer = issue.issues.filter((child) => expectedOf(child) === "an integer");
2729
+ return integer.length ? integer : issue.issues;
2730
+ }
2731
+ const value = valueAt(input, path);
2732
+ if (ast._tag !== "Arrays" || !Array.isArray(value) || issue.issues.some((child) => child._tag === "Filter")) return issue.issues;
2733
+ const known = (check) => /^a value with a length of at (least|most) \d+$|^an array with unique items$/.test(check.annotations?.expected);
2734
+ const failed = filtersOf(ast.checks ?? []).filter(known).flatMap((check) => {
2735
+ const found = check.run(value, ast, { errors: "all" });
2736
+ return found ? [new SchemaIssue.Filter(check, found, value, {})] : [];
2737
+ });
2738
+ const unique = (child) => expectedOf(child) === "an array with unique items";
2739
+ return [
2740
+ ...failed.filter((child) => !unique(child)),
2741
+ ...issue.issues,
2742
+ ...failed.filter(unique)
2743
+ ];
2744
+ }
2745
+ function collect(issue, path, parent, override, out, phase) {
2746
+ const add = (message) => {
2747
+ out.items.push({
2748
+ path,
2749
+ message
2750
+ });
2751
+ };
2752
+ switch (issue._tag) {
2753
+ case "Filter": return collect(issue.issue, path, parent, override ?? checkMessage(issue, parent) ?? stockMessage(issue), out);
2754
+ case "Encoding": {
2755
+ const message = (issue.ast._tag === "Number" || issue.ast._tag === "Boolean") && typeof issue.ast.annotations?.message !== "string" ? typeMessage(issue.ast) : void 0;
2756
+ if (message !== void 0) return add(override ?? message);
2757
+ return collect(issue.issue, path, parent, override, out);
2758
+ }
2759
+ case "Pointer": return collect(issue.issue, [...path, ...issue.path], parent, override, out, phase);
2760
+ case "Composite": {
2761
+ if (issue.ast._tag !== "Objects") {
2762
+ const { ast } = issue;
2763
+ const value = valueAt(out.input, path);
2764
+ if (ast._tag === "Arrays" && ast.rest.length === 0 && Array.isArray(value) && value.length !== ast.elements.length) return add(override ?? `Expected tuple to have ${ast.elements.length} elements`);
2765
+ for (const child of childrenOf(issue, path, out.input)) collect(child, path, ast, override, out);
2766
+ return;
2767
+ }
2768
+ if (out.extras === "rootOnly") {
2769
+ if (path.length === 0) for (const child of issue.issues.filter(isExtra)) collect(child, path, issue.ast, override, out);
2770
+ return;
2771
+ }
2772
+ const missing = issue.issues.filter((child) => isMissing(child));
2773
+ const extra = issue.issues.filter((child) => isExtra(child));
2774
+ for (const child of missing) collect(child, path, issue.ast, override, out, "required");
2775
+ if (out.extras !== "ignoreNested" || path.length === 0) for (const child of extra) collect(child, path, issue.ast, override, out);
2776
+ for (const child of issue.issues) if (!extra.includes(child)) collect(child, path, issue.ast, override, out, isMissing(child) ? "type" : void 0);
2777
+ return;
2778
+ }
2779
+ case "AnyOf": {
2780
+ const failedOnlyOnExtraKeys = issue.issues.some(onlyExtraKeys);
2781
+ if (out.extras === "ignoreNested" && failedOnlyOnExtraKeys) return;
2782
+ if (override !== void 0) return add(override);
2783
+ if (typeof issue.ast.annotations?.message === "string") return add(stockMessage(issue));
2784
+ const { types } = issue.ast;
2785
+ if (types.length === 2 && types.some((type) => type._tag === "Undefined")) {
2786
+ const issues = issue.issues.filter(notUndefined);
2787
+ if (issues.length) return issues.forEach((child) => collect(child, path, parent, override, out));
2788
+ }
2789
+ return add(typeMessage(issue.ast) ?? stockMessage(issue));
2790
+ }
2791
+ case "InvalidType": return add(override ?? (typeof issue.ast.annotations?.message === "string" ? void 0 : typeMessage(issue.ast)) ?? stockMessage(issue));
2792
+ case "MissingKey": {
2793
+ if (override !== void 0 || typeof issue.annotations?.messageMissingKey === "string") return phase === "type" ? void 0 : add(override ?? stockMessage(issue));
2794
+ if (phase !== "type") add("Expected required property");
2795
+ if (phase === "required") return;
2796
+ const key = path[path.length - 1];
2797
+ const property = parent?._tag === "Objects" ? parent.propertySignatures.find((item) => item.name === key) : void 0;
2798
+ const message = property && typeMessage(property.type);
2799
+ if (message) add(message);
2800
+ return;
2801
+ }
2802
+ case "UnexpectedKey": return add(override ?? (typeof issue.ast.annotations?.messageUnexpectedKey === "string" ? stockMessage(issue) : "Unexpected property"));
2803
+ default: return add(override ?? stockMessage(issue));
2804
+ }
2805
+ }
2806
+ const pointer = (path) => path.map((item) => String(typeof item === "object" && item !== null && "key" in item ? item.key : item).replaceAll("~", "~0").replaceAll("/", "~1")).map((key) => `/${key}`).join("");
2807
+ /**
2808
+ * The `{ path, message }` items of a schema failure, worded as `@brickkit/core`
2809
+ * words TypeBox's: a missing key is "Expected required property" and then the
2810
+ * type of the absent value, an extra key is "Unexpected property", and string,
2811
+ * number and array bounds, patterns, literals and unions use TypeBox's text.
2812
+ * Paths are JSON pointers, and messages never carry the rejected value.
2813
+ * A custom `message` annotation wins; a check or schema core has no wording for
2814
+ * keeps Effect's own text.
2815
+ */
2816
+ function issuesOf(error, input, options) {
2817
+ const out = {
2818
+ input,
2819
+ items: [],
2820
+ ...options
2821
+ };
2822
+ collect(error.issue, [], void 0, void 0, out);
2823
+ return out.items.map(({ path, message }) => ({
2824
+ path: pointer(path),
2825
+ message
2826
+ }));
2827
+ }
2511
2828
  // src/action.ts
2512
2829
  /** The HTTP methods an action can use. */
2513
2830
  const HTTP_METHODS = [
@@ -2531,14 +2848,6 @@ function errorHelpers(errors) {
2531
2848
  }));
2532
2849
  return helpers;
2533
2850
  }
2534
- const pointer = (path) => path.map((item) => String(typeof item === "object" && item !== null && "key" in item ? item.key : item)).map((key) => `/${key}`).join("");
2535
- /** The `{ path, message }` items of a schema failure. Paths are JSON pointers, as in core; messages never carry the rejected value. */
2536
- function issuesOf(error) {
2537
- return SchemaIssue.makeFormatterStandardSchemaV1()(error.issue).issues.map(({ path, message }) => ({
2538
- path: pointer(path ?? []),
2539
- message
2540
- }));
2541
- }
2542
2851
  /** The error for input (400) or output (500) that fails its schema. */
2543
2852
  function invalid$1(action, stage, errors) {
2544
2853
  return new ValidationError({
@@ -2572,7 +2881,8 @@ function stagesOf(config, host, action) {
2572
2881
  value: Schema.decodeUnknownEffect(Schema.toType(input)),
2573
2882
  json: Schema.decodeUnknownEffect(Schema.toCodecJson(input)),
2574
2883
  query: Schema.decodeUnknownEffect(Schema.toCodecArrayFromSingle(Schema.toCodecStringTree(input))),
2575
- form: formDecoder(input)
2884
+ form: formDecoder(input),
2885
+ absent: Schema.decodeUnknownEffect(input)
2576
2886
  };
2577
2887
  const check = output && {
2578
2888
  value: Schema.decodeUnknownEffect(Schema.toType(output)),
@@ -2583,6 +2893,15 @@ function stagesOf(config, host, action) {
2583
2893
  ...all,
2584
2894
  ...strict && { onExcessProperty: "error" }
2585
2895
  };
2896
+ const strictRoot = strict === true;
2897
+ const decodeInput = (call) => {
2898
+ const run = (options) => decode[call.input === void 0 ? call.wire ? "absent" : "value" : call.wire ?? "value"](call.input, options);
2899
+ const reject = (error, options) => Effect.fail(invalid$1(name, "input", issuesOf(error, call.input, options)));
2900
+ return run(strictInput).pipe(Effect.catch((error) => !strictRoot ? reject(error) : run(all).pipe(Effect.matchEffect({
2901
+ onFailure: (plain) => issuesOf(error, call.input, { extras: "rootOnly" }).length ? reject(error, { extras: "ignoreNested" }) : reject(plain),
2902
+ onSuccess: (value) => issuesOf(error, call.input, { extras: "rootOnly" }).length ? reject(error, { extras: "rootOnly" }) : Effect.succeed(value)
2903
+ }))));
2904
+ };
2586
2905
  return [
2587
2906
  ...dashboard ? [{
2588
2907
  name: "dashboard",
@@ -2601,7 +2920,7 @@ function stagesOf(config, host, action) {
2601
2920
  }] : [],
2602
2921
  ...decode ? [{
2603
2922
  name: "input",
2604
- run: (call, next) => decode[call.wire ?? "value"](call.input, strictInput).pipe(Effect.mapError((error) => invalid$1(name, "input", issuesOf(error))), Effect.flatMap((decoded) => next({
2923
+ run: (call, next) => decodeInput(call).pipe(Effect.flatMap((decoded) => next({
2605
2924
  ...call,
2606
2925
  input: decoded
2607
2926
  })))
@@ -2615,7 +2934,7 @@ function stagesOf(config, host, action) {
2615
2934
  ...audit ? [audit] : [],
2616
2935
  ...check ? [{
2617
2936
  name: "output",
2618
- run: (call, next) => next(call).pipe(Effect.flatMap((result) => check[call.wire ? "json" : "value"](result, all).pipe(Effect.mapError((error) => invalid$1(name, "output", issuesOf(error))))))
2937
+ run: (call, next) => next(call).pipe(Effect.flatMap((result) => omittingUndefined((value) => check[call.wire ? "json" : "value"](value, all))(result).pipe(Effect.mapError((error) => invalid$1(name, "output", issuesOf(error, result))))))
2619
2938
  }] : [],
2620
2939
  {
2621
2940
  name: "execute",
@@ -2666,6 +2985,110 @@ function createAction(host, config, deferred = false) {
2666
2985
  Object.defineProperty(action, RESET_STAGES, { value: () => void (built = deferred ? void 0 : built) });
2667
2986
  return action;
2668
2987
  }
2988
+ // src/json-schema.ts
2989
+ /**
2990
+ * Marks the string side of a number a path carries (`/orders/:id`). The wire
2991
+ * holds the number as text, but a client sends a number, as core's `t.Number()`
2992
+ * says, so the JSON Schema writes it as `number`.
2993
+ */
2994
+ const NUMBER_IN_PATH = "brickkit.effect.number-in-path";
2995
+ const JSON_IDS = ["effect/schema/Json", "effect/schema/MutableJson"];
2996
+ /**
2997
+ * What a client sends and receives for `Schema.Json` and `Schema.MutableJson`:
2998
+ * a recursive JSON value, as core's `t.Json()` says. Effect's own JSON Schema
2999
+ * of them is `{}`, which a client types as `unknown`. It exports as a `$ref`
3000
+ * to a `Json` definition, in the order of `t.Json()`'s union.
3001
+ */
3002
+ const JsonValue = Schema.Union([
3003
+ Schema.Null,
3004
+ Schema.Boolean,
3005
+ Schema.Number,
3006
+ Schema.String,
3007
+ Schema.Array(Schema.suspend(() => JsonValue)),
3008
+ Schema.Record(Schema.String, Schema.suspend(() => JsonValue))
3009
+ ]).annotate({ identifier: "Json" });
3010
+ /** Whether `node` is `Schema.Json` or `Schema.MutableJson`. */
3011
+ const isJsonDeclaration = (node) => SchemaAST.isDeclaration(node) && JSON_IDS.includes(node.annotations?.representation?.id);
3012
+ /**
3013
+ * Effect describes a field written `Schema.optional(X)` as `X | undefined`,
3014
+ * and its JSON codec writes `undefined` as `null`, so a JSON Schema document
3015
+ * of it says `X | null`. A Brick client never sends that and the server never
3016
+ * answers it (an `undefined` key is left out, as in core): `optional(X)` is
3017
+ * the key left out or `X`, as TypeBox's `Optional(X)` is. This writes it as
3018
+ * `optionalKey(X)`, at every depth. A `NullOr` stays `null`, and so does a
3019
+ * required `UndefinedOr`, which has no key to leave out.
3020
+ *
3021
+ * shortcut: `recur` is internal to effect 4.1.7, which is pinned, and the
3022
+ * parity test in packages/cli fails if an upgrade drops it. There is no
3023
+ * public way to rewrite a schema's nodes.
3024
+ */
3025
+ function withoutUndefinedKeys(ast) {
3026
+ const done = /* @__PURE__ */ new WeakMap();
3027
+ const visit = (node) => {
3028
+ const known = done.get(node);
3029
+ if (known) return known;
3030
+ if (isJsonDeclaration(node)) {
3031
+ const json = SchemaAST.isOptional(node) ? Schema.optionalKey(JsonValue).ast : JsonValue.ast;
3032
+ done.set(node, json);
3033
+ return json;
3034
+ }
3035
+ const recur = node.recur;
3036
+ let next = recur ? recur.call(node, visit) : node;
3037
+ if (SchemaAST.isOptional(next) && SchemaAST.isUnion(next) && !next.checks && next.types.some(SchemaAST.isUndefined)) {
3038
+ const kept = next.types.filter((type) => !SchemaAST.isUndefined(type));
3039
+ if (kept.length) next = Schema.optionalKey(Schema.make(kept.length === 1 ? kept[0] : new SchemaAST.Union(kept, next.options, next.annotations))).ast;
3040
+ }
3041
+ done.set(node, next);
3042
+ return next;
3043
+ };
3044
+ return visit(ast);
3045
+ }
3046
+ const NON_FINITE = [
3047
+ "Infinity",
3048
+ "-Infinity",
3049
+ "NaN"
3050
+ ];
3051
+ const isNonFinite = (node) => node.type === "string" && Array.isArray(node.enum) && node.enum.length === NON_FINITE.length && NON_FINITE.every((value) => node.enum.includes(value));
3052
+ /**
3053
+ * `Schema.Number` encodes Infinity and NaN as strings, so its JSON Schema is
3054
+ * `number | "Infinity" | "-Infinity" | "NaN"`. A client works with numbers, as
3055
+ * with core's `t.Number()`, so the strings are dropped. JSON has no
3056
+ * Infinity or NaN: core's `JSON.stringify` writes them as `null`.
3057
+ */
3058
+ function plainNumbers(node) {
3059
+ if (Array.isArray(node)) return node.map(plainNumbers);
3060
+ if (!node || typeof node !== "object") return node;
3061
+ if (node.description === "brickkit.effect.number-in-path") return { type: "number" };
3062
+ const entries = Object.entries(node);
3063
+ const members = node.anyOf;
3064
+ if (Array.isArray(members) && members.some((member) => member?.type === "number") && members.some((member) => member && isNonFinite(member))) {
3065
+ const kept = members.filter((member) => !isNonFinite(member));
3066
+ const { anyOf: _, ...rest } = node;
3067
+ return plainNumbers(kept.length === 1 ? {
3068
+ ...rest,
3069
+ ...kept[0]
3070
+ } : {
3071
+ ...rest,
3072
+ anyOf: kept
3073
+ });
3074
+ }
3075
+ return Object.fromEntries(entries.map(([key, value]) => [key, plainNumbers(value)]));
3076
+ }
3077
+ /**
3078
+ * The JSON Schema document of what a client sends and receives for `schema`:
3079
+ * `Schema.toJsonSchemaDocument`, with an optional key as a key that may be
3080
+ * left out and a number as a number. Core's OpenAPI document, MCP tools and
3081
+ * client contract read the same.
3082
+ */
3083
+ function toJsonSchemaDocument(schema) {
3084
+ const encoded = SchemaAST.toEncoded(schema.ast);
3085
+ const rewritten = withoutUndefinedKeys(encoded);
3086
+ const { schema: root, definitions } = Schema.toJsonSchemaDocument(rewritten === encoded ? schema : Schema.make(rewritten));
3087
+ return {
3088
+ schema: plainNumbers(root),
3089
+ definitions: plainNumbers(definitions)
3090
+ };
3091
+ }
2669
3092
  // src/crud/codec.ts
2670
3093
  const isoPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
2671
3094
  /** A failure thrown while building a query: `perform` turns it into the call's failure. */
@@ -2726,6 +3149,7 @@ function checkJsonSchema(schema) {
2726
3149
  const walk = (ast) => {
2727
3150
  if (seen.has(ast)) return;
2728
3151
  seen.add(ast);
3152
+ if (isJsonDeclaration(ast)) return;
2729
3153
  if (NOT_JSON.has(ast._tag)) throw new Error(`CRUD schema '${ast._tag}' is not JSON-safe; use string date-time or decimal strings`);
2730
3154
  if (ast._tag === "Suspend") return walk(ast.thunk());
2731
3155
  for (const child of [
@@ -2795,7 +3219,7 @@ function withoutNull(schema) {
2795
3219
  return rest.length === ast.types.length ? schema : Schema.Union(rest.map((member) => Schema.make(member)));
2796
3220
  }
2797
3221
  /** The schema of a resource's `:id`: a string on the wire for a number column, as paths carry it. */
2798
- const idSchema$1 = (column, wire) => kindOf(column) === "number" ? wire ? Schema.FiniteFromString : Schema.Finite : Schema.String;
3222
+ const idSchema$1 = (column, wire) => kindOf(column) === "number" ? wire ? Schema.String.annotate({ description: NUMBER_IN_PATH }).pipe(Schema.decodeTo(Schema.Finite, SchemaTransformation.numberFromString)) : Schema.Finite : Schema.String;
2799
3223
  /** An opaque list cursor: the orderBy it was made for, and the last row's sort values. */
2800
3224
  function encodeCursor(spec, values) {
2801
3225
  return Buffer.from(JSON.stringify([spec, values.map(jsonValue)])).toString("base64url");
@@ -3026,9 +3450,47 @@ function actionOwners(action) {
3026
3450
  }
3027
3451
  /** Whether a schema describes an object, which an absent input then stands for as `{}`. */
3028
3452
  const isObjectSchema = (schema) => Schema.isSchema(schema) && schema.ast._tag === "Objects";
3453
+ // src/body-limit.ts
3454
+ /** The 413 every body cap answers with: the same `PAYLOAD_TOO_LARGE` JSON as `@brickkit/core`. */
3455
+ const payloadTooLarge = (limit) => new BrickError({
3456
+ code: "PAYLOAD_TOO_LARGE",
3457
+ message: `Request body exceeds ${limit} bytes`,
3458
+ status: 413
3459
+ });
3460
+ /** Whether the request says, in `Content-Length`, that its body is over `limit`: refused before it is read. */
3461
+ const declaresOver = (request, limit) => Number(request.headers.get("content-length")) > limit;
3462
+ /**
3463
+ * The body's bytes, or `undefined` once it is over `limit`. A chunked body has
3464
+ * no `Content-Length` to check, so the stream is counted as it arrives and
3465
+ * cancelled the moment it passes `limit`: at most one chunk past it is held.
3466
+ * Reads `request.body`, so pass a `clone()` to leave the original unread.
3467
+ */
3468
+ async function readCapped(request, limit) {
3469
+ if (declaresOver(request, limit)) return void 0;
3470
+ const chunks = [];
3471
+ let size = 0;
3472
+ if (request.body) {
3473
+ const reader = request.body.getReader();
3474
+ for (;;) {
3475
+ const { done, value } = await reader.read();
3476
+ if (done) break;
3477
+ size += value.byteLength;
3478
+ if (size > limit) {
3479
+ reader.cancel().catch(() => {});
3480
+ return;
3481
+ }
3482
+ chunks.push(value);
3483
+ }
3484
+ }
3485
+ return new Uint8Array(Buffer.concat(chunks));
3486
+ }
3487
+ /** Throws on a `maxBodyBytes` that is not a positive integer. */
3488
+ function checkBodyLimit(where, limit) {
3489
+ if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 1)) throw new Error(`${where}: maxBodyBytes must be a positive integer.`);
3490
+ }
3029
3491
  // src/architecture.ts
3030
3492
  const jsonSchema$1 = (schema) => {
3031
- const { schema: root, definitions } = Schema.toJsonSchemaDocument(schema);
3493
+ const { schema: root, definitions } = toJsonSchemaDocument(schema);
3032
3494
  return Object.keys(definitions).length ? {
3033
3495
  ...root,
3034
3496
  $defs: definitions
@@ -3607,7 +4069,7 @@ function generateOpenApiSpec({ title = OPENAPI_DEFAULTS.title, version = OPENAPI
3607
4069
  const schemas = { ErrorEnvelope };
3608
4070
  let authorizes = false;
3609
4071
  const toJson = (schema) => {
3610
- const { schema: root, definitions } = Schema.toJsonSchemaDocument(schema);
4072
+ const { schema: root, definitions } = toJsonSchemaDocument(schema);
3611
4073
  const keys = new Map(Object.keys(definitions).map((name) => [name, name]));
3612
4074
  const rewrite = (value) => Array.isArray(value) ? value.map(rewrite) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, key === "$ref" && typeof item === "string" ? item.replace(/[^/]+$/, (name) => keys.get(name) ?? name) : rewrite(item)])) : value;
3613
4075
  for (let changed = true; changed;) {
@@ -3861,7 +4323,7 @@ function defineEvents(service, catalog) {
3861
4323
  *
3862
4324
  * @throws (as a defect) When the payload does not match.
3863
4325
  */
3864
- const encodePayload = (ref, payload) => Schema.encodeUnknownEffect(Schema.toCodecJson(ref.schema))(payload, { errors: "all" }).pipe(Effect.catch((error) => Effect.die(/* @__PURE__ */ new Error(`Event "${ref.name}" payload does not match its schema: ${error.message}`))));
4326
+ const encodePayload = (ref, payload) => omittingUndefined((value) => Schema.encodeUnknownEffect(Schema.toCodecJson(ref.schema))(value, { errors: "all" }))(payload).pipe(Effect.catch((error) => Effect.die(/* @__PURE__ */ new Error(`Event "${ref.name}" payload does not match its schema: ${error.message}`))));
3865
4327
  /** The payload of a delivery, decoded with the event's schema. */
3866
4328
  const decodePayload = (ref, payload) => Schema.decodeUnknownEffect(Schema.toCodecJson(ref.schema))(payload);
3867
4329
  /** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
@@ -3950,6 +4412,27 @@ const queueOnCommit = (effect, wanted) => Effect.flatMap(Effect.serviceOption(Op
3950
4412
  if (wanted(commits)) commits.push(effect);
3951
4413
  })
3952
4414
  }));
4415
+ /** The `@effect/sql` client of a drizzle Effect database, which owns its transactions. */
4416
+ const clientOf = (db) => {
4417
+ const client = db?.$client;
4418
+ return typeof client?.afterCommit === "function" ? client : void 0;
4419
+ };
4420
+ /**
4421
+ * Run `effect` once the outermost transaction on `db` has committed, whoever
4422
+ * opened it (`runInTransaction`, or the app's own drizzle `db.transaction`); at
4423
+ * once when none is open. Never when it rolls back. It runs without that
4424
+ * transaction, so what it forks never touches its connection.
4425
+ */
4426
+ const afterCommitOn = (db, effect) => clientOf(db)?.afterCommit(effect) ?? effect;
4427
+ /**
4428
+ * `effect` without the transaction `db`'s client has open in the fiber. A fiber
4429
+ * forked from inside a transaction inherits it, and fails once it ends (or
4430
+ * delivers from an uncommitted row while it is open).
4431
+ */
4432
+ const outsideTransaction = (db, effect) => {
4433
+ const client = clientOf(db);
4434
+ return client ? Effect.updateContext(effect, Context.omit(client.transactionService)) : effect;
4435
+ };
3953
4436
  /** `brick.token.<token>`: a bearer token carried as a subprotocol, since browsers can't set headers on a WebSocket. */
3954
4437
  const SOCKET_TOKEN_PROTOCOL = "brick.token.";
3955
4438
  /** Control messages, sent as frames whose event starts with `$`. */
@@ -4030,7 +4513,7 @@ function socketCodecs(schemas) {
4030
4513
  const refuse = (message) => Effect.die(new Error(message));
4031
4514
  if (!codec) return refuse("Invalid socket output");
4032
4515
  return Effect.gen(function* () {
4033
- const json = yield* codec.encode(data).pipe(Effect.catch(() => refuse("Invalid socket output")));
4516
+ const json = yield* omittingUndefined(codec.encode)(data).pipe(Effect.catch(() => refuse("Invalid socket output")));
4034
4517
  const frame = encodeFrame(event, json);
4035
4518
  if (byteLength(frame) > 65536) return yield* refuse("Socket output too large");
4036
4519
  return frame;
@@ -5338,11 +5821,12 @@ const brokenRetry = /* @__PURE__ */ new WeakSet();
5338
5821
  /** Asks the listener's `retry` what to do with a failure. A `retry` that throws counts as "retry", and is logged once. */
5339
5822
  function decideRetry(name, listener, error) {
5340
5823
  if (!listener.retry) return "retry";
5824
+ const declared = asFailure(error);
5341
5825
  try {
5342
- return listener.retry(error instanceof BrickError && listener.errors?.[error.code] ? {
5343
- code: error.code,
5344
- message: error.message,
5345
- details: error.details
5826
+ return listener.retry(declared instanceof BrickError && listener.errors?.[declared.code] ? {
5827
+ code: declared.code,
5828
+ message: declared.message,
5829
+ details: declared.details
5346
5830
  } : {
5347
5831
  code: "UNKNOWN",
5348
5832
  message: error instanceof Error ? error.message : String(error),
@@ -5463,7 +5947,7 @@ function makeDispatcher(config) {
5463
5947
  return {
5464
5948
  start: Effect.suspend(() => {
5465
5949
  if (worker || !options.timer) return Effect.void;
5466
- return pollUnref(tick, Schedule.fixed(options.intervalMs)).pipe(Effect.forkIn(scope), Effect.map((fiber) => {
5950
+ return outsideTransaction(db, pollUnref(tick, Schedule.fixed(options.intervalMs))).pipe(Effect.forkIn(scope), Effect.map((fiber) => {
5467
5951
  worker = fiber;
5468
5952
  }));
5469
5953
  }),
@@ -5474,7 +5958,7 @@ function makeDispatcher(config) {
5474
5958
  yield* turn.withPermits(1)(Effect.void);
5475
5959
  yield* settled;
5476
5960
  }),
5477
- notify: Effect.suspend(() => worker ? Effect.asVoid(Effect.forkIn(backgroundTick, scope)) : Effect.void),
5961
+ notify: Effect.suspend(() => worker ? Effect.asVoid(Effect.forkIn(outsideTransaction(db, backgroundTick), scope)) : Effect.void),
5478
5962
  drain: Effect.gen(function* () {
5479
5963
  let total = 0;
5480
5964
  for (;;) {
@@ -5523,26 +6007,28 @@ const RunFields = {
5523
6007
  trigger: Schema.Literals(["schedule", "manual"]),
5524
6008
  runKey: Schema.String
5525
6009
  };
6010
+ /** Dies when the app has no `WorkflowEngine` for the listener or schedule `kind`/`name`, which runs a workflow. */
6011
+ const requireEngine = (kind, name, context) => Context.getOption(context, WorkflowEngine$1.WorkflowEngine)._tag === "None" ? Effect.die(/* @__PURE__ */ new Error(`${kind === "Listener" ? "Event listener" : "Schedule"} '${name}' runs a workflow, so the app's layer needs a workflow engine: add workflowEngine(database) to \`brick({ layer })\`.`)) : Effect.void;
5526
6012
  /**
5527
6013
  * Registers `run` as a durable workflow on the app's `WorkflowEngine`, for the
5528
6014
  * listener or schedule `kind`/`name`. The run is named after `key`, so a delivery
5529
6015
  * or a due time that is tried again finds the run it started instead of
5530
- * starting another. A failure of `run` ends the run and is logged: the workflow
5531
- * retries its own steps, not the delivery.
6016
+ * starting another. A failure of `run` ends the run as failed, with its cause,
6017
+ * and is logged: the workflow retries its own steps, not the delivery.
5532
6018
  *
5533
6019
  * @param context - The app's context, which holds the engine and what `run` needs.
5534
6020
  * @throws (as a defect) When the app has no `WorkflowEngine`.
5535
6021
  */
5536
6022
  function register(kind, name, fields, key, run, context) {
5537
6023
  return Effect.gen(function* () {
5538
- if (Context.getOption(context(), WorkflowEngine$1.WorkflowEngine)._tag === "None") return yield* Effect.die(/* @__PURE__ */ new Error(`${kind === "Listener" ? "Event listener" : "Schedule"} '${name}' runs a workflow, so the app's layer needs a workflow engine: add workflowEngine(database) to \`brick({ layer })\`.`));
6024
+ yield* requireEngine(kind, name, context());
5539
6025
  const workflow = Workflow$1.make(`Brick${kind}/${name}`, {
5540
6026
  payload: fields,
5541
6027
  idempotencyKey: key
5542
6028
  });
5543
6029
  const handler = (input) => Effect.suspend(() => run(input)).pipe(Effect.provideContext(context()), Effect.tapCause((cause) => Effect.sync(() => {
5544
6030
  if (!Cause.hasInterruptsOnly(cause)) console.error(`[Brick] ${kind === "Listener" ? "Workflow listener" : "Workflow schedule"} '${name}' failed:`, Cause.pretty(cause));
5545
- })), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.void));
6031
+ })));
5546
6032
  yield* Layer.build(workflow.toLayer(handler)).pipe(Effect.provideContext(context()));
5547
6033
  return {
5548
6034
  name,
@@ -5679,8 +6165,16 @@ function createEvents(options, services, telemetry = false) {
5679
6165
  let context = yield* Effect.context();
5680
6166
  const deliverables = /* @__PURE__ */ new Map();
5681
6167
  const starters = /* @__PURE__ */ new Map();
5682
- for (const listener of byName.values()) if (listener.workflow) starters.set(`listener:${listener.name}`, yield* listenerWorkflow(listener, () => context));
5683
- for (const schedule of schedules) if (schedule.workflow) starters.set(`schedule:${schedule.name}`, yield* scheduleWorkflow(schedule, () => context));
6168
+ const registering = Semaphore.makeUnsafe(1);
6169
+ const starter = (key) => registering.withPermits(1)(Effect.suspend(() => {
6170
+ const found = starters.get(key);
6171
+ if (found) return Effect.succeed(found);
6172
+ const name = key.slice(key.indexOf(":") + 1);
6173
+ const made = key.startsWith("listener:") ? listenerWorkflow(byName.get(name), () => context) : scheduleWorkflow(schedules.find((schedule) => schedule.name === name), () => context);
6174
+ return Effect.tap(Effect.provideService(made, Scope.Scope, scope), (made) => Effect.sync(() => starters.set(key, made)));
6175
+ }));
6176
+ for (const listener of byName.values()) if (listener.workflow) yield* dispatch !== false ? starter(`listener:${listener.name}`) : requireEngine("Listener", listener.name, context);
6177
+ for (const schedule of schedules) if (schedule.workflow) yield* dispatch !== false ? starter(`schedule:${schedule.name}`) : requireEngine("Schedule", schedule.name, context);
5684
6178
  const deliverable = (name) => {
5685
6179
  const listener = byName.get(name);
5686
6180
  if (!listener) return void 0;
@@ -5691,7 +6185,7 @@ function createEvents(options, services, telemetry = false) {
5691
6185
  ...errors ? { errors } : {},
5692
6186
  ...retry ? { retry } : {},
5693
6187
  ...maxAttempts !== void 0 ? { maxAttempts } : {},
5694
- run: listener.workflow ? ({ attempt: _attempt, ...event }) => starters.get(`listener:${name}`).start(event) : (delivery) => Effect.suspend(() => run(delivery)).pipe(Effect.provideContext(context))
6188
+ run: listener.workflow ? ({ attempt: _attempt, ...event }) => Effect.flatMap(starter(`listener:${name}`), (found) => found.start(event)) : (delivery) => Effect.suspend(() => run(delivery)).pipe(Effect.provideContext(context))
5695
6189
  };
5696
6190
  deliverables.set(name, found);
5697
6191
  }
@@ -5724,7 +6218,7 @@ function createEvents(options, services, telemetry = false) {
5724
6218
  runner: (schedule, run) => {
5725
6219
  const ran = schedule.workflow ? Effect.suspend(() => {
5726
6220
  const { attempt: _attempt, ...started } = run;
5727
- return starters.get(`schedule:${schedule.name}`).start(started);
6221
+ return Effect.flatMap(starter(`schedule:${schedule.name}`), (found) => found.start(started));
5728
6222
  }) : Effect.suspend(() => schedule.run(run)).pipe(Effect.provideContext(context));
5729
6223
  return telemetry ? traceScheduleRun(run, ran) : ran;
5730
6224
  },
@@ -5765,7 +6259,7 @@ function createEvents(options, services, telemetry = false) {
5765
6259
  transaction: (db, eventContext, fn) => Effect.suspend(() => {
5766
6260
  const recorder = recorders.get(db);
5767
6261
  if (!recorder) return Effect.die(/* @__PURE__ */ new Error(NO_OUTBOX));
5768
- const notify = Effect.andThen(start, recorder.dispatcher.notify);
6262
+ const notify = afterCommitOn(db, Effect.andThen(start, recorder.dispatcher.notify));
5769
6263
  return runInTransaction(db, (tx) => fn(tx, (name, payload, options) => Effect.flatMap(insert(recorder, tx, eventContext, name, payload, options?.encoded), (recorded) => recorded ? onTransactionCommitOnce(notify) : Effect.void)));
5770
6264
  }),
5771
6265
  start,
@@ -5991,7 +6485,8 @@ function defineCommand(service, resource, name, config) {
5991
6485
  const id = row[resource.idField];
5992
6486
  for (const child of loaded) row[child.name] = yield* tx.select().from(child.table).where(eq(child.parent, id));
5993
6487
  const decision = decide(row, input);
5994
- if (decision instanceof BrickError) return yield* Effect.fail(decision);
6488
+ const rejected = asFailure(decision);
6489
+ if (rejected instanceof BrickError) return yield* Effect.fail(rejected);
5995
6490
  const { set, children, emit } = decision ?? {};
5996
6491
  const declared = service.events;
5997
6492
  const emits = [];
@@ -6097,7 +6592,7 @@ const withoutOpenObjects = (node) => {
6097
6592
  };
6098
6593
  /** The JSON form of a schema: what the client sends and receives. */
6099
6594
  function jsonSchemaOf(schema) {
6100
- const { schema: root, definitions } = Schema.toJsonSchemaDocument(schema);
6595
+ const { schema: root, definitions } = toJsonSchemaDocument(schema);
6101
6596
  return withoutOpenObjects(Object.keys(definitions).length ? {
6102
6597
  ...root,
6103
6598
  $defs: definitions
@@ -6186,6 +6681,26 @@ function corsHook(cors) {
6186
6681
  };
6187
6682
  };
6188
6683
  }
6684
+ // src/response-hooks.ts
6685
+ /** The same response with other headers. */
6686
+ const withHeaders = (response, headers) => new Response(response.body, {
6687
+ status: response.status,
6688
+ statusText: response.statusText,
6689
+ headers
6690
+ });
6691
+ /** What an `onError` replacement keeps of the response it replaces, unless it sets its own. */
6692
+ function keepTraceIds(replacement, replaced) {
6693
+ const headers = new Headers(replacement.headers);
6694
+ for (const name of [
6695
+ "x-trace-id",
6696
+ "x-request-id",
6697
+ "traceparent"
6698
+ ]) {
6699
+ const value = replaced.headers.get(name);
6700
+ if (value !== null && !headers.has(name)) headers.set(name, value);
6701
+ }
6702
+ return withHeaders(replacement, headers);
6703
+ }
6189
6704
  // src/dashboard.ts
6190
6705
  /** Where the app answers MCP for the dashboard's `/mcp`, to a request the dashboard signed. */
6191
6706
  const DASHBOARD_MCP_ROUTE = "/_brick/dashboard/mcp";
@@ -6213,18 +6728,24 @@ const MIN_TOKEN_LENGTH = 16;
6213
6728
  */
6214
6729
  function normalizeDashboard(options) {
6215
6730
  if (options === void 0) return void 0;
6216
- const { port, host, auth, historyDays, inspector, mcp } = options;
6731
+ const { port, host, auth, historyDays, inspector, mcp, name, peers, peerSyncMinutes } = options;
6217
6732
  if (port !== void 0 && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new Error(`Brick: dashboard port must be an integer from 1 to 65535, not ${String(port)}.`);
6218
6733
  if (host !== void 0 && (typeof host !== "string" || host.trim() === "")) throw new Error("Brick: dashboard host must be an address, such as '0.0.0.0'.");
6219
6734
  if (historyDays !== void 0 && (!Number.isInteger(historyDays) || historyDays < 0)) throw new Error(`Brick: dashboard historyDays must be a whole number of days, not ${String(historyDays)}.`);
6220
6735
  if (inspector !== void 0 && typeof inspector !== "boolean") throw new Error("Brick: dashboard inspector must be true or false.");
6221
6736
  if (mcp !== void 0 && typeof mcp !== "boolean") throw new Error("Brick: dashboard mcp must be true or false.");
6737
+ if (name !== void 0 && (typeof name !== "string" || !INSTANCE_NAME.test(name))) throw new Error(`Brick: dashboard name must be letters, digits, '-' and '_', not ${JSON.stringify(name)}.`);
6738
+ const peerList = peers === void 0 ? void 0 : normalizePeers(peers, name);
6739
+ if (peerList && peerList.length > 0 && !(Number(historyDays) > 0)) throw new Error("Brick: dashboard peers need historyDays: the copies of their requests are kept on disk.");
6740
+ if (peerSyncMinutes !== void 0 && (typeof peerSyncMinutes !== "number" || !(peerSyncMinutes > 0 && peerSyncMinutes <= MAX_SYNC_MINUTES))) throw new Error(`Brick: dashboard peerSyncMinutes must be more than 0 and at most ${MAX_SYNC_MINUTES} minutes, not ${String(peerSyncMinutes)}.`);
6222
6741
  const normalized = {
6223
6742
  ...port !== void 0 ? { port } : {},
6224
6743
  ...host !== void 0 ? { host: host.trim() } : {},
6225
6744
  ...historyDays !== void 0 ? { historyDays } : {},
6226
6745
  ...inspector !== void 0 ? { inspector } : {},
6227
- ...mcp !== void 0 ? { mcp } : {}
6746
+ ...mcp !== void 0 ? { mcp } : {},
6747
+ ...name !== void 0 ? { name } : {},
6748
+ ...peerSyncMinutes !== void 0 ? { peerSyncMinutes } : {}
6228
6749
  };
6229
6750
  if (auth !== void 0) {
6230
6751
  if (typeof auth !== "object" || auth === null) throw new Error("Brick: dashboard auth must be an object.");
@@ -6242,8 +6763,38 @@ function normalizeDashboard(options) {
6242
6763
  get: () => secrets
6243
6764
  });
6244
6765
  }
6766
+ if (peerList !== void 0) Object.defineProperty(normalized, "peers", {
6767
+ enumerable: false,
6768
+ get: () => peerList
6769
+ });
6245
6770
  return Object.freeze(normalized);
6246
6771
  }
6772
+ /** The longest timer interval Node and Bun keep (2^31 - 1 ms), in whole minutes. */
6773
+ const MAX_SYNC_MINUTES = 35791;
6774
+ const INSTANCE_NAME = /^[\w-]{1,64}$/;
6775
+ function normalizePeers(peers, self) {
6776
+ if (!Array.isArray(peers)) throw new Error("Brick: dashboard peers must be an array.");
6777
+ const names = /* @__PURE__ */ new Set([self ?? "local"]);
6778
+ return Object.freeze(peers.map((peer) => {
6779
+ const { name, url, token } = peer ?? {};
6780
+ if (typeof name !== "string" || !INSTANCE_NAME.test(name)) throw new Error(`Brick: a dashboard peer's name must be letters, digits, '-' and '_', not ${JSON.stringify(name)}.`);
6781
+ if (names.has(name)) throw new Error(`Brick: dashboard peer '${name}' has the name of another instance; give each its own.`);
6782
+ names.add(name);
6783
+ let parsed;
6784
+ try {
6785
+ parsed = new URL(url);
6786
+ } catch {
6787
+ throw new Error(`Brick: dashboard peer '${name}' needs a url, such as 'https://brick-in.example.com'.`);
6788
+ }
6789
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new Error(`Brick: dashboard peer '${name}' url must be http or https.`);
6790
+ if (typeof token !== "string" || token.length < MIN_TOKEN_LENGTH) throw new Error(`Brick: dashboard peer '${name}' needs its dashboard token (at least ${MIN_TOKEN_LENGTH} characters).`);
6791
+ return Object.freeze({
6792
+ name,
6793
+ url: parsed.origin + parsed.pathname.replace(/\/+$/, ""),
6794
+ token
6795
+ });
6796
+ }));
6797
+ }
6247
6798
  // src/mcp.ts
6248
6799
  var UnknownToolError = class extends Error {
6249
6800
  name = "UnknownToolError";
@@ -6253,7 +6804,7 @@ var UnknownToolError = class extends Error {
6253
6804
  };
6254
6805
  const WRAP_RESULT = "x-brick-wrap-result";
6255
6806
  const jsonSchema = (schema) => {
6256
- const { schema: root, definitions } = Schema.toJsonSchemaDocument(schema);
6807
+ const { schema: root, definitions } = toJsonSchemaDocument(schema);
6257
6808
  const ref = root.$ref;
6258
6809
  const base = typeof ref === "string" && definitions[ref.split("/").pop()] ? { ...definitions[ref.split("/").pop()] } : root;
6259
6810
  return Object.keys(definitions).length ? {
@@ -6665,9 +7216,11 @@ function mountSocket({ service, definition }, broker, run, getServer, sign, veri
6665
7216
  if (Exit.isSuccess(exit)) return exit.value;
6666
7217
  throw new Failed(exit.cause);
6667
7218
  };
6668
- /** The typed failure of a run, else what was thrown. */
7219
+ /** The declared or core failure of a run, else the typed failure, else what was thrown. */
6669
7220
  const failureOf = (error) => {
6670
7221
  if (!(error instanceof Failed)) return error;
7222
+ const known = failureOfCause(error.cause);
7223
+ if (known) return known;
6671
7224
  const found = Cause.findError(error.cause);
6672
7225
  return Result.isSuccess(found) ? found.success : error;
6673
7226
  };
@@ -6897,9 +7450,194 @@ function mountSocket({ service, definition }, broker, run, getServer, sign, veri
6897
7450
  };
6898
7451
  return mounted;
6899
7452
  }
6900
- // src/workflows.ts
6901
- /** The table the database-backed engine keeps its state in. It creates it when missing. */
7453
+ // src/workflow-store.ts
7454
+ /** The table the database-backed workflow engine keeps its state in. It creates it when missing. */
6902
7455
  const WORKFLOW_TABLE = "brick_workflow_state";
7456
+ /** The columns the engine added to `key` and `value`, with their SQL types. All are NULL on rows an older version wrote. */
7457
+ const ADDED_COLUMNS = {
7458
+ run_id: "text",
7459
+ parent_id: "text",
7460
+ status: "text",
7461
+ owner: "text",
7462
+ lease_until: "bigint",
7463
+ finished_at: "bigint"
7464
+ };
7465
+ /** The Postgres advisory lock key `ensure` holds while it changes the table. */
7466
+ const ENSURE_LOCK = 7240815302;
7467
+ /**
7468
+ * The run a state row belongs to, from its key: `execution/<workflow>/<id>`
7469
+ * (a workflow's name may hold slashes, an id does not), or `<kind>/<id>/...`.
7470
+ * `undefined` for a key that belongs to no run.
7471
+ */
7472
+ function runIdOf(key) {
7473
+ if (key.startsWith("execution/")) return key.slice(key.lastIndexOf("/") + 1);
7474
+ const [kind, id] = key.split("/");
7475
+ return [
7476
+ "activity",
7477
+ "activity-at",
7478
+ "deferred",
7479
+ "clock",
7480
+ "sleep"
7481
+ ].includes(kind) ? id : void 0;
7482
+ }
7483
+ /** What an execution row written before the engine kept `status` says about the run. */
7484
+ const legacyStatus = (value) => {
7485
+ if (!value.done) return "running";
7486
+ try {
7487
+ return JSON.parse(value.result ?? "null")?.exit?._tag === "Failure" ? "failed" : "done";
7488
+ } catch {
7489
+ return "done";
7490
+ }
7491
+ };
7492
+ /**
7493
+ * The engine's rows: `key` and `value` hold the state, one kind of record per
7494
+ * key prefix. An execution's row also carries what the engine asks of a whole
7495
+ * run, in columns it can index: `status`, `owner` and `lease_until` (the
7496
+ * process that runs it, and until when), and `finished_at`. Every row of a run
7497
+ * carries its `run_id`, so retention removes the run in one statement.
7498
+ */
7499
+ function makeStore(database, db) {
7500
+ const postgres = database.engine !== "sqlite";
7501
+ const table = postgres ? pgTable(WORKFLOW_TABLE, {
7502
+ key: text("key").primaryKey(),
7503
+ value: text("value").notNull(),
7504
+ runId: text("run_id"),
7505
+ parentId: text("parent_id"),
7506
+ status: text("status"),
7507
+ owner: text("owner"),
7508
+ leaseUntil: bigint("lease_until", { mode: "number" }),
7509
+ finishedAt: bigint("finished_at", { mode: "number" })
7510
+ }) : sqliteTable(WORKFLOW_TABLE, {
7511
+ key: text$1("key").primaryKey(),
7512
+ value: text$1("value").notNull(),
7513
+ runId: text$1("run_id"),
7514
+ parentId: text$1("parent_id"),
7515
+ status: text$1("status"),
7516
+ owner: text$1("owner"),
7517
+ leaseUntil: integer$1("lease_until"),
7518
+ finishedAt: integer$1("finished_at")
7519
+ });
7520
+ const dead = (effect) => Effect.orDie(effect);
7521
+ const statement = (text, handle = db) => dead(postgres ? handle.execute(sql.raw(text)) : handle.run(sql.raw(text)));
7522
+ /** A run no process holds: no owner, or one whose lease ran out. */
7523
+ const free = (now) => or(isNull(table.owner), lt(table.leaseUntil, now));
7524
+ const unfinished = or(isNull(table.status), eq(table.status, "running"));
7525
+ const columns = (handle = db) => Effect.gen(function* () {
7526
+ if (postgres) {
7527
+ const found = yield* dead(handle.execute(sql`select column_name as name from information_schema.columns where table_name = ${WORKFLOW_TABLE} and table_schema = current_schema()`));
7528
+ return new Set(found.rows.map((row) => row.name));
7529
+ }
7530
+ const found = yield* dead(handle.all(sql.raw(`pragma table_info(${WORKFLOW_TABLE})`)));
7531
+ return new Set(found.map((row) => row.name));
7532
+ });
7533
+ const set = (key, value) => dead(db.insert(table).values({
7534
+ key,
7535
+ value,
7536
+ runId: runIdOf(key) ?? ""
7537
+ }).onConflictDoUpdate({
7538
+ target: table.key,
7539
+ set: { value }
7540
+ }));
7541
+ /**
7542
+ * Rows an older version wrote have no `run_id`: give each its run, and each
7543
+ * execution its status. Cheap when there are none, which is every start but
7544
+ * the first after an upgrade (or a process of the old version still running).
7545
+ */
7546
+ const backfill = () => Effect.gen(function* () {
7547
+ for (;;) {
7548
+ const rows = yield* dead(db.select({
7549
+ key: table.key,
7550
+ value: table.value
7551
+ }).from(table).where(isNull(table.runId)).orderBy(table.key).limit(500));
7552
+ if (rows.length === 0) return;
7553
+ for (const { key, value } of rows) {
7554
+ const execution = key.startsWith("execution/") ? JSON.parse(value) : void 0;
7555
+ const status = execution && legacyStatus(execution);
7556
+ yield* dead(db.update(table).set({
7557
+ runId: runIdOf(key) ?? "",
7558
+ ...status && {
7559
+ status,
7560
+ ...status !== "running" && { finishedAt: execution.completedAt ?? Date.now() }
7561
+ }
7562
+ }).where(eq(table.key, key)));
7563
+ }
7564
+ }
7565
+ });
7566
+ const upgrade = (handle = db) => Effect.gen(function* () {
7567
+ yield* statement(`create table if not exists ${WORKFLOW_TABLE} (key text primary key, value text not null, ${Object.entries(ADDED_COLUMNS).map(([name, type]) => `${name} ${type}`).join(", ")})`, handle);
7568
+ const present = yield* columns(handle);
7569
+ for (const [name, type] of Object.entries(ADDED_COLUMNS)) if (!present.has(name)) yield* Effect.catchCause(statement(`alter table ${WORKFLOW_TABLE} add column ${postgres ? "if not exists " : ""}${name} ${type}`, handle), () => Effect.void);
7570
+ yield* statement(`create index if not exists ${WORKFLOW_TABLE}_status on ${WORKFLOW_TABLE} (status, finished_at)`, handle);
7571
+ yield* statement(`create index if not exists ${WORKFLOW_TABLE}_run on ${WORKFLOW_TABLE} (run_id)`, handle);
7572
+ });
7573
+ return {
7574
+ /**
7575
+ * Make the table, add the columns an older version lacks, index them, and
7576
+ * backfill the rows already there. Safe to run from several processes at once:
7577
+ * on Postgres they take turns, because concurrent `create ... if not exists`
7578
+ * statements still fail with a unique violation on its catalog. Only that
7579
+ * part holds the lock: the backfill is batches that commit on their own, so
7580
+ * a big legacy table blocks neither other engines nor the rows they write.
7581
+ */
7582
+ ensure: () => Effect.andThen(postgres ? db.transaction((tx) => Effect.andThen(dead(tx.execute(sql`select pg_advisory_xact_lock(${ENSURE_LOCK})`)), upgrade(tx))).pipe(Effect.orDie) : upgrade(), backfill()),
7583
+ /** Give the rows an older version wrote after this process started their run and status, so they are taken, renewed and swept. */
7584
+ backfill: backfill(),
7585
+ get: (key) => dead(db.select().from(table).where(eq(table.key, key))).pipe(Effect.map((rows) => rows[0]?.value)),
7586
+ set,
7587
+ list: (prefix) => dead(db.select().from(table).where(like(table.key, `${prefix}%`))).pipe(Effect.map((rows) => rows.filter((r) => r.key.startsWith(prefix)))),
7588
+ /** Insert a run held by `owner` until `until`, started by the run `parentId`, if any. `false` when the run already has a row. */
7589
+ begin: (key, value, owner, until, parentId) => dead(db.insert(table).values({
7590
+ key,
7591
+ value,
7592
+ runId: runIdOf(key) ?? "",
7593
+ parentId,
7594
+ status: "running",
7595
+ owner,
7596
+ leaseUntil: until
7597
+ }).onConflictDoNothing().returning({ key: table.key })).pipe(Effect.map((rows) => rows.length > 0)),
7598
+ /**
7599
+ * Take a run no process holds. `false` when it is finished or another process holds it.
7600
+ * A row a process of an older version wrote has no `status` or `run_id` yet: they are set here, or the renewal and the retention would pass it by.
7601
+ */
7602
+ claim: (key, owner, now, until) => dead(db.update(table).set({
7603
+ owner,
7604
+ leaseUntil: until,
7605
+ status: "running",
7606
+ runId: runIdOf(key) ?? ""
7607
+ }).where(and(eq(table.key, key), unfinished, free(now))).returning({ key: table.key })).pipe(Effect.map((rows) => rows.length > 0)),
7608
+ /** Extend every lease `owner` holds. Returns the keys it still holds. */
7609
+ renew: (owner, until) => dead(db.update(table).set({ leaseUntil: until }).where(and(eq(table.owner, owner), eq(table.status, "running"))).returning({ key: table.key })).pipe(Effect.map((rows) => new Set(rows.map((row) => row.key)))),
7610
+ /** Let go of every lease `owner` holds, so another process takes those runs without waiting. */
7611
+ release: (owner) => dead(db.update(table).set({
7612
+ owner: null,
7613
+ leaseUntil: null
7614
+ }).where(and(eq(table.owner, owner), eq(table.status, "running")))),
7615
+ /** End a run: its final value, its status and when it ended, and nobody holds it. */
7616
+ finish: (key, value, status, at) => dead(db.update(table).set({
7617
+ value,
7618
+ status,
7619
+ finishedAt: at,
7620
+ owner: null,
7621
+ leaseUntil: null
7622
+ }).where(eq(table.key, key))),
7623
+ /** Unfinished runs nobody holds. */
7624
+ unheld: (now) => dead(db.select({
7625
+ key: table.key,
7626
+ value: table.value
7627
+ }).from(table).where(and(eq(table.status, "running"), free(now)))),
7628
+ /**
7629
+ * The ids of up to `limit` runs that ended with `status` before `before`,
7630
+ * and whose parent run, if any, is not running: the parent's replay reads
7631
+ * what its children ended with.
7632
+ */
7633
+ endedBefore: (status, before, limit) => dead(db.select({ runId: table.runId }).from(table).where(and(eq(table.status, status), lt(table.finishedAt, before), sql`not exists (select 1 from ${sql.raw(WORKFLOW_TABLE)} parent where parent.run_id = ${table.parentId} and parent.status = 'running')`)).limit(limit)).pipe(Effect.map((rows) => rows.map((row) => row.runId))),
7634
+ /** Delete every row of these runs. */
7635
+ remove: (runIds) => dead(db.delete(table).where(inArray(table.runId, [...runIds]))),
7636
+ /** The keys of the durable deferreds saved for these runs. */
7637
+ deferreds: (runIds) => dead(db.select({ key: table.key }).from(table).where(and(inArray(table.runId, [...runIds]), like(table.key, "deferred/%")))).pipe(Effect.map((rows) => rows.map((row) => row.key)))
7638
+ };
7639
+ }
7640
+ // src/workflows.ts
6903
7641
  const AnyOrVoid = Schema.Union([Schema.Any, Schema.Void]);
6904
7642
  const resultCodec = Schema.toCodecJson(Workflow$1.Result({
6905
7643
  success: AnyOrVoid,
@@ -6921,64 +7659,71 @@ const stateKeys = {
6921
7659
  activity: (id, name, attempt) => `activity/${id}/${name}/${attempt}`,
6922
7660
  activityAt: (id, name, attempt) => `activity-at/${id}/${name}/${attempt}`
6923
7661
  };
6924
- /** Rows of `key` and `value`: one kind of record per key prefix. */
6925
- function makeStore(database, db) {
6926
- const table = database.engine === "sqlite" ? sqliteTable(WORKFLOW_TABLE, {
6927
- key: text$1("key").primaryKey(),
6928
- value: text$1("value").notNull()
6929
- }) : pgTable(WORKFLOW_TABLE, {
6930
- key: text("key").primaryKey(),
6931
- value: text("value").notNull()
6932
- });
6933
- const create = sql.raw(`create table if not exists ${WORKFLOW_TABLE} (key text primary key, value text not null)`);
6934
- const dead = (effect) => Effect.orDie(effect);
6935
- return {
6936
- create: () => dead(database.engine === "sqlite" ? db.run(create) : db.execute(create)),
6937
- get: (key) => dead(Effect.map(db.select().from(table).where(eq(table.key, key)), (rows) => rows[0]?.value)),
6938
- set: (key, value) => dead(db.insert(table).values({
6939
- key,
6940
- value
6941
- }).onConflictDoUpdate({
6942
- target: table.key,
6943
- set: { value }
6944
- })),
6945
- list: (prefix) => dead(Effect.map(db.select().from(table).where(like(table.key, `${prefix}%`)), (rows) => rows.filter((row) => row.key.startsWith(prefix))))
6946
- };
6947
- }
6948
7662
  const RetryingExecution = Context.Reference("effect/workflow/Activity/RetryingExecution", { defaultValue: () => void 0 });
6949
7663
  /** Reuses `prev` while it is still an empty child of `parent`, so replays that register nothing do not grow `parent`. */
6950
7664
  const reuseOrForkScope = (prev, parent) => prev !== void 0 && prev.parent === parent && prev.state._tag === "Empty" ? prev : Scope.forkUnsafe(parent);
6951
7665
  const isUnwakeable = (result, mode) => result._tag === "Complete" || mode === "automatic" && result.failed === true;
7666
+ const DAY = 864e5;
6952
7667
  /**
6953
7668
  * A workflow engine that keeps its state in the app's database, so a run
6954
7669
  * survives a restart. It runs workflows as the in-memory engine of
6955
7670
  * `effect/workflow` does, and writes through what a restart needs:
6956
7671
  *
6957
- * - each execution with its payload, until it finishes;
7672
+ * - each execution with its payload, until it finishes, and then its result;
6958
7673
  * - the result of each activity attempt that finished;
6959
7674
  * - each durable deferred that completed;
6960
7675
  * - the wake time of each durable clock.
6961
7676
  *
6962
- * When a workflow registers (its `toLayer`), the executions of it that never
6963
- * finished start again. They replay, reading the saved results, so an activity
6964
- * that finished does not run twice; a durable clock sleeps only what was left.
7677
+ * A run ends `done`, or `failed` when it fails (its handler fails or dies, or an
7678
+ * activity's retries run out and the failure escapes). The `status` column and
7679
+ * the run's value hold which, and the cause.
7680
+ *
7681
+ * One process runs a run at a time. A process takes a run by writing its own
7682
+ * `owner` and a `lease_until` on it, and renews that while the run lives; other
7683
+ * processes leave it alone. When a workflow registers (its `toLayer`), and then
7684
+ * on every renewal, the process takes the unfinished runs of its workflows that
7685
+ * nobody holds: ones a process released when it stopped, or whose lease ran out
7686
+ * because it died. They replay, reading the saved results, so an activity that
7687
+ * finished does not run twice; a durable clock sleeps only what was left. Run
7688
+ * workflows only in the processes that should run them: a process that does not
7689
+ * register a workflow never takes its runs.
7690
+ *
7691
+ * Finished runs are deleted by a periodic sweep: see `retention`.
6965
7692
  *
6966
- * It creates the `brick_workflow_state` table on first use. Put it in the app's
6967
- * `layer`, with the workflows' `toLayer` layers provided by it.
7693
+ * It creates the `brick_workflow_state` table on first use, and adds the columns
7694
+ * it needs to one an older version made. Put it in the app's `layer`, with the
7695
+ * workflows' `toLayer` layers provided by it.
6968
7696
  *
6969
7697
  * @example
6970
- * const engine = workflowEngine(database);
7698
+ * const engine = workflowEngine(database, { retention: { doneDays: 3 } });
6971
7699
  * brick({ services, layer: Layer.mergeAll(engine, Layer.provide(OrderFlow.toLayer(run), engine)) });
6972
7700
  */
6973
- function workflowEngine(database) {
7701
+ function workflowEngine(database, options = {}) {
7702
+ const leaseMs = options.leaseMs ?? 3e4;
7703
+ const retention = options.retention === false ? void 0 : {
7704
+ doneDays: options.retention?.doneDays ?? 7,
7705
+ failedDays: options.retention?.failedDays ?? 30,
7706
+ intervalMs: options.retention?.intervalMs ?? 36e5
7707
+ };
6974
7708
  const build = Effect.gen(function* () {
6975
7709
  const store = makeStore(database, yield* database.Database);
6976
- yield* store.create();
7710
+ yield* store.ensure();
6977
7711
  const scope = yield* Effect.scope;
7712
+ const owner = randomUUID();
7713
+ yield* Effect.addFinalizer(() => Effect.catchCause(store.release(owner), () => Effect.void));
6978
7714
  const executionKey = stateKeys.execution;
6979
7715
  const activityKey = stateKeys.activity;
6980
7716
  const deferredKey = (id, name) => `deferred/${id}/${name}`;
6981
7717
  const clockKey = (id, name) => `clock/${id}/${name}`;
7718
+ const seenDeferreds = /* @__PURE__ */ new Map();
7719
+ const sawDeferred = (key) => {
7720
+ const runId = runIdOf(key);
7721
+ const state = executions.get(runId);
7722
+ if (!state || state.finished) return;
7723
+ const seen = seenDeferreds.get(runId) ?? /* @__PURE__ */ new Set();
7724
+ seenDeferreds.set(runId, seen);
7725
+ seen.add(key);
7726
+ };
6982
7727
  const sleepKey = (id, name, attempt) => `sleep/${id}/${name}/${attempt}`;
6983
7728
  /**
6984
7729
  * `DurableClock.sleep` of at most 60 seconds is an in-memory sleep inside an
@@ -6996,17 +7741,37 @@ function workflowEngine(database) {
6996
7741
  const activities = /* @__PURE__ */ new Map();
6997
7742
  const deferredState = WorkflowEngine$1.makeDeferredState();
6998
7743
  const deferredResults = /* @__PURE__ */ new Map();
7744
+ /** Drops a run that leaves this process, with what it cached, so a later run of the same id reads the store. */
7745
+ const forget = (executionId) => {
7746
+ executions.delete(executionId);
7747
+ const prefix = `${executionId}/`;
7748
+ for (const cache of [activities, deferredResults]) for (const key of cache.keys()) if (key.startsWith(prefix)) cache.delete(key);
7749
+ };
6999
7750
  const clocks = yield* FiberMap.make();
7000
7751
  const runSetup = Semaphore.makeUnsafe(1);
7752
+ const unsaved = /* @__PURE__ */ new Map();
7753
+ const awaitedElsewhere = /* @__PURE__ */ new Map();
7754
+ const lost = /* @__PURE__ */ new Map();
7001
7755
  let lastStamp = 0;
7002
7756
  const stamp = () => lastStamp = Math.max(Date.now(), lastStamp + .001);
7003
- /** Marks the execution done, with its result, which `poll` reads once the process that ran it is gone. */
7004
- const finish = (name, executionId, result) => Effect.flatMap(store.get(executionKey(name, executionId)), (row) => row === void 0 ? Effect.void : Effect.flatMap(encodeResult(result), (saved) => Effect.asVoid(store.set(executionKey(name, executionId), JSON.stringify({
7005
- ...JSON.parse(row),
7006
- done: true,
7007
- result: saved,
7008
- completedAt: Date.now()
7009
- })))));
7757
+ /**
7758
+ * Ends the execution, `failed` when its result is a failure, with the result,
7759
+ * which `poll` reads once the process that ran it is gone, and the cause.
7760
+ */
7761
+ const finish = (name, executionId, result) => Effect.flatMap(store.get(executionKey(name, executionId)), (row) => row === void 0 ? Effect.void : Effect.flatMap(encodeResult(result), (saved) => {
7762
+ const failed = result._tag === "Complete" && Exit.isFailure(result.exit);
7763
+ const at = Date.now();
7764
+ return Effect.asVoid(store.finish(executionKey(name, executionId), JSON.stringify({
7765
+ ...JSON.parse(row),
7766
+ done: true,
7767
+ ...failed && {
7768
+ failed: true,
7769
+ error: Cause.pretty(result.exit.cause).slice(0, 4e3)
7770
+ },
7771
+ result: saved,
7772
+ completedAt: at
7773
+ }), failed ? "failed" : "done", at));
7774
+ }));
7010
7775
  /** The result of an execution that finished before this process started, if it did. */
7011
7776
  const saved = (name, executionId) => Effect.gen(function* () {
7012
7777
  const row = yield* store.get(executionKey(name, executionId));
@@ -7044,9 +7809,45 @@ function workflowEngine(database) {
7044
7809
  const close = Scope.close(executionScope, Exit.void);
7045
7810
  if (Exit.isFailure(exit)) return close;
7046
7811
  const wakeParents = (fiber) => Fiber.await(fiber).pipe(Effect.flatMap(() => Effect.forEach(state.parents, (parent) => Effect.forkIn(resume(parent, "automatic"), scope), { discard: true })), Effect.forkIn(scope));
7047
- return close.pipe(Effect.andThen(finish(instance.workflow._tag, instance.executionId, exit.value)), Effect.andThen(Deferred.succeed(state.done, void 0)), Effect.ensuring(Effect.withFiber(wakeParents)));
7812
+ return close.pipe(Effect.andThen(Effect.suspend(() => {
7813
+ state.finished = true;
7814
+ seenDeferreds.delete(instance.executionId);
7815
+ const write = finish(instance.workflow._tag, instance.executionId, exit.value);
7816
+ return write.pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.sync(() => {
7817
+ console.error(`[Brick] Workflow run ${instance.executionId} ended, but its end could not be saved; trying again:`, Cause.pretty(cause));
7818
+ unsaved.set(instance.executionId, write);
7819
+ })));
7820
+ })), Effect.andThen(Deferred.succeed(state.done, void 0)), Effect.andThen(Effect.sync(() => {
7821
+ if (!unsaved.has(instance.executionId) && executions.get(instance.executionId) === state) forget(instance.executionId);
7822
+ })), Effect.ensuring(Effect.withFiber(wakeParents)));
7048
7823
  }), Effect.forkIn(entry.scope));
7049
7824
  }, runSetup.withPermits(1));
7825
+ /**
7826
+ * What a start that did not take the run waits for: its result, once the
7827
+ * process that holds it has finished it, or its state here, if this process
7828
+ * takes it over meanwhile. A parent run does not wait: it suspends, and is
7829
+ * woken when the result is there (see `awaitedElsewhere`).
7830
+ */
7831
+ const held = (name, executionId, parentId) => Effect.gen(function* () {
7832
+ for (let delay = 20;; delay = Math.min(delay * 2, 500)) {
7833
+ const state = executions.get(executionId);
7834
+ if (state?.fiber) return { state };
7835
+ const row = yield* store.get(executionKey(name, executionId));
7836
+ if (row === void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`Workflow run "${executionId}" was deleted`));
7837
+ const { result } = JSON.parse(row);
7838
+ if (result !== void 0) return { result: yield* decodeResult(result) };
7839
+ if (parentId !== void 0) {
7840
+ const waiting = awaitedElsewhere.get(executionId);
7841
+ if (waiting) waiting.parents.add(parentId);
7842
+ else awaitedElsewhere.set(executionId, {
7843
+ name,
7844
+ parents: /* @__PURE__ */ new Set([parentId])
7845
+ });
7846
+ return { suspended: true };
7847
+ }
7848
+ yield* Effect.sleep(delay);
7849
+ }
7850
+ });
7050
7851
  const start = (workflow, options) => Effect.gen(function* () {
7051
7852
  const entry = workflows.get(workflow._tag);
7052
7853
  if (!entry) return yield* Effect.orDie(Effect.fail(`Workflow ${workflow._tag} is not registered`));
@@ -7054,55 +7855,177 @@ function workflowEngine(database) {
7054
7855
  let state = executions.get(options.executionId);
7055
7856
  if (!state) {
7056
7857
  const key = executionKey(workflow._tag, options.executionId);
7057
- if ((yield* store.get(key)) === void 0) yield* store.set(key, JSON.stringify({
7858
+ const now = Date.now();
7859
+ if (!((yield* store.begin(key, JSON.stringify({
7058
7860
  payload: options.payload,
7059
7861
  done: false,
7060
- startedAt: Date.now()
7061
- }));
7062
- state = {
7063
- payload: options.payload,
7064
- execute: entry.execute,
7065
- instance: WorkflowEngine$1.WorkflowInstance.initial(workflow, options.executionId),
7066
- interrupted: false,
7067
- interruptedUnsafe: false,
7068
- resumeRequested: void 0,
7069
- fiber: void 0,
7070
- done: Deferred.makeUnsafe(),
7071
- scope: Scope.makeUnsafe(),
7072
- parents: new Set(parentId === void 0 ? [] : [parentId])
7073
- };
7074
- executions.set(options.executionId, state);
7075
- yield* resume(options.executionId, "explicit");
7862
+ startedAt: now
7863
+ }), owner, now + leaseMs, options.parent?.executionId)) || (yield* store.claim(key, owner, now, now + leaseMs)))) {
7864
+ if (options.discard) return;
7865
+ const found = yield* held(workflow._tag, options.executionId, parentId);
7866
+ if ("suspended" in found) return new Workflow$1.Suspended({});
7867
+ if ("result" in found) return found.result;
7868
+ state = found.state;
7869
+ } else {
7870
+ state = {
7871
+ payload: options.payload,
7872
+ execute: entry.execute,
7873
+ instance: WorkflowEngine$1.WorkflowInstance.initial(workflow, options.executionId),
7874
+ interrupted: false,
7875
+ interruptedUnsafe: false,
7876
+ resumeRequested: void 0,
7877
+ fiber: void 0,
7878
+ done: Deferred.makeUnsafe(),
7879
+ scope: Scope.makeUnsafe(),
7880
+ finished: false,
7881
+ parents: new Set(parentId === void 0 ? [] : [parentId])
7882
+ };
7883
+ executions.set(options.executionId, state);
7884
+ yield* resume(options.executionId, "explicit");
7885
+ }
7076
7886
  } else if (parentId !== void 0) state.parents.add(parentId);
7077
7887
  if (options.discard) return;
7078
- const instance = state.instance;
7079
- const exit = yield* Fiber.await(state.fiber);
7080
- if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause) && instance.suspended) return new Workflow$1.Suspended({});
7081
- return yield* exit;
7888
+ for (;;) {
7889
+ const instance = state.instance;
7890
+ const exit = yield* Fiber.await(state.fiber);
7891
+ if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) {
7892
+ if (instance.suspended) return new Workflow$1.Suspended({});
7893
+ if (executions.get(options.executionId) !== state) {
7894
+ const found = yield* held(workflow._tag, options.executionId, parentId);
7895
+ if ("suspended" in found) return new Workflow$1.Suspended({});
7896
+ if ("result" in found) return found.result;
7897
+ state = found.state;
7898
+ continue;
7899
+ }
7900
+ }
7901
+ return yield* exit;
7902
+ }
7903
+ });
7904
+ /** Takes the unfinished runs of the registered workflows that no process holds, and runs them. */
7905
+ const recover = Effect.gen(function* () {
7906
+ for (const { key, value } of yield* store.unheld(Date.now())) {
7907
+ const rest = key.slice(10);
7908
+ const slash = rest.lastIndexOf("/");
7909
+ const entry = workflows.get(rest.slice(0, slash));
7910
+ const executionId = rest.slice(slash + 1);
7911
+ if (!entry || executions.has(executionId)) continue;
7912
+ yield* start(entry.workflow, {
7913
+ executionId,
7914
+ payload: JSON.parse(value).payload,
7915
+ discard: true
7916
+ });
7917
+ }
7918
+ });
7919
+ /** Extends the leases this process holds. A run it no longer holds was taken by another process, which found its lease run out: stop running it here. */
7920
+ const renew = Effect.gen(function* () {
7921
+ const before = [...executions.keys()];
7922
+ const kept = yield* store.renew(owner, Date.now() + leaseMs);
7923
+ for (const executionId of before) {
7924
+ const state = executions.get(executionId);
7925
+ if (!state || state.finished || kept.has(executionKey(state.instance.workflow._tag, executionId))) continue;
7926
+ forget(executionId);
7927
+ seenDeferreds.delete(executionId);
7928
+ console.warn(`[Brick] Workflow run ${executionId} was taken by another process: its lease ran out here.`);
7929
+ if (state.fiber) yield* Fiber.interrupt(state.fiber);
7930
+ const waiting = lost.get(executionId);
7931
+ if (waiting) waiting.dones.push(state.done);
7932
+ else lost.set(executionId, {
7933
+ name: state.instance.workflow._tag,
7934
+ dones: [state.done]
7935
+ });
7936
+ }
7937
+ });
7938
+ /** Completes the `done` of the lost runs that have ended, here or in the process that took them: one read of each per turn, and none for a run this process took back. */
7939
+ const settleLost = Effect.gen(function* () {
7940
+ for (const [executionId, { name, dones }] of lost) {
7941
+ const here = executions.get(executionId);
7942
+ if (here && !here.finished) continue;
7943
+ if (!here) {
7944
+ const row = yield* store.get(executionKey(name, executionId));
7945
+ if (row !== void 0 && JSON.parse(row).result === void 0) continue;
7946
+ }
7947
+ lost.delete(executionId);
7948
+ for (const done of dones) yield* Deferred.succeed(done, void 0);
7949
+ }
7950
+ });
7951
+ /** Writes the end of the runs whose write failed. */
7952
+ const saveUnsaved = Effect.gen(function* () {
7953
+ for (const [executionId, write] of unsaved) {
7954
+ const exit = yield* Effect.exit(write);
7955
+ if (Exit.isSuccess(exit)) {
7956
+ unsaved.delete(executionId);
7957
+ if (executions.get(executionId)?.finished) forget(executionId);
7958
+ } else if (Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause);
7959
+ }
7960
+ });
7961
+ /**
7962
+ * A durable deferred another process completed was saved, but only the
7963
+ * process that holds a suspended run can wake it: look for those. A parent
7964
+ * suspended on a child another process runs is woken when the child ends.
7965
+ */
7966
+ const wake = Effect.gen(function* () {
7967
+ for (const [executionId, { name, parents }] of awaitedElsewhere) {
7968
+ const row = yield* store.get(executionKey(name, executionId));
7969
+ if (row !== void 0 && JSON.parse(row).result === void 0) continue;
7970
+ awaitedElsewhere.delete(executionId);
7971
+ for (const parent of parents) yield* Effect.forkIn(resume(parent, "automatic"), scope);
7972
+ }
7973
+ const suspended = [...executions].filter(([, state]) => {
7974
+ const exit = state.fiber?.pollUnsafe();
7975
+ return !state.finished && exit?._tag === "Success" && exit.value._tag === "Suspended";
7976
+ }).map(([executionId]) => executionId);
7977
+ for (let i = 0; i < suspended.length; i += 200) for (const key of yield* store.deferreds(suspended.slice(i, i + 200))) {
7978
+ if (seenDeferreds.get(runIdOf(key))?.has(key)) continue;
7979
+ sawDeferred(key);
7980
+ yield* resume(runIdOf(key), "automatic");
7981
+ }
7982
+ });
7983
+ /** Deletes the runs that ended before the retention allows. */
7984
+ const sweep = Effect.gen(function* () {
7985
+ if (!retention) return;
7986
+ for (const [status, days] of [["done", retention.doneDays], ["failed", retention.failedDays]]) for (;;) {
7987
+ const ids = yield* store.endedBefore(status, Date.now() - days * DAY, 500);
7988
+ if (ids.length === 0) break;
7989
+ yield* store.remove(ids);
7990
+ }
7991
+ });
7992
+ const guarded = (what, effect) => Effect.catchCause(effect, (cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.sync(() => console.error(`[Brick] Workflow engine ${what} failed:`, Cause.pretty(cause))));
7993
+ let lastSweep = 0;
7994
+ const turn = Effect.gen(function* () {
7995
+ yield* guarded("saving the end of runs", saveUnsaved);
7996
+ yield* guarded("backfill", store.backfill);
7997
+ yield* guarded("recovery", recover);
7998
+ yield* guarded("deferred check", wake);
7999
+ yield* guarded("lost runs", settleLost);
8000
+ if (Date.now() - lastSweep >= (retention?.intervalMs ?? 0)) {
8001
+ lastSweep = Date.now();
8002
+ yield* guarded("retention sweep", sweep);
8003
+ }
8004
+ });
8005
+ let maintaining = false;
8006
+ /** What a process does once it runs workflows: take what is free now, and go on renewing, taking and sweeping. A process that registers none never starts it. */
8007
+ const maintain = Effect.gen(function* () {
8008
+ yield* recover;
8009
+ if (maintaining) return;
8010
+ maintaining = true;
8011
+ const every = Schedule.spaced(Math.max(10, Math.floor(leaseMs / 3)));
8012
+ yield* Effect.forkIn(pollUnref(guarded("lease renewal", renew), every), scope);
8013
+ yield* Effect.forkIn(pollUnref(turn, every), scope);
7082
8014
  });
7083
8015
  const engine = WorkflowEngine$1.makeUnsafe({
7084
8016
  register: Effect.fnUntraced(function* (workflow, execute) {
7085
- const entry = {
8017
+ workflows.set(workflow._tag, {
7086
8018
  workflow,
7087
8019
  execute,
7088
8020
  scope: yield* Effect.scope
7089
- };
7090
- workflows.set(workflow._tag, entry);
7091
- const prefix = executionKey(workflow._tag, "");
7092
- for (const { key, value } of yield* store.list(prefix)) {
7093
- const row = JSON.parse(value);
7094
- if (row.done) continue;
7095
- yield* start(workflow, {
7096
- executionId: key.slice(prefix.length),
7097
- payload: row.payload,
7098
- discard: true
7099
- });
7100
- }
8021
+ });
8022
+ yield* maintain;
7101
8023
  }),
7102
8024
  execute: start,
7103
- awaitComplete: (_workflow, executionId) => Effect.suspend(() => {
8025
+ awaitComplete: (workflow, executionId) => Effect.suspend(() => {
7104
8026
  const state = executions.get(executionId);
7105
- return state ? Deferred.await(state.done) : Effect.never;
8027
+ if (state) return Deferred.await(state.done);
8028
+ return saved(workflow._tag, executionId).pipe(Effect.flatMap((result) => Option.isSome(result) ? Effect.void : Effect.never));
7106
8029
  }),
7107
8030
  interrupt: Effect.fnUntraced(function* (_workflow, executionId) {
7108
8031
  const state = executions.get(executionId);
@@ -7155,8 +8078,10 @@ function workflowEngine(database) {
7155
8078
  const id = `${instance.executionId}/${deferred.name}`;
7156
8079
  const known = deferredResults.get(id);
7157
8080
  if (known) return Option.some(known);
7158
- const saved = yield* store.get(deferredKey(instance.executionId, deferred.name));
8081
+ const key = deferredKey(instance.executionId, deferred.name);
8082
+ const saved = yield* store.get(key);
7159
8083
  if (saved === void 0) return Option.none();
8084
+ sawDeferred(key);
7160
8085
  const result = yield* decodeResult(saved);
7161
8086
  if (result._tag !== "Complete") return Option.none();
7162
8087
  deferredResults.set(id, result.exit);
@@ -7166,6 +8091,7 @@ function workflowEngine(database) {
7166
8091
  const id = `${options.executionId}/${options.deferredName}`;
7167
8092
  if (deferredResults.has(id)) return Effect.void;
7168
8093
  deferredResults.set(id, options.exit);
8094
+ sawDeferred(deferredKey(options.executionId, options.deferredName));
7169
8095
  const wake = Effect.andThen(deferredState.deferredDone(options.executionId, options.deferredName), resume(options.executionId, "automatic"));
7170
8096
  return Effect.flatMap(Effect.flatMap(encodeResult(new Workflow$1.Complete({ exit: options.exit })), (saved) => store.set(deferredKey(options.executionId, options.deferredName), saved)), () => Effect.flatMap(Effect.serviceOption(WorkflowEngine$1.WorkflowInstance), (instance) => Option.isSome(instance) && instance.value.executionId === options.executionId ? wake.pipe(Effect.forkIn(scope), Effect.asVoid) : wake));
7171
8097
  }),
@@ -7222,6 +8148,12 @@ const outcome = (text) => Effect.map(decodeResult(text), (result) => result._tag
7222
8148
  status: "failed",
7223
8149
  error: failure(result._tag === "Complete" && Exit.isFailure(result.exit) ? result.exit.cause : Cause.fail("The workflow suspended"))
7224
8150
  });
8151
+ /**
8152
+ * The Workflow SDK names a workflow `workflow//<module>//<name>`, and the
8153
+ * inspector shows `?` for a name that is not in that form, so an Effect
8154
+ * workflow is presented as one in the module `effect`.
8155
+ */
8156
+ const machineName = (name) => `workflow//effect//${name}`;
7225
8157
  const stepIdOf = (name, attempt) => `${name}:${attempt}`;
7226
8158
  /** Pages `items` (already in ascending order) by an offset cursor. */
7227
8159
  function paginate(items, options = {}) {
@@ -7267,7 +8199,7 @@ function workflowWorld(state, run) {
7267
8199
  runId: id,
7268
8200
  status: done?.status ?? "running",
7269
8201
  deploymentId: "effect",
7270
- workflowName: name,
8202
+ workflowName: machineName(name),
7271
8203
  attributes: {},
7272
8204
  createdAt: startedAt,
7273
8205
  startedAt,
@@ -7330,7 +8262,7 @@ function workflowWorld(state, run) {
7330
8262
  createdAt: current.createdAt,
7331
8263
  eventData: {
7332
8264
  deploymentId: current.deploymentId,
7333
- workflowName: name,
8265
+ workflowName: machineName(name),
7334
8266
  ...data && { input: current.input }
7335
8267
  }
7336
8268
  }, {
@@ -7383,7 +8315,7 @@ function workflowWorld(state, run) {
7383
8315
  return {
7384
8316
  runs: {
7385
8317
  list: (options = {}) => run(Effect.gen(function* () {
7386
- const all = (yield* executions).filter((item) => !options.workflowName || item.name === options.workflowName);
8318
+ const all = (yield* executions).filter((item) => !options.workflowName || machineName(item.name) === options.workflowName);
7387
8319
  return paginate((yield* Effect.forEach(all, (item) => toRun(item.name, item.id, item.row, withData(options)))).filter((item) => !options.status || item.status === options.status).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()), options);
7388
8320
  })),
7389
8321
  get: (runId, options) => run(Effect.flatMap(find(runId), (item) => toRun(item.name, item.id, item.row, withData(options))))
@@ -7428,11 +8360,17 @@ function workflowWorld(state, run) {
7428
8360
  // src/server.ts
7429
8361
  const success = (result) => result === void 0 ? HttpServerResponse.empty({ status: 200 }) : result instanceof Response ? HttpServerResponse.fromWeb(result) : typeof result === "string" ? HttpServerResponse.text(result) : HttpServerResponse.jsonUnsafe(result);
7430
8362
  const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7431
- /** The body of a plugin endpoint's request: JSON, else text. Read from a copy, so the handler's `request` stays unread. */
7432
- const readBody = (web) => web.method === "GET" || web.method === "HEAD" ? Effect.succeed(void 0) : Effect.gen(function* () {
7433
- const text = yield* Effect.promise(() => web.clone().text());
8363
+ /** The body of a plugin endpoint's request: JSON, else text, read up to `limit` bytes. Read from a copy, so the handler's `request` stays unread. */
8364
+ const readBody = (web, limit) => web.method === "GET" || web.method === "HEAD" ? Effect.succeed(void 0) : Effect.gen(function* () {
8365
+ let text;
8366
+ if (limit === void 0) text = yield* Effect.promise(() => web.clone().text());
8367
+ else {
8368
+ const bytes = yield* Effect.promise(() => readCapped(web.clone(), limit));
8369
+ if (bytes === void 0) return yield* payloadTooLarge(limit);
8370
+ text = new TextDecoder().decode(bytes);
8371
+ }
7434
8372
  if (!text) return void 0;
7435
- if (!web.headers.get("content-type")?.includes("json")) return text;
8373
+ if (!web.headers.get("content-type")?.toLowerCase().includes("json")) return text;
7436
8374
  try {
7437
8375
  return JSON.parse(text);
7438
8376
  } catch {
@@ -7455,29 +8393,14 @@ const formObject = (form) => Object.fromEntries([...new Set(form.keys())].map((k
7455
8393
  const values = form.getAll(key);
7456
8394
  return [key, values.length > 1 ? values : values[0]];
7457
8395
  }));
7458
- /** The body's bytes, or `undefined` once it passes `limit`: a chunked body has no Content-Length to check. */
7459
- const readBounded = async (body, limit) => {
7460
- const chunks = [];
7461
- let size = 0;
7462
- for await (const chunk of body) {
7463
- size += chunk.byteLength;
7464
- if (size > limit) return void 0;
7465
- chunks.push(chunk);
7466
- }
7467
- return new Uint8Array(Buffer.concat(chunks));
7468
- };
7469
8396
  /**
7470
8397
  * The action's input and how it arrived: the query string, a multipart form, or
7471
8398
  * the JSON body, with the path parameters on top.
7472
8399
  */
7473
8400
  const readInput = (route, action, web) => Effect.gen(function* () {
7474
8401
  const { input } = action.config;
7475
- const tooLarge = () => new BrickError({
7476
- code: "PAYLOAD_TOO_LARGE",
7477
- message: `Request body exceeds ${route.bodyLimit} bytes`,
7478
- status: 413
7479
- });
7480
- if (route.bodyLimit !== void 0 && Number(web.headers.get("content-length")) > route.bodyLimit) return yield* tooLarge();
8402
+ const { bodyLimit } = route;
8403
+ if (bodyLimit !== void 0 && declaresOver(web, bodyLimit)) return yield* payloadTooLarge(bodyLimit);
7481
8404
  if (!input) return {
7482
8405
  input: void 0,
7483
8406
  wire: "json"
@@ -7490,11 +8413,13 @@ const readInput = (route, action, web) => Effect.gen(function* () {
7490
8413
  },
7491
8414
  wire: "query"
7492
8415
  };
7493
- const bounded = route.bodyLimit !== void 0 && web.body ? yield* Effect.promise(() => readBounded(web.body, route.bodyLimit)) : void 0;
7494
- if (route.bodyLimit !== void 0 && web.body && !bounded) return yield* tooLarge();
7495
- if (web.headers.get("content-type")?.startsWith("multipart/form-data")) {
8416
+ const bounded = bodyLimit !== void 0 && web.body ? yield* Effect.promise(() => readCapped(web, bodyLimit)) : void 0;
8417
+ if (bodyLimit !== void 0 && web.body && !bounded) return yield* payloadTooLarge(bodyLimit);
8418
+ const contentType = web.headers.get("content-type") ?? "";
8419
+ const type = contentType.toLowerCase();
8420
+ if (type.startsWith("multipart/form-data")) {
7496
8421
  const form = yield* Effect.tryPromise({
7497
- try: () => (bounded ? new Response(bounded, { headers: { "content-type": web.headers.get("content-type") } }) : web).formData(),
8422
+ try: () => (bounded ? new Response(bounded, { headers: { "content-type": contentType } }) : web).formData(),
7498
8423
  catch: () => invalid$1(action.name, "input", [{
7499
8424
  path: "",
7500
8425
  message: "Body is not valid multipart/form-data"
@@ -7511,14 +8436,16 @@ const readInput = (route, action, web) => Effect.gen(function* () {
7511
8436
  const request = yield* HttpServerRequest.HttpServerRequest;
7512
8437
  const text = bounded ? new TextDecoder().decode(bounded) : yield* request.text;
7513
8438
  let body;
7514
- if (text) try {
7515
- body = JSON.parse(text);
8439
+ if (type.includes("json")) try {
8440
+ body = text ? JSON.parse(text) ?? void 0 : void 0;
7516
8441
  } catch {
7517
8442
  return yield* invalid$1(action.name, "input", [{
7518
8443
  path: "",
7519
8444
  message: "Body is not valid JSON"
7520
8445
  }]);
7521
8446
  }
8447
+ else if (type.startsWith("application/x-www-form-urlencoded")) body = text ? formObject(new URLSearchParams(text)) : void 0;
8448
+ else body = type.startsWith("text/") ? text || void 0 : void 0;
7522
8449
  return {
7523
8450
  input: Object.keys(params).length && (body === void 0 || isPlainObject(body)) ? {
7524
8451
  ...body,
@@ -7528,7 +8455,7 @@ const readInput = (route, action, web) => Effect.gen(function* () {
7528
8455
  };
7529
8456
  });
7530
8457
  /** The error an endpoint's handler failed with, as a 4xx the way a thrown `{ status }` is in core. */
7531
- const httpStatusError = (error) => !(error instanceof BrickError || error instanceof ValidationError) && error !== null && typeof error === "object" && "status" in error && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 400 && error.status < 500 ? new BrickError({
8458
+ const httpStatusError = (error) => !asFailure(error) && error !== null && typeof error === "object" && "status" in error && typeof error.status === "number" && Number.isInteger(error.status) && error.status >= 400 && error.status < 500 ? new BrickError({
7532
8459
  code: "HTTP_ERROR",
7533
8460
  message: "message" in error && typeof error.message === "string" ? error.message : "Endpoint error",
7534
8461
  status: error.status
@@ -7624,6 +8551,7 @@ function brick(options = {}) {
7624
8551
  });
7625
8552
  const mountedEndpoints = [];
7626
8553
  const mountEndpoint = (def, plugin = false) => {
8554
+ checkBodyLimit(`Endpoint '${def.method} ${def.path}'`, def.maxBodyBytes);
7627
8555
  const mounted = claim(def.method, def.path, plugin);
7628
8556
  endpointDefs.push(def);
7629
8557
  if (mounted) served.add(def);
@@ -7706,6 +8634,12 @@ function brick(options = {}) {
7706
8634
  const runtime = ManagedRuntime.make(events ? events.layer.pipe(Layer.provideMerge(base)) : base);
7707
8635
  const appEvents = events?.bind(runtime);
7708
8636
  const log = loggerOf(requestLogging);
8637
+ const failures = /* @__PURE__ */ new WeakMap();
8638
+ const noteFailure = (request, cause, envelope) => {
8639
+ if (envelope.status < 500) return;
8640
+ const error = Cause.squash(cause);
8641
+ failures.set(request, (error instanceof BrickError || error instanceof ValidationError) && error.cause !== void 0 ? error.cause : error);
8642
+ };
7709
8643
  /**
7710
8644
  * The route's response, with the trace ids echoed and the request logged.
7711
8645
  * With `trace`, and `telemetry` on, the request is a span.
@@ -7724,6 +8658,7 @@ function brick(options = {}) {
7724
8658
  requestId: ids.requestId
7725
8659
  });
7726
8660
  failure = envelope;
8661
+ noteFailure(web, cause, envelope);
7727
8662
  const retry = envelope.details?.retryAfterSeconds;
7728
8663
  return HttpServerResponse.jsonUnsafe(envelope, {
7729
8664
  status: envelope.status,
@@ -7766,7 +8701,7 @@ function brick(options = {}) {
7766
8701
  return HttpRouter.route(def.method, def.path, serve(({ traceId, requestId }, web) => Effect.gen(function* () {
7767
8702
  const set = { headers: {} };
7768
8703
  const params = Object.fromEntries(Object.entries(yield* HttpRouter.params).filter(([, value]) => value !== void 0));
7769
- const body = yield* readBody(web);
8704
+ const body = yield* readBody(web, def.maxBodyBytes);
7770
8705
  const result = yield* Effect.gen(function* () {
7771
8706
  const db = database && (yield* database.Database);
7772
8707
  return yield* def.handler({
@@ -7781,7 +8716,11 @@ function brick(options = {}) {
7781
8716
  traceId,
7782
8717
  requestId
7783
8718
  });
7784
- }).pipe(Effect.mapError(httpStatusError), Effect.provideContext(yield* runtime.contextEffect));
8719
+ }).pipe(Effect.catchCause((cause) => {
8720
+ const thrown = Cause.findDefect(cause);
8721
+ const failure = Result.isSuccess(thrown) ? httpStatusError(thrown.success) : thrown;
8722
+ return failure instanceof BrickError ? Effect.fail(failure) : Effect.failCause(cause);
8723
+ }), Effect.mapError(httpStatusError), Effect.provideContext(yield* runtime.contextEffect));
7785
8724
  return HttpServerResponse.fromWeb(answer(result, set));
7786
8725
  }), {
7787
8726
  method: def.method,
@@ -7879,8 +8818,8 @@ function brick(options = {}) {
7879
8818
  }
7880
8819
  return web;
7881
8820
  };
7882
- /** What a plugin's middleware answers with, or `undefined` to let the request through. */
7883
- const intercept = async (request) => {
8821
+ /** What a plugin's middleware answers with, or `undefined` to let the request through. `carried` collects the headers each one set, for the response either way. */
8822
+ const intercept = async (request, carried) => {
7884
8823
  for (const handler of plugins.middleware) {
7885
8824
  const set = { headers: {} };
7886
8825
  const answered = await runtime.runPromise(handler({
@@ -7888,11 +8827,41 @@ function brick(options = {}) {
7888
8827
  set
7889
8828
  }).pipe(Effect.map((result) => result === void 0 ? void 0 : answer(result, set)), Effect.catchCause((cause) => Effect.sync(() => {
7890
8829
  const envelope = toErrorResponse(cause, { logger });
8830
+ noteFailure(request, cause, envelope);
7891
8831
  return Response.json(envelope, { status: envelope.status });
7892
8832
  }))));
8833
+ Object.assign(carried, set.headers);
7893
8834
  if (answered) return answered;
7894
8835
  }
7895
8836
  };
8837
+ /** Run an app hook: its result, or `undefined` after logging a failure of it, which is never the request's. */
8838
+ const runHook = async (name, effect) => {
8839
+ try {
8840
+ return await runtime.runPromise(effect.pipe(Effect.map((value) => ({ value })), Effect.catchCause((cause) => Effect.sync(() => {
8841
+ logger.error(`The ${name} hook failed`, {}, Cause.pretty(cause));
8842
+ }))));
8843
+ } catch (error) {
8844
+ logger.error(`The ${name} hook failed`, {}, error);
8845
+ }
8846
+ };
8847
+ /** `onError`, then `onResponse`, on what the app is about to send. */
8848
+ const hooked = async (request, response) => {
8849
+ if (options.onError && response.status >= 500 && failures.has(request)) {
8850
+ const replacement = await runHook("onError", options.onError({
8851
+ error: failures.get(request),
8852
+ request,
8853
+ response
8854
+ }));
8855
+ if (replacement?.value instanceof Response) response = keepTraceIds(replacement.value, response);
8856
+ }
8857
+ if (!options.onResponse) return response;
8858
+ const headers = new Headers(response.headers);
8859
+ return await runHook("onResponse", options.onResponse({
8860
+ request,
8861
+ status: response.status,
8862
+ headers
8863
+ })) ? withHeaders(response, headers) : response;
8864
+ };
7896
8865
  const fetch = async (input, init) => {
7897
8866
  const request = input instanceof Request && init === void 0 ? input : new Request(input, init);
7898
8867
  markAddressSource(request, {
@@ -7900,16 +8869,17 @@ function brick(options = {}) {
7900
8869
  server: () => server
7901
8870
  });
7902
8871
  const policy = cors?.(request);
7903
- if (policy?.preflight) return policy.preflight;
7904
- const response = (plugins.middleware.length ? await intercept(request) : void 0) ?? await router().handler(request);
7905
- if (!policy || !Object.keys(policy.headers).length) return response;
7906
- const headers = new Headers(response.headers);
7907
- for (const [name, value] of Object.entries(policy.headers)) headers.set(name, value);
7908
- return new Response(response.body, {
7909
- status: response.status,
7910
- statusText: response.statusText,
7911
- headers
7912
- });
8872
+ if (policy?.preflight) return hooked(request, policy.preflight);
8873
+ const carried = {};
8874
+ let response = (plugins.middleware.length ? await intercept(request, carried) : void 0) ?? await router().handler(request);
8875
+ const corsHeaders = policy?.headers ?? {};
8876
+ if (Object.keys(carried).length || Object.keys(corsHeaders).length) {
8877
+ const headers = new Headers(response.headers);
8878
+ for (const [name, value] of Object.entries(carried)) if (!headers.has(name)) headers.set(name, value);
8879
+ for (const [name, value] of Object.entries(corsHeaders)) headers.set(name, value);
8880
+ response = withHeaders(response, headers);
8881
+ }
8882
+ return hooked(request, response);
7913
8883
  };
7914
8884
  const run = (effect) => runtime.runPromiseExit(effect);
7915
8885
  const raw = mountRawSockets({
@@ -7928,6 +8898,11 @@ function brick(options = {}) {
7928
8898
  run
7929
8899
  });
7930
8900
  const plugged = pluginLifecycle(plugins.lifecycles, (effect) => runtime.runPromise(effect));
8901
+ let stopped = false;
8902
+ const live = () => {
8903
+ if (stopped) throw new Error("Brick: the app has stopped, so it cannot run an effect in its runtime");
8904
+ return runtime;
8905
+ };
7931
8906
  let server;
7932
8907
  const app = {
7933
8908
  fetch,
@@ -7968,10 +8943,13 @@ function brick(options = {}) {
7968
8943
  await appEvents?.stop();
7969
8944
  } finally {
7970
8945
  for (const handler of [web, ...retired.splice(0)]) await handler.dispose();
8946
+ stopped = true;
7971
8947
  await runtime.dispose();
7972
8948
  }
7973
8949
  }
7974
8950
  },
8951
+ runPromise: (effect) => Promise.resolve().then(() => live().runPromise(effect)),
8952
+ runFork: (effect) => live().runFork(effect),
7975
8953
  events: appEvents,
7976
8954
  get server() {
7977
8955
  return server;
@@ -8020,6 +8998,6 @@ function brick(options = {}) {
8020
8998
  };
8021
8999
  return app;
8022
9000
  }
8023
- export { PLUGIN_KIND as $, envSource as $t, onTransactionCommit as A, telemetryLayer as An, errorHelpers as At, scalarDocsHTML as B, signDashboardIdentity as Bn, defineStorage as Bt, scheduleTable as C, baseContext as Cn, kindOf as Ct, defineServiceSocket as D, Telemetry as Dn, RESET_STAGES as Dt, SocketDenied as E, SpanStore as En, HTTP_METHODS as Et, encodePayload as F, dashboardIdentity as Fn, hasSensitive as Ft, getPluginActionRoute as G, actionMeta as Gn, storageKey as Gt, copyControls as H, ATTR as Hn, memory as Ht, isCrudEvent as I, dashboardKey as In, redact as It, installPlugin as J, STANDARD_ERRORS as Jn, scopeFiles as Jt, getPluginEndpoints as K, BrickError as Kn, LOCAL_FILES_ROUTE as Kt, OPENAPI_DEFAULTS as L, dashboardMcpCaller as Ln, sensitivePointer as Lt, crudEventName as M, traceScheduleRun as Mn, runStages as Mt, crudEventSource as N, DASHBOARD_IDENTITY_HEADER as Nn, stagesOf as Nt, localBroker as O, recordWebhook as On, createAction as Ot, defineEvents as P, DASHBOARD_KEY_ENV as Pn, Sensitive as Pt, PLUGIN_COMMIT as Q, toWireError as Qn, defineSecret as Qt, generateOpenApiSpec as R, dashboardUser as Rn, carryClientRequest as Rt, outboxTable as S, actorOf as Sn, jsonValue as St, defineRawSocket as T, defaultLogger as Tn, withoutNull as Tt, defineResourcePlugin as U, GLOBAL_SYMBOL as Un, redis as Ut, claimSegment as V, signDashboardMcp as Vn, frameworkStorage as Vt, defineServicePlugin as W, SPAN as Wn, requireStorage as Wt, internalsOf$1 as X, normalizeFailures as Xn, StorageUnavailableError as Xt, validatePath as Y, ValidationError as Yn, StorageError as Yt, setInternals as Z, toErrorResponse as Zn, SecretRef as Zt, idSchema as _, inlineAuditOptions as _n, databaseValue as _t, WORKFLOW_TABLE as a, definitionSite as an, getActionRoute as at, stopAllEvents as b, recordAudit as bn, idSchema$1 as bt, workflowEngine as c, ownDeps as cn, getActionAccess as ct, createMcpHandler as d, UploadedFile as dn, ORDERED_TYPES as dt, listSecrets as en, getGlobalRegistry as et, createMcpRegistry as f, UploadedFiles as fn, SORTABLE_TYPES as ft, defineResource as g, bindAuditTarget as gn, columnValue as gt, normalizeDashboard as h, auditTableOf as hn, columnSchema as ht, DurableDeferred as i, claimName as in, actionOwners as it, runInTransaction as j, traceRoute as jn, invalid$1 as jt, splitSeq as k, spanStore as kn, deny as kt, INTERNALS as l, useDeps as ln, setActionAccess as lt, DASHBOARD_MCP_TOOLS as m, auditTable as mn, checkJsonSchema as mt, Activity as n, resetSecrets as nn, exportArchitecture as nt, Workflow as o, depsOverride as on, isObjectSchema as ot, DASHBOARD_MCP_ROUTE as p, fileFields as pn, UNFILTERABLE_TYPES as pt, hasPlugin as q, DuplicateNameError as qn, s3 as qt, DurableClock as r, resolveSecrets as rn, DEFAULT_PREFIX as rt, WorkflowEngine as s, freezeAsBuiltDeps as sn, kebabCase as st, brick as t, overrideSecret as tn, resetGlobalRegistry as tt, UnknownToolError as u, withOverride as un, setActionAudit as ut, loadRecord as v, isAuditTable as vn, decodeCursor as vt, defineSchedule as w, createLogger as wn, reject as wt, defineListener as x, recordInline as xn, invalid as xt, Events as y, isInlineAudit as yn, encodeCursor as yt, requestLoggingPlugin as z, markDashboardArrival as zn, clientAddress as zt };
9001
+ export { PLUGIN_KIND as $, failureOfCause as $n, StorageUnavailableError as $t, onTransactionCommit as A, Telemetry as An, RESET_STAGES as At, scalarDocsHTML as B, dashboardMcpCaller as Bn, sensitivePointer as Bt, scheduleTable as C, recordAudit as Cn, idSchema$1 as Ct, defineServiceSocket as D, createLogger as Dn, reject as Dt, SocketDenied as E, baseContext as En, kindOf as Et, encodePayload as F, traceScheduleRun as Fn, runStages as Ft, getPluginActionRoute as G, ATTR as Gn, memory as Gt, copyControls as H, markDashboardArrival as Hn, clientAddress as Ht, isCrudEvent as I, DASHBOARD_IDENTITY_HEADER as In, stagesOf as It, installPlugin as J, actionMeta as Jn, storageKey as Jt, getPluginEndpoints as K, GLOBAL_SYMBOL as Kn, redis as Kt, OPENAPI_DEFAULTS as L, DASHBOARD_KEY_ENV as Ln, Sensitive as Lt, crudEventName as M, spanStore as Mn, deny as Mt, crudEventSource as N, telemetryLayer as Nn, errorHelpers as Nt, localBroker as O, defaultLogger as On, withoutNull as Ot, defineEvents as P, traceRoute as Pn, invalid$1 as Pt, PLUGIN_COMMIT as Q, ValidationError as Qn, StorageError as Qt, generateOpenApiSpec as R, dashboardIdentity as Rn, hasSensitive as Rt, outboxTable as S, isInlineAudit as Sn, encodeCursor as St, defineRawSocket as T, actorOf as Tn, jsonValue as Tt, defineResourcePlugin as U, signDashboardIdentity as Un, defineStorage as Ut, claimSegment as V, dashboardUser as Vn, carryClientRequest as Vt, defineServicePlugin as W, signDashboardMcp as Wn, frameworkStorage as Wt, internalsOf$1 as X, DuplicateNameError as Xn, s3 as Xt, validatePath as Y, BrickError as Yn, LOCAL_FILES_ROUTE as Yt, setInternals as Z, STANDARD_ERRORS as Zn, scopeFiles as Zt, idSchema as _, auditTable as _n, checkJsonSchema as _t, Workflow as a, resetSecrets as an, readCapped as at, stopAllEvents as b, inlineAuditOptions as bn, databaseValue as bt, WORKFLOW_TABLE as c, definitionSite as cn, getActionRoute as ct, createMcpHandler as d, ownDeps as dn, getActionAccess as dt, SecretRef as en, normalizeFailures as er, getGlobalRegistry as et, createMcpRegistry as f, useDeps as fn, setActionAccess as ft, defineResource as g, fileFields as gn, UNFILTERABLE_TYPES as gt, normalizeDashboard as h, UploadedFiles as hn, SORTABLE_TYPES as ht, DurableDeferred as i, overrideSecret as in, payloadTooLarge as it, runInTransaction as j, recordWebhook as jn, createAction as jt, splitSeq as k, SpanStore as kn, HTTP_METHODS as kt, INTERNALS as l, depsOverride as ln, isObjectSchema as lt, DASHBOARD_MCP_TOOLS as m, UploadedFile as mn, ORDERED_TYPES as mt, Activity as n, envSource as nn, toErrorResponse as nr, exportArchitecture as nt, WorkflowEngine as o, resolveSecrets as on, DEFAULT_PREFIX as ot, DASHBOARD_MCP_ROUTE as p, withOverride as pn, setActionAudit as pt, hasPlugin as q, SPAN as qn, requireStorage as qt, DurableClock as r, listSecrets as rn, toWireError as rr, checkBodyLimit as rt, workflowEngine as s, claimName as sn, actionOwners as st, brick as t, defineSecret as tn, prefixedFailure as tr, resetGlobalRegistry as tt, UnknownToolError as u, freezeAsBuiltDeps as un, kebabCase as ut, loadRecord as v, auditTableOf as vn, columnSchema as vt, defineSchedule as w, recordInline as wn, invalid as wt, defineListener as x, isAuditTable as xn, decodeCursor as xt, Events as y, bindAuditTarget as yn, columnValue as yt, requestLoggingPlugin as z, dashboardKey as zn, redact as zt };
8024
9002
 
8025
- //# sourceMappingURL=server-D-fDM98-.js.map
9003
+ //# sourceMappingURL=server-CqCh1xgf.js.map