@effected/engine 0.12.0 → 0.13.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.
@@ -0,0 +1,324 @@
1
+ import { AjvInstanceValidator } from "./AjvInstanceValidator.js";
2
+ import { ConfigLoader } from "./ConfigLoader.js";
3
+ import { VersionCheck, VersionMismatch, VersionMismatchError } from "./VersionCheck.js";
4
+ import { Effect, FileSystem, JsonPointer, Option, Path, Predicate, Result, Schema, SchemaTransformation } from "effect";
5
+ import { InstanceValidator } from "@effected/schemastore";
6
+ import { LineIndex } from "@effected/source";
7
+ import { Jsonc } from "@effected/jsonc";
8
+
9
+ // src/schema/SchemaValidate.ts
10
+ /**
11
+ * The payload file could not be read or parsed: it does not exist, the
12
+ * filesystem refused it, or its contents are not JSON. Nothing was validated.
13
+ *
14
+ * @public
15
+ */
16
+ var PayloadError = class extends Schema.TaggedError()("PayloadError", {
17
+ path: Schema.String,
18
+ reason: Schema.String
19
+ }) {
20
+ get message() {
21
+ return `Failed to read payload ${this.path}: ${this.reason}`;
22
+ }
23
+ };
24
+ /**
25
+ * The payload names no schema and none was given, so there is nothing to
26
+ * validate against. A usage error: the remedy is in how it was invoked.
27
+ *
28
+ * @public
29
+ */
30
+ var MissingSchemaRefError = class extends Schema.TaggedError()("MissingSchemaRefError", { path: Schema.String }) {
31
+ get message() {
32
+ return `Payload ${this.path} has no "$schema" property; pass --schema <path|$id> to name the document to validate against.`;
33
+ }
34
+ };
35
+ /**
36
+ * The schema reference resolved to no readable document: it is neither an
37
+ * existing file nor an identity any config schema derives (`$id`, a frozen
38
+ * `$id`/`url`, a catalog `url`), or the document it names could not be read or
39
+ * parsed.
40
+ *
41
+ * @public
42
+ */
43
+ var SchemaResolutionError = class extends Schema.TaggedError()("SchemaResolutionError", {
44
+ $ref: Schema.String,
45
+ reason: Schema.String
46
+ }) {
47
+ get message() {
48
+ return `Failed to resolve schema "${this.$ref}": ${this.reason}`;
49
+ }
50
+ };
51
+ /**
52
+ * A place in a file. `line` and `column` are one-based, and `column` counts
53
+ * UTF-16 code units, as an editor does.
54
+ *
55
+ * @public
56
+ */
57
+ var SourcePoint = class extends Schema.Class("SourcePoint")({
58
+ file: Schema.String,
59
+ line: Schema.Number,
60
+ column: Schema.Number
61
+ }) {};
62
+ /**
63
+ * One way a payload fails its document, with where the offending value sits.
64
+ *
65
+ * @remarks
66
+ * `location` is omitted when the payload's tree could not be built. A pointer
67
+ * that does not resolve, such as a missing required property's parent chain
68
+ * ending early, points at the deepest node that does.
69
+ *
70
+ * @public
71
+ */
72
+ var LocatedFinding = class extends Schema.Class("LocatedFinding")({
73
+ /** A JSON pointer into the payload; `""` is the root. */
74
+ path: Schema.String,
75
+ message: Schema.String,
76
+ keyword: Schema.optionalKey(Schema.String),
77
+ location: Schema.optionalKey(SourcePoint)
78
+ }) {};
79
+ const JsonDocument = Schema.Struct({
80
+ payload: Schema.String,
81
+ schema: Schema.String,
82
+ document: Schema.String,
83
+ valid: Schema.Boolean,
84
+ findings: Schema.Array(Schema.toEncoded(LocatedFinding)),
85
+ versionMismatch: Schema.optionalKey(Schema.toEncoded(VersionMismatch))
86
+ });
87
+ /**
88
+ * The answer to one `validate`. A payload that does not conform is
89
+ * `valid: false`, an ordinary result.
90
+ *
91
+ * @public
92
+ */
93
+ var ValidateReport = class ValidateReport extends Schema.Class("ValidateReport")({
94
+ /** The payload's resolved path. */
95
+ payload: Schema.String,
96
+ /** The schema reference that was resolved. */
97
+ $ref: Schema.String,
98
+ /** The resolved path of the document the payload was validated against. */
99
+ source: Schema.String,
100
+ valid: Schema.Boolean,
101
+ findings: Schema.Array(LocatedFinding),
102
+ /** Present when the config's values came from another `@effected/schemastore` and the run went on. */
103
+ versionMismatch: Schema.optionalKey(VersionMismatch)
104
+ }) {
105
+ /**
106
+ * The report as the CLI's `--format=json` document: `$ref` is `schema` and
107
+ * `source` is `document`. Decoding it gives back the same report, so a consumer
108
+ * of the CLI's stdout reads the class the MCP result encodes.
109
+ */
110
+ static Json = JsonDocument.pipe(Schema.decodeTo(ValidateReport, SchemaTransformation.transform({
111
+ decode: ({ schema, document, ...rest }) => ({
112
+ ...rest,
113
+ $ref: schema,
114
+ source: document
115
+ }),
116
+ encode: ({ payload, $ref, source, ...rest }) => ({
117
+ payload,
118
+ schema: $ref,
119
+ document: source,
120
+ ...rest
121
+ })
122
+ })));
123
+ };
124
+ var ReadJsonError = class extends Schema.TaggedError()("ReadJsonError", {
125
+ path: Schema.String,
126
+ reason: Schema.String
127
+ }) {};
128
+ const stripBom = (text) => text.charCodeAt(0) === 65279 ? text.slice(1) : text;
129
+ const readText = (file) => Effect.gen(function* () {
130
+ const fs = yield* FileSystem.FileSystem;
131
+ return stripBom(yield* fs.readFileString(file).pipe(Effect.mapError((cause) => new ReadJsonError({
132
+ path: file,
133
+ reason: cause.message
134
+ }))));
135
+ });
136
+ const parseJson = (file, text) => Effect.try({
137
+ try: () => JSON.parse(text),
138
+ catch: (cause) => new ReadJsonError({
139
+ path: file,
140
+ reason: cause instanceof Error ? cause.message : String(cause)
141
+ })
142
+ });
143
+ const identityMap = (config) => {
144
+ const identities = /* @__PURE__ */ new Map();
145
+ const add = (identity, name, path) => {
146
+ if (identity !== void 0 && !identities.has(identity)) identities.set(identity, {
147
+ name,
148
+ path
149
+ });
150
+ };
151
+ for (const schema of config.schemas) {
152
+ add(schema.target.$id, schema.name, schema.target.path);
153
+ for (const frozen of schema.frozen) {
154
+ add(frozen.$id, schema.name, frozen.path);
155
+ add(frozen.url, schema.name, frozen.path);
156
+ }
157
+ add(schema.catalog?.url, schema.name, schema.target.path);
158
+ }
159
+ return identities;
160
+ };
161
+ const schemaPropertyOf = (payload) => Predicate.isObject(payload) && typeof payload.$schema === "string" ? payload.$schema : void 0;
162
+ const defsTarget = (document, ref) => {
163
+ if (!ref.startsWith("#/")) return;
164
+ let name;
165
+ try {
166
+ const tokens = ref.slice(2).split("/").map((token) => JsonPointer.unescapeToken(decodeURIComponent(token)));
167
+ if (tokens.length !== 2 || tokens[0] !== "$defs") return;
168
+ name = tokens[1];
169
+ } catch {
170
+ return;
171
+ }
172
+ const defs = document.$defs;
173
+ if (!Predicate.isObject(defs) || !Object.hasOwn(defs, name)) return;
174
+ const entry = defs[name];
175
+ return Predicate.isObject(entry) ? entry : void 0;
176
+ };
177
+ const declaresSchemaProperty = (document) => {
178
+ const declares = (node) => {
179
+ const properties = node.properties;
180
+ return Predicate.isObject(properties) && "$schema" in properties;
181
+ };
182
+ const seen = /* @__PURE__ */ new Set();
183
+ const queue = [document];
184
+ for (let node = queue.shift(); node !== void 0; node = queue.shift()) {
185
+ if (declares(node)) return true;
186
+ if (typeof node.$ref === "string" && !seen.has(node.$ref)) {
187
+ seen.add(node.$ref);
188
+ const target = defsTarget(document, node.$ref);
189
+ if (target !== void 0) queue.push(target);
190
+ }
191
+ if (Array.isArray(node.allOf)) {
192
+ for (const member of node.allOf) if (Predicate.isObject(member)) queue.push(member);
193
+ }
194
+ }
195
+ return false;
196
+ };
197
+ const withoutSchemaRef = (payload, document) => {
198
+ if (schemaPropertyOf(payload) === void 0 || declaresSchemaProperty(document)) return payload;
199
+ const rest = { ...payload };
200
+ delete rest.$schema;
201
+ return rest;
202
+ };
203
+ const nodeAt = (root, pointer) => {
204
+ if (pointer === "") return root;
205
+ let current = root;
206
+ for (const raw of pointer.slice(1).split("/")) {
207
+ const token = JsonPointer.unescapeToken(raw);
208
+ let next;
209
+ if (current.type === "object") next = current.children?.findLast((child) => child.type === "property" && child.children?.[0]?.value === token)?.children?.[1];
210
+ else if (current.type === "array" && /^(0|[1-9]\d*)$/.test(token)) next = current.children?.[Number(token)];
211
+ if (next === void 0) return current;
212
+ current = next;
213
+ }
214
+ return current;
215
+ };
216
+ const locator = (file, text) => {
217
+ const tree = Jsonc.parseTreeResult(text);
218
+ if (Result.isFailure(tree) || Option.isNone(tree.success)) return;
219
+ const root = tree.success.value;
220
+ const index = LineIndex.make(text);
221
+ return (pointer) => {
222
+ const { line, character } = index.positionAt(nodeAt(root, pointer).offset);
223
+ return SourcePoint.make({
224
+ file,
225
+ line: line + 1,
226
+ column: character + 1
227
+ });
228
+ };
229
+ };
230
+ /**
231
+ * Validates one payload against a published schema document.
232
+ *
233
+ * @remarks
234
+ * The reference (`schema`, else the payload's `$schema`) resolves file-first, then
235
+ * against the config's derived identities, so only an identity loads the config
236
+ * and only then is the version checked: `"fail"` refuses a mismatch and `"warn"`
237
+ * carries it on the report. A `Started` event is told to `deps.onProgress` once
238
+ * the config loads, carrying the mismatch, so a warn that is followed by a failure
239
+ * can still be shown. A top-level string `$schema` on the payload is stripped
240
+ * before validating unless the document declares it, and the rest goes verbatim.
241
+ * Findings that do not conform are `valid: false`, never a failure. A leading BOM
242
+ * is ignored, and `column` counts UTF-16 code units.
243
+ *
244
+ * @public
245
+ */
246
+ var SchemaValidate = class {
247
+ constructor() {}
248
+ static run = Effect.fn("SchemaValidate.run")(function* (input, deps) {
249
+ const path = yield* Path.Path;
250
+ const fs = yield* FileSystem.FileSystem;
251
+ const payloadPath = path.resolve(deps.cwd, input.payload);
252
+ const text = yield* readText(payloadPath).pipe(Effect.catchTag("ReadJsonError", ({ reason }) => Effect.fail(new PayloadError({
253
+ path: payloadPath,
254
+ reason
255
+ }))));
256
+ const payload = yield* parseJson(payloadPath, text).pipe(Effect.catchTag("ReadJsonError", ({ reason }) => Effect.fail(new PayloadError({
257
+ path: payloadPath,
258
+ reason
259
+ }))));
260
+ const $ref = input.schema ?? schemaPropertyOf(payload);
261
+ if ($ref === void 0) return yield* new MissingSchemaRefError({ path: payloadPath });
262
+ const unresolved = (reason) => Effect.fail(new SchemaResolutionError({
263
+ $ref,
264
+ reason
265
+ }));
266
+ let mismatch = Option.none();
267
+ let source;
268
+ let parsed;
269
+ const candidate = path.resolve(deps.cwd, $ref);
270
+ if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
271
+ source = candidate;
272
+ parsed = yield* readText(candidate).pipe(Effect.flatMap((documentText) => parseJson(candidate, documentText)), Effect.catchTag("ReadJsonError", ({ reason }) => unresolved(reason)));
273
+ } else {
274
+ const loaded = yield* ConfigLoader.load({
275
+ cwd: deps.cwd,
276
+ ...input.config !== void 0 ? { explicit: input.config } : {},
277
+ ...deps.discoveryCeiling !== void 0 ? { ceiling: deps.discoveryCeiling } : {},
278
+ ...deps.importModule !== void 0 ? { importModule: deps.importModule } : {}
279
+ });
280
+ mismatch = VersionCheck.inspect(loaded.config);
281
+ if (Option.isSome(mismatch) && input.versionMismatch === "fail") {
282
+ const { tool, found, message } = mismatch.value;
283
+ return yield* new VersionMismatchError({
284
+ tool,
285
+ found,
286
+ message
287
+ });
288
+ }
289
+ yield* deps.onProgress?.({
290
+ _tag: "Started",
291
+ names: loaded.config.schemas.map((schema) => schema.name),
292
+ ...Option.isSome(mismatch) ? { versionMismatch: mismatch.value } : {}
293
+ }) ?? Effect.void;
294
+ const match = identityMap(loaded.config).get($ref);
295
+ if (match === void 0) return yield* unresolved("not an existing file, and no schema in the config derives this $id or url");
296
+ source = match.path;
297
+ parsed = yield* readText(match.path).pipe(Effect.flatMap((documentText) => parseJson(match.path, documentText)), Effect.catchTag("ReadJsonError", ({ reason }) => unresolved(`schema "${match.name}" resolves to ${match.path}, which ${reason}`)));
298
+ }
299
+ if (!Predicate.isObject(parsed)) return yield* unresolved(`${source} is not a JSON object`);
300
+ const document = parsed;
301
+ const found = yield* Effect.gen(function* () {
302
+ return yield* (yield* InstanceValidator).validate(document, withoutSchemaRef(payload, document));
303
+ }).pipe(Effect.provide(deps.instanceValidator ?? AjvInstanceValidator.layer));
304
+ const locate = locator(payloadPath, text);
305
+ return ValidateReport.make({
306
+ payload: payloadPath,
307
+ $ref,
308
+ source,
309
+ valid: found.length === 0,
310
+ findings: found.map((finding) => {
311
+ const location = locate?.(finding.path);
312
+ return LocatedFinding.make({
313
+ path: finding.path,
314
+ message: finding.message,
315
+ ...finding.keyword !== void 0 ? { keyword: finding.keyword } : {},
316
+ ...location !== void 0 ? { location } : {}
317
+ });
318
+ }),
319
+ ...Option.isSome(mismatch) ? { versionMismatch: mismatch.value } : {}
320
+ });
321
+ });
322
+ };
323
+
324
+ export { LocatedFinding, MissingSchemaRefError, PayloadError, SchemaResolutionError, SchemaValidate, SourcePoint, ValidateReport };
@@ -0,0 +1,30 @@
1
+ import { Config, Effect, FileSystem, Option } from "effect";
2
+
3
+ // src/schema/StepSummary.ts
4
+ const summaryTarget = Config.String("GITHUB_STEP_SUMMARY").pipe(Config.option);
5
+ /**
6
+ * Appends a rendered {@link Report.markdown} document to `GITHUB_STEP_SUMMARY`.
7
+ *
8
+ * @public
9
+ */
10
+ var StepSummary = class {
11
+ constructor() {}
12
+ /**
13
+ * `true` when appended; `false` when `GITHUB_STEP_SUMMARY` is unset or
14
+ * empty, or when the read/write failed — a failure is logged at warning
15
+ * and never fails the run it is reporting on.
16
+ */
17
+ static append = Effect.fn("StepSummary.append")(function* (markdown) {
18
+ const fs = yield* FileSystem.FileSystem;
19
+ return yield* Effect.gen(function* () {
20
+ const target = yield* summaryTarget;
21
+ if (Option.isNone(target)) return false;
22
+ const existing = (yield* fs.exists(target.value)) ? yield* fs.readFileString(target.value) : "";
23
+ const separator = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
24
+ yield* fs.writeFileString(target.value, existing + separator + markdown);
25
+ return true;
26
+ }).pipe(Effect.catch((error) => Effect.logWarning("StepSummary.append: could not update GITHUB_STEP_SUMMARY", error).pipe(Effect.as(false))));
27
+ });
28
+ };
29
+
30
+ export { StepSummary };
@@ -0,0 +1,81 @@
1
+ import { Option, Schema } from "effect";
2
+ import { SchemastoreVersion } from "@effected/schemastore";
3
+
4
+ // src/schema/VersionCheck.ts
5
+ const UNBUILT = "0.0.0";
6
+ const FoundVersion = Schema.Struct({
7
+ /** What carries the stamp: `config`, or a schema's hosted identity. */
8
+ where: Schema.String,
9
+ /** The stamped version. */
10
+ version: Schema.String
11
+ });
12
+ /**
13
+ * A config whose values came from a different `@effected/schemastore` than the
14
+ * one this tool was built against.
15
+ *
16
+ * @public
17
+ */
18
+ var VersionMismatch = class extends Schema.Class("VersionMismatch")({
19
+ /** The version of the copy of `@effected/schemastore` the tool was built against. */
20
+ tool: Schema.String,
21
+ /** Every stamp that differs from `tool`. */
22
+ found: Schema.Array(FoundVersion),
23
+ /** Names both versions and how to align them. */
24
+ message: Schema.String
25
+ }) {};
26
+ /**
27
+ * The run refused a version mismatch, before generating anything.
28
+ *
29
+ * @public
30
+ */
31
+ var VersionMismatchError = class extends Schema.TaggedError()("VersionMismatchError", {
32
+ /** The version of the copy of `@effected/schemastore` the tool was built against. */
33
+ tool: Schema.String,
34
+ /** Every stamp that differs from `tool`. */
35
+ found: Schema.Array(FoundVersion),
36
+ /** Names both versions and how to align them. */
37
+ message: Schema.String
38
+ }) {};
39
+ /**
40
+ * Compares the `@effected/schemastore` versions stamped on a config's values
41
+ * with the version this tool was built against.
42
+ *
43
+ * @remarks
44
+ * The catalog normally keeps the two equal, but a partial bump can leave an older
45
+ * copy beside a newer one. A value from another copy is read only through
46
+ * `SchemastoreVersion.of`, because it may lack this copy's methods. A value with
47
+ * no stamp cannot be compared and is passed over, and so is `"0.0.0"` on either
48
+ * side, which is an unbuilt source run. Two copies at one version are
49
+ * indistinguishable, and are not the case this check targets.
50
+ *
51
+ * @public
52
+ */
53
+ var VersionCheck = class {
54
+ constructor() {}
55
+ /**
56
+ * The mismatch, or `Option.none()` when the stamps agree. `tool` defaults to
57
+ * this copy's `SchemastoreVersion.current`.
58
+ */
59
+ static inspect(config, tool = SchemastoreVersion.current) {
60
+ if (tool === UNBUILT) return Option.none();
61
+ const found = [{
62
+ where: "config",
63
+ stamp: SchemastoreVersion.of(config)
64
+ }, ...config.schemas.map((schema) => ({
65
+ where: `schema "${schema.name}" hosted identity`,
66
+ stamp: SchemastoreVersion.of(schema.hosted)
67
+ }))].flatMap(({ where, stamp }) => Option.isSome(stamp) && stamp.value !== UNBUILT && stamp.value !== tool ? [{
68
+ where,
69
+ version: stamp.value
70
+ }] : []);
71
+ if (found.length === 0) return Option.none();
72
+ const lines = found.map(({ where, version }) => `${where}: ${version}`).join(", ");
73
+ return Option.some(VersionMismatch.make({
74
+ tool,
75
+ found,
76
+ message: `The tool uses @effected/schemastore ${tool}, but the config's values come from another version (${lines}). Align @effected/schemastore and @effected/plugin on one version, as catalog:effected does.`
77
+ }));
78
+ }
79
+ };
80
+
81
+ export { VersionCheck, VersionMismatch, VersionMismatchError };
@@ -0,0 +1,50 @@
1
+ import { KeywordFamilies } from "@effected/schemastore";
2
+ import { Ajv } from "ajv";
3
+ import ajvFormats from "ajv-formats";
4
+
5
+ // src/schema/internal/ajv.ts
6
+ const addFormats = ajvFormats.default;
7
+ const MAX_KEYWORD_WALK_DEPTH = 256;
8
+ const collectDeclaredKeywords = (node, into, depth) => {
9
+ if (depth >= MAX_KEYWORD_WALK_DEPTH || typeof node !== "object" || node === null) return;
10
+ if (Array.isArray(node)) {
11
+ for (const element of node) collectDeclaredKeywords(element, into, depth + 1);
12
+ return;
13
+ }
14
+ for (const [key, value] of Object.entries(node)) {
15
+ if (KeywordFamilies.isDeclared(key)) {
16
+ into.add(key);
17
+ continue;
18
+ }
19
+ collectDeclaredKeywords(value, into, depth + 1);
20
+ }
21
+ };
22
+ /**
23
+ * Build the shared strict-mode ajv instance over a document: the standard
24
+ * `ajv-formats` vocabulary registered (`keywords: false` is load-bearing —
25
+ * the plugin's default ALSO registers `formatMaximum` / `formatMinimum` and
26
+ * their exclusive variants, which `DocumentLint` answers as unknown
27
+ * keywords, and registering them would drift the two verdicts apart), plus
28
+ * every declared `KeywordFamilies` keyword the document carries.
29
+ *
30
+ * THROWS when ajv itself refuses the setup — most often a declared keyword
31
+ * whose NAME ajv's own grammar (`/^[a-z_$][a-z0-9_$:-]*$/i`) rejects, such
32
+ * as an `x-ai-*` key carrying a dot or a space. Each caller decides what
33
+ * that throw means for its subject: a finding for `AjvValidator` (the
34
+ * document IS the subject there), an engine failure for
35
+ * `AjvInstanceValidator` (there the subject is the instance, and a document
36
+ * that will not compile yields no verdict about it).
37
+ */
38
+ const makeAjv = (document, strict) => {
39
+ const ajv = new Ajv({
40
+ strict,
41
+ allErrors: true
42
+ });
43
+ addFormats(ajv, { keywords: false });
44
+ const declared = /* @__PURE__ */ new Set();
45
+ collectDeclaredKeywords(document, declared, 0);
46
+ for (const keyword of declared) ajv.addKeyword({ keyword });
47
+ return ajv;
48
+ };
49
+
50
+ export { makeAjv };
@@ -0,0 +1,57 @@
1
+ import { Predicate } from "effect";
2
+
3
+ // src/schema/internal/causeMessage.ts
4
+ /** How many nodes of a cause chain the walk reads before stopping, so a cyclic chain cannot spin. */
5
+ const CAUSE_DEPTH = 8;
6
+ /**
7
+ * The message a single node carries: a thrown string, or a non-empty string `message` property. A getter or
8
+ * proxy trap that throws is a node with no message.
9
+ */
10
+ const messageAt = (node) => {
11
+ try {
12
+ const text = Predicate.isString(node) ? node : Predicate.hasProperty(node, "message") && Predicate.isString(node.message) ? node.message : void 0;
13
+ return text === void 0 || text.trim() === "" ? void 0 : text;
14
+ } catch {
15
+ return;
16
+ }
17
+ };
18
+ /** The next link of the chain: a node's `cause`, or `undefined` when it has none or reading it throws. */
19
+ const causeAt = (node) => {
20
+ try {
21
+ return Predicate.hasProperty(node, "cause") ? node.cause : void 0;
22
+ } catch {
23
+ return;
24
+ }
25
+ };
26
+ /**
27
+ * Every distinct non-empty message a preserved cause chain carries, nearest
28
+ * first and joined with `: `, or `undefined` when nothing along it has one.
29
+ *
30
+ * A `Schema.Defect()` field holds whatever was thrown, so the read is guarded
31
+ * rather than assumed: `Predicate.hasProperty` + `Predicate.isString` accepts
32
+ * an `Error`, a cross-realm `Error` that fails `instanceof`, a plain
33
+ * `{ message }` object and a thrown string alike. An empty or whitespace-only
34
+ * message counts as none. The walk follows `cause` links because a wrapper's
35
+ * text is often the generic summary and the driver's text underneath is the
36
+ * actionable detail, yet a wrapper that composes its own context must not
37
+ * lose it either; so nothing is dropped, and a deeper text the nearer one
38
+ * already contains is not repeated. The walk is bounded, so a cycle terminates.
39
+ *
40
+ * It never throws: every property read is guarded, so a `message` getter that throws leaves that link
41
+ * without text, and a `cause` getter that throws ends the walk with what was found so far.
42
+ */
43
+ const causeMessage = (cause) => {
44
+ let message;
45
+ let node = cause;
46
+ for (let depth = 0; depth < CAUSE_DEPTH && node !== void 0 && node !== null; depth++) {
47
+ const text = messageAt(node);
48
+ if (text !== void 0) {
49
+ if (message === void 0 || text.includes(message)) message = text;
50
+ else if (!message.includes(text)) message = `${message}: ${text}`;
51
+ }
52
+ node = causeAt(node);
53
+ }
54
+ return message;
55
+ };
56
+
57
+ export { causeMessage };
@@ -0,0 +1,23 @@
1
+ import { Schema } from "effect";
2
+
3
+ // src/schema/internal/decode.ts
4
+ /**
5
+ * JSON text to an untyped value, failing typed (never throwing) on text that
6
+ * does not parse. Bound once: every `decodeUnknownResult` call derives a
7
+ * decoder. Callers keep the parse and the shape decode as two steps where
8
+ * they must tell "not JSON" from "the wrong shape" — a one-step
9
+ * `fromJsonString(S)` separates the two only by issue tag.
10
+ *
11
+ * @internal
12
+ */
13
+ const decodeJson = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Unknown));
14
+ /**
15
+ * Flatten a Schema decode failure to one line: each issue as
16
+ * `<message> at <path>`, issues separated by `"; "`. Run the decode with
17
+ * `errors: "all"` so every issue is reported, not only the first.
18
+ *
19
+ * @internal
20
+ */
21
+ const flattenSchemaError = (error) => error.message.replace(/\n\s+at /g, " at ").replace(/\n/g, "; ");
22
+
23
+ export { decodeJson, flattenSchemaError };