@brickkit/effect 0.16.0-beta.9 → 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.
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -28
- package/dist/index.js.map +1 -1
- package/dist/{server-B1gl742e.js → server-CqCh1xgf.js} +346 -60
- package/dist/server-CqCh1xgf.js.map +1 -0
- package/dist/{server-CxyGTnai.d.ts → server-OV8Hd6Tx.d.ts} +79 -9
- package/dist/server-OV8Hd6Tx.d.ts.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- package/dist/server-B1gl742e.js.map +0 -1
- package/dist/server-CxyGTnai.d.ts.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
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";
|
|
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
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";
|
|
@@ -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. */
|
|
@@ -191,7 +197,8 @@ function toFailure(cause, { logger, requestId }) {
|
|
|
191
197
|
logger.error("Unexpected action error", { requestId }, Cause.pretty(cause));
|
|
192
198
|
const failure = new BrickError({
|
|
193
199
|
...STANDARD_ERRORS.INTERNAL_SERVER_ERROR,
|
|
194
|
-
code: "INTERNAL_SERVER_ERROR"
|
|
200
|
+
code: "INTERNAL_SERVER_ERROR",
|
|
201
|
+
cause: Cause.squash(cause)
|
|
195
202
|
});
|
|
196
203
|
built$1.add(failure);
|
|
197
204
|
logged$1.add(failure);
|
|
@@ -201,14 +208,15 @@ function toFailure(cause, { logger, requestId }) {
|
|
|
201
208
|
const normalizeFailures = (context) => (self) => Effect.catchCause(self, (cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.fail(toFailure(cause, context)));
|
|
202
209
|
/**
|
|
203
210
|
* The JSON body of a failed HTTP call. Declared failures and validation errors
|
|
204
|
-
* keep their code, status and details;
|
|
205
|
-
*
|
|
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.
|
|
206
214
|
*/
|
|
207
215
|
function toErrorResponse(cause, context) {
|
|
208
216
|
const known = failureOfCause(cause);
|
|
209
217
|
if (known) logServerFailure(known, cause, context);
|
|
210
218
|
return {
|
|
211
|
-
...toWireError(known ?? toFailure(cause, context)),
|
|
219
|
+
...toWireError(known ?? (Cause.hasInterruptsOnly(cause) ? new BrickError(CLIENT_CLOSED_REQUEST) : toFailure(cause, context))),
|
|
212
220
|
requestId: context.requestId ?? ""
|
|
213
221
|
};
|
|
214
222
|
}
|
|
@@ -2235,6 +2243,30 @@ function rateLimitStage(config, service) {
|
|
|
2235
2243
|
})
|
|
2236
2244
|
};
|
|
2237
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)));
|
|
2238
2270
|
// src/sensitive.ts
|
|
2239
2271
|
const MARK = "brickSensitive";
|
|
2240
2272
|
/**
|
|
@@ -2671,6 +2703,16 @@ function checkMessage(issue, parent) {
|
|
|
2671
2703
|
const notUndefined = (issue) => !(issue._tag === "InvalidType" && issue.ast._tag === "Undefined");
|
|
2672
2704
|
const isMissing = (issue) => issue._tag === "Pointer" && issue.issue._tag === "MissingKey";
|
|
2673
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
|
+
};
|
|
2674
2716
|
const expectedOf = (issue) => issue._tag === "Filter" ? issue.filter.annotations?.expected : void 0;
|
|
2675
2717
|
const filtersOf = (checks) => checks.flatMap((check) => check._tag === "FilterGroup" ? filtersOf(check.checks) : [check]);
|
|
2676
2718
|
const valueAt = (input, path) => path.reduce((value, key) => value?.[key], input);
|
|
@@ -2723,14 +2765,20 @@ function collect(issue, path, parent, override, out, phase) {
|
|
|
2723
2765
|
for (const child of childrenOf(issue, path, out.input)) collect(child, path, ast, override, out);
|
|
2724
2766
|
return;
|
|
2725
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
|
+
}
|
|
2726
2772
|
const missing = issue.issues.filter((child) => isMissing(child));
|
|
2727
2773
|
const extra = issue.issues.filter((child) => isExtra(child));
|
|
2728
2774
|
for (const child of missing) collect(child, path, issue.ast, override, out, "required");
|
|
2729
|
-
for (const child of extra) collect(child, path, issue.ast, override, out);
|
|
2775
|
+
if (out.extras !== "ignoreNested" || path.length === 0) for (const child of extra) collect(child, path, issue.ast, override, out);
|
|
2730
2776
|
for (const child of issue.issues) if (!extra.includes(child)) collect(child, path, issue.ast, override, out, isMissing(child) ? "type" : void 0);
|
|
2731
2777
|
return;
|
|
2732
2778
|
}
|
|
2733
2779
|
case "AnyOf": {
|
|
2780
|
+
const failedOnlyOnExtraKeys = issue.issues.some(onlyExtraKeys);
|
|
2781
|
+
if (out.extras === "ignoreNested" && failedOnlyOnExtraKeys) return;
|
|
2734
2782
|
if (override !== void 0) return add(override);
|
|
2735
2783
|
if (typeof issue.ast.annotations?.message === "string") return add(stockMessage(issue));
|
|
2736
2784
|
const { types } = issue.ast;
|
|
@@ -2765,10 +2813,11 @@ const pointer = (path) => path.map((item) => String(typeof item === "object" &&
|
|
|
2765
2813
|
* A custom `message` annotation wins; a check or schema core has no wording for
|
|
2766
2814
|
* keeps Effect's own text.
|
|
2767
2815
|
*/
|
|
2768
|
-
function issuesOf(error, input) {
|
|
2816
|
+
function issuesOf(error, input, options) {
|
|
2769
2817
|
const out = {
|
|
2770
2818
|
input,
|
|
2771
|
-
items: []
|
|
2819
|
+
items: [],
|
|
2820
|
+
...options
|
|
2772
2821
|
};
|
|
2773
2822
|
collect(error.issue, [], void 0, void 0, out);
|
|
2774
2823
|
return out.items.map(({ path, message }) => ({
|
|
@@ -2844,6 +2893,15 @@ function stagesOf(config, host, action) {
|
|
|
2844
2893
|
...all,
|
|
2845
2894
|
...strict && { onExcessProperty: "error" }
|
|
2846
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
|
+
};
|
|
2847
2905
|
return [
|
|
2848
2906
|
...dashboard ? [{
|
|
2849
2907
|
name: "dashboard",
|
|
@@ -2862,7 +2920,7 @@ function stagesOf(config, host, action) {
|
|
|
2862
2920
|
}] : [],
|
|
2863
2921
|
...decode ? [{
|
|
2864
2922
|
name: "input",
|
|
2865
|
-
run: (call, next) =>
|
|
2923
|
+
run: (call, next) => decodeInput(call).pipe(Effect.flatMap((decoded) => next({
|
|
2866
2924
|
...call,
|
|
2867
2925
|
input: decoded
|
|
2868
2926
|
})))
|
|
@@ -2876,7 +2934,7 @@ function stagesOf(config, host, action) {
|
|
|
2876
2934
|
...audit ? [audit] : [],
|
|
2877
2935
|
...check ? [{
|
|
2878
2936
|
name: "output",
|
|
2879
|
-
run: (call, next) => next(call).pipe(Effect.flatMap((result) => check[call.wire ? "json" : "value"](
|
|
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))))))
|
|
2880
2938
|
}] : [],
|
|
2881
2939
|
{
|
|
2882
2940
|
name: "execute",
|
|
@@ -2927,6 +2985,110 @@ function createAction(host, config, deferred = false) {
|
|
|
2927
2985
|
Object.defineProperty(action, RESET_STAGES, { value: () => void (built = deferred ? void 0 : built) });
|
|
2928
2986
|
return action;
|
|
2929
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
|
+
}
|
|
2930
3092
|
// src/crud/codec.ts
|
|
2931
3093
|
const isoPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
|
|
2932
3094
|
/** A failure thrown while building a query: `perform` turns it into the call's failure. */
|
|
@@ -2987,6 +3149,7 @@ function checkJsonSchema(schema) {
|
|
|
2987
3149
|
const walk = (ast) => {
|
|
2988
3150
|
if (seen.has(ast)) return;
|
|
2989
3151
|
seen.add(ast);
|
|
3152
|
+
if (isJsonDeclaration(ast)) return;
|
|
2990
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`);
|
|
2991
3154
|
if (ast._tag === "Suspend") return walk(ast.thunk());
|
|
2992
3155
|
for (const child of [
|
|
@@ -3056,7 +3219,7 @@ function withoutNull(schema) {
|
|
|
3056
3219
|
return rest.length === ast.types.length ? schema : Schema.Union(rest.map((member) => Schema.make(member)));
|
|
3057
3220
|
}
|
|
3058
3221
|
/** The schema of a resource's `:id`: a string on the wire for a number column, as paths carry it. */
|
|
3059
|
-
const idSchema$1 = (column, wire) => kindOf(column) === "number" ? wire ? Schema.
|
|
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;
|
|
3060
3223
|
/** An opaque list cursor: the orderBy it was made for, and the last row's sort values. */
|
|
3061
3224
|
function encodeCursor(spec, values) {
|
|
3062
3225
|
return Buffer.from(JSON.stringify([spec, values.map(jsonValue)])).toString("base64url");
|
|
@@ -3287,9 +3450,47 @@ function actionOwners(action) {
|
|
|
3287
3450
|
}
|
|
3288
3451
|
/** Whether a schema describes an object, which an absent input then stands for as `{}`. */
|
|
3289
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
|
+
}
|
|
3290
3491
|
// src/architecture.ts
|
|
3291
3492
|
const jsonSchema$1 = (schema) => {
|
|
3292
|
-
const { schema: root, definitions } =
|
|
3493
|
+
const { schema: root, definitions } = toJsonSchemaDocument(schema);
|
|
3293
3494
|
return Object.keys(definitions).length ? {
|
|
3294
3495
|
...root,
|
|
3295
3496
|
$defs: definitions
|
|
@@ -3868,7 +4069,7 @@ function generateOpenApiSpec({ title = OPENAPI_DEFAULTS.title, version = OPENAPI
|
|
|
3868
4069
|
const schemas = { ErrorEnvelope };
|
|
3869
4070
|
let authorizes = false;
|
|
3870
4071
|
const toJson = (schema) => {
|
|
3871
|
-
const { schema: root, definitions } =
|
|
4072
|
+
const { schema: root, definitions } = toJsonSchemaDocument(schema);
|
|
3872
4073
|
const keys = new Map(Object.keys(definitions).map((name) => [name, name]));
|
|
3873
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;
|
|
3874
4075
|
for (let changed = true; changed;) {
|
|
@@ -4122,7 +4323,7 @@ function defineEvents(service, catalog) {
|
|
|
4122
4323
|
*
|
|
4123
4324
|
* @throws (as a defect) When the payload does not match.
|
|
4124
4325
|
*/
|
|
4125
|
-
const encodePayload = (ref, payload) => Schema.encodeUnknownEffect(Schema.toCodecJson(ref.schema))(
|
|
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}`))));
|
|
4126
4327
|
/** The payload of a delivery, decoded with the event's schema. */
|
|
4127
4328
|
const decodePayload = (ref, payload) => Schema.decodeUnknownEffect(Schema.toCodecJson(ref.schema))(payload);
|
|
4128
4329
|
/** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
|
|
@@ -4211,6 +4412,27 @@ const queueOnCommit = (effect, wanted) => Effect.flatMap(Effect.serviceOption(Op
|
|
|
4211
4412
|
if (wanted(commits)) commits.push(effect);
|
|
4212
4413
|
})
|
|
4213
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
|
+
};
|
|
4214
4436
|
/** `brick.token.<token>`: a bearer token carried as a subprotocol, since browsers can't set headers on a WebSocket. */
|
|
4215
4437
|
const SOCKET_TOKEN_PROTOCOL = "brick.token.";
|
|
4216
4438
|
/** Control messages, sent as frames whose event starts with `$`. */
|
|
@@ -4291,7 +4513,7 @@ function socketCodecs(schemas) {
|
|
|
4291
4513
|
const refuse = (message) => Effect.die(new Error(message));
|
|
4292
4514
|
if (!codec) return refuse("Invalid socket output");
|
|
4293
4515
|
return Effect.gen(function* () {
|
|
4294
|
-
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")));
|
|
4295
4517
|
const frame = encodeFrame(event, json);
|
|
4296
4518
|
if (byteLength(frame) > 65536) return yield* refuse("Socket output too large");
|
|
4297
4519
|
return frame;
|
|
@@ -5725,7 +5947,7 @@ function makeDispatcher(config) {
|
|
|
5725
5947
|
return {
|
|
5726
5948
|
start: Effect.suspend(() => {
|
|
5727
5949
|
if (worker || !options.timer) return Effect.void;
|
|
5728
|
-
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) => {
|
|
5729
5951
|
worker = fiber;
|
|
5730
5952
|
}));
|
|
5731
5953
|
}),
|
|
@@ -5736,7 +5958,7 @@ function makeDispatcher(config) {
|
|
|
5736
5958
|
yield* turn.withPermits(1)(Effect.void);
|
|
5737
5959
|
yield* settled;
|
|
5738
5960
|
}),
|
|
5739
|
-
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),
|
|
5740
5962
|
drain: Effect.gen(function* () {
|
|
5741
5963
|
let total = 0;
|
|
5742
5964
|
for (;;) {
|
|
@@ -6037,7 +6259,7 @@ function createEvents(options, services, telemetry = false) {
|
|
|
6037
6259
|
transaction: (db, eventContext, fn) => Effect.suspend(() => {
|
|
6038
6260
|
const recorder = recorders.get(db);
|
|
6039
6261
|
if (!recorder) return Effect.die(/* @__PURE__ */ new Error(NO_OUTBOX));
|
|
6040
|
-
const notify = Effect.andThen(start, recorder.dispatcher.notify);
|
|
6262
|
+
const notify = afterCommitOn(db, Effect.andThen(start, recorder.dispatcher.notify));
|
|
6041
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)));
|
|
6042
6264
|
}),
|
|
6043
6265
|
start,
|
|
@@ -6370,7 +6592,7 @@ const withoutOpenObjects = (node) => {
|
|
|
6370
6592
|
};
|
|
6371
6593
|
/** The JSON form of a schema: what the client sends and receives. */
|
|
6372
6594
|
function jsonSchemaOf(schema) {
|
|
6373
|
-
const { schema: root, definitions } =
|
|
6595
|
+
const { schema: root, definitions } = toJsonSchemaDocument(schema);
|
|
6374
6596
|
return withoutOpenObjects(Object.keys(definitions).length ? {
|
|
6375
6597
|
...root,
|
|
6376
6598
|
$defs: definitions
|
|
@@ -6459,6 +6681,26 @@ function corsHook(cors) {
|
|
|
6459
6681
|
};
|
|
6460
6682
|
};
|
|
6461
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
|
+
}
|
|
6462
6704
|
// src/dashboard.ts
|
|
6463
6705
|
/** Where the app answers MCP for the dashboard's `/mcp`, to a request the dashboard signed. */
|
|
6464
6706
|
const DASHBOARD_MCP_ROUTE = "/_brick/dashboard/mcp";
|
|
@@ -6562,7 +6804,7 @@ var UnknownToolError = class extends Error {
|
|
|
6562
6804
|
};
|
|
6563
6805
|
const WRAP_RESULT = "x-brick-wrap-result";
|
|
6564
6806
|
const jsonSchema = (schema) => {
|
|
6565
|
-
const { schema: root, definitions } =
|
|
6807
|
+
const { schema: root, definitions } = toJsonSchemaDocument(schema);
|
|
6566
6808
|
const ref = root.$ref;
|
|
6567
6809
|
const base = typeof ref === "string" && definitions[ref.split("/").pop()] ? { ...definitions[ref.split("/").pop()] } : root;
|
|
6568
6810
|
return Object.keys(definitions).length ? {
|
|
@@ -7906,6 +8148,12 @@ const outcome = (text) => Effect.map(decodeResult(text), (result) => result._tag
|
|
|
7906
8148
|
status: "failed",
|
|
7907
8149
|
error: failure(result._tag === "Complete" && Exit.isFailure(result.exit) ? result.exit.cause : Cause.fail("The workflow suspended"))
|
|
7908
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}`;
|
|
7909
8157
|
const stepIdOf = (name, attempt) => `${name}:${attempt}`;
|
|
7910
8158
|
/** Pages `items` (already in ascending order) by an offset cursor. */
|
|
7911
8159
|
function paginate(items, options = {}) {
|
|
@@ -7951,7 +8199,7 @@ function workflowWorld(state, run) {
|
|
|
7951
8199
|
runId: id,
|
|
7952
8200
|
status: done?.status ?? "running",
|
|
7953
8201
|
deploymentId: "effect",
|
|
7954
|
-
workflowName: name,
|
|
8202
|
+
workflowName: machineName(name),
|
|
7955
8203
|
attributes: {},
|
|
7956
8204
|
createdAt: startedAt,
|
|
7957
8205
|
startedAt,
|
|
@@ -8014,7 +8262,7 @@ function workflowWorld(state, run) {
|
|
|
8014
8262
|
createdAt: current.createdAt,
|
|
8015
8263
|
eventData: {
|
|
8016
8264
|
deploymentId: current.deploymentId,
|
|
8017
|
-
workflowName: name,
|
|
8265
|
+
workflowName: machineName(name),
|
|
8018
8266
|
...data && { input: current.input }
|
|
8019
8267
|
}
|
|
8020
8268
|
}, {
|
|
@@ -8067,7 +8315,7 @@ function workflowWorld(state, run) {
|
|
|
8067
8315
|
return {
|
|
8068
8316
|
runs: {
|
|
8069
8317
|
list: (options = {}) => run(Effect.gen(function* () {
|
|
8070
|
-
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);
|
|
8071
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);
|
|
8072
8320
|
})),
|
|
8073
8321
|
get: (runId, options) => run(Effect.flatMap(find(runId), (item) => toRun(item.name, item.id, item.row, withData(options))))
|
|
@@ -8112,9 +8360,15 @@ function workflowWorld(state, run) {
|
|
|
8112
8360
|
// src/server.ts
|
|
8113
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);
|
|
8114
8362
|
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8115
|
-
/** The body of a plugin endpoint's request: JSON, else text. Read from a copy, so the handler's `request` stays unread. */
|
|
8116
|
-
const readBody = (web) => web.method === "GET" || web.method === "HEAD" ? Effect.succeed(void 0) : Effect.gen(function* () {
|
|
8117
|
-
|
|
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
|
+
}
|
|
8118
8372
|
if (!text) return void 0;
|
|
8119
8373
|
if (!web.headers.get("content-type")?.toLowerCase().includes("json")) return text;
|
|
8120
8374
|
try {
|
|
@@ -8139,29 +8393,14 @@ const formObject = (form) => Object.fromEntries([...new Set(form.keys())].map((k
|
|
|
8139
8393
|
const values = form.getAll(key);
|
|
8140
8394
|
return [key, values.length > 1 ? values : values[0]];
|
|
8141
8395
|
}));
|
|
8142
|
-
/** The body's bytes, or `undefined` once it passes `limit`: a chunked body has no Content-Length to check. */
|
|
8143
|
-
const readBounded = async (body, limit) => {
|
|
8144
|
-
const chunks = [];
|
|
8145
|
-
let size = 0;
|
|
8146
|
-
for await (const chunk of body) {
|
|
8147
|
-
size += chunk.byteLength;
|
|
8148
|
-
if (size > limit) return void 0;
|
|
8149
|
-
chunks.push(chunk);
|
|
8150
|
-
}
|
|
8151
|
-
return new Uint8Array(Buffer.concat(chunks));
|
|
8152
|
-
};
|
|
8153
8396
|
/**
|
|
8154
8397
|
* The action's input and how it arrived: the query string, a multipart form, or
|
|
8155
8398
|
* the JSON body, with the path parameters on top.
|
|
8156
8399
|
*/
|
|
8157
8400
|
const readInput = (route, action, web) => Effect.gen(function* () {
|
|
8158
8401
|
const { input } = action.config;
|
|
8159
|
-
const
|
|
8160
|
-
|
|
8161
|
-
message: `Request body exceeds ${route.bodyLimit} bytes`,
|
|
8162
|
-
status: 413
|
|
8163
|
-
});
|
|
8164
|
-
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);
|
|
8165
8404
|
if (!input) return {
|
|
8166
8405
|
input: void 0,
|
|
8167
8406
|
wire: "json"
|
|
@@ -8174,8 +8413,8 @@ const readInput = (route, action, web) => Effect.gen(function* () {
|
|
|
8174
8413
|
},
|
|
8175
8414
|
wire: "query"
|
|
8176
8415
|
};
|
|
8177
|
-
const bounded =
|
|
8178
|
-
if (
|
|
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);
|
|
8179
8418
|
const contentType = web.headers.get("content-type") ?? "";
|
|
8180
8419
|
const type = contentType.toLowerCase();
|
|
8181
8420
|
if (type.startsWith("multipart/form-data")) {
|
|
@@ -8312,6 +8551,7 @@ function brick(options = {}) {
|
|
|
8312
8551
|
});
|
|
8313
8552
|
const mountedEndpoints = [];
|
|
8314
8553
|
const mountEndpoint = (def, plugin = false) => {
|
|
8554
|
+
checkBodyLimit(`Endpoint '${def.method} ${def.path}'`, def.maxBodyBytes);
|
|
8315
8555
|
const mounted = claim(def.method, def.path, plugin);
|
|
8316
8556
|
endpointDefs.push(def);
|
|
8317
8557
|
if (mounted) served.add(def);
|
|
@@ -8394,6 +8634,12 @@ function brick(options = {}) {
|
|
|
8394
8634
|
const runtime = ManagedRuntime.make(events ? events.layer.pipe(Layer.provideMerge(base)) : base);
|
|
8395
8635
|
const appEvents = events?.bind(runtime);
|
|
8396
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
|
+
};
|
|
8397
8643
|
/**
|
|
8398
8644
|
* The route's response, with the trace ids echoed and the request logged.
|
|
8399
8645
|
* With `trace`, and `telemetry` on, the request is a span.
|
|
@@ -8412,6 +8658,7 @@ function brick(options = {}) {
|
|
|
8412
8658
|
requestId: ids.requestId
|
|
8413
8659
|
});
|
|
8414
8660
|
failure = envelope;
|
|
8661
|
+
noteFailure(web, cause, envelope);
|
|
8415
8662
|
const retry = envelope.details?.retryAfterSeconds;
|
|
8416
8663
|
return HttpServerResponse.jsonUnsafe(envelope, {
|
|
8417
8664
|
status: envelope.status,
|
|
@@ -8454,7 +8701,7 @@ function brick(options = {}) {
|
|
|
8454
8701
|
return HttpRouter.route(def.method, def.path, serve(({ traceId, requestId }, web) => Effect.gen(function* () {
|
|
8455
8702
|
const set = { headers: {} };
|
|
8456
8703
|
const params = Object.fromEntries(Object.entries(yield* HttpRouter.params).filter(([, value]) => value !== void 0));
|
|
8457
|
-
const body = yield* readBody(web);
|
|
8704
|
+
const body = yield* readBody(web, def.maxBodyBytes);
|
|
8458
8705
|
const result = yield* Effect.gen(function* () {
|
|
8459
8706
|
const db = database && (yield* database.Database);
|
|
8460
8707
|
return yield* def.handler({
|
|
@@ -8571,8 +8818,8 @@ function brick(options = {}) {
|
|
|
8571
8818
|
}
|
|
8572
8819
|
return web;
|
|
8573
8820
|
};
|
|
8574
|
-
/** What a plugin's middleware answers with, or `undefined` to let the request through. */
|
|
8575
|
-
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) => {
|
|
8576
8823
|
for (const handler of plugins.middleware) {
|
|
8577
8824
|
const set = { headers: {} };
|
|
8578
8825
|
const answered = await runtime.runPromise(handler({
|
|
@@ -8580,11 +8827,41 @@ function brick(options = {}) {
|
|
|
8580
8827
|
set
|
|
8581
8828
|
}).pipe(Effect.map((result) => result === void 0 ? void 0 : answer(result, set)), Effect.catchCause((cause) => Effect.sync(() => {
|
|
8582
8829
|
const envelope = toErrorResponse(cause, { logger });
|
|
8830
|
+
noteFailure(request, cause, envelope);
|
|
8583
8831
|
return Response.json(envelope, { status: envelope.status });
|
|
8584
8832
|
}))));
|
|
8833
|
+
Object.assign(carried, set.headers);
|
|
8585
8834
|
if (answered) return answered;
|
|
8586
8835
|
}
|
|
8587
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
|
+
};
|
|
8588
8865
|
const fetch = async (input, init) => {
|
|
8589
8866
|
const request = input instanceof Request && init === void 0 ? input : new Request(input, init);
|
|
8590
8867
|
markAddressSource(request, {
|
|
@@ -8592,16 +8869,17 @@ function brick(options = {}) {
|
|
|
8592
8869
|
server: () => server
|
|
8593
8870
|
});
|
|
8594
8871
|
const policy = cors?.(request);
|
|
8595
|
-
if (policy?.preflight) return policy.preflight;
|
|
8596
|
-
const
|
|
8597
|
-
|
|
8598
|
-
const
|
|
8599
|
-
|
|
8600
|
-
|
|
8601
|
-
|
|
8602
|
-
|
|
8603
|
-
headers
|
|
8604
|
-
}
|
|
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);
|
|
8605
8883
|
};
|
|
8606
8884
|
const run = (effect) => runtime.runPromiseExit(effect);
|
|
8607
8885
|
const raw = mountRawSockets({
|
|
@@ -8620,6 +8898,11 @@ function brick(options = {}) {
|
|
|
8620
8898
|
run
|
|
8621
8899
|
});
|
|
8622
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
|
+
};
|
|
8623
8906
|
let server;
|
|
8624
8907
|
const app = {
|
|
8625
8908
|
fetch,
|
|
@@ -8660,10 +8943,13 @@ function brick(options = {}) {
|
|
|
8660
8943
|
await appEvents?.stop();
|
|
8661
8944
|
} finally {
|
|
8662
8945
|
for (const handler of [web, ...retired.splice(0)]) await handler.dispose();
|
|
8946
|
+
stopped = true;
|
|
8663
8947
|
await runtime.dispose();
|
|
8664
8948
|
}
|
|
8665
8949
|
}
|
|
8666
8950
|
},
|
|
8951
|
+
runPromise: (effect) => Promise.resolve().then(() => live().runPromise(effect)),
|
|
8952
|
+
runFork: (effect) => live().runFork(effect),
|
|
8667
8953
|
events: appEvents,
|
|
8668
8954
|
get server() {
|
|
8669
8955
|
return server;
|
|
@@ -8712,6 +8998,6 @@ function brick(options = {}) {
|
|
|
8712
8998
|
};
|
|
8713
8999
|
return app;
|
|
8714
9000
|
}
|
|
8715
|
-
export { PLUGIN_KIND as $,
|
|
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 };
|
|
8716
9002
|
|
|
8717
|
-
//# sourceMappingURL=server-
|
|
9003
|
+
//# sourceMappingURL=server-CqCh1xgf.js.map
|